PackageManagerService.java revision a1d12cfdb072acb14fa95d5e771e23396e6bd8e1
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.OWNER)) { 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_OWNER, 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_OWNER) { 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, null); 2280 } catch (PackageManagerException e) { 2281 Slog.e(TAG, "Failed to parse original system package: " 2282 + e.getMessage()); 2283 } 2284 } 2285 } 2286 } 2287 mExpectingBetter.clear(); 2288 2289 // Now that we know all of the shared libraries, update all clients to have 2290 // the correct library paths. 2291 updateAllSharedLibrariesLPw(); 2292 2293 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2294 // NOTE: We ignore potential failures here during a system scan (like 2295 // the rest of the commands above) because there's precious little we 2296 // can do about it. A settings error is reported, though. 2297 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2298 false /* force dexopt */, false /* defer dexopt */, 2299 false /* boot complete */); 2300 } 2301 2302 // Now that we know all the packages we are keeping, 2303 // read and update their last usage times. 2304 mPackageUsage.readLP(); 2305 2306 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2307 SystemClock.uptimeMillis()); 2308 Slog.i(TAG, "Time to scan packages: " 2309 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2310 + " seconds"); 2311 2312 // If the platform SDK has changed since the last time we booted, 2313 // we need to re-grant app permission to catch any new ones that 2314 // appear. This is really a hack, and means that apps can in some 2315 // cases get permissions that the user didn't initially explicitly 2316 // allow... it would be nice to have some better way to handle 2317 // this situation. 2318 int updateFlags = UPDATE_PERMISSIONS_ALL; 2319 if (ver.sdkVersion != mSdkVersion) { 2320 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2321 + mSdkVersion + "; regranting permissions for internal storage"); 2322 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2323 } 2324 updatePermissionsLPw(null, null, updateFlags); 2325 ver.sdkVersion = mSdkVersion; 2326 2327 // If this is the first boot or an update from pre-M, and it is a normal 2328 // boot, then we need to initialize the default preferred apps across 2329 // all defined users. 2330 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2331 for (UserInfo user : sUserManager.getUsers(true)) { 2332 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2333 applyFactoryDefaultBrowserLPw(user.id); 2334 primeDomainVerificationsLPw(user.id); 2335 } 2336 } 2337 2338 // If this is first boot after an OTA, and a normal boot, then 2339 // we need to clear code cache directories. 2340 if (mIsUpgrade && !onlyCore) { 2341 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2342 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2343 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2344 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2345 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2346 } 2347 } 2348 ver.fingerprint = Build.FINGERPRINT; 2349 } 2350 2351 checkDefaultBrowser(); 2352 2353 // clear only after permissions and other defaults have been updated 2354 mExistingSystemPackages.clear(); 2355 mPromoteSystemApps = false; 2356 2357 // All the changes are done during package scanning. 2358 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2359 2360 // can downgrade to reader 2361 mSettings.writeLPr(); 2362 2363 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2364 SystemClock.uptimeMillis()); 2365 2366 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2367 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2368 2369 mInstallerService = new PackageInstallerService(context, this); 2370 2371 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2372 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2373 mIntentFilterVerifierComponent); 2374 2375 } // synchronized (mPackages) 2376 } // synchronized (mInstallLock) 2377 2378 // Now after opening every single application zip, make sure they 2379 // are all flushed. Not really needed, but keeps things nice and 2380 // tidy. 2381 Runtime.getRuntime().gc(); 2382 2383 // Expose private service for system components to use. 2384 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2385 } 2386 2387 @Override 2388 public boolean isFirstBoot() { 2389 return !mRestoredSettings; 2390 } 2391 2392 @Override 2393 public boolean isOnlyCoreApps() { 2394 return mOnlyCore; 2395 } 2396 2397 @Override 2398 public boolean isUpgrade() { 2399 return mIsUpgrade; 2400 } 2401 2402 private String getRequiredVerifierLPr() { 2403 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2404 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2405 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2406 2407 String requiredVerifier = null; 2408 2409 final int N = receivers.size(); 2410 for (int i = 0; i < N; i++) { 2411 final ResolveInfo info = receivers.get(i); 2412 2413 if (info.activityInfo == null) { 2414 continue; 2415 } 2416 2417 final String packageName = info.activityInfo.packageName; 2418 2419 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2420 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2421 continue; 2422 } 2423 2424 if (requiredVerifier != null) { 2425 throw new RuntimeException("There can be only one required verifier"); 2426 } 2427 2428 requiredVerifier = packageName; 2429 } 2430 2431 return requiredVerifier; 2432 } 2433 2434 private String getRequiredInstallerLPr() { 2435 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2436 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2437 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2438 2439 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2440 PACKAGE_MIME_TYPE, 0, 0); 2441 2442 String requiredInstaller = null; 2443 2444 final int N = installers.size(); 2445 for (int i = 0; i < N; i++) { 2446 final ResolveInfo info = installers.get(i); 2447 final String packageName = info.activityInfo.packageName; 2448 2449 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2450 continue; 2451 } 2452 2453 if (requiredInstaller != null) { 2454 throw new RuntimeException("There must be one required installer"); 2455 } 2456 2457 requiredInstaller = packageName; 2458 } 2459 2460 if (requiredInstaller == null) { 2461 throw new RuntimeException("There must be one required installer"); 2462 } 2463 2464 return requiredInstaller; 2465 } 2466 2467 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2468 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2469 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2470 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2471 2472 ComponentName verifierComponentName = null; 2473 2474 int priority = -1000; 2475 final int N = receivers.size(); 2476 for (int i = 0; i < N; i++) { 2477 final ResolveInfo info = receivers.get(i); 2478 2479 if (info.activityInfo == null) { 2480 continue; 2481 } 2482 2483 final String packageName = info.activityInfo.packageName; 2484 2485 final PackageSetting ps = mSettings.mPackages.get(packageName); 2486 if (ps == null) { 2487 continue; 2488 } 2489 2490 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2491 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2492 continue; 2493 } 2494 2495 // Select the IntentFilterVerifier with the highest priority 2496 if (priority < info.priority) { 2497 priority = info.priority; 2498 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2499 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2500 + verifierComponentName + " with priority: " + info.priority); 2501 } 2502 } 2503 2504 return verifierComponentName; 2505 } 2506 2507 private void primeDomainVerificationsLPw(int userId) { 2508 if (DEBUG_DOMAIN_VERIFICATION) { 2509 Slog.d(TAG, "Priming domain verifications in user " + userId); 2510 } 2511 2512 SystemConfig systemConfig = SystemConfig.getInstance(); 2513 ArraySet<String> packages = systemConfig.getLinkedApps(); 2514 ArraySet<String> domains = new ArraySet<String>(); 2515 2516 for (String packageName : packages) { 2517 PackageParser.Package pkg = mPackages.get(packageName); 2518 if (pkg != null) { 2519 if (!pkg.isSystemApp()) { 2520 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2521 continue; 2522 } 2523 2524 domains.clear(); 2525 for (PackageParser.Activity a : pkg.activities) { 2526 for (ActivityIntentInfo filter : a.intents) { 2527 if (hasValidDomains(filter)) { 2528 domains.addAll(filter.getHostsList()); 2529 } 2530 } 2531 } 2532 2533 if (domains.size() > 0) { 2534 if (DEBUG_DOMAIN_VERIFICATION) { 2535 Slog.v(TAG, " + " + packageName); 2536 } 2537 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2538 // state w.r.t. the formal app-linkage "no verification attempted" state; 2539 // and then 'always' in the per-user state actually used for intent resolution. 2540 final IntentFilterVerificationInfo ivi; 2541 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2542 new ArrayList<String>(domains)); 2543 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2544 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2545 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2546 } else { 2547 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2548 + "' does not handle web links"); 2549 } 2550 } else { 2551 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2552 } 2553 } 2554 2555 scheduleWritePackageRestrictionsLocked(userId); 2556 scheduleWriteSettingsLocked(); 2557 } 2558 2559 private void applyFactoryDefaultBrowserLPw(int userId) { 2560 // The default browser app's package name is stored in a string resource, 2561 // with a product-specific overlay used for vendor customization. 2562 String browserPkg = mContext.getResources().getString( 2563 com.android.internal.R.string.default_browser); 2564 if (!TextUtils.isEmpty(browserPkg)) { 2565 // non-empty string => required to be a known package 2566 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2567 if (ps == null) { 2568 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2569 browserPkg = null; 2570 } else { 2571 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2572 } 2573 } 2574 2575 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2576 // default. If there's more than one, just leave everything alone. 2577 if (browserPkg == null) { 2578 calculateDefaultBrowserLPw(userId); 2579 } 2580 } 2581 2582 private void calculateDefaultBrowserLPw(int userId) { 2583 List<String> allBrowsers = resolveAllBrowserApps(userId); 2584 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2585 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2586 } 2587 2588 private List<String> resolveAllBrowserApps(int userId) { 2589 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2590 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2591 PackageManager.MATCH_ALL, userId); 2592 2593 final int count = list.size(); 2594 List<String> result = new ArrayList<String>(count); 2595 for (int i=0; i<count; i++) { 2596 ResolveInfo info = list.get(i); 2597 if (info.activityInfo == null 2598 || !info.handleAllWebDataURI 2599 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2600 || result.contains(info.activityInfo.packageName)) { 2601 continue; 2602 } 2603 result.add(info.activityInfo.packageName); 2604 } 2605 2606 return result; 2607 } 2608 2609 private boolean packageIsBrowser(String packageName, int userId) { 2610 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2611 PackageManager.MATCH_ALL, userId); 2612 final int N = list.size(); 2613 for (int i = 0; i < N; i++) { 2614 ResolveInfo info = list.get(i); 2615 if (packageName.equals(info.activityInfo.packageName)) { 2616 return true; 2617 } 2618 } 2619 return false; 2620 } 2621 2622 private void checkDefaultBrowser() { 2623 final int myUserId = UserHandle.myUserId(); 2624 final String packageName = getDefaultBrowserPackageName(myUserId); 2625 if (packageName != null) { 2626 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2627 if (info == null) { 2628 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2629 synchronized (mPackages) { 2630 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2631 } 2632 } 2633 } 2634 } 2635 2636 @Override 2637 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2638 throws RemoteException { 2639 try { 2640 return super.onTransact(code, data, reply, flags); 2641 } catch (RuntimeException e) { 2642 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2643 Slog.wtf(TAG, "Package Manager Crash", e); 2644 } 2645 throw e; 2646 } 2647 } 2648 2649 void cleanupInstallFailedPackage(PackageSetting ps) { 2650 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2651 2652 removeDataDirsLI(ps.volumeUuid, ps.name); 2653 if (ps.codePath != null) { 2654 if (ps.codePath.isDirectory()) { 2655 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2656 } else { 2657 ps.codePath.delete(); 2658 } 2659 } 2660 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2661 if (ps.resourcePath.isDirectory()) { 2662 FileUtils.deleteContents(ps.resourcePath); 2663 } 2664 ps.resourcePath.delete(); 2665 } 2666 mSettings.removePackageLPw(ps.name); 2667 } 2668 2669 static int[] appendInts(int[] cur, int[] add) { 2670 if (add == null) return cur; 2671 if (cur == null) return add; 2672 final int N = add.length; 2673 for (int i=0; i<N; i++) { 2674 cur = appendInt(cur, add[i]); 2675 } 2676 return cur; 2677 } 2678 2679 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2680 if (!sUserManager.exists(userId)) return null; 2681 final PackageSetting ps = (PackageSetting) p.mExtras; 2682 if (ps == null) { 2683 return null; 2684 } 2685 2686 final PermissionsState permissionsState = ps.getPermissionsState(); 2687 2688 final int[] gids = permissionsState.computeGids(userId); 2689 final Set<String> permissions = permissionsState.getPermissions(userId); 2690 final PackageUserState state = ps.readUserState(userId); 2691 2692 return PackageParser.generatePackageInfo(p, gids, flags, 2693 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2694 } 2695 2696 @Override 2697 public boolean isPackageFrozen(String packageName) { 2698 synchronized (mPackages) { 2699 final PackageSetting ps = mSettings.mPackages.get(packageName); 2700 if (ps != null) { 2701 return ps.frozen; 2702 } 2703 } 2704 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2705 return true; 2706 } 2707 2708 @Override 2709 public boolean isPackageAvailable(String packageName, int userId) { 2710 if (!sUserManager.exists(userId)) return false; 2711 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2712 synchronized (mPackages) { 2713 PackageParser.Package p = mPackages.get(packageName); 2714 if (p != null) { 2715 final PackageSetting ps = (PackageSetting) p.mExtras; 2716 if (ps != null) { 2717 final PackageUserState state = ps.readUserState(userId); 2718 if (state != null) { 2719 return PackageParser.isAvailable(state); 2720 } 2721 } 2722 } 2723 } 2724 return false; 2725 } 2726 2727 @Override 2728 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2729 if (!sUserManager.exists(userId)) return null; 2730 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2731 // reader 2732 synchronized (mPackages) { 2733 PackageParser.Package p = mPackages.get(packageName); 2734 if (DEBUG_PACKAGE_INFO) 2735 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2736 if (p != null) { 2737 return generatePackageInfo(p, flags, userId); 2738 } 2739 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2740 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2741 } 2742 } 2743 return null; 2744 } 2745 2746 @Override 2747 public String[] currentToCanonicalPackageNames(String[] names) { 2748 String[] out = new String[names.length]; 2749 // reader 2750 synchronized (mPackages) { 2751 for (int i=names.length-1; i>=0; i--) { 2752 PackageSetting ps = mSettings.mPackages.get(names[i]); 2753 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2754 } 2755 } 2756 return out; 2757 } 2758 2759 @Override 2760 public String[] canonicalToCurrentPackageNames(String[] names) { 2761 String[] out = new String[names.length]; 2762 // reader 2763 synchronized (mPackages) { 2764 for (int i=names.length-1; i>=0; i--) { 2765 String cur = mSettings.mRenamedPackages.get(names[i]); 2766 out[i] = cur != null ? cur : names[i]; 2767 } 2768 } 2769 return out; 2770 } 2771 2772 @Override 2773 public int getPackageUid(String packageName, int userId) { 2774 if (!sUserManager.exists(userId)) return -1; 2775 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2776 2777 // reader 2778 synchronized (mPackages) { 2779 PackageParser.Package p = mPackages.get(packageName); 2780 if(p != null) { 2781 return UserHandle.getUid(userId, p.applicationInfo.uid); 2782 } 2783 PackageSetting ps = mSettings.mPackages.get(packageName); 2784 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2785 return -1; 2786 } 2787 p = ps.pkg; 2788 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2789 } 2790 } 2791 2792 @Override 2793 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2794 if (!sUserManager.exists(userId)) { 2795 return null; 2796 } 2797 2798 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2799 "getPackageGids"); 2800 2801 // reader 2802 synchronized (mPackages) { 2803 PackageParser.Package p = mPackages.get(packageName); 2804 if (DEBUG_PACKAGE_INFO) { 2805 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2806 } 2807 if (p != null) { 2808 PackageSetting ps = (PackageSetting) p.mExtras; 2809 return ps.getPermissionsState().computeGids(userId); 2810 } 2811 } 2812 2813 return null; 2814 } 2815 2816 static PermissionInfo generatePermissionInfo( 2817 BasePermission bp, int flags) { 2818 if (bp.perm != null) { 2819 return PackageParser.generatePermissionInfo(bp.perm, flags); 2820 } 2821 PermissionInfo pi = new PermissionInfo(); 2822 pi.name = bp.name; 2823 pi.packageName = bp.sourcePackage; 2824 pi.nonLocalizedLabel = bp.name; 2825 pi.protectionLevel = bp.protectionLevel; 2826 return pi; 2827 } 2828 2829 @Override 2830 public PermissionInfo getPermissionInfo(String name, int flags) { 2831 // reader 2832 synchronized (mPackages) { 2833 final BasePermission p = mSettings.mPermissions.get(name); 2834 if (p != null) { 2835 return generatePermissionInfo(p, flags); 2836 } 2837 return null; 2838 } 2839 } 2840 2841 @Override 2842 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2843 // reader 2844 synchronized (mPackages) { 2845 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2846 for (BasePermission p : mSettings.mPermissions.values()) { 2847 if (group == null) { 2848 if (p.perm == null || p.perm.info.group == null) { 2849 out.add(generatePermissionInfo(p, flags)); 2850 } 2851 } else { 2852 if (p.perm != null && group.equals(p.perm.info.group)) { 2853 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2854 } 2855 } 2856 } 2857 2858 if (out.size() > 0) { 2859 return out; 2860 } 2861 return mPermissionGroups.containsKey(group) ? out : null; 2862 } 2863 } 2864 2865 @Override 2866 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2867 // reader 2868 synchronized (mPackages) { 2869 return PackageParser.generatePermissionGroupInfo( 2870 mPermissionGroups.get(name), flags); 2871 } 2872 } 2873 2874 @Override 2875 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2876 // reader 2877 synchronized (mPackages) { 2878 final int N = mPermissionGroups.size(); 2879 ArrayList<PermissionGroupInfo> out 2880 = new ArrayList<PermissionGroupInfo>(N); 2881 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2882 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2883 } 2884 return out; 2885 } 2886 } 2887 2888 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2889 int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 PackageSetting ps = mSettings.mPackages.get(packageName); 2892 if (ps != null) { 2893 if (ps.pkg == null) { 2894 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2895 flags, userId); 2896 if (pInfo != null) { 2897 return pInfo.applicationInfo; 2898 } 2899 return null; 2900 } 2901 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2902 ps.readUserState(userId), userId); 2903 } 2904 return null; 2905 } 2906 2907 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2908 int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 PackageSetting ps = mSettings.mPackages.get(packageName); 2911 if (ps != null) { 2912 PackageParser.Package pkg = ps.pkg; 2913 if (pkg == null) { 2914 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2915 return null; 2916 } 2917 // Only data remains, so we aren't worried about code paths 2918 pkg = new PackageParser.Package(packageName); 2919 pkg.applicationInfo.packageName = packageName; 2920 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2921 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2922 pkg.applicationInfo.dataDir = Environment 2923 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2924 .getAbsolutePath(); 2925 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2926 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2927 } 2928 return generatePackageInfo(pkg, flags, userId); 2929 } 2930 return null; 2931 } 2932 2933 @Override 2934 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2935 if (!sUserManager.exists(userId)) return null; 2936 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2937 // writer 2938 synchronized (mPackages) { 2939 PackageParser.Package p = mPackages.get(packageName); 2940 if (DEBUG_PACKAGE_INFO) Log.v( 2941 TAG, "getApplicationInfo " + packageName 2942 + ": " + p); 2943 if (p != null) { 2944 PackageSetting ps = mSettings.mPackages.get(packageName); 2945 if (ps == null) return null; 2946 // Note: isEnabledLP() does not apply here - always return info 2947 return PackageParser.generateApplicationInfo( 2948 p, flags, ps.readUserState(userId), userId); 2949 } 2950 if ("android".equals(packageName)||"system".equals(packageName)) { 2951 return mAndroidApplication; 2952 } 2953 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2954 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2955 } 2956 } 2957 return null; 2958 } 2959 2960 @Override 2961 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2962 final IPackageDataObserver observer) { 2963 mContext.enforceCallingOrSelfPermission( 2964 android.Manifest.permission.CLEAR_APP_CACHE, null); 2965 // Queue up an async operation since clearing cache may take a little while. 2966 mHandler.post(new Runnable() { 2967 public void run() { 2968 mHandler.removeCallbacks(this); 2969 int retCode = -1; 2970 synchronized (mInstallLock) { 2971 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2972 if (retCode < 0) { 2973 Slog.w(TAG, "Couldn't clear application caches"); 2974 } 2975 } 2976 if (observer != null) { 2977 try { 2978 observer.onRemoveCompleted(null, (retCode >= 0)); 2979 } catch (RemoteException e) { 2980 Slog.w(TAG, "RemoveException when invoking call back"); 2981 } 2982 } 2983 } 2984 }); 2985 } 2986 2987 @Override 2988 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2989 final IntentSender pi) { 2990 mContext.enforceCallingOrSelfPermission( 2991 android.Manifest.permission.CLEAR_APP_CACHE, null); 2992 // Queue up an async operation since clearing cache may take a little while. 2993 mHandler.post(new Runnable() { 2994 public void run() { 2995 mHandler.removeCallbacks(this); 2996 int retCode = -1; 2997 synchronized (mInstallLock) { 2998 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2999 if (retCode < 0) { 3000 Slog.w(TAG, "Couldn't clear application caches"); 3001 } 3002 } 3003 if(pi != null) { 3004 try { 3005 // Callback via pending intent 3006 int code = (retCode >= 0) ? 1 : 0; 3007 pi.sendIntent(null, code, null, 3008 null, null); 3009 } catch (SendIntentException e1) { 3010 Slog.i(TAG, "Failed to send pending intent"); 3011 } 3012 } 3013 } 3014 }); 3015 } 3016 3017 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3018 synchronized (mInstallLock) { 3019 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3020 throw new IOException("Failed to free enough space"); 3021 } 3022 } 3023 } 3024 3025 @Override 3026 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3027 if (!sUserManager.exists(userId)) return null; 3028 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3029 synchronized (mPackages) { 3030 PackageParser.Activity a = mActivities.mActivities.get(component); 3031 3032 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3033 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3034 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3035 if (ps == null) return null; 3036 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3037 userId); 3038 } 3039 if (mResolveComponentName.equals(component)) { 3040 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3041 new PackageUserState(), userId); 3042 } 3043 } 3044 return null; 3045 } 3046 3047 @Override 3048 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3049 String resolvedType) { 3050 synchronized (mPackages) { 3051 if (component.equals(mResolveComponentName)) { 3052 // The resolver supports EVERYTHING! 3053 return true; 3054 } 3055 PackageParser.Activity a = mActivities.mActivities.get(component); 3056 if (a == null) { 3057 return false; 3058 } 3059 for (int i=0; i<a.intents.size(); i++) { 3060 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3061 intent.getData(), intent.getCategories(), TAG) >= 0) { 3062 return true; 3063 } 3064 } 3065 return false; 3066 } 3067 } 3068 3069 @Override 3070 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3071 if (!sUserManager.exists(userId)) return null; 3072 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3073 synchronized (mPackages) { 3074 PackageParser.Activity a = mReceivers.mActivities.get(component); 3075 if (DEBUG_PACKAGE_INFO) Log.v( 3076 TAG, "getReceiverInfo " + component + ": " + a); 3077 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3078 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3079 if (ps == null) return null; 3080 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3081 userId); 3082 } 3083 } 3084 return null; 3085 } 3086 3087 @Override 3088 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3089 if (!sUserManager.exists(userId)) return null; 3090 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3091 synchronized (mPackages) { 3092 PackageParser.Service s = mServices.mServices.get(component); 3093 if (DEBUG_PACKAGE_INFO) Log.v( 3094 TAG, "getServiceInfo " + component + ": " + s); 3095 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3096 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3097 if (ps == null) return null; 3098 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3099 userId); 3100 } 3101 } 3102 return null; 3103 } 3104 3105 @Override 3106 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3107 if (!sUserManager.exists(userId)) return null; 3108 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3109 synchronized (mPackages) { 3110 PackageParser.Provider p = mProviders.mProviders.get(component); 3111 if (DEBUG_PACKAGE_INFO) Log.v( 3112 TAG, "getProviderInfo " + component + ": " + p); 3113 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3114 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3115 if (ps == null) return null; 3116 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3117 userId); 3118 } 3119 } 3120 return null; 3121 } 3122 3123 @Override 3124 public String[] getSystemSharedLibraryNames() { 3125 Set<String> libSet; 3126 synchronized (mPackages) { 3127 libSet = mSharedLibraries.keySet(); 3128 int size = libSet.size(); 3129 if (size > 0) { 3130 String[] libs = new String[size]; 3131 libSet.toArray(libs); 3132 return libs; 3133 } 3134 } 3135 return null; 3136 } 3137 3138 /** 3139 * @hide 3140 */ 3141 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3142 synchronized (mPackages) { 3143 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3144 if (lib != null && lib.apk != null) { 3145 return mPackages.get(lib.apk); 3146 } 3147 } 3148 return null; 3149 } 3150 3151 @Override 3152 public FeatureInfo[] getSystemAvailableFeatures() { 3153 Collection<FeatureInfo> featSet; 3154 synchronized (mPackages) { 3155 featSet = mAvailableFeatures.values(); 3156 int size = featSet.size(); 3157 if (size > 0) { 3158 FeatureInfo[] features = new FeatureInfo[size+1]; 3159 featSet.toArray(features); 3160 FeatureInfo fi = new FeatureInfo(); 3161 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3162 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3163 features[size] = fi; 3164 return features; 3165 } 3166 } 3167 return null; 3168 } 3169 3170 @Override 3171 public boolean hasSystemFeature(String name) { 3172 synchronized (mPackages) { 3173 return mAvailableFeatures.containsKey(name); 3174 } 3175 } 3176 3177 private void checkValidCaller(int uid, int userId) { 3178 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3179 return; 3180 3181 throw new SecurityException("Caller uid=" + uid 3182 + " is not privileged to communicate with user=" + userId); 3183 } 3184 3185 @Override 3186 public int checkPermission(String permName, String pkgName, int userId) { 3187 if (!sUserManager.exists(userId)) { 3188 return PackageManager.PERMISSION_DENIED; 3189 } 3190 3191 synchronized (mPackages) { 3192 final PackageParser.Package p = mPackages.get(pkgName); 3193 if (p != null && p.mExtras != null) { 3194 final PackageSetting ps = (PackageSetting) p.mExtras; 3195 final PermissionsState permissionsState = ps.getPermissionsState(); 3196 if (permissionsState.hasPermission(permName, userId)) { 3197 return PackageManager.PERMISSION_GRANTED; 3198 } 3199 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3200 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3201 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3202 return PackageManager.PERMISSION_GRANTED; 3203 } 3204 } 3205 } 3206 3207 return PackageManager.PERMISSION_DENIED; 3208 } 3209 3210 @Override 3211 public int checkUidPermission(String permName, int uid) { 3212 final int userId = UserHandle.getUserId(uid); 3213 3214 if (!sUserManager.exists(userId)) { 3215 return PackageManager.PERMISSION_DENIED; 3216 } 3217 3218 synchronized (mPackages) { 3219 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3220 if (obj != null) { 3221 final SettingBase ps = (SettingBase) obj; 3222 final PermissionsState permissionsState = ps.getPermissionsState(); 3223 if (permissionsState.hasPermission(permName, userId)) { 3224 return PackageManager.PERMISSION_GRANTED; 3225 } 3226 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3227 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3228 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3229 return PackageManager.PERMISSION_GRANTED; 3230 } 3231 } else { 3232 ArraySet<String> perms = mSystemPermissions.get(uid); 3233 if (perms != null) { 3234 if (perms.contains(permName)) { 3235 return PackageManager.PERMISSION_GRANTED; 3236 } 3237 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3238 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3239 return PackageManager.PERMISSION_GRANTED; 3240 } 3241 } 3242 } 3243 } 3244 3245 return PackageManager.PERMISSION_DENIED; 3246 } 3247 3248 @Override 3249 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3250 if (UserHandle.getCallingUserId() != userId) { 3251 mContext.enforceCallingPermission( 3252 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3253 "isPermissionRevokedByPolicy for user " + userId); 3254 } 3255 3256 if (checkPermission(permission, packageName, userId) 3257 == PackageManager.PERMISSION_GRANTED) { 3258 return false; 3259 } 3260 3261 final long identity = Binder.clearCallingIdentity(); 3262 try { 3263 final int flags = getPermissionFlags(permission, packageName, userId); 3264 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3265 } finally { 3266 Binder.restoreCallingIdentity(identity); 3267 } 3268 } 3269 3270 @Override 3271 public String getPermissionControllerPackageName() { 3272 synchronized (mPackages) { 3273 return mRequiredInstallerPackage; 3274 } 3275 } 3276 3277 /** 3278 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3279 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3280 * @param checkShell TODO(yamasani): 3281 * @param message the message to log on security exception 3282 */ 3283 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3284 boolean checkShell, String message) { 3285 if (userId < 0) { 3286 throw new IllegalArgumentException("Invalid userId " + userId); 3287 } 3288 if (checkShell) { 3289 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3290 } 3291 if (userId == UserHandle.getUserId(callingUid)) return; 3292 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3293 if (requireFullPermission) { 3294 mContext.enforceCallingOrSelfPermission( 3295 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3296 } else { 3297 try { 3298 mContext.enforceCallingOrSelfPermission( 3299 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3300 } catch (SecurityException se) { 3301 mContext.enforceCallingOrSelfPermission( 3302 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3303 } 3304 } 3305 } 3306 } 3307 3308 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3309 if (callingUid == Process.SHELL_UID) { 3310 if (userHandle >= 0 3311 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3312 throw new SecurityException("Shell does not have permission to access user " 3313 + userHandle); 3314 } else if (userHandle < 0) { 3315 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3316 + Debug.getCallers(3)); 3317 } 3318 } 3319 } 3320 3321 private BasePermission findPermissionTreeLP(String permName) { 3322 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3323 if (permName.startsWith(bp.name) && 3324 permName.length() > bp.name.length() && 3325 permName.charAt(bp.name.length()) == '.') { 3326 return bp; 3327 } 3328 } 3329 return null; 3330 } 3331 3332 private BasePermission checkPermissionTreeLP(String permName) { 3333 if (permName != null) { 3334 BasePermission bp = findPermissionTreeLP(permName); 3335 if (bp != null) { 3336 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3337 return bp; 3338 } 3339 throw new SecurityException("Calling uid " 3340 + Binder.getCallingUid() 3341 + " is not allowed to add to permission tree " 3342 + bp.name + " owned by uid " + bp.uid); 3343 } 3344 } 3345 throw new SecurityException("No permission tree found for " + permName); 3346 } 3347 3348 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3349 if (s1 == null) { 3350 return s2 == null; 3351 } 3352 if (s2 == null) { 3353 return false; 3354 } 3355 if (s1.getClass() != s2.getClass()) { 3356 return false; 3357 } 3358 return s1.equals(s2); 3359 } 3360 3361 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3362 if (pi1.icon != pi2.icon) return false; 3363 if (pi1.logo != pi2.logo) return false; 3364 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3365 if (!compareStrings(pi1.name, pi2.name)) return false; 3366 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3367 // We'll take care of setting this one. 3368 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3369 // These are not currently stored in settings. 3370 //if (!compareStrings(pi1.group, pi2.group)) return false; 3371 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3372 //if (pi1.labelRes != pi2.labelRes) return false; 3373 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3374 return true; 3375 } 3376 3377 int permissionInfoFootprint(PermissionInfo info) { 3378 int size = info.name.length(); 3379 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3380 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3381 return size; 3382 } 3383 3384 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3385 int size = 0; 3386 for (BasePermission perm : mSettings.mPermissions.values()) { 3387 if (perm.uid == tree.uid) { 3388 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3389 } 3390 } 3391 return size; 3392 } 3393 3394 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3395 // We calculate the max size of permissions defined by this uid and throw 3396 // if that plus the size of 'info' would exceed our stated maximum. 3397 if (tree.uid != Process.SYSTEM_UID) { 3398 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3399 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3400 throw new SecurityException("Permission tree size cap exceeded"); 3401 } 3402 } 3403 } 3404 3405 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3406 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3407 throw new SecurityException("Label must be specified in permission"); 3408 } 3409 BasePermission tree = checkPermissionTreeLP(info.name); 3410 BasePermission bp = mSettings.mPermissions.get(info.name); 3411 boolean added = bp == null; 3412 boolean changed = true; 3413 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3414 if (added) { 3415 enforcePermissionCapLocked(info, tree); 3416 bp = new BasePermission(info.name, tree.sourcePackage, 3417 BasePermission.TYPE_DYNAMIC); 3418 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3419 throw new SecurityException( 3420 "Not allowed to modify non-dynamic permission " 3421 + info.name); 3422 } else { 3423 if (bp.protectionLevel == fixedLevel 3424 && bp.perm.owner.equals(tree.perm.owner) 3425 && bp.uid == tree.uid 3426 && comparePermissionInfos(bp.perm.info, info)) { 3427 changed = false; 3428 } 3429 } 3430 bp.protectionLevel = fixedLevel; 3431 info = new PermissionInfo(info); 3432 info.protectionLevel = fixedLevel; 3433 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3434 bp.perm.info.packageName = tree.perm.info.packageName; 3435 bp.uid = tree.uid; 3436 if (added) { 3437 mSettings.mPermissions.put(info.name, bp); 3438 } 3439 if (changed) { 3440 if (!async) { 3441 mSettings.writeLPr(); 3442 } else { 3443 scheduleWriteSettingsLocked(); 3444 } 3445 } 3446 return added; 3447 } 3448 3449 @Override 3450 public boolean addPermission(PermissionInfo info) { 3451 synchronized (mPackages) { 3452 return addPermissionLocked(info, false); 3453 } 3454 } 3455 3456 @Override 3457 public boolean addPermissionAsync(PermissionInfo info) { 3458 synchronized (mPackages) { 3459 return addPermissionLocked(info, true); 3460 } 3461 } 3462 3463 @Override 3464 public void removePermission(String name) { 3465 synchronized (mPackages) { 3466 checkPermissionTreeLP(name); 3467 BasePermission bp = mSettings.mPermissions.get(name); 3468 if (bp != null) { 3469 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3470 throw new SecurityException( 3471 "Not allowed to modify non-dynamic permission " 3472 + name); 3473 } 3474 mSettings.mPermissions.remove(name); 3475 mSettings.writeLPr(); 3476 } 3477 } 3478 } 3479 3480 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3481 BasePermission bp) { 3482 int index = pkg.requestedPermissions.indexOf(bp.name); 3483 if (index == -1) { 3484 throw new SecurityException("Package " + pkg.packageName 3485 + " has not requested permission " + bp.name); 3486 } 3487 if (!bp.isRuntime() && !bp.isDevelopment()) { 3488 throw new SecurityException("Permission " + bp.name 3489 + " is not a changeable permission type"); 3490 } 3491 } 3492 3493 @Override 3494 public void grantRuntimePermission(String packageName, String name, final int userId) { 3495 if (!sUserManager.exists(userId)) { 3496 Log.e(TAG, "No such user:" + userId); 3497 return; 3498 } 3499 3500 mContext.enforceCallingOrSelfPermission( 3501 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3502 "grantRuntimePermission"); 3503 3504 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3505 "grantRuntimePermission"); 3506 3507 final int uid; 3508 final SettingBase sb; 3509 3510 synchronized (mPackages) { 3511 final PackageParser.Package pkg = mPackages.get(packageName); 3512 if (pkg == null) { 3513 throw new IllegalArgumentException("Unknown package: " + packageName); 3514 } 3515 3516 final BasePermission bp = mSettings.mPermissions.get(name); 3517 if (bp == null) { 3518 throw new IllegalArgumentException("Unknown permission: " + name); 3519 } 3520 3521 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3522 3523 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3524 sb = (SettingBase) pkg.mExtras; 3525 if (sb == null) { 3526 throw new IllegalArgumentException("Unknown package: " + packageName); 3527 } 3528 3529 final PermissionsState permissionsState = sb.getPermissionsState(); 3530 3531 final int flags = permissionsState.getPermissionFlags(name, userId); 3532 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3533 throw new SecurityException("Cannot grant system fixed permission: " 3534 + name + " for package: " + packageName); 3535 } 3536 3537 if (bp.isDevelopment()) { 3538 // Development permissions must be handled specially, since they are not 3539 // normal runtime permissions. For now they apply to all users. 3540 if (permissionsState.grantInstallPermission(bp) != 3541 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3542 scheduleWriteSettingsLocked(); 3543 } 3544 return; 3545 } 3546 3547 final int result = permissionsState.grantRuntimePermission(bp, userId); 3548 switch (result) { 3549 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3550 return; 3551 } 3552 3553 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3554 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3555 mHandler.post(new Runnable() { 3556 @Override 3557 public void run() { 3558 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3559 } 3560 }); 3561 } break; 3562 } 3563 3564 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3565 3566 // Not critical if that is lost - app has to request again. 3567 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3568 } 3569 3570 // Only need to do this if user is initialized. Otherwise it's a new user 3571 // and there are no processes running as the user yet and there's no need 3572 // to make an expensive call to remount processes for the changed permissions. 3573 if (READ_EXTERNAL_STORAGE.equals(name) 3574 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3575 final long token = Binder.clearCallingIdentity(); 3576 try { 3577 if (sUserManager.isInitialized(userId)) { 3578 MountServiceInternal mountServiceInternal = LocalServices.getService( 3579 MountServiceInternal.class); 3580 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3581 } 3582 } finally { 3583 Binder.restoreCallingIdentity(token); 3584 } 3585 } 3586 } 3587 3588 @Override 3589 public void revokeRuntimePermission(String packageName, String name, int userId) { 3590 if (!sUserManager.exists(userId)) { 3591 Log.e(TAG, "No such user:" + userId); 3592 return; 3593 } 3594 3595 mContext.enforceCallingOrSelfPermission( 3596 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3597 "revokeRuntimePermission"); 3598 3599 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3600 "revokeRuntimePermission"); 3601 3602 final int appId; 3603 3604 synchronized (mPackages) { 3605 final PackageParser.Package pkg = mPackages.get(packageName); 3606 if (pkg == null) { 3607 throw new IllegalArgumentException("Unknown package: " + packageName); 3608 } 3609 3610 final BasePermission bp = mSettings.mPermissions.get(name); 3611 if (bp == null) { 3612 throw new IllegalArgumentException("Unknown permission: " + name); 3613 } 3614 3615 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3616 3617 SettingBase sb = (SettingBase) pkg.mExtras; 3618 if (sb == null) { 3619 throw new IllegalArgumentException("Unknown package: " + packageName); 3620 } 3621 3622 final PermissionsState permissionsState = sb.getPermissionsState(); 3623 3624 final int flags = permissionsState.getPermissionFlags(name, userId); 3625 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3626 throw new SecurityException("Cannot revoke system fixed permission: " 3627 + name + " for package: " + packageName); 3628 } 3629 3630 if (bp.isDevelopment()) { 3631 // Development permissions must be handled specially, since they are not 3632 // normal runtime permissions. For now they apply to all users. 3633 if (permissionsState.revokeInstallPermission(bp) != 3634 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3635 scheduleWriteSettingsLocked(); 3636 } 3637 return; 3638 } 3639 3640 if (permissionsState.revokeRuntimePermission(bp, userId) == 3641 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3642 return; 3643 } 3644 3645 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3646 3647 // Critical, after this call app should never have the permission. 3648 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3649 3650 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3651 } 3652 3653 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3654 } 3655 3656 @Override 3657 public void resetRuntimePermissions() { 3658 mContext.enforceCallingOrSelfPermission( 3659 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3660 "revokeRuntimePermission"); 3661 3662 int callingUid = Binder.getCallingUid(); 3663 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3664 mContext.enforceCallingOrSelfPermission( 3665 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3666 "resetRuntimePermissions"); 3667 } 3668 3669 synchronized (mPackages) { 3670 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3671 for (int userId : UserManagerService.getInstance().getUserIds()) { 3672 final int packageCount = mPackages.size(); 3673 for (int i = 0; i < packageCount; i++) { 3674 PackageParser.Package pkg = mPackages.valueAt(i); 3675 if (!(pkg.mExtras instanceof PackageSetting)) { 3676 continue; 3677 } 3678 PackageSetting ps = (PackageSetting) pkg.mExtras; 3679 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3680 } 3681 } 3682 } 3683 } 3684 3685 @Override 3686 public int getPermissionFlags(String name, String packageName, int userId) { 3687 if (!sUserManager.exists(userId)) { 3688 return 0; 3689 } 3690 3691 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3692 3693 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3694 "getPermissionFlags"); 3695 3696 synchronized (mPackages) { 3697 final PackageParser.Package pkg = mPackages.get(packageName); 3698 if (pkg == null) { 3699 throw new IllegalArgumentException("Unknown package: " + packageName); 3700 } 3701 3702 final BasePermission bp = mSettings.mPermissions.get(name); 3703 if (bp == null) { 3704 throw new IllegalArgumentException("Unknown permission: " + name); 3705 } 3706 3707 SettingBase sb = (SettingBase) pkg.mExtras; 3708 if (sb == null) { 3709 throw new IllegalArgumentException("Unknown package: " + packageName); 3710 } 3711 3712 PermissionsState permissionsState = sb.getPermissionsState(); 3713 return permissionsState.getPermissionFlags(name, userId); 3714 } 3715 } 3716 3717 @Override 3718 public void updatePermissionFlags(String name, String packageName, int flagMask, 3719 int flagValues, int userId) { 3720 if (!sUserManager.exists(userId)) { 3721 return; 3722 } 3723 3724 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3725 3726 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3727 "updatePermissionFlags"); 3728 3729 // Only the system can change these flags and nothing else. 3730 if (getCallingUid() != Process.SYSTEM_UID) { 3731 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3732 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3733 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3734 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3735 } 3736 3737 synchronized (mPackages) { 3738 final PackageParser.Package pkg = mPackages.get(packageName); 3739 if (pkg == null) { 3740 throw new IllegalArgumentException("Unknown package: " + packageName); 3741 } 3742 3743 final BasePermission bp = mSettings.mPermissions.get(name); 3744 if (bp == null) { 3745 throw new IllegalArgumentException("Unknown permission: " + name); 3746 } 3747 3748 SettingBase sb = (SettingBase) pkg.mExtras; 3749 if (sb == null) { 3750 throw new IllegalArgumentException("Unknown package: " + packageName); 3751 } 3752 3753 PermissionsState permissionsState = sb.getPermissionsState(); 3754 3755 // Only the package manager can change flags for system component permissions. 3756 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3757 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3758 return; 3759 } 3760 3761 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3762 3763 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3764 // Install and runtime permissions are stored in different places, 3765 // so figure out what permission changed and persist the change. 3766 if (permissionsState.getInstallPermissionState(name) != null) { 3767 scheduleWriteSettingsLocked(); 3768 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3769 || hadState) { 3770 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3771 } 3772 } 3773 } 3774 } 3775 3776 /** 3777 * Update the permission flags for all packages and runtime permissions of a user in order 3778 * to allow device or profile owner to remove POLICY_FIXED. 3779 */ 3780 @Override 3781 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3782 if (!sUserManager.exists(userId)) { 3783 return; 3784 } 3785 3786 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3787 3788 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3789 "updatePermissionFlagsForAllApps"); 3790 3791 // Only the system can change system fixed flags. 3792 if (getCallingUid() != Process.SYSTEM_UID) { 3793 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3794 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3795 } 3796 3797 synchronized (mPackages) { 3798 boolean changed = false; 3799 final int packageCount = mPackages.size(); 3800 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3801 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3802 SettingBase sb = (SettingBase) pkg.mExtras; 3803 if (sb == null) { 3804 continue; 3805 } 3806 PermissionsState permissionsState = sb.getPermissionsState(); 3807 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3808 userId, flagMask, flagValues); 3809 } 3810 if (changed) { 3811 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3812 } 3813 } 3814 } 3815 3816 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3817 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3818 != PackageManager.PERMISSION_GRANTED 3819 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3820 != PackageManager.PERMISSION_GRANTED) { 3821 throw new SecurityException(message + " requires " 3822 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3823 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3824 } 3825 } 3826 3827 @Override 3828 public boolean shouldShowRequestPermissionRationale(String permissionName, 3829 String packageName, int userId) { 3830 if (UserHandle.getCallingUserId() != userId) { 3831 mContext.enforceCallingPermission( 3832 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3833 "canShowRequestPermissionRationale for user " + userId); 3834 } 3835 3836 final int uid = getPackageUid(packageName, userId); 3837 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3838 return false; 3839 } 3840 3841 if (checkPermission(permissionName, packageName, userId) 3842 == PackageManager.PERMISSION_GRANTED) { 3843 return false; 3844 } 3845 3846 final int flags; 3847 3848 final long identity = Binder.clearCallingIdentity(); 3849 try { 3850 flags = getPermissionFlags(permissionName, 3851 packageName, userId); 3852 } finally { 3853 Binder.restoreCallingIdentity(identity); 3854 } 3855 3856 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3857 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3858 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3859 3860 if ((flags & fixedFlags) != 0) { 3861 return false; 3862 } 3863 3864 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3865 } 3866 3867 @Override 3868 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3869 mContext.enforceCallingOrSelfPermission( 3870 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3871 "addOnPermissionsChangeListener"); 3872 3873 synchronized (mPackages) { 3874 mOnPermissionChangeListeners.addListenerLocked(listener); 3875 } 3876 } 3877 3878 @Override 3879 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3880 synchronized (mPackages) { 3881 mOnPermissionChangeListeners.removeListenerLocked(listener); 3882 } 3883 } 3884 3885 @Override 3886 public boolean isProtectedBroadcast(String actionName) { 3887 synchronized (mPackages) { 3888 return mProtectedBroadcasts.contains(actionName); 3889 } 3890 } 3891 3892 @Override 3893 public int checkSignatures(String pkg1, String pkg2) { 3894 synchronized (mPackages) { 3895 final PackageParser.Package p1 = mPackages.get(pkg1); 3896 final PackageParser.Package p2 = mPackages.get(pkg2); 3897 if (p1 == null || p1.mExtras == null 3898 || p2 == null || p2.mExtras == null) { 3899 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3900 } 3901 return compareSignatures(p1.mSignatures, p2.mSignatures); 3902 } 3903 } 3904 3905 @Override 3906 public int checkUidSignatures(int uid1, int uid2) { 3907 // Map to base uids. 3908 uid1 = UserHandle.getAppId(uid1); 3909 uid2 = UserHandle.getAppId(uid2); 3910 // reader 3911 synchronized (mPackages) { 3912 Signature[] s1; 3913 Signature[] s2; 3914 Object obj = mSettings.getUserIdLPr(uid1); 3915 if (obj != null) { 3916 if (obj instanceof SharedUserSetting) { 3917 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3918 } else if (obj instanceof PackageSetting) { 3919 s1 = ((PackageSetting)obj).signatures.mSignatures; 3920 } else { 3921 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3922 } 3923 } else { 3924 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3925 } 3926 obj = mSettings.getUserIdLPr(uid2); 3927 if (obj != null) { 3928 if (obj instanceof SharedUserSetting) { 3929 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3930 } else if (obj instanceof PackageSetting) { 3931 s2 = ((PackageSetting)obj).signatures.mSignatures; 3932 } else { 3933 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3934 } 3935 } else { 3936 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3937 } 3938 return compareSignatures(s1, s2); 3939 } 3940 } 3941 3942 private void killUid(int appId, int userId, String reason) { 3943 final long identity = Binder.clearCallingIdentity(); 3944 try { 3945 IActivityManager am = ActivityManagerNative.getDefault(); 3946 if (am != null) { 3947 try { 3948 am.killUid(appId, userId, reason); 3949 } catch (RemoteException e) { 3950 /* ignore - same process */ 3951 } 3952 } 3953 } finally { 3954 Binder.restoreCallingIdentity(identity); 3955 } 3956 } 3957 3958 /** 3959 * Compares two sets of signatures. Returns: 3960 * <br /> 3961 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3962 * <br /> 3963 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3964 * <br /> 3965 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3966 * <br /> 3967 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3968 * <br /> 3969 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3970 */ 3971 static int compareSignatures(Signature[] s1, Signature[] s2) { 3972 if (s1 == null) { 3973 return s2 == null 3974 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3975 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3976 } 3977 3978 if (s2 == null) { 3979 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3980 } 3981 3982 if (s1.length != s2.length) { 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 // Since both signature sets are of size 1, we can compare without HashSets. 3987 if (s1.length == 1) { 3988 return s1[0].equals(s2[0]) ? 3989 PackageManager.SIGNATURE_MATCH : 3990 PackageManager.SIGNATURE_NO_MATCH; 3991 } 3992 3993 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3994 for (Signature sig : s1) { 3995 set1.add(sig); 3996 } 3997 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3998 for (Signature sig : s2) { 3999 set2.add(sig); 4000 } 4001 // Make sure s2 contains all signatures in s1. 4002 if (set1.equals(set2)) { 4003 return PackageManager.SIGNATURE_MATCH; 4004 } 4005 return PackageManager.SIGNATURE_NO_MATCH; 4006 } 4007 4008 /** 4009 * If the database version for this type of package (internal storage or 4010 * external storage) is less than the version where package signatures 4011 * were updated, return true. 4012 */ 4013 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4014 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4015 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4016 } 4017 4018 /** 4019 * Used for backward compatibility to make sure any packages with 4020 * certificate chains get upgraded to the new style. {@code existingSigs} 4021 * will be in the old format (since they were stored on disk from before the 4022 * system upgrade) and {@code scannedSigs} will be in the newer format. 4023 */ 4024 private int compareSignaturesCompat(PackageSignatures existingSigs, 4025 PackageParser.Package scannedPkg) { 4026 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4027 return PackageManager.SIGNATURE_NO_MATCH; 4028 } 4029 4030 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4031 for (Signature sig : existingSigs.mSignatures) { 4032 existingSet.add(sig); 4033 } 4034 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4035 for (Signature sig : scannedPkg.mSignatures) { 4036 try { 4037 Signature[] chainSignatures = sig.getChainSignatures(); 4038 for (Signature chainSig : chainSignatures) { 4039 scannedCompatSet.add(chainSig); 4040 } 4041 } catch (CertificateEncodingException e) { 4042 scannedCompatSet.add(sig); 4043 } 4044 } 4045 /* 4046 * Make sure the expanded scanned set contains all signatures in the 4047 * existing one. 4048 */ 4049 if (scannedCompatSet.equals(existingSet)) { 4050 // Migrate the old signatures to the new scheme. 4051 existingSigs.assignSignatures(scannedPkg.mSignatures); 4052 // The new KeySets will be re-added later in the scanning process. 4053 synchronized (mPackages) { 4054 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4055 } 4056 return PackageManager.SIGNATURE_MATCH; 4057 } 4058 return PackageManager.SIGNATURE_NO_MATCH; 4059 } 4060 4061 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4062 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4063 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4064 } 4065 4066 private int compareSignaturesRecover(PackageSignatures existingSigs, 4067 PackageParser.Package scannedPkg) { 4068 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4069 return PackageManager.SIGNATURE_NO_MATCH; 4070 } 4071 4072 String msg = null; 4073 try { 4074 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4075 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4076 + scannedPkg.packageName); 4077 return PackageManager.SIGNATURE_MATCH; 4078 } 4079 } catch (CertificateException e) { 4080 msg = e.getMessage(); 4081 } 4082 4083 logCriticalInfo(Log.INFO, 4084 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4085 return PackageManager.SIGNATURE_NO_MATCH; 4086 } 4087 4088 @Override 4089 public String[] getPackagesForUid(int uid) { 4090 uid = UserHandle.getAppId(uid); 4091 // reader 4092 synchronized (mPackages) { 4093 Object obj = mSettings.getUserIdLPr(uid); 4094 if (obj instanceof SharedUserSetting) { 4095 final SharedUserSetting sus = (SharedUserSetting) obj; 4096 final int N = sus.packages.size(); 4097 final String[] res = new String[N]; 4098 final Iterator<PackageSetting> it = sus.packages.iterator(); 4099 int i = 0; 4100 while (it.hasNext()) { 4101 res[i++] = it.next().name; 4102 } 4103 return res; 4104 } else if (obj instanceof PackageSetting) { 4105 final PackageSetting ps = (PackageSetting) obj; 4106 return new String[] { ps.name }; 4107 } 4108 } 4109 return null; 4110 } 4111 4112 @Override 4113 public String getNameForUid(int uid) { 4114 // reader 4115 synchronized (mPackages) { 4116 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4117 if (obj instanceof SharedUserSetting) { 4118 final SharedUserSetting sus = (SharedUserSetting) obj; 4119 return sus.name + ":" + sus.userId; 4120 } else if (obj instanceof PackageSetting) { 4121 final PackageSetting ps = (PackageSetting) obj; 4122 return ps.name; 4123 } 4124 } 4125 return null; 4126 } 4127 4128 @Override 4129 public int getUidForSharedUser(String sharedUserName) { 4130 if(sharedUserName == null) { 4131 return -1; 4132 } 4133 // reader 4134 synchronized (mPackages) { 4135 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4136 if (suid == null) { 4137 return -1; 4138 } 4139 return suid.userId; 4140 } 4141 } 4142 4143 @Override 4144 public int getFlagsForUid(int uid) { 4145 synchronized (mPackages) { 4146 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4147 if (obj instanceof SharedUserSetting) { 4148 final SharedUserSetting sus = (SharedUserSetting) obj; 4149 return sus.pkgFlags; 4150 } else if (obj instanceof PackageSetting) { 4151 final PackageSetting ps = (PackageSetting) obj; 4152 return ps.pkgFlags; 4153 } 4154 } 4155 return 0; 4156 } 4157 4158 @Override 4159 public int getPrivateFlagsForUid(int uid) { 4160 synchronized (mPackages) { 4161 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4162 if (obj instanceof SharedUserSetting) { 4163 final SharedUserSetting sus = (SharedUserSetting) obj; 4164 return sus.pkgPrivateFlags; 4165 } else if (obj instanceof PackageSetting) { 4166 final PackageSetting ps = (PackageSetting) obj; 4167 return ps.pkgPrivateFlags; 4168 } 4169 } 4170 return 0; 4171 } 4172 4173 @Override 4174 public boolean isUidPrivileged(int uid) { 4175 uid = UserHandle.getAppId(uid); 4176 // reader 4177 synchronized (mPackages) { 4178 Object obj = mSettings.getUserIdLPr(uid); 4179 if (obj instanceof SharedUserSetting) { 4180 final SharedUserSetting sus = (SharedUserSetting) obj; 4181 final Iterator<PackageSetting> it = sus.packages.iterator(); 4182 while (it.hasNext()) { 4183 if (it.next().isPrivileged()) { 4184 return true; 4185 } 4186 } 4187 } else if (obj instanceof PackageSetting) { 4188 final PackageSetting ps = (PackageSetting) obj; 4189 return ps.isPrivileged(); 4190 } 4191 } 4192 return false; 4193 } 4194 4195 @Override 4196 public String[] getAppOpPermissionPackages(String permissionName) { 4197 synchronized (mPackages) { 4198 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4199 if (pkgs == null) { 4200 return null; 4201 } 4202 return pkgs.toArray(new String[pkgs.size()]); 4203 } 4204 } 4205 4206 @Override 4207 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4208 int flags, int userId) { 4209 if (!sUserManager.exists(userId)) return null; 4210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4211 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4212 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4213 } 4214 4215 @Override 4216 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4217 IntentFilter filter, int match, ComponentName activity) { 4218 final int userId = UserHandle.getCallingUserId(); 4219 if (DEBUG_PREFERRED) { 4220 Log.v(TAG, "setLastChosenActivity intent=" + intent 4221 + " resolvedType=" + resolvedType 4222 + " flags=" + flags 4223 + " filter=" + filter 4224 + " match=" + match 4225 + " activity=" + activity); 4226 filter.dump(new PrintStreamPrinter(System.out), " "); 4227 } 4228 intent.setComponent(null); 4229 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4230 // Find any earlier preferred or last chosen entries and nuke them 4231 findPreferredActivity(intent, resolvedType, 4232 flags, query, 0, false, true, false, userId); 4233 // Add the new activity as the last chosen for this filter 4234 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4235 "Setting last chosen"); 4236 } 4237 4238 @Override 4239 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4240 final int userId = UserHandle.getCallingUserId(); 4241 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4242 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4243 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4244 false, false, false, userId); 4245 } 4246 4247 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4248 int flags, List<ResolveInfo> query, int userId) { 4249 if (query != null) { 4250 final int N = query.size(); 4251 if (N == 1) { 4252 return query.get(0); 4253 } else if (N > 1) { 4254 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4255 // If there is more than one activity with the same priority, 4256 // then let the user decide between them. 4257 ResolveInfo r0 = query.get(0); 4258 ResolveInfo r1 = query.get(1); 4259 if (DEBUG_INTENT_MATCHING || debug) { 4260 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4261 + r1.activityInfo.name + "=" + r1.priority); 4262 } 4263 // If the first activity has a higher priority, or a different 4264 // default, then it is always desireable to pick it. 4265 if (r0.priority != r1.priority 4266 || r0.preferredOrder != r1.preferredOrder 4267 || r0.isDefault != r1.isDefault) { 4268 return query.get(0); 4269 } 4270 // If we have saved a preference for a preferred activity for 4271 // this Intent, use that. 4272 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4273 flags, query, r0.priority, true, false, debug, userId); 4274 if (ri != null) { 4275 return ri; 4276 } 4277 ri = new ResolveInfo(mResolveInfo); 4278 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4279 ri.activityInfo.applicationInfo = new ApplicationInfo( 4280 ri.activityInfo.applicationInfo); 4281 if (userId != 0) { 4282 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4283 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4284 } 4285 // Make sure that the resolver is displayable in car mode 4286 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4287 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4288 return ri; 4289 } 4290 } 4291 return null; 4292 } 4293 4294 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4295 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4296 final int N = query.size(); 4297 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4298 .get(userId); 4299 // Get the list of persistent preferred activities that handle the intent 4300 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4301 List<PersistentPreferredActivity> pprefs = ppir != null 4302 ? ppir.queryIntent(intent, resolvedType, 4303 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4304 : null; 4305 if (pprefs != null && pprefs.size() > 0) { 4306 final int M = pprefs.size(); 4307 for (int i=0; i<M; i++) { 4308 final PersistentPreferredActivity ppa = pprefs.get(i); 4309 if (DEBUG_PREFERRED || debug) { 4310 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4311 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4312 + "\n component=" + ppa.mComponent); 4313 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4314 } 4315 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4316 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4317 if (DEBUG_PREFERRED || debug) { 4318 Slog.v(TAG, "Found persistent preferred activity:"); 4319 if (ai != null) { 4320 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4321 } else { 4322 Slog.v(TAG, " null"); 4323 } 4324 } 4325 if (ai == null) { 4326 // This previously registered persistent preferred activity 4327 // component is no longer known. Ignore it and do NOT remove it. 4328 continue; 4329 } 4330 for (int j=0; j<N; j++) { 4331 final ResolveInfo ri = query.get(j); 4332 if (!ri.activityInfo.applicationInfo.packageName 4333 .equals(ai.applicationInfo.packageName)) { 4334 continue; 4335 } 4336 if (!ri.activityInfo.name.equals(ai.name)) { 4337 continue; 4338 } 4339 // Found a persistent preference that can handle the intent. 4340 if (DEBUG_PREFERRED || debug) { 4341 Slog.v(TAG, "Returning persistent preferred activity: " + 4342 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4343 } 4344 return ri; 4345 } 4346 } 4347 } 4348 return null; 4349 } 4350 4351 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4352 List<ResolveInfo> query, int priority, boolean always, 4353 boolean removeMatches, boolean debug, int userId) { 4354 if (!sUserManager.exists(userId)) return null; 4355 // writer 4356 synchronized (mPackages) { 4357 if (intent.getSelector() != null) { 4358 intent = intent.getSelector(); 4359 } 4360 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4361 4362 // Try to find a matching persistent preferred activity. 4363 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4364 debug, userId); 4365 4366 // If a persistent preferred activity matched, use it. 4367 if (pri != null) { 4368 return pri; 4369 } 4370 4371 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4372 // Get the list of preferred activities that handle the intent 4373 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4374 List<PreferredActivity> prefs = pir != null 4375 ? pir.queryIntent(intent, resolvedType, 4376 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4377 : null; 4378 if (prefs != null && prefs.size() > 0) { 4379 boolean changed = false; 4380 try { 4381 // First figure out how good the original match set is. 4382 // We will only allow preferred activities that came 4383 // from the same match quality. 4384 int match = 0; 4385 4386 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4387 4388 final int N = query.size(); 4389 for (int j=0; j<N; j++) { 4390 final ResolveInfo ri = query.get(j); 4391 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4392 + ": 0x" + Integer.toHexString(match)); 4393 if (ri.match > match) { 4394 match = ri.match; 4395 } 4396 } 4397 4398 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4399 + Integer.toHexString(match)); 4400 4401 match &= IntentFilter.MATCH_CATEGORY_MASK; 4402 final int M = prefs.size(); 4403 for (int i=0; i<M; i++) { 4404 final PreferredActivity pa = prefs.get(i); 4405 if (DEBUG_PREFERRED || debug) { 4406 Slog.v(TAG, "Checking PreferredActivity ds=" 4407 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4408 + "\n component=" + pa.mPref.mComponent); 4409 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4410 } 4411 if (pa.mPref.mMatch != match) { 4412 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4413 + Integer.toHexString(pa.mPref.mMatch)); 4414 continue; 4415 } 4416 // If it's not an "always" type preferred activity and that's what we're 4417 // looking for, skip it. 4418 if (always && !pa.mPref.mAlways) { 4419 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4420 continue; 4421 } 4422 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4423 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4424 if (DEBUG_PREFERRED || debug) { 4425 Slog.v(TAG, "Found preferred activity:"); 4426 if (ai != null) { 4427 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4428 } else { 4429 Slog.v(TAG, " null"); 4430 } 4431 } 4432 if (ai == null) { 4433 // This previously registered preferred activity 4434 // component is no longer known. Most likely an update 4435 // to the app was installed and in the new version this 4436 // component no longer exists. Clean it up by removing 4437 // it from the preferred activities list, and skip it. 4438 Slog.w(TAG, "Removing dangling preferred activity: " 4439 + pa.mPref.mComponent); 4440 pir.removeFilter(pa); 4441 changed = true; 4442 continue; 4443 } 4444 for (int j=0; j<N; j++) { 4445 final ResolveInfo ri = query.get(j); 4446 if (!ri.activityInfo.applicationInfo.packageName 4447 .equals(ai.applicationInfo.packageName)) { 4448 continue; 4449 } 4450 if (!ri.activityInfo.name.equals(ai.name)) { 4451 continue; 4452 } 4453 4454 if (removeMatches) { 4455 pir.removeFilter(pa); 4456 changed = true; 4457 if (DEBUG_PREFERRED) { 4458 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4459 } 4460 break; 4461 } 4462 4463 // Okay we found a previously set preferred or last chosen app. 4464 // If the result set is different from when this 4465 // was created, we need to clear it and re-ask the 4466 // user their preference, if we're looking for an "always" type entry. 4467 if (always && !pa.mPref.sameSet(query)) { 4468 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4469 + intent + " type " + resolvedType); 4470 if (DEBUG_PREFERRED) { 4471 Slog.v(TAG, "Removing preferred activity since set changed " 4472 + pa.mPref.mComponent); 4473 } 4474 pir.removeFilter(pa); 4475 // Re-add the filter as a "last chosen" entry (!always) 4476 PreferredActivity lastChosen = new PreferredActivity( 4477 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4478 pir.addFilter(lastChosen); 4479 changed = true; 4480 return null; 4481 } 4482 4483 // Yay! Either the set matched or we're looking for the last chosen 4484 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4485 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4486 return ri; 4487 } 4488 } 4489 } finally { 4490 if (changed) { 4491 if (DEBUG_PREFERRED) { 4492 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4493 } 4494 scheduleWritePackageRestrictionsLocked(userId); 4495 } 4496 } 4497 } 4498 } 4499 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4500 return null; 4501 } 4502 4503 /* 4504 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4505 */ 4506 @Override 4507 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4508 int targetUserId) { 4509 mContext.enforceCallingOrSelfPermission( 4510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4511 List<CrossProfileIntentFilter> matches = 4512 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4513 if (matches != null) { 4514 int size = matches.size(); 4515 for (int i = 0; i < size; i++) { 4516 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4517 } 4518 } 4519 if (hasWebURI(intent)) { 4520 // cross-profile app linking works only towards the parent. 4521 final UserInfo parent = getProfileParent(sourceUserId); 4522 synchronized(mPackages) { 4523 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4524 intent, resolvedType, 0, sourceUserId, parent.id); 4525 return xpDomainInfo != null; 4526 } 4527 } 4528 return false; 4529 } 4530 4531 private UserInfo getProfileParent(int userId) { 4532 final long identity = Binder.clearCallingIdentity(); 4533 try { 4534 return sUserManager.getProfileParent(userId); 4535 } finally { 4536 Binder.restoreCallingIdentity(identity); 4537 } 4538 } 4539 4540 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4541 String resolvedType, int userId) { 4542 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4543 if (resolver != null) { 4544 return resolver.queryIntent(intent, resolvedType, false, userId); 4545 } 4546 return null; 4547 } 4548 4549 @Override 4550 public List<ResolveInfo> queryIntentActivities(Intent intent, 4551 String resolvedType, int flags, int userId) { 4552 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4553 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4554 ComponentName comp = intent.getComponent(); 4555 if (comp == null) { 4556 if (intent.getSelector() != null) { 4557 intent = intent.getSelector(); 4558 comp = intent.getComponent(); 4559 } 4560 } 4561 4562 if (comp != null) { 4563 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4564 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4565 if (ai != null) { 4566 final ResolveInfo ri = new ResolveInfo(); 4567 ri.activityInfo = ai; 4568 list.add(ri); 4569 } 4570 return list; 4571 } 4572 4573 // reader 4574 synchronized (mPackages) { 4575 final String pkgName = intent.getPackage(); 4576 if (pkgName == null) { 4577 List<CrossProfileIntentFilter> matchingFilters = 4578 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4579 // Check for results that need to skip the current profile. 4580 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4581 resolvedType, flags, userId); 4582 if (xpResolveInfo != null) { 4583 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4584 result.add(xpResolveInfo); 4585 return filterIfNotSystemUser(result, userId); 4586 } 4587 4588 // Check for results in the current profile. 4589 List<ResolveInfo> result = mActivities.queryIntent( 4590 intent, resolvedType, flags, userId); 4591 4592 // Check for cross profile results. 4593 xpResolveInfo = queryCrossProfileIntents( 4594 matchingFilters, intent, resolvedType, flags, userId); 4595 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4596 result.add(xpResolveInfo); 4597 Collections.sort(result, mResolvePrioritySorter); 4598 } 4599 result = filterIfNotSystemUser(result, userId); 4600 if (hasWebURI(intent)) { 4601 CrossProfileDomainInfo xpDomainInfo = null; 4602 final UserInfo parent = getProfileParent(userId); 4603 if (parent != null) { 4604 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4605 flags, userId, parent.id); 4606 } 4607 if (xpDomainInfo != null) { 4608 if (xpResolveInfo != null) { 4609 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4610 // in the result. 4611 result.remove(xpResolveInfo); 4612 } 4613 if (result.size() == 0) { 4614 result.add(xpDomainInfo.resolveInfo); 4615 return result; 4616 } 4617 } else if (result.size() <= 1) { 4618 return result; 4619 } 4620 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4621 xpDomainInfo, userId); 4622 Collections.sort(result, mResolvePrioritySorter); 4623 } 4624 return result; 4625 } 4626 final PackageParser.Package pkg = mPackages.get(pkgName); 4627 if (pkg != null) { 4628 return filterIfNotSystemUser( 4629 mActivities.queryIntentForPackage( 4630 intent, resolvedType, flags, pkg.activities, userId), 4631 userId); 4632 } 4633 return new ArrayList<ResolveInfo>(); 4634 } 4635 } 4636 4637 private static class CrossProfileDomainInfo { 4638 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4639 ResolveInfo resolveInfo; 4640 /* Best domain verification status of the activities found in the other profile */ 4641 int bestDomainVerificationStatus; 4642 } 4643 4644 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4645 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4646 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4647 sourceUserId)) { 4648 return null; 4649 } 4650 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4651 resolvedType, flags, parentUserId); 4652 4653 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4654 return null; 4655 } 4656 CrossProfileDomainInfo result = null; 4657 int size = resultTargetUser.size(); 4658 for (int i = 0; i < size; i++) { 4659 ResolveInfo riTargetUser = resultTargetUser.get(i); 4660 // Intent filter verification is only for filters that specify a host. So don't return 4661 // those that handle all web uris. 4662 if (riTargetUser.handleAllWebDataURI) { 4663 continue; 4664 } 4665 String packageName = riTargetUser.activityInfo.packageName; 4666 PackageSetting ps = mSettings.mPackages.get(packageName); 4667 if (ps == null) { 4668 continue; 4669 } 4670 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4671 int status = (int)(verificationState >> 32); 4672 if (result == null) { 4673 result = new CrossProfileDomainInfo(); 4674 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4675 sourceUserId, parentUserId); 4676 result.bestDomainVerificationStatus = status; 4677 } else { 4678 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4679 result.bestDomainVerificationStatus); 4680 } 4681 } 4682 // Don't consider matches with status NEVER across profiles. 4683 if (result != null && result.bestDomainVerificationStatus 4684 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4685 return null; 4686 } 4687 return result; 4688 } 4689 4690 /** 4691 * Verification statuses are ordered from the worse to the best, except for 4692 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4693 */ 4694 private int bestDomainVerificationStatus(int status1, int status2) { 4695 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4696 return status2; 4697 } 4698 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4699 return status1; 4700 } 4701 return (int) MathUtils.max(status1, status2); 4702 } 4703 4704 private boolean isUserEnabled(int userId) { 4705 long callingId = Binder.clearCallingIdentity(); 4706 try { 4707 UserInfo userInfo = sUserManager.getUserInfo(userId); 4708 return userInfo != null && userInfo.isEnabled(); 4709 } finally { 4710 Binder.restoreCallingIdentity(callingId); 4711 } 4712 } 4713 4714 /** 4715 * Filter out activities with systemUserOnly flag set, when current user is not System. 4716 * 4717 * @return filtered list 4718 */ 4719 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4720 if (userId == UserHandle.USER_SYSTEM) { 4721 return resolveInfos; 4722 } 4723 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4724 ResolveInfo info = resolveInfos.get(i); 4725 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4726 resolveInfos.remove(i); 4727 } 4728 } 4729 return resolveInfos; 4730 } 4731 4732 private static boolean hasWebURI(Intent intent) { 4733 if (intent.getData() == null) { 4734 return false; 4735 } 4736 final String scheme = intent.getScheme(); 4737 if (TextUtils.isEmpty(scheme)) { 4738 return false; 4739 } 4740 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4741 } 4742 4743 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4744 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4745 int userId) { 4746 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4747 4748 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4749 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4750 candidates.size()); 4751 } 4752 4753 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4754 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4755 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4756 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4757 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4758 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4759 4760 synchronized (mPackages) { 4761 final int count = candidates.size(); 4762 // First, try to use linked apps. Partition the candidates into four lists: 4763 // one for the final results, one for the "do not use ever", one for "undefined status" 4764 // and finally one for "browser app type". 4765 for (int n=0; n<count; n++) { 4766 ResolveInfo info = candidates.get(n); 4767 String packageName = info.activityInfo.packageName; 4768 PackageSetting ps = mSettings.mPackages.get(packageName); 4769 if (ps != null) { 4770 // Add to the special match all list (Browser use case) 4771 if (info.handleAllWebDataURI) { 4772 matchAllList.add(info); 4773 continue; 4774 } 4775 // Try to get the status from User settings first 4776 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4777 int status = (int)(packedStatus >> 32); 4778 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4779 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4780 if (DEBUG_DOMAIN_VERIFICATION) { 4781 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4782 + " : linkgen=" + linkGeneration); 4783 } 4784 // Use link-enabled generation as preferredOrder, i.e. 4785 // prefer newly-enabled over earlier-enabled. 4786 info.preferredOrder = linkGeneration; 4787 alwaysList.add(info); 4788 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4789 if (DEBUG_DOMAIN_VERIFICATION) { 4790 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4791 } 4792 neverList.add(info); 4793 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4794 if (DEBUG_DOMAIN_VERIFICATION) { 4795 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4796 } 4797 alwaysAskList.add(info); 4798 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4799 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4800 if (DEBUG_DOMAIN_VERIFICATION) { 4801 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4802 } 4803 undefinedList.add(info); 4804 } 4805 } 4806 } 4807 4808 // We'll want to include browser possibilities in a few cases 4809 boolean includeBrowser = false; 4810 4811 // First try to add the "always" resolution(s) for the current user, if any 4812 if (alwaysList.size() > 0) { 4813 result.addAll(alwaysList); 4814 // if there is an "always" for the parent user, add it. 4815 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4816 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4817 result.add(xpDomainInfo.resolveInfo); 4818 } else { 4819 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4820 result.addAll(undefinedList); 4821 if (xpDomainInfo != null && ( 4822 xpDomainInfo.bestDomainVerificationStatus 4823 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4824 || xpDomainInfo.bestDomainVerificationStatus 4825 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4826 result.add(xpDomainInfo.resolveInfo); 4827 } 4828 includeBrowser = true; 4829 } 4830 4831 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4832 // If there were 'always' entries their preferred order has been set, so we also 4833 // back that off to make the alternatives equivalent 4834 if (alwaysAskList.size() > 0) { 4835 for (ResolveInfo i : result) { 4836 i.preferredOrder = 0; 4837 } 4838 result.addAll(alwaysAskList); 4839 includeBrowser = true; 4840 } 4841 4842 if (includeBrowser) { 4843 // Also add browsers (all of them or only the default one) 4844 if (DEBUG_DOMAIN_VERIFICATION) { 4845 Slog.v(TAG, " ...including browsers in candidate set"); 4846 } 4847 if ((matchFlags & MATCH_ALL) != 0) { 4848 result.addAll(matchAllList); 4849 } else { 4850 // Browser/generic handling case. If there's a default browser, go straight 4851 // to that (but only if there is no other higher-priority match). 4852 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4853 int maxMatchPrio = 0; 4854 ResolveInfo defaultBrowserMatch = null; 4855 final int numCandidates = matchAllList.size(); 4856 for (int n = 0; n < numCandidates; n++) { 4857 ResolveInfo info = matchAllList.get(n); 4858 // track the highest overall match priority... 4859 if (info.priority > maxMatchPrio) { 4860 maxMatchPrio = info.priority; 4861 } 4862 // ...and the highest-priority default browser match 4863 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4864 if (defaultBrowserMatch == null 4865 || (defaultBrowserMatch.priority < info.priority)) { 4866 if (debug) { 4867 Slog.v(TAG, "Considering default browser match " + info); 4868 } 4869 defaultBrowserMatch = info; 4870 } 4871 } 4872 } 4873 if (defaultBrowserMatch != null 4874 && defaultBrowserMatch.priority >= maxMatchPrio 4875 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4876 { 4877 if (debug) { 4878 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4879 } 4880 result.add(defaultBrowserMatch); 4881 } else { 4882 result.addAll(matchAllList); 4883 } 4884 } 4885 4886 // If there is nothing selected, add all candidates and remove the ones that the user 4887 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4888 if (result.size() == 0) { 4889 result.addAll(candidates); 4890 result.removeAll(neverList); 4891 } 4892 } 4893 } 4894 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4895 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4896 result.size()); 4897 for (ResolveInfo info : result) { 4898 Slog.v(TAG, " + " + info.activityInfo); 4899 } 4900 } 4901 return result; 4902 } 4903 4904 // Returns a packed value as a long: 4905 // 4906 // high 'int'-sized word: link status: undefined/ask/never/always. 4907 // low 'int'-sized word: relative priority among 'always' results. 4908 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4909 long result = ps.getDomainVerificationStatusForUser(userId); 4910 // if none available, get the master status 4911 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4912 if (ps.getIntentFilterVerificationInfo() != null) { 4913 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4914 } 4915 } 4916 return result; 4917 } 4918 4919 private ResolveInfo querySkipCurrentProfileIntents( 4920 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4921 int flags, int sourceUserId) { 4922 if (matchingFilters != null) { 4923 int size = matchingFilters.size(); 4924 for (int i = 0; i < size; i ++) { 4925 CrossProfileIntentFilter filter = matchingFilters.get(i); 4926 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4927 // Checking if there are activities in the target user that can handle the 4928 // intent. 4929 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4930 resolvedType, flags, sourceUserId); 4931 if (resolveInfo != null) { 4932 return resolveInfo; 4933 } 4934 } 4935 } 4936 } 4937 return null; 4938 } 4939 4940 // Return matching ResolveInfo if any for skip current profile intent filters. 4941 private ResolveInfo queryCrossProfileIntents( 4942 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4943 int flags, int sourceUserId) { 4944 if (matchingFilters != null) { 4945 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4946 // match the same intent. For performance reasons, it is better not to 4947 // run queryIntent twice for the same userId 4948 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4949 int size = matchingFilters.size(); 4950 for (int i = 0; i < size; i++) { 4951 CrossProfileIntentFilter filter = matchingFilters.get(i); 4952 int targetUserId = filter.getTargetUserId(); 4953 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4954 && !alreadyTriedUserIds.get(targetUserId)) { 4955 // Checking if there are activities in the target user that can handle the 4956 // intent. 4957 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4958 resolvedType, flags, sourceUserId); 4959 if (resolveInfo != null) return resolveInfo; 4960 alreadyTriedUserIds.put(targetUserId, true); 4961 } 4962 } 4963 } 4964 return null; 4965 } 4966 4967 /** 4968 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4969 * will forward the intent to the filter's target user. 4970 * Otherwise, returns null. 4971 */ 4972 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4973 String resolvedType, int flags, int sourceUserId) { 4974 int targetUserId = filter.getTargetUserId(); 4975 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4976 resolvedType, flags, targetUserId); 4977 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4978 && isUserEnabled(targetUserId)) { 4979 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 4980 } 4981 return null; 4982 } 4983 4984 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 4985 int sourceUserId, int targetUserId) { 4986 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4987 long ident = Binder.clearCallingIdentity(); 4988 boolean targetIsProfile; 4989 try { 4990 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4991 } finally { 4992 Binder.restoreCallingIdentity(ident); 4993 } 4994 String className; 4995 if (targetIsProfile) { 4996 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4997 } else { 4998 className = FORWARD_INTENT_TO_PARENT; 4999 } 5000 ComponentName forwardingActivityComponentName = new ComponentName( 5001 mAndroidApplication.packageName, className); 5002 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5003 sourceUserId); 5004 if (!targetIsProfile) { 5005 forwardingActivityInfo.showUserIcon = targetUserId; 5006 forwardingResolveInfo.noResourceId = true; 5007 } 5008 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5009 forwardingResolveInfo.priority = 0; 5010 forwardingResolveInfo.preferredOrder = 0; 5011 forwardingResolveInfo.match = 0; 5012 forwardingResolveInfo.isDefault = true; 5013 forwardingResolveInfo.filter = filter; 5014 forwardingResolveInfo.targetUserId = targetUserId; 5015 return forwardingResolveInfo; 5016 } 5017 5018 @Override 5019 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5020 Intent[] specifics, String[] specificTypes, Intent intent, 5021 String resolvedType, int flags, int userId) { 5022 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5023 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5024 false, "query intent activity options"); 5025 final String resultsAction = intent.getAction(); 5026 5027 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5028 | PackageManager.GET_RESOLVED_FILTER, userId); 5029 5030 if (DEBUG_INTENT_MATCHING) { 5031 Log.v(TAG, "Query " + intent + ": " + results); 5032 } 5033 5034 int specificsPos = 0; 5035 int N; 5036 5037 // todo: note that the algorithm used here is O(N^2). This 5038 // isn't a problem in our current environment, but if we start running 5039 // into situations where we have more than 5 or 10 matches then this 5040 // should probably be changed to something smarter... 5041 5042 // First we go through and resolve each of the specific items 5043 // that were supplied, taking care of removing any corresponding 5044 // duplicate items in the generic resolve list. 5045 if (specifics != null) { 5046 for (int i=0; i<specifics.length; i++) { 5047 final Intent sintent = specifics[i]; 5048 if (sintent == null) { 5049 continue; 5050 } 5051 5052 if (DEBUG_INTENT_MATCHING) { 5053 Log.v(TAG, "Specific #" + i + ": " + sintent); 5054 } 5055 5056 String action = sintent.getAction(); 5057 if (resultsAction != null && resultsAction.equals(action)) { 5058 // If this action was explicitly requested, then don't 5059 // remove things that have it. 5060 action = null; 5061 } 5062 5063 ResolveInfo ri = null; 5064 ActivityInfo ai = null; 5065 5066 ComponentName comp = sintent.getComponent(); 5067 if (comp == null) { 5068 ri = resolveIntent( 5069 sintent, 5070 specificTypes != null ? specificTypes[i] : null, 5071 flags, userId); 5072 if (ri == null) { 5073 continue; 5074 } 5075 if (ri == mResolveInfo) { 5076 // ACK! Must do something better with this. 5077 } 5078 ai = ri.activityInfo; 5079 comp = new ComponentName(ai.applicationInfo.packageName, 5080 ai.name); 5081 } else { 5082 ai = getActivityInfo(comp, flags, userId); 5083 if (ai == null) { 5084 continue; 5085 } 5086 } 5087 5088 // Look for any generic query activities that are duplicates 5089 // of this specific one, and remove them from the results. 5090 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5091 N = results.size(); 5092 int j; 5093 for (j=specificsPos; j<N; j++) { 5094 ResolveInfo sri = results.get(j); 5095 if ((sri.activityInfo.name.equals(comp.getClassName()) 5096 && sri.activityInfo.applicationInfo.packageName.equals( 5097 comp.getPackageName())) 5098 || (action != null && sri.filter.matchAction(action))) { 5099 results.remove(j); 5100 if (DEBUG_INTENT_MATCHING) Log.v( 5101 TAG, "Removing duplicate item from " + j 5102 + " due to specific " + specificsPos); 5103 if (ri == null) { 5104 ri = sri; 5105 } 5106 j--; 5107 N--; 5108 } 5109 } 5110 5111 // Add this specific item to its proper place. 5112 if (ri == null) { 5113 ri = new ResolveInfo(); 5114 ri.activityInfo = ai; 5115 } 5116 results.add(specificsPos, ri); 5117 ri.specificIndex = i; 5118 specificsPos++; 5119 } 5120 } 5121 5122 // Now we go through the remaining generic results and remove any 5123 // duplicate actions that are found here. 5124 N = results.size(); 5125 for (int i=specificsPos; i<N-1; i++) { 5126 final ResolveInfo rii = results.get(i); 5127 if (rii.filter == null) { 5128 continue; 5129 } 5130 5131 // Iterate over all of the actions of this result's intent 5132 // filter... typically this should be just one. 5133 final Iterator<String> it = rii.filter.actionsIterator(); 5134 if (it == null) { 5135 continue; 5136 } 5137 while (it.hasNext()) { 5138 final String action = it.next(); 5139 if (resultsAction != null && resultsAction.equals(action)) { 5140 // If this action was explicitly requested, then don't 5141 // remove things that have it. 5142 continue; 5143 } 5144 for (int j=i+1; j<N; j++) { 5145 final ResolveInfo rij = results.get(j); 5146 if (rij.filter != null && rij.filter.hasAction(action)) { 5147 results.remove(j); 5148 if (DEBUG_INTENT_MATCHING) Log.v( 5149 TAG, "Removing duplicate item from " + j 5150 + " due to action " + action + " at " + i); 5151 j--; 5152 N--; 5153 } 5154 } 5155 } 5156 5157 // If the caller didn't request filter information, drop it now 5158 // so we don't have to marshall/unmarshall it. 5159 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5160 rii.filter = null; 5161 } 5162 } 5163 5164 // Filter out the caller activity if so requested. 5165 if (caller != null) { 5166 N = results.size(); 5167 for (int i=0; i<N; i++) { 5168 ActivityInfo ainfo = results.get(i).activityInfo; 5169 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5170 && caller.getClassName().equals(ainfo.name)) { 5171 results.remove(i); 5172 break; 5173 } 5174 } 5175 } 5176 5177 // If the caller didn't request filter information, 5178 // drop them now so we don't have to 5179 // marshall/unmarshall it. 5180 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5181 N = results.size(); 5182 for (int i=0; i<N; i++) { 5183 results.get(i).filter = null; 5184 } 5185 } 5186 5187 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5188 return results; 5189 } 5190 5191 @Override 5192 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5193 int userId) { 5194 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5195 ComponentName comp = intent.getComponent(); 5196 if (comp == null) { 5197 if (intent.getSelector() != null) { 5198 intent = intent.getSelector(); 5199 comp = intent.getComponent(); 5200 } 5201 } 5202 if (comp != null) { 5203 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5204 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5205 if (ai != null) { 5206 ResolveInfo ri = new ResolveInfo(); 5207 ri.activityInfo = ai; 5208 list.add(ri); 5209 } 5210 return list; 5211 } 5212 5213 // reader 5214 synchronized (mPackages) { 5215 String pkgName = intent.getPackage(); 5216 if (pkgName == null) { 5217 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5218 } 5219 final PackageParser.Package pkg = mPackages.get(pkgName); 5220 if (pkg != null) { 5221 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5222 userId); 5223 } 5224 return null; 5225 } 5226 } 5227 5228 @Override 5229 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5230 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5231 if (!sUserManager.exists(userId)) return null; 5232 if (query != null) { 5233 if (query.size() >= 1) { 5234 // If there is more than one service with the same priority, 5235 // just arbitrarily pick the first one. 5236 return query.get(0); 5237 } 5238 } 5239 return null; 5240 } 5241 5242 @Override 5243 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5244 int userId) { 5245 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5246 ComponentName comp = intent.getComponent(); 5247 if (comp == null) { 5248 if (intent.getSelector() != null) { 5249 intent = intent.getSelector(); 5250 comp = intent.getComponent(); 5251 } 5252 } 5253 if (comp != null) { 5254 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5255 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5256 if (si != null) { 5257 final ResolveInfo ri = new ResolveInfo(); 5258 ri.serviceInfo = si; 5259 list.add(ri); 5260 } 5261 return list; 5262 } 5263 5264 // reader 5265 synchronized (mPackages) { 5266 String pkgName = intent.getPackage(); 5267 if (pkgName == null) { 5268 return mServices.queryIntent(intent, resolvedType, flags, userId); 5269 } 5270 final PackageParser.Package pkg = mPackages.get(pkgName); 5271 if (pkg != null) { 5272 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5273 userId); 5274 } 5275 return null; 5276 } 5277 } 5278 5279 @Override 5280 public List<ResolveInfo> queryIntentContentProviders( 5281 Intent intent, String resolvedType, int flags, int userId) { 5282 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5283 ComponentName comp = intent.getComponent(); 5284 if (comp == null) { 5285 if (intent.getSelector() != null) { 5286 intent = intent.getSelector(); 5287 comp = intent.getComponent(); 5288 } 5289 } 5290 if (comp != null) { 5291 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5292 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5293 if (pi != null) { 5294 final ResolveInfo ri = new ResolveInfo(); 5295 ri.providerInfo = pi; 5296 list.add(ri); 5297 } 5298 return list; 5299 } 5300 5301 // reader 5302 synchronized (mPackages) { 5303 String pkgName = intent.getPackage(); 5304 if (pkgName == null) { 5305 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5306 } 5307 final PackageParser.Package pkg = mPackages.get(pkgName); 5308 if (pkg != null) { 5309 return mProviders.queryIntentForPackage( 5310 intent, resolvedType, flags, pkg.providers, userId); 5311 } 5312 return null; 5313 } 5314 } 5315 5316 @Override 5317 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5318 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5319 5320 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5321 5322 // writer 5323 synchronized (mPackages) { 5324 ArrayList<PackageInfo> list; 5325 if (listUninstalled) { 5326 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5327 for (PackageSetting ps : mSettings.mPackages.values()) { 5328 PackageInfo pi; 5329 if (ps.pkg != null) { 5330 pi = generatePackageInfo(ps.pkg, flags, userId); 5331 } else { 5332 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5333 } 5334 if (pi != null) { 5335 list.add(pi); 5336 } 5337 } 5338 } else { 5339 list = new ArrayList<PackageInfo>(mPackages.size()); 5340 for (PackageParser.Package p : mPackages.values()) { 5341 PackageInfo pi = generatePackageInfo(p, flags, userId); 5342 if (pi != null) { 5343 list.add(pi); 5344 } 5345 } 5346 } 5347 5348 return new ParceledListSlice<PackageInfo>(list); 5349 } 5350 } 5351 5352 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5353 String[] permissions, boolean[] tmp, int flags, int userId) { 5354 int numMatch = 0; 5355 final PermissionsState permissionsState = ps.getPermissionsState(); 5356 for (int i=0; i<permissions.length; i++) { 5357 final String permission = permissions[i]; 5358 if (permissionsState.hasPermission(permission, userId)) { 5359 tmp[i] = true; 5360 numMatch++; 5361 } else { 5362 tmp[i] = false; 5363 } 5364 } 5365 if (numMatch == 0) { 5366 return; 5367 } 5368 PackageInfo pi; 5369 if (ps.pkg != null) { 5370 pi = generatePackageInfo(ps.pkg, flags, userId); 5371 } else { 5372 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5373 } 5374 // The above might return null in cases of uninstalled apps or install-state 5375 // skew across users/profiles. 5376 if (pi != null) { 5377 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5378 if (numMatch == permissions.length) { 5379 pi.requestedPermissions = permissions; 5380 } else { 5381 pi.requestedPermissions = new String[numMatch]; 5382 numMatch = 0; 5383 for (int i=0; i<permissions.length; i++) { 5384 if (tmp[i]) { 5385 pi.requestedPermissions[numMatch] = permissions[i]; 5386 numMatch++; 5387 } 5388 } 5389 } 5390 } 5391 list.add(pi); 5392 } 5393 } 5394 5395 @Override 5396 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5397 String[] permissions, int flags, int userId) { 5398 if (!sUserManager.exists(userId)) return null; 5399 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5400 5401 // writer 5402 synchronized (mPackages) { 5403 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5404 boolean[] tmpBools = new boolean[permissions.length]; 5405 if (listUninstalled) { 5406 for (PackageSetting ps : mSettings.mPackages.values()) { 5407 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5408 } 5409 } else { 5410 for (PackageParser.Package pkg : mPackages.values()) { 5411 PackageSetting ps = (PackageSetting)pkg.mExtras; 5412 if (ps != null) { 5413 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5414 userId); 5415 } 5416 } 5417 } 5418 5419 return new ParceledListSlice<PackageInfo>(list); 5420 } 5421 } 5422 5423 @Override 5424 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5425 if (!sUserManager.exists(userId)) return null; 5426 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5427 5428 // writer 5429 synchronized (mPackages) { 5430 ArrayList<ApplicationInfo> list; 5431 if (listUninstalled) { 5432 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5433 for (PackageSetting ps : mSettings.mPackages.values()) { 5434 ApplicationInfo ai; 5435 if (ps.pkg != null) { 5436 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5437 ps.readUserState(userId), userId); 5438 } else { 5439 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5440 } 5441 if (ai != null) { 5442 list.add(ai); 5443 } 5444 } 5445 } else { 5446 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5447 for (PackageParser.Package p : mPackages.values()) { 5448 if (p.mExtras != null) { 5449 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5450 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5451 if (ai != null) { 5452 list.add(ai); 5453 } 5454 } 5455 } 5456 } 5457 5458 return new ParceledListSlice<ApplicationInfo>(list); 5459 } 5460 } 5461 5462 public List<ApplicationInfo> getPersistentApplications(int flags) { 5463 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5464 5465 // reader 5466 synchronized (mPackages) { 5467 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5468 final int userId = UserHandle.getCallingUserId(); 5469 while (i.hasNext()) { 5470 final PackageParser.Package p = i.next(); 5471 if (p.applicationInfo != null 5472 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5473 && (!mSafeMode || isSystemApp(p))) { 5474 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5475 if (ps != null) { 5476 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5477 ps.readUserState(userId), userId); 5478 if (ai != null) { 5479 finalList.add(ai); 5480 } 5481 } 5482 } 5483 } 5484 } 5485 5486 return finalList; 5487 } 5488 5489 @Override 5490 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5491 if (!sUserManager.exists(userId)) return null; 5492 // reader 5493 synchronized (mPackages) { 5494 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5495 PackageSetting ps = provider != null 5496 ? mSettings.mPackages.get(provider.owner.packageName) 5497 : null; 5498 return ps != null 5499 && mSettings.isEnabledLPr(provider.info, flags, userId) 5500 && (!mSafeMode || (provider.info.applicationInfo.flags 5501 &ApplicationInfo.FLAG_SYSTEM) != 0) 5502 ? PackageParser.generateProviderInfo(provider, flags, 5503 ps.readUserState(userId), userId) 5504 : null; 5505 } 5506 } 5507 5508 /** 5509 * @deprecated 5510 */ 5511 @Deprecated 5512 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5513 // reader 5514 synchronized (mPackages) { 5515 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5516 .entrySet().iterator(); 5517 final int userId = UserHandle.getCallingUserId(); 5518 while (i.hasNext()) { 5519 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5520 PackageParser.Provider p = entry.getValue(); 5521 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5522 5523 if (ps != null && p.syncable 5524 && (!mSafeMode || (p.info.applicationInfo.flags 5525 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5526 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5527 ps.readUserState(userId), userId); 5528 if (info != null) { 5529 outNames.add(entry.getKey()); 5530 outInfo.add(info); 5531 } 5532 } 5533 } 5534 } 5535 } 5536 5537 @Override 5538 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5539 int uid, int flags) { 5540 ArrayList<ProviderInfo> finalList = null; 5541 // reader 5542 synchronized (mPackages) { 5543 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5544 final int userId = processName != null ? 5545 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5546 while (i.hasNext()) { 5547 final PackageParser.Provider p = i.next(); 5548 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5549 if (ps != null && p.info.authority != null 5550 && (processName == null 5551 || (p.info.processName.equals(processName) 5552 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5553 && mSettings.isEnabledLPr(p.info, flags, userId) 5554 && (!mSafeMode 5555 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5556 if (finalList == null) { 5557 finalList = new ArrayList<ProviderInfo>(3); 5558 } 5559 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5560 ps.readUserState(userId), userId); 5561 if (info != null) { 5562 finalList.add(info); 5563 } 5564 } 5565 } 5566 } 5567 5568 if (finalList != null) { 5569 Collections.sort(finalList, mProviderInitOrderSorter); 5570 return new ParceledListSlice<ProviderInfo>(finalList); 5571 } 5572 5573 return null; 5574 } 5575 5576 @Override 5577 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5578 int flags) { 5579 // reader 5580 synchronized (mPackages) { 5581 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5582 return PackageParser.generateInstrumentationInfo(i, flags); 5583 } 5584 } 5585 5586 @Override 5587 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5588 int flags) { 5589 ArrayList<InstrumentationInfo> finalList = 5590 new ArrayList<InstrumentationInfo>(); 5591 5592 // reader 5593 synchronized (mPackages) { 5594 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5595 while (i.hasNext()) { 5596 final PackageParser.Instrumentation p = i.next(); 5597 if (targetPackage == null 5598 || targetPackage.equals(p.info.targetPackage)) { 5599 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5600 flags); 5601 if (ii != null) { 5602 finalList.add(ii); 5603 } 5604 } 5605 } 5606 } 5607 5608 return finalList; 5609 } 5610 5611 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5612 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5613 if (overlays == null) { 5614 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5615 return; 5616 } 5617 for (PackageParser.Package opkg : overlays.values()) { 5618 // Not much to do if idmap fails: we already logged the error 5619 // and we certainly don't want to abort installation of pkg simply 5620 // because an overlay didn't fit properly. For these reasons, 5621 // ignore the return value of createIdmapForPackagePairLI. 5622 createIdmapForPackagePairLI(pkg, opkg); 5623 } 5624 } 5625 5626 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5627 PackageParser.Package opkg) { 5628 if (!opkg.mTrustedOverlay) { 5629 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5630 opkg.baseCodePath + ": overlay not trusted"); 5631 return false; 5632 } 5633 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5634 if (overlaySet == null) { 5635 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5636 opkg.baseCodePath + " but target package has no known overlays"); 5637 return false; 5638 } 5639 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5640 // TODO: generate idmap for split APKs 5641 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5642 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5643 + opkg.baseCodePath); 5644 return false; 5645 } 5646 PackageParser.Package[] overlayArray = 5647 overlaySet.values().toArray(new PackageParser.Package[0]); 5648 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5649 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5650 return p1.mOverlayPriority - p2.mOverlayPriority; 5651 } 5652 }; 5653 Arrays.sort(overlayArray, cmp); 5654 5655 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5656 int i = 0; 5657 for (PackageParser.Package p : overlayArray) { 5658 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5659 } 5660 return true; 5661 } 5662 5663 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5664 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5665 try { 5666 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5667 } finally { 5668 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5669 } 5670 } 5671 5672 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5673 final File[] files = dir.listFiles(); 5674 if (ArrayUtils.isEmpty(files)) { 5675 Log.d(TAG, "No files in app dir " + dir); 5676 return; 5677 } 5678 5679 if (DEBUG_PACKAGE_SCANNING) { 5680 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5681 + " flags=0x" + Integer.toHexString(parseFlags)); 5682 } 5683 5684 for (File file : files) { 5685 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5686 && !PackageInstallerService.isStageName(file.getName()); 5687 if (!isPackage) { 5688 // Ignore entries which are not packages 5689 continue; 5690 } 5691 try { 5692 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5693 scanFlags, currentTime, null); 5694 } catch (PackageManagerException e) { 5695 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5696 5697 // Delete invalid userdata apps 5698 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5699 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5700 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5701 if (file.isDirectory()) { 5702 mInstaller.rmPackageDir(file.getAbsolutePath()); 5703 } else { 5704 file.delete(); 5705 } 5706 } 5707 } 5708 } 5709 } 5710 5711 private static File getSettingsProblemFile() { 5712 File dataDir = Environment.getDataDirectory(); 5713 File systemDir = new File(dataDir, "system"); 5714 File fname = new File(systemDir, "uiderrors.txt"); 5715 return fname; 5716 } 5717 5718 static void reportSettingsProblem(int priority, String msg) { 5719 logCriticalInfo(priority, msg); 5720 } 5721 5722 static void logCriticalInfo(int priority, String msg) { 5723 Slog.println(priority, TAG, msg); 5724 EventLogTags.writePmCriticalInfo(msg); 5725 try { 5726 File fname = getSettingsProblemFile(); 5727 FileOutputStream out = new FileOutputStream(fname, true); 5728 PrintWriter pw = new FastPrintWriter(out); 5729 SimpleDateFormat formatter = new SimpleDateFormat(); 5730 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5731 pw.println(dateString + ": " + msg); 5732 pw.close(); 5733 FileUtils.setPermissions( 5734 fname.toString(), 5735 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5736 -1, -1); 5737 } catch (java.io.IOException e) { 5738 } 5739 } 5740 5741 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5742 PackageParser.Package pkg, File srcFile, int parseFlags) 5743 throws PackageManagerException { 5744 if (ps != null 5745 && ps.codePath.equals(srcFile) 5746 && ps.timeStamp == srcFile.lastModified() 5747 && !isCompatSignatureUpdateNeeded(pkg) 5748 && !isRecoverSignatureUpdateNeeded(pkg)) { 5749 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5750 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5751 ArraySet<PublicKey> signingKs; 5752 synchronized (mPackages) { 5753 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5754 } 5755 if (ps.signatures.mSignatures != null 5756 && ps.signatures.mSignatures.length != 0 5757 && signingKs != null) { 5758 // Optimization: reuse the existing cached certificates 5759 // if the package appears to be unchanged. 5760 pkg.mSignatures = ps.signatures.mSignatures; 5761 pkg.mSigningKeys = signingKs; 5762 return; 5763 } 5764 5765 Slog.w(TAG, "PackageSetting for " + ps.name 5766 + " is missing signatures. Collecting certs again to recover them."); 5767 } else { 5768 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5769 } 5770 5771 try { 5772 pp.collectCertificates(pkg, parseFlags); 5773 pp.collectManifestDigest(pkg); 5774 } catch (PackageParserException e) { 5775 throw PackageManagerException.from(e); 5776 } 5777 } 5778 5779 /** 5780 * Traces a package scan. 5781 * @see #scanPackageLI(File, int, int, long, UserHandle) 5782 */ 5783 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5784 long currentTime, UserHandle user) throws PackageManagerException { 5785 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5786 try { 5787 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5788 } finally { 5789 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5790 } 5791 } 5792 5793 /** 5794 * Scans a package and returns the newly parsed package. 5795 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5796 */ 5797 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5798 long currentTime, UserHandle user) throws PackageManagerException { 5799 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5800 parseFlags |= mDefParseFlags; 5801 PackageParser pp = new PackageParser(); 5802 pp.setSeparateProcesses(mSeparateProcesses); 5803 pp.setOnlyCoreApps(mOnlyCore); 5804 pp.setDisplayMetrics(mMetrics); 5805 5806 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5807 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5808 } 5809 5810 final PackageParser.Package pkg; 5811 try { 5812 pkg = pp.parsePackage(scanFile, parseFlags); 5813 } catch (PackageParserException e) { 5814 throw PackageManagerException.from(e); 5815 } 5816 5817 PackageSetting ps = null; 5818 PackageSetting updatedPkg; 5819 // reader 5820 synchronized (mPackages) { 5821 // Look to see if we already know about this package. 5822 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5823 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5824 // This package has been renamed to its original name. Let's 5825 // use that. 5826 ps = mSettings.peekPackageLPr(oldName); 5827 } 5828 // If there was no original package, see one for the real package name. 5829 if (ps == null) { 5830 ps = mSettings.peekPackageLPr(pkg.packageName); 5831 } 5832 // Check to see if this package could be hiding/updating a system 5833 // package. Must look for it either under the original or real 5834 // package name depending on our state. 5835 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5836 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5837 } 5838 boolean updatedPkgBetter = false; 5839 // First check if this is a system package that may involve an update 5840 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5841 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5842 // it needs to drop FLAG_PRIVILEGED. 5843 if (locationIsPrivileged(scanFile)) { 5844 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5845 } else { 5846 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5847 } 5848 5849 if (ps != null && !ps.codePath.equals(scanFile)) { 5850 // The path has changed from what was last scanned... check the 5851 // version of the new path against what we have stored to determine 5852 // what to do. 5853 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5854 if (pkg.mVersionCode <= ps.versionCode) { 5855 // The system package has been updated and the code path does not match 5856 // Ignore entry. Skip it. 5857 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5858 + " ignored: updated version " + ps.versionCode 5859 + " better than this " + pkg.mVersionCode); 5860 if (!updatedPkg.codePath.equals(scanFile)) { 5861 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5862 + ps.name + " changing from " + updatedPkg.codePathString 5863 + " to " + scanFile); 5864 updatedPkg.codePath = scanFile; 5865 updatedPkg.codePathString = scanFile.toString(); 5866 updatedPkg.resourcePath = scanFile; 5867 updatedPkg.resourcePathString = scanFile.toString(); 5868 } 5869 updatedPkg.pkg = pkg; 5870 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5871 "Package " + ps.name + " at " + scanFile 5872 + " ignored: updated version " + ps.versionCode 5873 + " better than this " + pkg.mVersionCode); 5874 } else { 5875 // The current app on the system partition is better than 5876 // what we have updated to on the data partition; switch 5877 // back to the system partition version. 5878 // At this point, its safely assumed that package installation for 5879 // apps in system partition will go through. If not there won't be a working 5880 // version of the app 5881 // writer 5882 synchronized (mPackages) { 5883 // Just remove the loaded entries from package lists. 5884 mPackages.remove(ps.name); 5885 } 5886 5887 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5888 + " reverting from " + ps.codePathString 5889 + ": new version " + pkg.mVersionCode 5890 + " better than installed " + ps.versionCode); 5891 5892 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5893 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5894 synchronized (mInstallLock) { 5895 args.cleanUpResourcesLI(); 5896 } 5897 synchronized (mPackages) { 5898 mSettings.enableSystemPackageLPw(ps.name); 5899 } 5900 updatedPkgBetter = true; 5901 } 5902 } 5903 } 5904 5905 if (updatedPkg != null) { 5906 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5907 // initially 5908 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5909 5910 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5911 // flag set initially 5912 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5913 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5914 } 5915 } 5916 5917 // Verify certificates against what was last scanned 5918 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5919 5920 /* 5921 * A new system app appeared, but we already had a non-system one of the 5922 * same name installed earlier. 5923 */ 5924 boolean shouldHideSystemApp = false; 5925 if (updatedPkg == null && ps != null 5926 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5927 /* 5928 * Check to make sure the signatures match first. If they don't, 5929 * wipe the installed application and its data. 5930 */ 5931 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5932 != PackageManager.SIGNATURE_MATCH) { 5933 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5934 + " signatures don't match existing userdata copy; removing"); 5935 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5936 ps = null; 5937 } else { 5938 /* 5939 * If the newly-added system app is an older version than the 5940 * already installed version, hide it. It will be scanned later 5941 * and re-added like an update. 5942 */ 5943 if (pkg.mVersionCode <= ps.versionCode) { 5944 shouldHideSystemApp = true; 5945 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5946 + " but new version " + pkg.mVersionCode + " better than installed " 5947 + ps.versionCode + "; hiding system"); 5948 } else { 5949 /* 5950 * The newly found system app is a newer version that the 5951 * one previously installed. Simply remove the 5952 * already-installed application and replace it with our own 5953 * while keeping the application data. 5954 */ 5955 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5956 + " reverting from " + ps.codePathString + ": new version " 5957 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5958 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5959 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5960 synchronized (mInstallLock) { 5961 args.cleanUpResourcesLI(); 5962 } 5963 } 5964 } 5965 } 5966 5967 // The apk is forward locked (not public) if its code and resources 5968 // are kept in different files. (except for app in either system or 5969 // vendor path). 5970 // TODO grab this value from PackageSettings 5971 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5972 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5973 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5974 } 5975 } 5976 5977 // TODO: extend to support forward-locked splits 5978 String resourcePath = null; 5979 String baseResourcePath = null; 5980 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5981 if (ps != null && ps.resourcePathString != null) { 5982 resourcePath = ps.resourcePathString; 5983 baseResourcePath = ps.resourcePathString; 5984 } else { 5985 // Should not happen at all. Just log an error. 5986 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5987 } 5988 } else { 5989 resourcePath = pkg.codePath; 5990 baseResourcePath = pkg.baseCodePath; 5991 } 5992 5993 // Set application objects path explicitly. 5994 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5995 pkg.applicationInfo.setCodePath(pkg.codePath); 5996 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5997 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5998 pkg.applicationInfo.setResourcePath(resourcePath); 5999 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6000 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6001 6002 // Note that we invoke the following method only if we are about to unpack an application 6003 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6004 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6005 6006 /* 6007 * If the system app should be overridden by a previously installed 6008 * data, hide the system app now and let the /data/app scan pick it up 6009 * again. 6010 */ 6011 if (shouldHideSystemApp) { 6012 synchronized (mPackages) { 6013 mSettings.disableSystemPackageLPw(pkg.packageName); 6014 } 6015 } 6016 6017 return scannedPkg; 6018 } 6019 6020 private static String fixProcessName(String defProcessName, 6021 String processName, int uid) { 6022 if (processName == null) { 6023 return defProcessName; 6024 } 6025 return processName; 6026 } 6027 6028 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6029 throws PackageManagerException { 6030 if (pkgSetting.signatures.mSignatures != null) { 6031 // Already existing package. Make sure signatures match 6032 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6033 == PackageManager.SIGNATURE_MATCH; 6034 if (!match) { 6035 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6036 == PackageManager.SIGNATURE_MATCH; 6037 } 6038 if (!match) { 6039 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6040 == PackageManager.SIGNATURE_MATCH; 6041 } 6042 if (!match) { 6043 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6044 + pkg.packageName + " signatures do not match the " 6045 + "previously installed version; ignoring!"); 6046 } 6047 } 6048 6049 // Check for shared user signatures 6050 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6051 // Already existing package. Make sure signatures match 6052 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6053 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6054 if (!match) { 6055 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6056 == PackageManager.SIGNATURE_MATCH; 6057 } 6058 if (!match) { 6059 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6060 == PackageManager.SIGNATURE_MATCH; 6061 } 6062 if (!match) { 6063 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6064 "Package " + pkg.packageName 6065 + " has no signatures that match those in shared user " 6066 + pkgSetting.sharedUser.name + "; ignoring!"); 6067 } 6068 } 6069 } 6070 6071 /** 6072 * Enforces that only the system UID or root's UID can call a method exposed 6073 * via Binder. 6074 * 6075 * @param message used as message if SecurityException is thrown 6076 * @throws SecurityException if the caller is not system or root 6077 */ 6078 private static final void enforceSystemOrRoot(String message) { 6079 final int uid = Binder.getCallingUid(); 6080 if (uid != Process.SYSTEM_UID && uid != 0) { 6081 throw new SecurityException(message); 6082 } 6083 } 6084 6085 @Override 6086 public void performBootDexOpt() { 6087 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6088 6089 // Before everything else, see whether we need to fstrim. 6090 try { 6091 IMountService ms = PackageHelper.getMountService(); 6092 if (ms != null) { 6093 final boolean isUpgrade = isUpgrade(); 6094 boolean doTrim = isUpgrade; 6095 if (doTrim) { 6096 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6097 } else { 6098 final long interval = android.provider.Settings.Global.getLong( 6099 mContext.getContentResolver(), 6100 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6101 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6102 if (interval > 0) { 6103 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6104 if (timeSinceLast > interval) { 6105 doTrim = true; 6106 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6107 + "; running immediately"); 6108 } 6109 } 6110 } 6111 if (doTrim) { 6112 if (!isFirstBoot()) { 6113 try { 6114 ActivityManagerNative.getDefault().showBootMessage( 6115 mContext.getResources().getString( 6116 R.string.android_upgrading_fstrim), true); 6117 } catch (RemoteException e) { 6118 } 6119 } 6120 ms.runMaintenance(); 6121 } 6122 } else { 6123 Slog.e(TAG, "Mount service unavailable!"); 6124 } 6125 } catch (RemoteException e) { 6126 // Can't happen; MountService is local 6127 } 6128 6129 final ArraySet<PackageParser.Package> pkgs; 6130 synchronized (mPackages) { 6131 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6132 } 6133 6134 if (pkgs != null) { 6135 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6136 // in case the device runs out of space. 6137 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6138 // Give priority to core apps. 6139 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6140 PackageParser.Package pkg = it.next(); 6141 if (pkg.coreApp) { 6142 if (DEBUG_DEXOPT) { 6143 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6144 } 6145 sortedPkgs.add(pkg); 6146 it.remove(); 6147 } 6148 } 6149 // Give priority to system apps that listen for pre boot complete. 6150 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6151 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6152 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6153 PackageParser.Package pkg = it.next(); 6154 if (pkgNames.contains(pkg.packageName)) { 6155 if (DEBUG_DEXOPT) { 6156 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6157 } 6158 sortedPkgs.add(pkg); 6159 it.remove(); 6160 } 6161 } 6162 // Filter out packages that aren't recently used. 6163 filterRecentlyUsedApps(pkgs); 6164 // Add all remaining apps. 6165 for (PackageParser.Package pkg : pkgs) { 6166 if (DEBUG_DEXOPT) { 6167 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6168 } 6169 sortedPkgs.add(pkg); 6170 } 6171 6172 // If we want to be lazy, filter everything that wasn't recently used. 6173 if (mLazyDexOpt) { 6174 filterRecentlyUsedApps(sortedPkgs); 6175 } 6176 6177 int i = 0; 6178 int total = sortedPkgs.size(); 6179 File dataDir = Environment.getDataDirectory(); 6180 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6181 if (lowThreshold == 0) { 6182 throw new IllegalStateException("Invalid low memory threshold"); 6183 } 6184 for (PackageParser.Package pkg : sortedPkgs) { 6185 long usableSpace = dataDir.getUsableSpace(); 6186 if (usableSpace < lowThreshold) { 6187 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6188 break; 6189 } 6190 performBootDexOpt(pkg, ++i, total); 6191 } 6192 } 6193 } 6194 6195 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6196 // Filter out packages that aren't recently used. 6197 // 6198 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6199 // should do a full dexopt. 6200 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6201 int total = pkgs.size(); 6202 int skipped = 0; 6203 long now = System.currentTimeMillis(); 6204 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6205 PackageParser.Package pkg = i.next(); 6206 long then = pkg.mLastPackageUsageTimeInMills; 6207 if (then + mDexOptLRUThresholdInMills < now) { 6208 if (DEBUG_DEXOPT) { 6209 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6210 ((then == 0) ? "never" : new Date(then))); 6211 } 6212 i.remove(); 6213 skipped++; 6214 } 6215 } 6216 if (DEBUG_DEXOPT) { 6217 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6218 } 6219 } 6220 } 6221 6222 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6223 List<ResolveInfo> ris = null; 6224 try { 6225 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6226 intent, null, 0, userId); 6227 } catch (RemoteException e) { 6228 } 6229 ArraySet<String> pkgNames = new ArraySet<String>(); 6230 if (ris != null) { 6231 for (ResolveInfo ri : ris) { 6232 pkgNames.add(ri.activityInfo.packageName); 6233 } 6234 } 6235 return pkgNames; 6236 } 6237 6238 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6239 if (DEBUG_DEXOPT) { 6240 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6241 } 6242 if (!isFirstBoot()) { 6243 try { 6244 ActivityManagerNative.getDefault().showBootMessage( 6245 mContext.getResources().getString(R.string.android_upgrading_apk, 6246 curr, total), true); 6247 } catch (RemoteException e) { 6248 } 6249 } 6250 PackageParser.Package p = pkg; 6251 synchronized (mInstallLock) { 6252 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6253 false /* force dex */, false /* defer */, true /* include dependencies */, 6254 false /* boot complete */, false /*useJit*/); 6255 } 6256 } 6257 6258 @Override 6259 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6260 return performDexOptTraced(packageName, instructionSet, false); 6261 } 6262 6263 public boolean performDexOpt( 6264 String packageName, String instructionSet, boolean backgroundDexopt) { 6265 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6266 } 6267 6268 private boolean performDexOptTraced( 6269 String packageName, String instructionSet, boolean backgroundDexopt) { 6270 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6271 try { 6272 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6273 } finally { 6274 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6275 } 6276 } 6277 6278 private boolean performDexOptInternal( 6279 String packageName, String instructionSet, boolean backgroundDexopt) { 6280 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6281 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6282 if (!dexopt && !updateUsage) { 6283 // We aren't going to dexopt or update usage, so bail early. 6284 return false; 6285 } 6286 PackageParser.Package p; 6287 final String targetInstructionSet; 6288 synchronized (mPackages) { 6289 p = mPackages.get(packageName); 6290 if (p == null) { 6291 return false; 6292 } 6293 if (updateUsage) { 6294 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6295 } 6296 mPackageUsage.write(false); 6297 if (!dexopt) { 6298 // We aren't going to dexopt, so bail early. 6299 return false; 6300 } 6301 6302 targetInstructionSet = instructionSet != null ? instructionSet : 6303 getPrimaryInstructionSet(p.applicationInfo); 6304 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6305 return false; 6306 } 6307 } 6308 long callingId = Binder.clearCallingIdentity(); 6309 try { 6310 synchronized (mInstallLock) { 6311 final String[] instructionSets = new String[] { targetInstructionSet }; 6312 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6313 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6314 true /* boot complete */, false /*useJit*/); 6315 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6316 } 6317 } finally { 6318 Binder.restoreCallingIdentity(callingId); 6319 } 6320 } 6321 6322 public ArraySet<String> getPackagesThatNeedDexOpt() { 6323 ArraySet<String> pkgs = null; 6324 synchronized (mPackages) { 6325 for (PackageParser.Package p : mPackages.values()) { 6326 if (DEBUG_DEXOPT) { 6327 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6328 } 6329 if (!p.mDexOptPerformed.isEmpty()) { 6330 continue; 6331 } 6332 if (pkgs == null) { 6333 pkgs = new ArraySet<String>(); 6334 } 6335 pkgs.add(p.packageName); 6336 } 6337 } 6338 return pkgs; 6339 } 6340 6341 public void shutdown() { 6342 mPackageUsage.write(true); 6343 } 6344 6345 @Override 6346 public void forceDexOpt(String packageName) { 6347 enforceSystemOrRoot("forceDexOpt"); 6348 6349 PackageParser.Package pkg; 6350 synchronized (mPackages) { 6351 pkg = mPackages.get(packageName); 6352 if (pkg == null) { 6353 throw new IllegalArgumentException("Missing package: " + packageName); 6354 } 6355 } 6356 6357 synchronized (mInstallLock) { 6358 final String[] instructionSets = new String[] { 6359 getPrimaryInstructionSet(pkg.applicationInfo) }; 6360 6361 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6362 6363 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6364 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6365 true /* boot complete */, false /*useJit*/); 6366 6367 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6368 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6369 throw new IllegalStateException("Failed to dexopt: " + res); 6370 } 6371 } 6372 } 6373 6374 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6375 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6376 Slog.w(TAG, "Unable to update from " + oldPkg.name 6377 + " to " + newPkg.packageName 6378 + ": old package not in system partition"); 6379 return false; 6380 } else if (mPackages.get(oldPkg.name) != null) { 6381 Slog.w(TAG, "Unable to update from " + oldPkg.name 6382 + " to " + newPkg.packageName 6383 + ": old package still exists"); 6384 return false; 6385 } 6386 return true; 6387 } 6388 6389 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6390 int[] users = sUserManager.getUserIds(); 6391 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6392 if (res < 0) { 6393 return res; 6394 } 6395 for (int user : users) { 6396 if (user != 0) { 6397 res = mInstaller.createUserData(volumeUuid, packageName, 6398 UserHandle.getUid(user, uid), user, seinfo); 6399 if (res < 0) { 6400 return res; 6401 } 6402 } 6403 } 6404 return res; 6405 } 6406 6407 private int removeDataDirsLI(String volumeUuid, String packageName) { 6408 int[] users = sUserManager.getUserIds(); 6409 int res = 0; 6410 for (int user : users) { 6411 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6412 if (resInner < 0) { 6413 res = resInner; 6414 } 6415 } 6416 6417 return res; 6418 } 6419 6420 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6421 int[] users = sUserManager.getUserIds(); 6422 int res = 0; 6423 for (int user : users) { 6424 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6425 if (resInner < 0) { 6426 res = resInner; 6427 } 6428 } 6429 return res; 6430 } 6431 6432 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6433 PackageParser.Package changingLib) { 6434 if (file.path != null) { 6435 usesLibraryFiles.add(file.path); 6436 return; 6437 } 6438 PackageParser.Package p = mPackages.get(file.apk); 6439 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6440 // If we are doing this while in the middle of updating a library apk, 6441 // then we need to make sure to use that new apk for determining the 6442 // dependencies here. (We haven't yet finished committing the new apk 6443 // to the package manager state.) 6444 if (p == null || p.packageName.equals(changingLib.packageName)) { 6445 p = changingLib; 6446 } 6447 } 6448 if (p != null) { 6449 usesLibraryFiles.addAll(p.getAllCodePaths()); 6450 } 6451 } 6452 6453 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6454 PackageParser.Package changingLib) throws PackageManagerException { 6455 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6456 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6457 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6458 for (int i=0; i<N; i++) { 6459 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6460 if (file == null) { 6461 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6462 "Package " + pkg.packageName + " requires unavailable shared library " 6463 + pkg.usesLibraries.get(i) + "; failing!"); 6464 } 6465 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6466 } 6467 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6468 for (int i=0; i<N; i++) { 6469 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6470 if (file == null) { 6471 Slog.w(TAG, "Package " + pkg.packageName 6472 + " desires unavailable shared library " 6473 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6474 } else { 6475 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6476 } 6477 } 6478 N = usesLibraryFiles.size(); 6479 if (N > 0) { 6480 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6481 } else { 6482 pkg.usesLibraryFiles = null; 6483 } 6484 } 6485 } 6486 6487 private static boolean hasString(List<String> list, List<String> which) { 6488 if (list == null) { 6489 return false; 6490 } 6491 for (int i=list.size()-1; i>=0; i--) { 6492 for (int j=which.size()-1; j>=0; j--) { 6493 if (which.get(j).equals(list.get(i))) { 6494 return true; 6495 } 6496 } 6497 } 6498 return false; 6499 } 6500 6501 private void updateAllSharedLibrariesLPw() { 6502 for (PackageParser.Package pkg : mPackages.values()) { 6503 try { 6504 updateSharedLibrariesLPw(pkg, null); 6505 } catch (PackageManagerException e) { 6506 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6507 } 6508 } 6509 } 6510 6511 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6512 PackageParser.Package changingPkg) { 6513 ArrayList<PackageParser.Package> res = null; 6514 for (PackageParser.Package pkg : mPackages.values()) { 6515 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6516 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6517 if (res == null) { 6518 res = new ArrayList<PackageParser.Package>(); 6519 } 6520 res.add(pkg); 6521 try { 6522 updateSharedLibrariesLPw(pkg, changingPkg); 6523 } catch (PackageManagerException e) { 6524 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6525 } 6526 } 6527 } 6528 return res; 6529 } 6530 6531 /** 6532 * Derive the value of the {@code cpuAbiOverride} based on the provided 6533 * value and an optional stored value from the package settings. 6534 */ 6535 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6536 String cpuAbiOverride = null; 6537 6538 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6539 cpuAbiOverride = null; 6540 } else if (abiOverride != null) { 6541 cpuAbiOverride = abiOverride; 6542 } else if (settings != null) { 6543 cpuAbiOverride = settings.cpuAbiOverrideString; 6544 } 6545 6546 return cpuAbiOverride; 6547 } 6548 6549 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6550 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6551 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6552 try { 6553 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6554 } finally { 6555 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6556 } 6557 } 6558 6559 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6560 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6561 boolean success = false; 6562 try { 6563 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6564 currentTime, user); 6565 success = true; 6566 return res; 6567 } finally { 6568 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6569 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6570 } 6571 } 6572 } 6573 6574 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6575 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6576 final File scanFile = new File(pkg.codePath); 6577 if (pkg.applicationInfo.getCodePath() == null || 6578 pkg.applicationInfo.getResourcePath() == null) { 6579 // Bail out. The resource and code paths haven't been set. 6580 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6581 "Code and resource paths haven't been set correctly"); 6582 } 6583 6584 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6585 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6586 } else { 6587 // Only allow system apps to be flagged as core apps. 6588 pkg.coreApp = false; 6589 } 6590 6591 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6592 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6593 } 6594 6595 if (mCustomResolverComponentName != null && 6596 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6597 setUpCustomResolverActivity(pkg); 6598 } 6599 6600 if (pkg.packageName.equals("android")) { 6601 synchronized (mPackages) { 6602 if (mAndroidApplication != null) { 6603 Slog.w(TAG, "*************************************************"); 6604 Slog.w(TAG, "Core android package being redefined. Skipping."); 6605 Slog.w(TAG, " file=" + scanFile); 6606 Slog.w(TAG, "*************************************************"); 6607 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6608 "Core android package being redefined. Skipping."); 6609 } 6610 6611 // Set up information for our fall-back user intent resolution activity. 6612 mPlatformPackage = pkg; 6613 pkg.mVersionCode = mSdkVersion; 6614 mAndroidApplication = pkg.applicationInfo; 6615 6616 if (!mResolverReplaced) { 6617 mResolveActivity.applicationInfo = mAndroidApplication; 6618 mResolveActivity.name = ResolverActivity.class.getName(); 6619 mResolveActivity.packageName = mAndroidApplication.packageName; 6620 mResolveActivity.processName = "system:ui"; 6621 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6622 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6623 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6624 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6625 mResolveActivity.exported = true; 6626 mResolveActivity.enabled = true; 6627 mResolveInfo.activityInfo = mResolveActivity; 6628 mResolveInfo.priority = 0; 6629 mResolveInfo.preferredOrder = 0; 6630 mResolveInfo.match = 0; 6631 mResolveComponentName = new ComponentName( 6632 mAndroidApplication.packageName, mResolveActivity.name); 6633 } 6634 } 6635 } 6636 6637 if (DEBUG_PACKAGE_SCANNING) { 6638 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6639 Log.d(TAG, "Scanning package " + pkg.packageName); 6640 } 6641 6642 if (mPackages.containsKey(pkg.packageName) 6643 || mSharedLibraries.containsKey(pkg.packageName)) { 6644 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6645 "Application package " + pkg.packageName 6646 + " already installed. Skipping duplicate."); 6647 } 6648 6649 // If we're only installing presumed-existing packages, require that the 6650 // scanned APK is both already known and at the path previously established 6651 // for it. Previously unknown packages we pick up normally, but if we have an 6652 // a priori expectation about this package's install presence, enforce it. 6653 // With a singular exception for new system packages. When an OTA contains 6654 // a new system package, we allow the codepath to change from a system location 6655 // to the user-installed location. If we don't allow this change, any newer, 6656 // user-installed version of the application will be ignored. 6657 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6658 if (mExpectingBetter.containsKey(pkg.packageName)) { 6659 logCriticalInfo(Log.WARN, 6660 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6661 } else { 6662 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6663 if (known != null) { 6664 if (DEBUG_PACKAGE_SCANNING) { 6665 Log.d(TAG, "Examining " + pkg.codePath 6666 + " and requiring known paths " + known.codePathString 6667 + " & " + known.resourcePathString); 6668 } 6669 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6670 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6671 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6672 "Application package " + pkg.packageName 6673 + " found at " + pkg.applicationInfo.getCodePath() 6674 + " but expected at " + known.codePathString + "; ignoring."); 6675 } 6676 } 6677 } 6678 } 6679 6680 // Initialize package source and resource directories 6681 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6682 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6683 6684 SharedUserSetting suid = null; 6685 PackageSetting pkgSetting = null; 6686 6687 if (!isSystemApp(pkg)) { 6688 // Only system apps can use these features. 6689 pkg.mOriginalPackages = null; 6690 pkg.mRealPackage = null; 6691 pkg.mAdoptPermissions = null; 6692 } 6693 6694 // writer 6695 synchronized (mPackages) { 6696 if (pkg.mSharedUserId != null) { 6697 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6698 if (suid == null) { 6699 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6700 "Creating application package " + pkg.packageName 6701 + " for shared user failed"); 6702 } 6703 if (DEBUG_PACKAGE_SCANNING) { 6704 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6705 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6706 + "): packages=" + suid.packages); 6707 } 6708 } 6709 6710 // Check if we are renaming from an original package name. 6711 PackageSetting origPackage = null; 6712 String realName = null; 6713 if (pkg.mOriginalPackages != null) { 6714 // This package may need to be renamed to a previously 6715 // installed name. Let's check on that... 6716 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6717 if (pkg.mOriginalPackages.contains(renamed)) { 6718 // This package had originally been installed as the 6719 // original name, and we have already taken care of 6720 // transitioning to the new one. Just update the new 6721 // one to continue using the old name. 6722 realName = pkg.mRealPackage; 6723 if (!pkg.packageName.equals(renamed)) { 6724 // Callers into this function may have already taken 6725 // care of renaming the package; only do it here if 6726 // it is not already done. 6727 pkg.setPackageName(renamed); 6728 } 6729 6730 } else { 6731 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6732 if ((origPackage = mSettings.peekPackageLPr( 6733 pkg.mOriginalPackages.get(i))) != null) { 6734 // We do have the package already installed under its 6735 // original name... should we use it? 6736 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6737 // New package is not compatible with original. 6738 origPackage = null; 6739 continue; 6740 } else if (origPackage.sharedUser != null) { 6741 // Make sure uid is compatible between packages. 6742 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6743 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6744 + " to " + pkg.packageName + ": old uid " 6745 + origPackage.sharedUser.name 6746 + " differs from " + pkg.mSharedUserId); 6747 origPackage = null; 6748 continue; 6749 } 6750 } else { 6751 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6752 + pkg.packageName + " to old name " + origPackage.name); 6753 } 6754 break; 6755 } 6756 } 6757 } 6758 } 6759 6760 if (mTransferedPackages.contains(pkg.packageName)) { 6761 Slog.w(TAG, "Package " + pkg.packageName 6762 + " was transferred to another, but its .apk remains"); 6763 } 6764 6765 // Just create the setting, don't add it yet. For already existing packages 6766 // the PkgSetting exists already and doesn't have to be created. 6767 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6768 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6769 pkg.applicationInfo.primaryCpuAbi, 6770 pkg.applicationInfo.secondaryCpuAbi, 6771 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6772 user, false); 6773 if (pkgSetting == null) { 6774 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6775 "Creating application package " + pkg.packageName + " failed"); 6776 } 6777 6778 if (pkgSetting.origPackage != null) { 6779 // If we are first transitioning from an original package, 6780 // fix up the new package's name now. We need to do this after 6781 // looking up the package under its new name, so getPackageLP 6782 // can take care of fiddling things correctly. 6783 pkg.setPackageName(origPackage.name); 6784 6785 // File a report about this. 6786 String msg = "New package " + pkgSetting.realName 6787 + " renamed to replace old package " + pkgSetting.name; 6788 reportSettingsProblem(Log.WARN, msg); 6789 6790 // Make a note of it. 6791 mTransferedPackages.add(origPackage.name); 6792 6793 // No longer need to retain this. 6794 pkgSetting.origPackage = null; 6795 } 6796 6797 if (realName != null) { 6798 // Make a note of it. 6799 mTransferedPackages.add(pkg.packageName); 6800 } 6801 6802 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6803 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6804 } 6805 6806 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6807 // Check all shared libraries and map to their actual file path. 6808 // We only do this here for apps not on a system dir, because those 6809 // are the only ones that can fail an install due to this. We 6810 // will take care of the system apps by updating all of their 6811 // library paths after the scan is done. 6812 updateSharedLibrariesLPw(pkg, null); 6813 } 6814 6815 if (mFoundPolicyFile) { 6816 SELinuxMMAC.assignSeinfoValue(pkg); 6817 } 6818 6819 pkg.applicationInfo.uid = pkgSetting.appId; 6820 pkg.mExtras = pkgSetting; 6821 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6822 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6823 // We just determined the app is signed correctly, so bring 6824 // over the latest parsed certs. 6825 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6826 } else { 6827 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6828 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6829 "Package " + pkg.packageName + " upgrade keys do not match the " 6830 + "previously installed version"); 6831 } else { 6832 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6833 String msg = "System package " + pkg.packageName 6834 + " signature changed; retaining data."; 6835 reportSettingsProblem(Log.WARN, msg); 6836 } 6837 } 6838 } else { 6839 try { 6840 verifySignaturesLP(pkgSetting, pkg); 6841 // We just determined the app is signed correctly, so bring 6842 // over the latest parsed certs. 6843 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6844 } catch (PackageManagerException e) { 6845 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6846 throw e; 6847 } 6848 // The signature has changed, but this package is in the system 6849 // image... let's recover! 6850 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6851 // However... if this package is part of a shared user, but it 6852 // doesn't match the signature of the shared user, let's fail. 6853 // What this means is that you can't change the signatures 6854 // associated with an overall shared user, which doesn't seem all 6855 // that unreasonable. 6856 if (pkgSetting.sharedUser != null) { 6857 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6858 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6859 throw new PackageManagerException( 6860 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6861 "Signature mismatch for shared user : " 6862 + pkgSetting.sharedUser); 6863 } 6864 } 6865 // File a report about this. 6866 String msg = "System package " + pkg.packageName 6867 + " signature changed; retaining data."; 6868 reportSettingsProblem(Log.WARN, msg); 6869 } 6870 } 6871 // Verify that this new package doesn't have any content providers 6872 // that conflict with existing packages. Only do this if the 6873 // package isn't already installed, since we don't want to break 6874 // things that are installed. 6875 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6876 final int N = pkg.providers.size(); 6877 int i; 6878 for (i=0; i<N; i++) { 6879 PackageParser.Provider p = pkg.providers.get(i); 6880 if (p.info.authority != null) { 6881 String names[] = p.info.authority.split(";"); 6882 for (int j = 0; j < names.length; j++) { 6883 if (mProvidersByAuthority.containsKey(names[j])) { 6884 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6885 final String otherPackageName = 6886 ((other != null && other.getComponentName() != null) ? 6887 other.getComponentName().getPackageName() : "?"); 6888 throw new PackageManagerException( 6889 INSTALL_FAILED_CONFLICTING_PROVIDER, 6890 "Can't install because provider name " + names[j] 6891 + " (in package " + pkg.applicationInfo.packageName 6892 + ") is already used by " + otherPackageName); 6893 } 6894 } 6895 } 6896 } 6897 } 6898 6899 if (pkg.mAdoptPermissions != null) { 6900 // This package wants to adopt ownership of permissions from 6901 // another package. 6902 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6903 final String origName = pkg.mAdoptPermissions.get(i); 6904 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6905 if (orig != null) { 6906 if (verifyPackageUpdateLPr(orig, pkg)) { 6907 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6908 + pkg.packageName); 6909 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6910 } 6911 } 6912 } 6913 } 6914 } 6915 6916 final String pkgName = pkg.packageName; 6917 6918 final long scanFileTime = scanFile.lastModified(); 6919 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6920 pkg.applicationInfo.processName = fixProcessName( 6921 pkg.applicationInfo.packageName, 6922 pkg.applicationInfo.processName, 6923 pkg.applicationInfo.uid); 6924 6925 File dataPath; 6926 if (mPlatformPackage == pkg) { 6927 // The system package is special. 6928 dataPath = new File(Environment.getDataDirectory(), "system"); 6929 6930 pkg.applicationInfo.dataDir = dataPath.getPath(); 6931 6932 } else { 6933 // This is a normal package, need to make its data directory. 6934 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6935 UserHandle.USER_OWNER, pkg.packageName); 6936 6937 boolean uidError = false; 6938 if (dataPath.exists()) { 6939 int currentUid = 0; 6940 try { 6941 StructStat stat = Os.stat(dataPath.getPath()); 6942 currentUid = stat.st_uid; 6943 } catch (ErrnoException e) { 6944 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6945 } 6946 6947 // If we have mismatched owners for the data path, we have a problem. 6948 if (currentUid != pkg.applicationInfo.uid) { 6949 boolean recovered = false; 6950 if (currentUid == 0) { 6951 // The directory somehow became owned by root. Wow. 6952 // This is probably because the system was stopped while 6953 // installd was in the middle of messing with its libs 6954 // directory. Ask installd to fix that. 6955 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6956 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6957 if (ret >= 0) { 6958 recovered = true; 6959 String msg = "Package " + pkg.packageName 6960 + " unexpectedly changed to uid 0; recovered to " + 6961 + pkg.applicationInfo.uid; 6962 reportSettingsProblem(Log.WARN, msg); 6963 } 6964 } 6965 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6966 || (scanFlags&SCAN_BOOTING) != 0)) { 6967 // If this is a system app, we can at least delete its 6968 // current data so the application will still work. 6969 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6970 if (ret >= 0) { 6971 // TODO: Kill the processes first 6972 // Old data gone! 6973 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6974 ? "System package " : "Third party package "; 6975 String msg = prefix + pkg.packageName 6976 + " has changed from uid: " 6977 + currentUid + " to " 6978 + pkg.applicationInfo.uid + "; old data erased"; 6979 reportSettingsProblem(Log.WARN, msg); 6980 recovered = true; 6981 6982 // And now re-install the app. 6983 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6984 pkg.applicationInfo.seinfo); 6985 if (ret == -1) { 6986 // Ack should not happen! 6987 msg = prefix + pkg.packageName 6988 + " could not have data directory re-created after delete."; 6989 reportSettingsProblem(Log.WARN, msg); 6990 throw new PackageManagerException( 6991 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6992 } 6993 } 6994 if (!recovered) { 6995 mHasSystemUidErrors = true; 6996 } 6997 } else if (!recovered) { 6998 // If we allow this install to proceed, we will be broken. 6999 // Abort, abort! 7000 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7001 "scanPackageLI"); 7002 } 7003 if (!recovered) { 7004 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7005 + pkg.applicationInfo.uid + "/fs_" 7006 + currentUid; 7007 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7008 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7009 String msg = "Package " + pkg.packageName 7010 + " has mismatched uid: " 7011 + currentUid + " on disk, " 7012 + pkg.applicationInfo.uid + " in settings"; 7013 // writer 7014 synchronized (mPackages) { 7015 mSettings.mReadMessages.append(msg); 7016 mSettings.mReadMessages.append('\n'); 7017 uidError = true; 7018 if (!pkgSetting.uidError) { 7019 reportSettingsProblem(Log.ERROR, msg); 7020 } 7021 } 7022 } 7023 } 7024 pkg.applicationInfo.dataDir = dataPath.getPath(); 7025 if (mShouldRestoreconData) { 7026 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7027 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7028 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7029 } 7030 } else { 7031 if (DEBUG_PACKAGE_SCANNING) { 7032 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7033 Log.v(TAG, "Want this data dir: " + dataPath); 7034 } 7035 //invoke installer to do the actual installation 7036 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7037 pkg.applicationInfo.seinfo); 7038 if (ret < 0) { 7039 // Error from installer 7040 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7041 "Unable to create data dirs [errorCode=" + ret + "]"); 7042 } 7043 7044 if (dataPath.exists()) { 7045 pkg.applicationInfo.dataDir = dataPath.getPath(); 7046 } else { 7047 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7048 pkg.applicationInfo.dataDir = null; 7049 } 7050 } 7051 7052 pkgSetting.uidError = uidError; 7053 } 7054 7055 final String path = scanFile.getPath(); 7056 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7057 7058 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7059 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7060 7061 // Some system apps still use directory structure for native libraries 7062 // in which case we might end up not detecting abi solely based on apk 7063 // structure. Try to detect abi based on directory structure. 7064 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7065 pkg.applicationInfo.primaryCpuAbi == null) { 7066 setBundledAppAbisAndRoots(pkg, pkgSetting); 7067 setNativeLibraryPaths(pkg); 7068 } 7069 7070 } else { 7071 if ((scanFlags & SCAN_MOVE) != 0) { 7072 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7073 // but we already have this packages package info in the PackageSetting. We just 7074 // use that and derive the native library path based on the new codepath. 7075 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7076 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7077 } 7078 7079 // Set native library paths again. For moves, the path will be updated based on the 7080 // ABIs we've determined above. For non-moves, the path will be updated based on the 7081 // ABIs we determined during compilation, but the path will depend on the final 7082 // package path (after the rename away from the stage path). 7083 setNativeLibraryPaths(pkg); 7084 } 7085 7086 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7087 final int[] userIds = sUserManager.getUserIds(); 7088 synchronized (mInstallLock) { 7089 // Make sure all user data directories are ready to roll; we're okay 7090 // if they already exist 7091 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7092 for (int userId : userIds) { 7093 if (userId != 0) { 7094 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7095 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7096 pkg.applicationInfo.seinfo); 7097 } 7098 } 7099 } 7100 7101 // Create a native library symlink only if we have native libraries 7102 // and if the native libraries are 32 bit libraries. We do not provide 7103 // this symlink for 64 bit libraries. 7104 if (pkg.applicationInfo.primaryCpuAbi != null && 7105 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7106 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7107 try { 7108 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7109 for (int userId : userIds) { 7110 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7111 nativeLibPath, userId) < 0) { 7112 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7113 "Failed linking native library dir (user=" + userId + ")"); 7114 } 7115 } 7116 } finally { 7117 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7118 } 7119 } 7120 } 7121 7122 // This is a special case for the "system" package, where the ABI is 7123 // dictated by the zygote configuration (and init.rc). We should keep track 7124 // of this ABI so that we can deal with "normal" applications that run under 7125 // the same UID correctly. 7126 if (mPlatformPackage == pkg) { 7127 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7128 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7129 } 7130 7131 // If there's a mismatch between the abi-override in the package setting 7132 // and the abiOverride specified for the install. Warn about this because we 7133 // would've already compiled the app without taking the package setting into 7134 // account. 7135 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7136 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7137 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7138 " for package: " + pkg.packageName); 7139 } 7140 } 7141 7142 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7143 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7144 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7145 7146 // Copy the derived override back to the parsed package, so that we can 7147 // update the package settings accordingly. 7148 pkg.cpuAbiOverride = cpuAbiOverride; 7149 7150 if (DEBUG_ABI_SELECTION) { 7151 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7152 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7153 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7154 } 7155 7156 // Push the derived path down into PackageSettings so we know what to 7157 // clean up at uninstall time. 7158 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7159 7160 if (DEBUG_ABI_SELECTION) { 7161 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7162 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7163 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7164 } 7165 7166 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7167 // We don't do this here during boot because we can do it all 7168 // at once after scanning all existing packages. 7169 // 7170 // We also do this *before* we perform dexopt on this package, so that 7171 // we can avoid redundant dexopts, and also to make sure we've got the 7172 // code and package path correct. 7173 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7174 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7175 } 7176 7177 if ((scanFlags & SCAN_NO_DEX) == 0) { 7178 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7179 7180 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7181 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7182 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7183 7184 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7185 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7186 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7187 } 7188 } 7189 if (mFactoryTest && pkg.requestedPermissions.contains( 7190 android.Manifest.permission.FACTORY_TEST)) { 7191 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7192 } 7193 7194 ArrayList<PackageParser.Package> clientLibPkgs = null; 7195 7196 // writer 7197 synchronized (mPackages) { 7198 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7199 // Only system apps can add new shared libraries. 7200 if (pkg.libraryNames != null) { 7201 for (int i=0; i<pkg.libraryNames.size(); i++) { 7202 String name = pkg.libraryNames.get(i); 7203 boolean allowed = false; 7204 if (pkg.isUpdatedSystemApp()) { 7205 // New library entries can only be added through the 7206 // system image. This is important to get rid of a lot 7207 // of nasty edge cases: for example if we allowed a non- 7208 // system update of the app to add a library, then uninstalling 7209 // the update would make the library go away, and assumptions 7210 // we made such as through app install filtering would now 7211 // have allowed apps on the device which aren't compatible 7212 // with it. Better to just have the restriction here, be 7213 // conservative, and create many fewer cases that can negatively 7214 // impact the user experience. 7215 final PackageSetting sysPs = mSettings 7216 .getDisabledSystemPkgLPr(pkg.packageName); 7217 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7218 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7219 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7220 allowed = true; 7221 allowed = true; 7222 break; 7223 } 7224 } 7225 } 7226 } else { 7227 allowed = true; 7228 } 7229 if (allowed) { 7230 if (!mSharedLibraries.containsKey(name)) { 7231 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7232 } else if (!name.equals(pkg.packageName)) { 7233 Slog.w(TAG, "Package " + pkg.packageName + " library " 7234 + name + " already exists; skipping"); 7235 } 7236 } else { 7237 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7238 + name + " that is not declared on system image; skipping"); 7239 } 7240 } 7241 if ((scanFlags&SCAN_BOOTING) == 0) { 7242 // If we are not booting, we need to update any applications 7243 // that are clients of our shared library. If we are booting, 7244 // this will all be done once the scan is complete. 7245 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7246 } 7247 } 7248 } 7249 } 7250 7251 // We also need to dexopt any apps that are dependent on this library. Note that 7252 // if these fail, we should abort the install since installing the library will 7253 // result in some apps being broken. 7254 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7255 try { 7256 if (clientLibPkgs != null) { 7257 if ((scanFlags & SCAN_NO_DEX) == 0) { 7258 for (int i = 0; i < clientLibPkgs.size(); i++) { 7259 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7260 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7261 null /* instruction sets */, forceDex, 7262 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7263 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7264 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7265 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7266 "scanPackageLI failed to dexopt clientLibPkgs"); 7267 } 7268 } 7269 } 7270 } 7271 } finally { 7272 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7273 } 7274 7275 // Request the ActivityManager to kill the process(only for existing packages) 7276 // so that we do not end up in a confused state while the user is still using the older 7277 // version of the application while the new one gets installed. 7278 if ((scanFlags & SCAN_REPLACING) != 0) { 7279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7280 7281 killApplication(pkg.applicationInfo.packageName, 7282 pkg.applicationInfo.uid, "replace pkg"); 7283 7284 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7285 } 7286 7287 // Also need to kill any apps that are dependent on the library. 7288 if (clientLibPkgs != null) { 7289 for (int i=0; i<clientLibPkgs.size(); i++) { 7290 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7291 killApplication(clientPkg.applicationInfo.packageName, 7292 clientPkg.applicationInfo.uid, "update lib"); 7293 } 7294 } 7295 7296 // Make sure we're not adding any bogus keyset info 7297 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7298 ksms.assertScannedPackageValid(pkg); 7299 7300 // writer 7301 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7302 7303 boolean createIdmapFailed = false; 7304 synchronized (mPackages) { 7305 // We don't expect installation to fail beyond this point 7306 7307 // Add the new setting to mSettings 7308 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7309 // Add the new setting to mPackages 7310 mPackages.put(pkg.applicationInfo.packageName, pkg); 7311 // Make sure we don't accidentally delete its data. 7312 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7313 while (iter.hasNext()) { 7314 PackageCleanItem item = iter.next(); 7315 if (pkgName.equals(item.packageName)) { 7316 iter.remove(); 7317 } 7318 } 7319 7320 // Take care of first install / last update times. 7321 if (currentTime != 0) { 7322 if (pkgSetting.firstInstallTime == 0) { 7323 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7324 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7325 pkgSetting.lastUpdateTime = currentTime; 7326 } 7327 } else if (pkgSetting.firstInstallTime == 0) { 7328 // We need *something*. Take time time stamp of the file. 7329 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7330 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7331 if (scanFileTime != pkgSetting.timeStamp) { 7332 // A package on the system image has changed; consider this 7333 // to be an update. 7334 pkgSetting.lastUpdateTime = scanFileTime; 7335 } 7336 } 7337 7338 // Add the package's KeySets to the global KeySetManagerService 7339 ksms.addScannedPackageLPw(pkg); 7340 7341 int N = pkg.providers.size(); 7342 StringBuilder r = null; 7343 int i; 7344 for (i=0; i<N; i++) { 7345 PackageParser.Provider p = pkg.providers.get(i); 7346 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7347 p.info.processName, pkg.applicationInfo.uid); 7348 mProviders.addProvider(p); 7349 p.syncable = p.info.isSyncable; 7350 if (p.info.authority != null) { 7351 String names[] = p.info.authority.split(";"); 7352 p.info.authority = null; 7353 for (int j = 0; j < names.length; j++) { 7354 if (j == 1 && p.syncable) { 7355 // We only want the first authority for a provider to possibly be 7356 // syncable, so if we already added this provider using a different 7357 // authority clear the syncable flag. We copy the provider before 7358 // changing it because the mProviders object contains a reference 7359 // to a provider that we don't want to change. 7360 // Only do this for the second authority since the resulting provider 7361 // object can be the same for all future authorities for this provider. 7362 p = new PackageParser.Provider(p); 7363 p.syncable = false; 7364 } 7365 if (!mProvidersByAuthority.containsKey(names[j])) { 7366 mProvidersByAuthority.put(names[j], p); 7367 if (p.info.authority == null) { 7368 p.info.authority = names[j]; 7369 } else { 7370 p.info.authority = p.info.authority + ";" + names[j]; 7371 } 7372 if (DEBUG_PACKAGE_SCANNING) { 7373 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7374 Log.d(TAG, "Registered content provider: " + names[j] 7375 + ", className = " + p.info.name + ", isSyncable = " 7376 + p.info.isSyncable); 7377 } 7378 } else { 7379 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7380 Slog.w(TAG, "Skipping provider name " + names[j] + 7381 " (in package " + pkg.applicationInfo.packageName + 7382 "): name already used by " 7383 + ((other != null && other.getComponentName() != null) 7384 ? other.getComponentName().getPackageName() : "?")); 7385 } 7386 } 7387 } 7388 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7389 if (r == null) { 7390 r = new StringBuilder(256); 7391 } else { 7392 r.append(' '); 7393 } 7394 r.append(p.info.name); 7395 } 7396 } 7397 if (r != null) { 7398 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7399 } 7400 7401 N = pkg.services.size(); 7402 r = null; 7403 for (i=0; i<N; i++) { 7404 PackageParser.Service s = pkg.services.get(i); 7405 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7406 s.info.processName, pkg.applicationInfo.uid); 7407 mServices.addService(s); 7408 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7409 if (r == null) { 7410 r = new StringBuilder(256); 7411 } else { 7412 r.append(' '); 7413 } 7414 r.append(s.info.name); 7415 } 7416 } 7417 if (r != null) { 7418 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7419 } 7420 7421 N = pkg.receivers.size(); 7422 r = null; 7423 for (i=0; i<N; i++) { 7424 PackageParser.Activity a = pkg.receivers.get(i); 7425 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7426 a.info.processName, pkg.applicationInfo.uid); 7427 mReceivers.addActivity(a, "receiver"); 7428 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7429 if (r == null) { 7430 r = new StringBuilder(256); 7431 } else { 7432 r.append(' '); 7433 } 7434 r.append(a.info.name); 7435 } 7436 } 7437 if (r != null) { 7438 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7439 } 7440 7441 N = pkg.activities.size(); 7442 r = null; 7443 for (i=0; i<N; i++) { 7444 PackageParser.Activity a = pkg.activities.get(i); 7445 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7446 a.info.processName, pkg.applicationInfo.uid); 7447 mActivities.addActivity(a, "activity"); 7448 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7449 if (r == null) { 7450 r = new StringBuilder(256); 7451 } else { 7452 r.append(' '); 7453 } 7454 r.append(a.info.name); 7455 } 7456 } 7457 if (r != null) { 7458 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7459 } 7460 7461 N = pkg.permissionGroups.size(); 7462 r = null; 7463 for (i=0; i<N; i++) { 7464 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7465 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7466 if (cur == null) { 7467 mPermissionGroups.put(pg.info.name, pg); 7468 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7469 if (r == null) { 7470 r = new StringBuilder(256); 7471 } else { 7472 r.append(' '); 7473 } 7474 r.append(pg.info.name); 7475 } 7476 } else { 7477 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7478 + pg.info.packageName + " ignored: original from " 7479 + cur.info.packageName); 7480 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7481 if (r == null) { 7482 r = new StringBuilder(256); 7483 } else { 7484 r.append(' '); 7485 } 7486 r.append("DUP:"); 7487 r.append(pg.info.name); 7488 } 7489 } 7490 } 7491 if (r != null) { 7492 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7493 } 7494 7495 N = pkg.permissions.size(); 7496 r = null; 7497 for (i=0; i<N; i++) { 7498 PackageParser.Permission p = pkg.permissions.get(i); 7499 7500 // Assume by default that we did not install this permission into the system. 7501 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7502 7503 // Now that permission groups have a special meaning, we ignore permission 7504 // groups for legacy apps to prevent unexpected behavior. In particular, 7505 // permissions for one app being granted to someone just becuase they happen 7506 // to be in a group defined by another app (before this had no implications). 7507 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7508 p.group = mPermissionGroups.get(p.info.group); 7509 // Warn for a permission in an unknown group. 7510 if (p.info.group != null && p.group == null) { 7511 Slog.w(TAG, "Permission " + p.info.name + " from package " 7512 + p.info.packageName + " in an unknown group " + p.info.group); 7513 } 7514 } 7515 7516 ArrayMap<String, BasePermission> permissionMap = 7517 p.tree ? mSettings.mPermissionTrees 7518 : mSettings.mPermissions; 7519 BasePermission bp = permissionMap.get(p.info.name); 7520 7521 // Allow system apps to redefine non-system permissions 7522 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7523 final boolean currentOwnerIsSystem = (bp.perm != null 7524 && isSystemApp(bp.perm.owner)); 7525 if (isSystemApp(p.owner)) { 7526 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7527 // It's a built-in permission and no owner, take ownership now 7528 bp.packageSetting = pkgSetting; 7529 bp.perm = p; 7530 bp.uid = pkg.applicationInfo.uid; 7531 bp.sourcePackage = p.info.packageName; 7532 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7533 } else if (!currentOwnerIsSystem) { 7534 String msg = "New decl " + p.owner + " of permission " 7535 + p.info.name + " is system; overriding " + bp.sourcePackage; 7536 reportSettingsProblem(Log.WARN, msg); 7537 bp = null; 7538 } 7539 } 7540 } 7541 7542 if (bp == null) { 7543 bp = new BasePermission(p.info.name, p.info.packageName, 7544 BasePermission.TYPE_NORMAL); 7545 permissionMap.put(p.info.name, bp); 7546 } 7547 7548 if (bp.perm == null) { 7549 if (bp.sourcePackage == null 7550 || bp.sourcePackage.equals(p.info.packageName)) { 7551 BasePermission tree = findPermissionTreeLP(p.info.name); 7552 if (tree == null 7553 || tree.sourcePackage.equals(p.info.packageName)) { 7554 bp.packageSetting = pkgSetting; 7555 bp.perm = p; 7556 bp.uid = pkg.applicationInfo.uid; 7557 bp.sourcePackage = p.info.packageName; 7558 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7559 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7560 if (r == null) { 7561 r = new StringBuilder(256); 7562 } else { 7563 r.append(' '); 7564 } 7565 r.append(p.info.name); 7566 } 7567 } else { 7568 Slog.w(TAG, "Permission " + p.info.name + " from package " 7569 + p.info.packageName + " ignored: base tree " 7570 + tree.name + " is from package " 7571 + tree.sourcePackage); 7572 } 7573 } else { 7574 Slog.w(TAG, "Permission " + p.info.name + " from package " 7575 + p.info.packageName + " ignored: original from " 7576 + bp.sourcePackage); 7577 } 7578 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7579 if (r == null) { 7580 r = new StringBuilder(256); 7581 } else { 7582 r.append(' '); 7583 } 7584 r.append("DUP:"); 7585 r.append(p.info.name); 7586 } 7587 if (bp.perm == p) { 7588 bp.protectionLevel = p.info.protectionLevel; 7589 } 7590 } 7591 7592 if (r != null) { 7593 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7594 } 7595 7596 N = pkg.instrumentation.size(); 7597 r = null; 7598 for (i=0; i<N; i++) { 7599 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7600 a.info.packageName = pkg.applicationInfo.packageName; 7601 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7602 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7603 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7604 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7605 a.info.dataDir = pkg.applicationInfo.dataDir; 7606 7607 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7608 // need other information about the application, like the ABI and what not ? 7609 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7610 mInstrumentation.put(a.getComponentName(), a); 7611 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7612 if (r == null) { 7613 r = new StringBuilder(256); 7614 } else { 7615 r.append(' '); 7616 } 7617 r.append(a.info.name); 7618 } 7619 } 7620 if (r != null) { 7621 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7622 } 7623 7624 if (pkg.protectedBroadcasts != null) { 7625 N = pkg.protectedBroadcasts.size(); 7626 for (i=0; i<N; i++) { 7627 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7628 } 7629 } 7630 7631 pkgSetting.setTimeStamp(scanFileTime); 7632 7633 // Create idmap files for pairs of (packages, overlay packages). 7634 // Note: "android", ie framework-res.apk, is handled by native layers. 7635 if (pkg.mOverlayTarget != null) { 7636 // This is an overlay package. 7637 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7638 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7639 mOverlays.put(pkg.mOverlayTarget, 7640 new ArrayMap<String, PackageParser.Package>()); 7641 } 7642 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7643 map.put(pkg.packageName, pkg); 7644 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7645 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7646 createIdmapFailed = true; 7647 } 7648 } 7649 } else if (mOverlays.containsKey(pkg.packageName) && 7650 !pkg.packageName.equals("android")) { 7651 // This is a regular package, with one or more known overlay packages. 7652 createIdmapsForPackageLI(pkg); 7653 } 7654 } 7655 7656 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7657 7658 if (createIdmapFailed) { 7659 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7660 "scanPackageLI failed to createIdmap"); 7661 } 7662 return pkg; 7663 } 7664 7665 /** 7666 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7667 * is derived purely on the basis of the contents of {@code scanFile} and 7668 * {@code cpuAbiOverride}. 7669 * 7670 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7671 */ 7672 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7673 String cpuAbiOverride, boolean extractLibs) 7674 throws PackageManagerException { 7675 // TODO: We can probably be smarter about this stuff. For installed apps, 7676 // we can calculate this information at install time once and for all. For 7677 // system apps, we can probably assume that this information doesn't change 7678 // after the first boot scan. As things stand, we do lots of unnecessary work. 7679 7680 // Give ourselves some initial paths; we'll come back for another 7681 // pass once we've determined ABI below. 7682 setNativeLibraryPaths(pkg); 7683 7684 // We would never need to extract libs for forward-locked and external packages, 7685 // since the container service will do it for us. We shouldn't attempt to 7686 // extract libs from system app when it was not updated. 7687 if (pkg.isForwardLocked() || isExternal(pkg) || 7688 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7689 extractLibs = false; 7690 } 7691 7692 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7693 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7694 7695 NativeLibraryHelper.Handle handle = null; 7696 try { 7697 handle = NativeLibraryHelper.Handle.create(pkg); 7698 // TODO(multiArch): This can be null for apps that didn't go through the 7699 // usual installation process. We can calculate it again, like we 7700 // do during install time. 7701 // 7702 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7703 // unnecessary. 7704 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7705 7706 // Null out the abis so that they can be recalculated. 7707 pkg.applicationInfo.primaryCpuAbi = null; 7708 pkg.applicationInfo.secondaryCpuAbi = null; 7709 if (isMultiArch(pkg.applicationInfo)) { 7710 // Warn if we've set an abiOverride for multi-lib packages.. 7711 // By definition, we need to copy both 32 and 64 bit libraries for 7712 // such packages. 7713 if (pkg.cpuAbiOverride != null 7714 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7715 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7716 } 7717 7718 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7719 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7720 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7721 if (extractLibs) { 7722 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7723 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7724 useIsaSpecificSubdirs); 7725 } else { 7726 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7727 } 7728 } 7729 7730 maybeThrowExceptionForMultiArchCopy( 7731 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7732 7733 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7734 if (extractLibs) { 7735 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7736 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7737 useIsaSpecificSubdirs); 7738 } else { 7739 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7740 } 7741 } 7742 7743 maybeThrowExceptionForMultiArchCopy( 7744 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7745 7746 if (abi64 >= 0) { 7747 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7748 } 7749 7750 if (abi32 >= 0) { 7751 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7752 if (abi64 >= 0) { 7753 pkg.applicationInfo.secondaryCpuAbi = abi; 7754 } else { 7755 pkg.applicationInfo.primaryCpuAbi = abi; 7756 } 7757 } 7758 } else { 7759 String[] abiList = (cpuAbiOverride != null) ? 7760 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7761 7762 // Enable gross and lame hacks for apps that are built with old 7763 // SDK tools. We must scan their APKs for renderscript bitcode and 7764 // not launch them if it's present. Don't bother checking on devices 7765 // that don't have 64 bit support. 7766 boolean needsRenderScriptOverride = false; 7767 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7768 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7769 abiList = Build.SUPPORTED_32_BIT_ABIS; 7770 needsRenderScriptOverride = true; 7771 } 7772 7773 final int copyRet; 7774 if (extractLibs) { 7775 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7776 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7777 } else { 7778 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7779 } 7780 7781 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7782 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7783 "Error unpackaging native libs for app, errorCode=" + copyRet); 7784 } 7785 7786 if (copyRet >= 0) { 7787 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7788 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7789 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7790 } else if (needsRenderScriptOverride) { 7791 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7792 } 7793 } 7794 } catch (IOException ioe) { 7795 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7796 } finally { 7797 IoUtils.closeQuietly(handle); 7798 } 7799 7800 // Now that we've calculated the ABIs and determined if it's an internal app, 7801 // we will go ahead and populate the nativeLibraryPath. 7802 setNativeLibraryPaths(pkg); 7803 } 7804 7805 /** 7806 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7807 * i.e, so that all packages can be run inside a single process if required. 7808 * 7809 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7810 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7811 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7812 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7813 * updating a package that belongs to a shared user. 7814 * 7815 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7816 * adds unnecessary complexity. 7817 */ 7818 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7819 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7820 boolean bootComplete) { 7821 String requiredInstructionSet = null; 7822 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7823 requiredInstructionSet = VMRuntime.getInstructionSet( 7824 scannedPackage.applicationInfo.primaryCpuAbi); 7825 } 7826 7827 PackageSetting requirer = null; 7828 for (PackageSetting ps : packagesForUser) { 7829 // If packagesForUser contains scannedPackage, we skip it. This will happen 7830 // when scannedPackage is an update of an existing package. Without this check, 7831 // we will never be able to change the ABI of any package belonging to a shared 7832 // user, even if it's compatible with other packages. 7833 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7834 if (ps.primaryCpuAbiString == null) { 7835 continue; 7836 } 7837 7838 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7839 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7840 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7841 // this but there's not much we can do. 7842 String errorMessage = "Instruction set mismatch, " 7843 + ((requirer == null) ? "[caller]" : requirer) 7844 + " requires " + requiredInstructionSet + " whereas " + ps 7845 + " requires " + instructionSet; 7846 Slog.w(TAG, errorMessage); 7847 } 7848 7849 if (requiredInstructionSet == null) { 7850 requiredInstructionSet = instructionSet; 7851 requirer = ps; 7852 } 7853 } 7854 } 7855 7856 if (requiredInstructionSet != null) { 7857 String adjustedAbi; 7858 if (requirer != null) { 7859 // requirer != null implies that either scannedPackage was null or that scannedPackage 7860 // did not require an ABI, in which case we have to adjust scannedPackage to match 7861 // the ABI of the set (which is the same as requirer's ABI) 7862 adjustedAbi = requirer.primaryCpuAbiString; 7863 if (scannedPackage != null) { 7864 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7865 } 7866 } else { 7867 // requirer == null implies that we're updating all ABIs in the set to 7868 // match scannedPackage. 7869 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7870 } 7871 7872 for (PackageSetting ps : packagesForUser) { 7873 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7874 if (ps.primaryCpuAbiString != null) { 7875 continue; 7876 } 7877 7878 ps.primaryCpuAbiString = adjustedAbi; 7879 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7880 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7881 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7882 7883 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7884 7885 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7886 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7887 bootComplete, false /*useJit*/); 7888 7889 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7890 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7891 ps.primaryCpuAbiString = null; 7892 ps.pkg.applicationInfo.primaryCpuAbi = null; 7893 return; 7894 } else { 7895 mInstaller.rmdex(ps.codePathString, 7896 getDexCodeInstructionSet(getPreferredInstructionSet())); 7897 } 7898 } 7899 } 7900 } 7901 } 7902 } 7903 7904 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7905 synchronized (mPackages) { 7906 mResolverReplaced = true; 7907 // Set up information for custom user intent resolution activity. 7908 mResolveActivity.applicationInfo = pkg.applicationInfo; 7909 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7910 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7911 mResolveActivity.processName = pkg.applicationInfo.packageName; 7912 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7913 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7914 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7915 mResolveActivity.theme = 0; 7916 mResolveActivity.exported = true; 7917 mResolveActivity.enabled = true; 7918 mResolveInfo.activityInfo = mResolveActivity; 7919 mResolveInfo.priority = 0; 7920 mResolveInfo.preferredOrder = 0; 7921 mResolveInfo.match = 0; 7922 mResolveComponentName = mCustomResolverComponentName; 7923 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7924 mResolveComponentName); 7925 } 7926 } 7927 7928 private static String calculateBundledApkRoot(final String codePathString) { 7929 final File codePath = new File(codePathString); 7930 final File codeRoot; 7931 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7932 codeRoot = Environment.getRootDirectory(); 7933 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7934 codeRoot = Environment.getOemDirectory(); 7935 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7936 codeRoot = Environment.getVendorDirectory(); 7937 } else { 7938 // Unrecognized code path; take its top real segment as the apk root: 7939 // e.g. /something/app/blah.apk => /something 7940 try { 7941 File f = codePath.getCanonicalFile(); 7942 File parent = f.getParentFile(); // non-null because codePath is a file 7943 File tmp; 7944 while ((tmp = parent.getParentFile()) != null) { 7945 f = parent; 7946 parent = tmp; 7947 } 7948 codeRoot = f; 7949 Slog.w(TAG, "Unrecognized code path " 7950 + codePath + " - using " + codeRoot); 7951 } catch (IOException e) { 7952 // Can't canonicalize the code path -- shenanigans? 7953 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7954 return Environment.getRootDirectory().getPath(); 7955 } 7956 } 7957 return codeRoot.getPath(); 7958 } 7959 7960 /** 7961 * Derive and set the location of native libraries for the given package, 7962 * which varies depending on where and how the package was installed. 7963 */ 7964 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7965 final ApplicationInfo info = pkg.applicationInfo; 7966 final String codePath = pkg.codePath; 7967 final File codeFile = new File(codePath); 7968 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7969 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7970 7971 info.nativeLibraryRootDir = null; 7972 info.nativeLibraryRootRequiresIsa = false; 7973 info.nativeLibraryDir = null; 7974 info.secondaryNativeLibraryDir = null; 7975 7976 if (isApkFile(codeFile)) { 7977 // Monolithic install 7978 if (bundledApp) { 7979 // If "/system/lib64/apkname" exists, assume that is the per-package 7980 // native library directory to use; otherwise use "/system/lib/apkname". 7981 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7982 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7983 getPrimaryInstructionSet(info)); 7984 7985 // This is a bundled system app so choose the path based on the ABI. 7986 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7987 // is just the default path. 7988 final String apkName = deriveCodePathName(codePath); 7989 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7990 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7991 apkName).getAbsolutePath(); 7992 7993 if (info.secondaryCpuAbi != null) { 7994 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7995 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7996 secondaryLibDir, apkName).getAbsolutePath(); 7997 } 7998 } else if (asecApp) { 7999 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8000 .getAbsolutePath(); 8001 } else { 8002 final String apkName = deriveCodePathName(codePath); 8003 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8004 .getAbsolutePath(); 8005 } 8006 8007 info.nativeLibraryRootRequiresIsa = false; 8008 info.nativeLibraryDir = info.nativeLibraryRootDir; 8009 } else { 8010 // Cluster install 8011 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8012 info.nativeLibraryRootRequiresIsa = true; 8013 8014 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8015 getPrimaryInstructionSet(info)).getAbsolutePath(); 8016 8017 if (info.secondaryCpuAbi != null) { 8018 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8019 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8020 } 8021 } 8022 } 8023 8024 /** 8025 * Calculate the abis and roots for a bundled app. These can uniquely 8026 * be determined from the contents of the system partition, i.e whether 8027 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8028 * of this information, and instead assume that the system was built 8029 * sensibly. 8030 */ 8031 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8032 PackageSetting pkgSetting) { 8033 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8034 8035 // If "/system/lib64/apkname" exists, assume that is the per-package 8036 // native library directory to use; otherwise use "/system/lib/apkname". 8037 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8038 setBundledAppAbi(pkg, apkRoot, apkName); 8039 // pkgSetting might be null during rescan following uninstall of updates 8040 // to a bundled app, so accommodate that possibility. The settings in 8041 // that case will be established later from the parsed package. 8042 // 8043 // If the settings aren't null, sync them up with what we've just derived. 8044 // note that apkRoot isn't stored in the package settings. 8045 if (pkgSetting != null) { 8046 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8047 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8048 } 8049 } 8050 8051 /** 8052 * Deduces the ABI of a bundled app and sets the relevant fields on the 8053 * parsed pkg object. 8054 * 8055 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8056 * under which system libraries are installed. 8057 * @param apkName the name of the installed package. 8058 */ 8059 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8060 final File codeFile = new File(pkg.codePath); 8061 8062 final boolean has64BitLibs; 8063 final boolean has32BitLibs; 8064 if (isApkFile(codeFile)) { 8065 // Monolithic install 8066 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8067 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8068 } else { 8069 // Cluster install 8070 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8071 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8072 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8073 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8074 has64BitLibs = (new File(rootDir, isa)).exists(); 8075 } else { 8076 has64BitLibs = false; 8077 } 8078 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8079 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8080 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8081 has32BitLibs = (new File(rootDir, isa)).exists(); 8082 } else { 8083 has32BitLibs = false; 8084 } 8085 } 8086 8087 if (has64BitLibs && !has32BitLibs) { 8088 // The package has 64 bit libs, but not 32 bit libs. Its primary 8089 // ABI should be 64 bit. We can safely assume here that the bundled 8090 // native libraries correspond to the most preferred ABI in the list. 8091 8092 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8093 pkg.applicationInfo.secondaryCpuAbi = null; 8094 } else if (has32BitLibs && !has64BitLibs) { 8095 // The package has 32 bit libs but not 64 bit libs. Its primary 8096 // ABI should be 32 bit. 8097 8098 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8099 pkg.applicationInfo.secondaryCpuAbi = null; 8100 } else if (has32BitLibs && has64BitLibs) { 8101 // The application has both 64 and 32 bit bundled libraries. We check 8102 // here that the app declares multiArch support, and warn if it doesn't. 8103 // 8104 // We will be lenient here and record both ABIs. The primary will be the 8105 // ABI that's higher on the list, i.e, a device that's configured to prefer 8106 // 64 bit apps will see a 64 bit primary ABI, 8107 8108 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8109 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8110 } 8111 8112 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8113 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8114 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8115 } else { 8116 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8117 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8118 } 8119 } else { 8120 pkg.applicationInfo.primaryCpuAbi = null; 8121 pkg.applicationInfo.secondaryCpuAbi = null; 8122 } 8123 } 8124 8125 private void killApplication(String pkgName, int appId, String reason) { 8126 // Request the ActivityManager to kill the process(only for existing packages) 8127 // so that we do not end up in a confused state while the user is still using the older 8128 // version of the application while the new one gets installed. 8129 IActivityManager am = ActivityManagerNative.getDefault(); 8130 if (am != null) { 8131 try { 8132 am.killApplicationWithAppId(pkgName, appId, reason); 8133 } catch (RemoteException e) { 8134 } 8135 } 8136 } 8137 8138 void removePackageLI(PackageSetting ps, boolean chatty) { 8139 if (DEBUG_INSTALL) { 8140 if (chatty) 8141 Log.d(TAG, "Removing package " + ps.name); 8142 } 8143 8144 // writer 8145 synchronized (mPackages) { 8146 mPackages.remove(ps.name); 8147 final PackageParser.Package pkg = ps.pkg; 8148 if (pkg != null) { 8149 cleanPackageDataStructuresLILPw(pkg, chatty); 8150 } 8151 } 8152 } 8153 8154 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8155 if (DEBUG_INSTALL) { 8156 if (chatty) 8157 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8158 } 8159 8160 // writer 8161 synchronized (mPackages) { 8162 mPackages.remove(pkg.applicationInfo.packageName); 8163 cleanPackageDataStructuresLILPw(pkg, chatty); 8164 } 8165 } 8166 8167 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8168 int N = pkg.providers.size(); 8169 StringBuilder r = null; 8170 int i; 8171 for (i=0; i<N; i++) { 8172 PackageParser.Provider p = pkg.providers.get(i); 8173 mProviders.removeProvider(p); 8174 if (p.info.authority == null) { 8175 8176 /* There was another ContentProvider with this authority when 8177 * this app was installed so this authority is null, 8178 * Ignore it as we don't have to unregister the provider. 8179 */ 8180 continue; 8181 } 8182 String names[] = p.info.authority.split(";"); 8183 for (int j = 0; j < names.length; j++) { 8184 if (mProvidersByAuthority.get(names[j]) == p) { 8185 mProvidersByAuthority.remove(names[j]); 8186 if (DEBUG_REMOVE) { 8187 if (chatty) 8188 Log.d(TAG, "Unregistered content provider: " + names[j] 8189 + ", className = " + p.info.name + ", isSyncable = " 8190 + p.info.isSyncable); 8191 } 8192 } 8193 } 8194 if (DEBUG_REMOVE && chatty) { 8195 if (r == null) { 8196 r = new StringBuilder(256); 8197 } else { 8198 r.append(' '); 8199 } 8200 r.append(p.info.name); 8201 } 8202 } 8203 if (r != null) { 8204 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8205 } 8206 8207 N = pkg.services.size(); 8208 r = null; 8209 for (i=0; i<N; i++) { 8210 PackageParser.Service s = pkg.services.get(i); 8211 mServices.removeService(s); 8212 if (chatty) { 8213 if (r == null) { 8214 r = new StringBuilder(256); 8215 } else { 8216 r.append(' '); 8217 } 8218 r.append(s.info.name); 8219 } 8220 } 8221 if (r != null) { 8222 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8223 } 8224 8225 N = pkg.receivers.size(); 8226 r = null; 8227 for (i=0; i<N; i++) { 8228 PackageParser.Activity a = pkg.receivers.get(i); 8229 mReceivers.removeActivity(a, "receiver"); 8230 if (DEBUG_REMOVE && chatty) { 8231 if (r == null) { 8232 r = new StringBuilder(256); 8233 } else { 8234 r.append(' '); 8235 } 8236 r.append(a.info.name); 8237 } 8238 } 8239 if (r != null) { 8240 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8241 } 8242 8243 N = pkg.activities.size(); 8244 r = null; 8245 for (i=0; i<N; i++) { 8246 PackageParser.Activity a = pkg.activities.get(i); 8247 mActivities.removeActivity(a, "activity"); 8248 if (DEBUG_REMOVE && chatty) { 8249 if (r == null) { 8250 r = new StringBuilder(256); 8251 } else { 8252 r.append(' '); 8253 } 8254 r.append(a.info.name); 8255 } 8256 } 8257 if (r != null) { 8258 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8259 } 8260 8261 N = pkg.permissions.size(); 8262 r = null; 8263 for (i=0; i<N; i++) { 8264 PackageParser.Permission p = pkg.permissions.get(i); 8265 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8266 if (bp == null) { 8267 bp = mSettings.mPermissionTrees.get(p.info.name); 8268 } 8269 if (bp != null && bp.perm == p) { 8270 bp.perm = null; 8271 if (DEBUG_REMOVE && chatty) { 8272 if (r == null) { 8273 r = new StringBuilder(256); 8274 } else { 8275 r.append(' '); 8276 } 8277 r.append(p.info.name); 8278 } 8279 } 8280 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8281 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8282 if (appOpPerms != null) { 8283 appOpPerms.remove(pkg.packageName); 8284 } 8285 } 8286 } 8287 if (r != null) { 8288 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8289 } 8290 8291 N = pkg.requestedPermissions.size(); 8292 r = null; 8293 for (i=0; i<N; i++) { 8294 String perm = pkg.requestedPermissions.get(i); 8295 BasePermission bp = mSettings.mPermissions.get(perm); 8296 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8297 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8298 if (appOpPerms != null) { 8299 appOpPerms.remove(pkg.packageName); 8300 if (appOpPerms.isEmpty()) { 8301 mAppOpPermissionPackages.remove(perm); 8302 } 8303 } 8304 } 8305 } 8306 if (r != null) { 8307 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8308 } 8309 8310 N = pkg.instrumentation.size(); 8311 r = null; 8312 for (i=0; i<N; i++) { 8313 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8314 mInstrumentation.remove(a.getComponentName()); 8315 if (DEBUG_REMOVE && chatty) { 8316 if (r == null) { 8317 r = new StringBuilder(256); 8318 } else { 8319 r.append(' '); 8320 } 8321 r.append(a.info.name); 8322 } 8323 } 8324 if (r != null) { 8325 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8326 } 8327 8328 r = null; 8329 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8330 // Only system apps can hold shared libraries. 8331 if (pkg.libraryNames != null) { 8332 for (i=0; i<pkg.libraryNames.size(); i++) { 8333 String name = pkg.libraryNames.get(i); 8334 SharedLibraryEntry cur = mSharedLibraries.get(name); 8335 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8336 mSharedLibraries.remove(name); 8337 if (DEBUG_REMOVE && chatty) { 8338 if (r == null) { 8339 r = new StringBuilder(256); 8340 } else { 8341 r.append(' '); 8342 } 8343 r.append(name); 8344 } 8345 } 8346 } 8347 } 8348 } 8349 if (r != null) { 8350 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8351 } 8352 } 8353 8354 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8355 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8356 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8357 return true; 8358 } 8359 } 8360 return false; 8361 } 8362 8363 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8364 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8365 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8366 8367 private void updatePermissionsLPw(String changingPkg, 8368 PackageParser.Package pkgInfo, int flags) { 8369 // Make sure there are no dangling permission trees. 8370 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8371 while (it.hasNext()) { 8372 final BasePermission bp = it.next(); 8373 if (bp.packageSetting == null) { 8374 // We may not yet have parsed the package, so just see if 8375 // we still know about its settings. 8376 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8377 } 8378 if (bp.packageSetting == null) { 8379 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8380 + " from package " + bp.sourcePackage); 8381 it.remove(); 8382 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8383 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8384 Slog.i(TAG, "Removing old permission tree: " + bp.name 8385 + " from package " + bp.sourcePackage); 8386 flags |= UPDATE_PERMISSIONS_ALL; 8387 it.remove(); 8388 } 8389 } 8390 } 8391 8392 // Make sure all dynamic permissions have been assigned to a package, 8393 // and make sure there are no dangling permissions. 8394 it = mSettings.mPermissions.values().iterator(); 8395 while (it.hasNext()) { 8396 final BasePermission bp = it.next(); 8397 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8398 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8399 + bp.name + " pkg=" + bp.sourcePackage 8400 + " info=" + bp.pendingInfo); 8401 if (bp.packageSetting == null && bp.pendingInfo != null) { 8402 final BasePermission tree = findPermissionTreeLP(bp.name); 8403 if (tree != null && tree.perm != null) { 8404 bp.packageSetting = tree.packageSetting; 8405 bp.perm = new PackageParser.Permission(tree.perm.owner, 8406 new PermissionInfo(bp.pendingInfo)); 8407 bp.perm.info.packageName = tree.perm.info.packageName; 8408 bp.perm.info.name = bp.name; 8409 bp.uid = tree.uid; 8410 } 8411 } 8412 } 8413 if (bp.packageSetting == null) { 8414 // We may not yet have parsed the package, so just see if 8415 // we still know about its settings. 8416 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8417 } 8418 if (bp.packageSetting == null) { 8419 Slog.w(TAG, "Removing dangling permission: " + bp.name 8420 + " from package " + bp.sourcePackage); 8421 it.remove(); 8422 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8423 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8424 Slog.i(TAG, "Removing old permission: " + bp.name 8425 + " from package " + bp.sourcePackage); 8426 flags |= UPDATE_PERMISSIONS_ALL; 8427 it.remove(); 8428 } 8429 } 8430 } 8431 8432 // Now update the permissions for all packages, in particular 8433 // replace the granted permissions of the system packages. 8434 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8435 for (PackageParser.Package pkg : mPackages.values()) { 8436 if (pkg != pkgInfo) { 8437 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8438 changingPkg); 8439 } 8440 } 8441 } 8442 8443 if (pkgInfo != null) { 8444 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8445 } 8446 } 8447 8448 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8449 String packageOfInterest) { 8450 // IMPORTANT: There are two types of permissions: install and runtime. 8451 // Install time permissions are granted when the app is installed to 8452 // all device users and users added in the future. Runtime permissions 8453 // are granted at runtime explicitly to specific users. Normal and signature 8454 // protected permissions are install time permissions. Dangerous permissions 8455 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8456 // otherwise they are runtime permissions. This function does not manage 8457 // runtime permissions except for the case an app targeting Lollipop MR1 8458 // being upgraded to target a newer SDK, in which case dangerous permissions 8459 // are transformed from install time to runtime ones. 8460 8461 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8462 if (ps == null) { 8463 return; 8464 } 8465 8466 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8467 8468 PermissionsState permissionsState = ps.getPermissionsState(); 8469 PermissionsState origPermissions = permissionsState; 8470 8471 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8472 8473 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8474 8475 boolean changedInstallPermission = false; 8476 8477 if (replace) { 8478 ps.installPermissionsFixed = false; 8479 if (!ps.isSharedUser()) { 8480 origPermissions = new PermissionsState(permissionsState); 8481 permissionsState.reset(); 8482 } 8483 } 8484 8485 permissionsState.setGlobalGids(mGlobalGids); 8486 8487 final int N = pkg.requestedPermissions.size(); 8488 for (int i=0; i<N; i++) { 8489 final String name = pkg.requestedPermissions.get(i); 8490 final BasePermission bp = mSettings.mPermissions.get(name); 8491 8492 if (DEBUG_INSTALL) { 8493 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8494 } 8495 8496 if (bp == null || bp.packageSetting == null) { 8497 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8498 Slog.w(TAG, "Unknown permission " + name 8499 + " in package " + pkg.packageName); 8500 } 8501 continue; 8502 } 8503 8504 final String perm = bp.name; 8505 boolean allowedSig = false; 8506 int grant = GRANT_DENIED; 8507 8508 // Keep track of app op permissions. 8509 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8510 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8511 if (pkgs == null) { 8512 pkgs = new ArraySet<>(); 8513 mAppOpPermissionPackages.put(bp.name, pkgs); 8514 } 8515 pkgs.add(pkg.packageName); 8516 } 8517 8518 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8519 switch (level) { 8520 case PermissionInfo.PROTECTION_NORMAL: { 8521 // For all apps normal permissions are install time ones. 8522 grant = GRANT_INSTALL; 8523 } break; 8524 8525 case PermissionInfo.PROTECTION_DANGEROUS: { 8526 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8527 // For legacy apps dangerous permissions are install time ones. 8528 grant = GRANT_INSTALL_LEGACY; 8529 } else if (origPermissions.hasInstallPermission(bp.name)) { 8530 // For legacy apps that became modern, install becomes runtime. 8531 grant = GRANT_UPGRADE; 8532 } else if (mPromoteSystemApps 8533 && isSystemApp(ps) 8534 && mExistingSystemPackages.contains(ps.name)) { 8535 // For legacy system apps, install becomes runtime. 8536 // We cannot check hasInstallPermission() for system apps since those 8537 // permissions were granted implicitly and not persisted pre-M. 8538 grant = GRANT_UPGRADE; 8539 } else { 8540 // For modern apps keep runtime permissions unchanged. 8541 grant = GRANT_RUNTIME; 8542 } 8543 } break; 8544 8545 case PermissionInfo.PROTECTION_SIGNATURE: { 8546 // For all apps signature permissions are install time ones. 8547 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8548 if (allowedSig) { 8549 grant = GRANT_INSTALL; 8550 } 8551 } break; 8552 } 8553 8554 if (DEBUG_INSTALL) { 8555 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8556 } 8557 8558 if (grant != GRANT_DENIED) { 8559 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8560 // If this is an existing, non-system package, then 8561 // we can't add any new permissions to it. 8562 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8563 // Except... if this is a permission that was added 8564 // to the platform (note: need to only do this when 8565 // updating the platform). 8566 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8567 grant = GRANT_DENIED; 8568 } 8569 } 8570 } 8571 8572 switch (grant) { 8573 case GRANT_INSTALL: { 8574 // Revoke this as runtime permission to handle the case of 8575 // a runtime permission being downgraded to an install one. 8576 for (int userId : UserManagerService.getInstance().getUserIds()) { 8577 if (origPermissions.getRuntimePermissionState( 8578 bp.name, userId) != null) { 8579 // Revoke the runtime permission and clear the flags. 8580 origPermissions.revokeRuntimePermission(bp, userId); 8581 origPermissions.updatePermissionFlags(bp, userId, 8582 PackageManager.MASK_PERMISSION_FLAGS, 0); 8583 // If we revoked a permission permission, we have to write. 8584 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8585 changedRuntimePermissionUserIds, userId); 8586 } 8587 } 8588 // Grant an install permission. 8589 if (permissionsState.grantInstallPermission(bp) != 8590 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8591 changedInstallPermission = true; 8592 } 8593 } break; 8594 8595 case GRANT_INSTALL_LEGACY: { 8596 // Grant an install permission. 8597 if (permissionsState.grantInstallPermission(bp) != 8598 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8599 changedInstallPermission = true; 8600 } 8601 } break; 8602 8603 case GRANT_RUNTIME: { 8604 // Grant previously granted runtime permissions. 8605 for (int userId : UserManagerService.getInstance().getUserIds()) { 8606 PermissionState permissionState = origPermissions 8607 .getRuntimePermissionState(bp.name, userId); 8608 final int flags = permissionState != null 8609 ? permissionState.getFlags() : 0; 8610 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8611 if (permissionsState.grantRuntimePermission(bp, userId) == 8612 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8613 // If we cannot put the permission as it was, we have to write. 8614 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8615 changedRuntimePermissionUserIds, userId); 8616 } 8617 } 8618 // Propagate the permission flags. 8619 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8620 } 8621 } break; 8622 8623 case GRANT_UPGRADE: { 8624 // Grant runtime permissions for a previously held install permission. 8625 PermissionState permissionState = origPermissions 8626 .getInstallPermissionState(bp.name); 8627 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8628 8629 if (origPermissions.revokeInstallPermission(bp) 8630 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8631 // We will be transferring the permission flags, so clear them. 8632 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8633 PackageManager.MASK_PERMISSION_FLAGS, 0); 8634 changedInstallPermission = true; 8635 } 8636 8637 // If the permission is not to be promoted to runtime we ignore it and 8638 // also its other flags as they are not applicable to install permissions. 8639 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8640 for (int userId : currentUserIds) { 8641 if (permissionsState.grantRuntimePermission(bp, userId) != 8642 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8643 // Transfer the permission flags. 8644 permissionsState.updatePermissionFlags(bp, userId, 8645 flags, flags); 8646 // If we granted the permission, we have to write. 8647 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8648 changedRuntimePermissionUserIds, userId); 8649 } 8650 } 8651 } 8652 } break; 8653 8654 default: { 8655 if (packageOfInterest == null 8656 || packageOfInterest.equals(pkg.packageName)) { 8657 Slog.w(TAG, "Not granting permission " + perm 8658 + " to package " + pkg.packageName 8659 + " because it was previously installed without"); 8660 } 8661 } break; 8662 } 8663 } else { 8664 if (permissionsState.revokeInstallPermission(bp) != 8665 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8666 // Also drop the permission flags. 8667 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8668 PackageManager.MASK_PERMISSION_FLAGS, 0); 8669 changedInstallPermission = true; 8670 Slog.i(TAG, "Un-granting permission " + perm 8671 + " from package " + pkg.packageName 8672 + " (protectionLevel=" + bp.protectionLevel 8673 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8674 + ")"); 8675 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8676 // Don't print warning for app op permissions, since it is fine for them 8677 // not to be granted, there is a UI for the user to decide. 8678 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8679 Slog.w(TAG, "Not granting permission " + perm 8680 + " to package " + pkg.packageName 8681 + " (protectionLevel=" + bp.protectionLevel 8682 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8683 + ")"); 8684 } 8685 } 8686 } 8687 } 8688 8689 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8690 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8691 // This is the first that we have heard about this package, so the 8692 // permissions we have now selected are fixed until explicitly 8693 // changed. 8694 ps.installPermissionsFixed = true; 8695 } 8696 8697 // Persist the runtime permissions state for users with changes. 8698 for (int userId : changedRuntimePermissionUserIds) { 8699 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8700 } 8701 8702 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8703 } 8704 8705 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8706 boolean allowed = false; 8707 final int NP = PackageParser.NEW_PERMISSIONS.length; 8708 for (int ip=0; ip<NP; ip++) { 8709 final PackageParser.NewPermissionInfo npi 8710 = PackageParser.NEW_PERMISSIONS[ip]; 8711 if (npi.name.equals(perm) 8712 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8713 allowed = true; 8714 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8715 + pkg.packageName); 8716 break; 8717 } 8718 } 8719 return allowed; 8720 } 8721 8722 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8723 BasePermission bp, PermissionsState origPermissions) { 8724 boolean allowed; 8725 allowed = (compareSignatures( 8726 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8727 == PackageManager.SIGNATURE_MATCH) 8728 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8729 == PackageManager.SIGNATURE_MATCH); 8730 if (!allowed && (bp.protectionLevel 8731 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8732 if (isSystemApp(pkg)) { 8733 // For updated system applications, a system permission 8734 // is granted only if it had been defined by the original application. 8735 if (pkg.isUpdatedSystemApp()) { 8736 final PackageSetting sysPs = mSettings 8737 .getDisabledSystemPkgLPr(pkg.packageName); 8738 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8739 // If the original was granted this permission, we take 8740 // that grant decision as read and propagate it to the 8741 // update. 8742 if (sysPs.isPrivileged()) { 8743 allowed = true; 8744 } 8745 } else { 8746 // The system apk may have been updated with an older 8747 // version of the one on the data partition, but which 8748 // granted a new system permission that it didn't have 8749 // before. In this case we do want to allow the app to 8750 // now get the new permission if the ancestral apk is 8751 // privileged to get it. 8752 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8753 for (int j=0; 8754 j<sysPs.pkg.requestedPermissions.size(); j++) { 8755 if (perm.equals( 8756 sysPs.pkg.requestedPermissions.get(j))) { 8757 allowed = true; 8758 break; 8759 } 8760 } 8761 } 8762 } 8763 } else { 8764 allowed = isPrivilegedApp(pkg); 8765 } 8766 } 8767 } 8768 if (!allowed) { 8769 if (!allowed && (bp.protectionLevel 8770 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8771 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8772 // If this was a previously normal/dangerous permission that got moved 8773 // to a system permission as part of the runtime permission redesign, then 8774 // we still want to blindly grant it to old apps. 8775 allowed = true; 8776 } 8777 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8778 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8779 // If this permission is to be granted to the system installer and 8780 // this app is an installer, then it gets the permission. 8781 allowed = true; 8782 } 8783 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8784 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8785 // If this permission is to be granted to the system verifier and 8786 // this app is a verifier, then it gets the permission. 8787 allowed = true; 8788 } 8789 if (!allowed && (bp.protectionLevel 8790 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8791 && isSystemApp(pkg)) { 8792 // Any pre-installed system app is allowed to get this permission. 8793 allowed = true; 8794 } 8795 if (!allowed && (bp.protectionLevel 8796 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8797 // For development permissions, a development permission 8798 // is granted only if it was already granted. 8799 allowed = origPermissions.hasInstallPermission(perm); 8800 } 8801 } 8802 return allowed; 8803 } 8804 8805 final class ActivityIntentResolver 8806 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8807 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8808 boolean defaultOnly, int userId) { 8809 if (!sUserManager.exists(userId)) return null; 8810 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8811 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8812 } 8813 8814 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8815 int userId) { 8816 if (!sUserManager.exists(userId)) return null; 8817 mFlags = flags; 8818 return super.queryIntent(intent, resolvedType, 8819 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8820 } 8821 8822 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8823 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8824 if (!sUserManager.exists(userId)) return null; 8825 if (packageActivities == null) { 8826 return null; 8827 } 8828 mFlags = flags; 8829 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8830 final int N = packageActivities.size(); 8831 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8832 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8833 8834 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8835 for (int i = 0; i < N; ++i) { 8836 intentFilters = packageActivities.get(i).intents; 8837 if (intentFilters != null && intentFilters.size() > 0) { 8838 PackageParser.ActivityIntentInfo[] array = 8839 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8840 intentFilters.toArray(array); 8841 listCut.add(array); 8842 } 8843 } 8844 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8845 } 8846 8847 public final void addActivity(PackageParser.Activity a, String type) { 8848 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8849 mActivities.put(a.getComponentName(), a); 8850 if (DEBUG_SHOW_INFO) 8851 Log.v( 8852 TAG, " " + type + " " + 8853 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8854 if (DEBUG_SHOW_INFO) 8855 Log.v(TAG, " Class=" + a.info.name); 8856 final int NI = a.intents.size(); 8857 for (int j=0; j<NI; j++) { 8858 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8859 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8860 intent.setPriority(0); 8861 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8862 + a.className + " with priority > 0, forcing to 0"); 8863 } 8864 if (DEBUG_SHOW_INFO) { 8865 Log.v(TAG, " IntentFilter:"); 8866 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8867 } 8868 if (!intent.debugCheck()) { 8869 Log.w(TAG, "==> For Activity " + a.info.name); 8870 } 8871 addFilter(intent); 8872 } 8873 } 8874 8875 public final void removeActivity(PackageParser.Activity a, String type) { 8876 mActivities.remove(a.getComponentName()); 8877 if (DEBUG_SHOW_INFO) { 8878 Log.v(TAG, " " + type + " " 8879 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8880 : a.info.name) + ":"); 8881 Log.v(TAG, " Class=" + a.info.name); 8882 } 8883 final int NI = a.intents.size(); 8884 for (int j=0; j<NI; j++) { 8885 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8886 if (DEBUG_SHOW_INFO) { 8887 Log.v(TAG, " IntentFilter:"); 8888 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8889 } 8890 removeFilter(intent); 8891 } 8892 } 8893 8894 @Override 8895 protected boolean allowFilterResult( 8896 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8897 ActivityInfo filterAi = filter.activity.info; 8898 for (int i=dest.size()-1; i>=0; i--) { 8899 ActivityInfo destAi = dest.get(i).activityInfo; 8900 if (destAi.name == filterAi.name 8901 && destAi.packageName == filterAi.packageName) { 8902 return false; 8903 } 8904 } 8905 return true; 8906 } 8907 8908 @Override 8909 protected ActivityIntentInfo[] newArray(int size) { 8910 return new ActivityIntentInfo[size]; 8911 } 8912 8913 @Override 8914 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8915 if (!sUserManager.exists(userId)) return true; 8916 PackageParser.Package p = filter.activity.owner; 8917 if (p != null) { 8918 PackageSetting ps = (PackageSetting)p.mExtras; 8919 if (ps != null) { 8920 // System apps are never considered stopped for purposes of 8921 // filtering, because there may be no way for the user to 8922 // actually re-launch them. 8923 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8924 && ps.getStopped(userId); 8925 } 8926 } 8927 return false; 8928 } 8929 8930 @Override 8931 protected boolean isPackageForFilter(String packageName, 8932 PackageParser.ActivityIntentInfo info) { 8933 return packageName.equals(info.activity.owner.packageName); 8934 } 8935 8936 @Override 8937 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8938 int match, int userId) { 8939 if (!sUserManager.exists(userId)) return null; 8940 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8941 return null; 8942 } 8943 final PackageParser.Activity activity = info.activity; 8944 if (mSafeMode && (activity.info.applicationInfo.flags 8945 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8946 return null; 8947 } 8948 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8949 if (ps == null) { 8950 return null; 8951 } 8952 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8953 ps.readUserState(userId), userId); 8954 if (ai == null) { 8955 return null; 8956 } 8957 final ResolveInfo res = new ResolveInfo(); 8958 res.activityInfo = ai; 8959 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8960 res.filter = info; 8961 } 8962 if (info != null) { 8963 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8964 } 8965 res.priority = info.getPriority(); 8966 res.preferredOrder = activity.owner.mPreferredOrder; 8967 //System.out.println("Result: " + res.activityInfo.className + 8968 // " = " + res.priority); 8969 res.match = match; 8970 res.isDefault = info.hasDefault; 8971 res.labelRes = info.labelRes; 8972 res.nonLocalizedLabel = info.nonLocalizedLabel; 8973 if (userNeedsBadging(userId)) { 8974 res.noResourceId = true; 8975 } else { 8976 res.icon = info.icon; 8977 } 8978 res.iconResourceId = info.icon; 8979 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8980 return res; 8981 } 8982 8983 @Override 8984 protected void sortResults(List<ResolveInfo> results) { 8985 Collections.sort(results, mResolvePrioritySorter); 8986 } 8987 8988 @Override 8989 protected void dumpFilter(PrintWriter out, String prefix, 8990 PackageParser.ActivityIntentInfo filter) { 8991 out.print(prefix); out.print( 8992 Integer.toHexString(System.identityHashCode(filter.activity))); 8993 out.print(' '); 8994 filter.activity.printComponentShortName(out); 8995 out.print(" filter "); 8996 out.println(Integer.toHexString(System.identityHashCode(filter))); 8997 } 8998 8999 @Override 9000 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9001 return filter.activity; 9002 } 9003 9004 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9005 PackageParser.Activity activity = (PackageParser.Activity)label; 9006 out.print(prefix); out.print( 9007 Integer.toHexString(System.identityHashCode(activity))); 9008 out.print(' '); 9009 activity.printComponentShortName(out); 9010 if (count > 1) { 9011 out.print(" ("); out.print(count); out.print(" filters)"); 9012 } 9013 out.println(); 9014 } 9015 9016// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9017// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9018// final List<ResolveInfo> retList = Lists.newArrayList(); 9019// while (i.hasNext()) { 9020// final ResolveInfo resolveInfo = i.next(); 9021// if (isEnabledLP(resolveInfo.activityInfo)) { 9022// retList.add(resolveInfo); 9023// } 9024// } 9025// return retList; 9026// } 9027 9028 // Keys are String (activity class name), values are Activity. 9029 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9030 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9031 private int mFlags; 9032 } 9033 9034 private final class ServiceIntentResolver 9035 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9036 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9037 boolean defaultOnly, int userId) { 9038 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9039 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9040 } 9041 9042 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9043 int userId) { 9044 if (!sUserManager.exists(userId)) return null; 9045 mFlags = flags; 9046 return super.queryIntent(intent, resolvedType, 9047 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9048 } 9049 9050 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9051 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9052 if (!sUserManager.exists(userId)) return null; 9053 if (packageServices == null) { 9054 return null; 9055 } 9056 mFlags = flags; 9057 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9058 final int N = packageServices.size(); 9059 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9060 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9061 9062 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9063 for (int i = 0; i < N; ++i) { 9064 intentFilters = packageServices.get(i).intents; 9065 if (intentFilters != null && intentFilters.size() > 0) { 9066 PackageParser.ServiceIntentInfo[] array = 9067 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9068 intentFilters.toArray(array); 9069 listCut.add(array); 9070 } 9071 } 9072 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9073 } 9074 9075 public final void addService(PackageParser.Service s) { 9076 mServices.put(s.getComponentName(), s); 9077 if (DEBUG_SHOW_INFO) { 9078 Log.v(TAG, " " 9079 + (s.info.nonLocalizedLabel != null 9080 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9081 Log.v(TAG, " Class=" + s.info.name); 9082 } 9083 final int NI = s.intents.size(); 9084 int j; 9085 for (j=0; j<NI; j++) { 9086 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9087 if (DEBUG_SHOW_INFO) { 9088 Log.v(TAG, " IntentFilter:"); 9089 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9090 } 9091 if (!intent.debugCheck()) { 9092 Log.w(TAG, "==> For Service " + s.info.name); 9093 } 9094 addFilter(intent); 9095 } 9096 } 9097 9098 public final void removeService(PackageParser.Service s) { 9099 mServices.remove(s.getComponentName()); 9100 if (DEBUG_SHOW_INFO) { 9101 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9102 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9103 Log.v(TAG, " Class=" + s.info.name); 9104 } 9105 final int NI = s.intents.size(); 9106 int j; 9107 for (j=0; j<NI; j++) { 9108 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9109 if (DEBUG_SHOW_INFO) { 9110 Log.v(TAG, " IntentFilter:"); 9111 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9112 } 9113 removeFilter(intent); 9114 } 9115 } 9116 9117 @Override 9118 protected boolean allowFilterResult( 9119 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9120 ServiceInfo filterSi = filter.service.info; 9121 for (int i=dest.size()-1; i>=0; i--) { 9122 ServiceInfo destAi = dest.get(i).serviceInfo; 9123 if (destAi.name == filterSi.name 9124 && destAi.packageName == filterSi.packageName) { 9125 return false; 9126 } 9127 } 9128 return true; 9129 } 9130 9131 @Override 9132 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9133 return new PackageParser.ServiceIntentInfo[size]; 9134 } 9135 9136 @Override 9137 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9138 if (!sUserManager.exists(userId)) return true; 9139 PackageParser.Package p = filter.service.owner; 9140 if (p != null) { 9141 PackageSetting ps = (PackageSetting)p.mExtras; 9142 if (ps != null) { 9143 // System apps are never considered stopped for purposes of 9144 // filtering, because there may be no way for the user to 9145 // actually re-launch them. 9146 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9147 && ps.getStopped(userId); 9148 } 9149 } 9150 return false; 9151 } 9152 9153 @Override 9154 protected boolean isPackageForFilter(String packageName, 9155 PackageParser.ServiceIntentInfo info) { 9156 return packageName.equals(info.service.owner.packageName); 9157 } 9158 9159 @Override 9160 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9161 int match, int userId) { 9162 if (!sUserManager.exists(userId)) return null; 9163 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9164 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9165 return null; 9166 } 9167 final PackageParser.Service service = info.service; 9168 if (mSafeMode && (service.info.applicationInfo.flags 9169 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9170 return null; 9171 } 9172 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9173 if (ps == null) { 9174 return null; 9175 } 9176 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9177 ps.readUserState(userId), userId); 9178 if (si == null) { 9179 return null; 9180 } 9181 final ResolveInfo res = new ResolveInfo(); 9182 res.serviceInfo = si; 9183 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9184 res.filter = filter; 9185 } 9186 res.priority = info.getPriority(); 9187 res.preferredOrder = service.owner.mPreferredOrder; 9188 res.match = match; 9189 res.isDefault = info.hasDefault; 9190 res.labelRes = info.labelRes; 9191 res.nonLocalizedLabel = info.nonLocalizedLabel; 9192 res.icon = info.icon; 9193 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9194 return res; 9195 } 9196 9197 @Override 9198 protected void sortResults(List<ResolveInfo> results) { 9199 Collections.sort(results, mResolvePrioritySorter); 9200 } 9201 9202 @Override 9203 protected void dumpFilter(PrintWriter out, String prefix, 9204 PackageParser.ServiceIntentInfo filter) { 9205 out.print(prefix); out.print( 9206 Integer.toHexString(System.identityHashCode(filter.service))); 9207 out.print(' '); 9208 filter.service.printComponentShortName(out); 9209 out.print(" filter "); 9210 out.println(Integer.toHexString(System.identityHashCode(filter))); 9211 } 9212 9213 @Override 9214 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9215 return filter.service; 9216 } 9217 9218 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9219 PackageParser.Service service = (PackageParser.Service)label; 9220 out.print(prefix); out.print( 9221 Integer.toHexString(System.identityHashCode(service))); 9222 out.print(' '); 9223 service.printComponentShortName(out); 9224 if (count > 1) { 9225 out.print(" ("); out.print(count); out.print(" filters)"); 9226 } 9227 out.println(); 9228 } 9229 9230// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9231// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9232// final List<ResolveInfo> retList = Lists.newArrayList(); 9233// while (i.hasNext()) { 9234// final ResolveInfo resolveInfo = (ResolveInfo) i; 9235// if (isEnabledLP(resolveInfo.serviceInfo)) { 9236// retList.add(resolveInfo); 9237// } 9238// } 9239// return retList; 9240// } 9241 9242 // Keys are String (activity class name), values are Activity. 9243 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9244 = new ArrayMap<ComponentName, PackageParser.Service>(); 9245 private int mFlags; 9246 }; 9247 9248 private final class ProviderIntentResolver 9249 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9250 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9251 boolean defaultOnly, int userId) { 9252 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9253 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9254 } 9255 9256 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9257 int userId) { 9258 if (!sUserManager.exists(userId)) 9259 return null; 9260 mFlags = flags; 9261 return super.queryIntent(intent, resolvedType, 9262 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9263 } 9264 9265 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9266 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9267 if (!sUserManager.exists(userId)) 9268 return null; 9269 if (packageProviders == null) { 9270 return null; 9271 } 9272 mFlags = flags; 9273 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9274 final int N = packageProviders.size(); 9275 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9276 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9277 9278 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9279 for (int i = 0; i < N; ++i) { 9280 intentFilters = packageProviders.get(i).intents; 9281 if (intentFilters != null && intentFilters.size() > 0) { 9282 PackageParser.ProviderIntentInfo[] array = 9283 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9284 intentFilters.toArray(array); 9285 listCut.add(array); 9286 } 9287 } 9288 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9289 } 9290 9291 public final void addProvider(PackageParser.Provider p) { 9292 if (mProviders.containsKey(p.getComponentName())) { 9293 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9294 return; 9295 } 9296 9297 mProviders.put(p.getComponentName(), p); 9298 if (DEBUG_SHOW_INFO) { 9299 Log.v(TAG, " " 9300 + (p.info.nonLocalizedLabel != null 9301 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9302 Log.v(TAG, " Class=" + p.info.name); 9303 } 9304 final int NI = p.intents.size(); 9305 int j; 9306 for (j = 0; j < NI; j++) { 9307 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9308 if (DEBUG_SHOW_INFO) { 9309 Log.v(TAG, " IntentFilter:"); 9310 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9311 } 9312 if (!intent.debugCheck()) { 9313 Log.w(TAG, "==> For Provider " + p.info.name); 9314 } 9315 addFilter(intent); 9316 } 9317 } 9318 9319 public final void removeProvider(PackageParser.Provider p) { 9320 mProviders.remove(p.getComponentName()); 9321 if (DEBUG_SHOW_INFO) { 9322 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9323 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9324 Log.v(TAG, " Class=" + p.info.name); 9325 } 9326 final int NI = p.intents.size(); 9327 int j; 9328 for (j = 0; j < NI; j++) { 9329 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9330 if (DEBUG_SHOW_INFO) { 9331 Log.v(TAG, " IntentFilter:"); 9332 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9333 } 9334 removeFilter(intent); 9335 } 9336 } 9337 9338 @Override 9339 protected boolean allowFilterResult( 9340 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9341 ProviderInfo filterPi = filter.provider.info; 9342 for (int i = dest.size() - 1; i >= 0; i--) { 9343 ProviderInfo destPi = dest.get(i).providerInfo; 9344 if (destPi.name == filterPi.name 9345 && destPi.packageName == filterPi.packageName) { 9346 return false; 9347 } 9348 } 9349 return true; 9350 } 9351 9352 @Override 9353 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9354 return new PackageParser.ProviderIntentInfo[size]; 9355 } 9356 9357 @Override 9358 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9359 if (!sUserManager.exists(userId)) 9360 return true; 9361 PackageParser.Package p = filter.provider.owner; 9362 if (p != null) { 9363 PackageSetting ps = (PackageSetting) p.mExtras; 9364 if (ps != null) { 9365 // System apps are never considered stopped for purposes of 9366 // filtering, because there may be no way for the user to 9367 // actually re-launch them. 9368 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9369 && ps.getStopped(userId); 9370 } 9371 } 9372 return false; 9373 } 9374 9375 @Override 9376 protected boolean isPackageForFilter(String packageName, 9377 PackageParser.ProviderIntentInfo info) { 9378 return packageName.equals(info.provider.owner.packageName); 9379 } 9380 9381 @Override 9382 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9383 int match, int userId) { 9384 if (!sUserManager.exists(userId)) 9385 return null; 9386 final PackageParser.ProviderIntentInfo info = filter; 9387 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9388 return null; 9389 } 9390 final PackageParser.Provider provider = info.provider; 9391 if (mSafeMode && (provider.info.applicationInfo.flags 9392 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9393 return null; 9394 } 9395 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9396 if (ps == null) { 9397 return null; 9398 } 9399 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9400 ps.readUserState(userId), userId); 9401 if (pi == null) { 9402 return null; 9403 } 9404 final ResolveInfo res = new ResolveInfo(); 9405 res.providerInfo = pi; 9406 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9407 res.filter = filter; 9408 } 9409 res.priority = info.getPriority(); 9410 res.preferredOrder = provider.owner.mPreferredOrder; 9411 res.match = match; 9412 res.isDefault = info.hasDefault; 9413 res.labelRes = info.labelRes; 9414 res.nonLocalizedLabel = info.nonLocalizedLabel; 9415 res.icon = info.icon; 9416 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9417 return res; 9418 } 9419 9420 @Override 9421 protected void sortResults(List<ResolveInfo> results) { 9422 Collections.sort(results, mResolvePrioritySorter); 9423 } 9424 9425 @Override 9426 protected void dumpFilter(PrintWriter out, String prefix, 9427 PackageParser.ProviderIntentInfo filter) { 9428 out.print(prefix); 9429 out.print( 9430 Integer.toHexString(System.identityHashCode(filter.provider))); 9431 out.print(' '); 9432 filter.provider.printComponentShortName(out); 9433 out.print(" filter "); 9434 out.println(Integer.toHexString(System.identityHashCode(filter))); 9435 } 9436 9437 @Override 9438 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9439 return filter.provider; 9440 } 9441 9442 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9443 PackageParser.Provider provider = (PackageParser.Provider)label; 9444 out.print(prefix); out.print( 9445 Integer.toHexString(System.identityHashCode(provider))); 9446 out.print(' '); 9447 provider.printComponentShortName(out); 9448 if (count > 1) { 9449 out.print(" ("); out.print(count); out.print(" filters)"); 9450 } 9451 out.println(); 9452 } 9453 9454 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9455 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9456 private int mFlags; 9457 }; 9458 9459 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9460 new Comparator<ResolveInfo>() { 9461 public int compare(ResolveInfo r1, ResolveInfo r2) { 9462 int v1 = r1.priority; 9463 int v2 = r2.priority; 9464 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9465 if (v1 != v2) { 9466 return (v1 > v2) ? -1 : 1; 9467 } 9468 v1 = r1.preferredOrder; 9469 v2 = r2.preferredOrder; 9470 if (v1 != v2) { 9471 return (v1 > v2) ? -1 : 1; 9472 } 9473 if (r1.isDefault != r2.isDefault) { 9474 return r1.isDefault ? -1 : 1; 9475 } 9476 v1 = r1.match; 9477 v2 = r2.match; 9478 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9479 if (v1 != v2) { 9480 return (v1 > v2) ? -1 : 1; 9481 } 9482 if (r1.system != r2.system) { 9483 return r1.system ? -1 : 1; 9484 } 9485 return 0; 9486 } 9487 }; 9488 9489 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9490 new Comparator<ProviderInfo>() { 9491 public int compare(ProviderInfo p1, ProviderInfo p2) { 9492 final int v1 = p1.initOrder; 9493 final int v2 = p2.initOrder; 9494 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9495 } 9496 }; 9497 9498 final void sendPackageBroadcast(final String action, final String pkg, 9499 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9500 final int[] userIds) { 9501 mHandler.post(new Runnable() { 9502 @Override 9503 public void run() { 9504 try { 9505 final IActivityManager am = ActivityManagerNative.getDefault(); 9506 if (am == null) return; 9507 final int[] resolvedUserIds; 9508 if (userIds == null) { 9509 resolvedUserIds = am.getRunningUserIds(); 9510 } else { 9511 resolvedUserIds = userIds; 9512 } 9513 for (int id : resolvedUserIds) { 9514 final Intent intent = new Intent(action, 9515 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9516 if (extras != null) { 9517 intent.putExtras(extras); 9518 } 9519 if (targetPkg != null) { 9520 intent.setPackage(targetPkg); 9521 } 9522 // Modify the UID when posting to other users 9523 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9524 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9525 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9526 intent.putExtra(Intent.EXTRA_UID, uid); 9527 } 9528 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9529 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9530 if (DEBUG_BROADCASTS) { 9531 RuntimeException here = new RuntimeException("here"); 9532 here.fillInStackTrace(); 9533 Slog.d(TAG, "Sending to user " + id + ": " 9534 + intent.toShortString(false, true, false, false) 9535 + " " + intent.getExtras(), here); 9536 } 9537 am.broadcastIntent(null, intent, null, finishedReceiver, 9538 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9539 null, finishedReceiver != null, false, id); 9540 } 9541 } catch (RemoteException ex) { 9542 } 9543 } 9544 }); 9545 } 9546 9547 /** 9548 * Check if the external storage media is available. This is true if there 9549 * is a mounted external storage medium or if the external storage is 9550 * emulated. 9551 */ 9552 private boolean isExternalMediaAvailable() { 9553 return mMediaMounted || Environment.isExternalStorageEmulated(); 9554 } 9555 9556 @Override 9557 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9558 // writer 9559 synchronized (mPackages) { 9560 if (!isExternalMediaAvailable()) { 9561 // If the external storage is no longer mounted at this point, 9562 // the caller may not have been able to delete all of this 9563 // packages files and can not delete any more. Bail. 9564 return null; 9565 } 9566 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9567 if (lastPackage != null) { 9568 pkgs.remove(lastPackage); 9569 } 9570 if (pkgs.size() > 0) { 9571 return pkgs.get(0); 9572 } 9573 } 9574 return null; 9575 } 9576 9577 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9578 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9579 userId, andCode ? 1 : 0, packageName); 9580 if (mSystemReady) { 9581 msg.sendToTarget(); 9582 } else { 9583 if (mPostSystemReadyMessages == null) { 9584 mPostSystemReadyMessages = new ArrayList<>(); 9585 } 9586 mPostSystemReadyMessages.add(msg); 9587 } 9588 } 9589 9590 void startCleaningPackages() { 9591 // reader 9592 synchronized (mPackages) { 9593 if (!isExternalMediaAvailable()) { 9594 return; 9595 } 9596 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9597 return; 9598 } 9599 } 9600 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9601 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9602 IActivityManager am = ActivityManagerNative.getDefault(); 9603 if (am != null) { 9604 try { 9605 am.startService(null, intent, null, mContext.getOpPackageName(), 9606 UserHandle.USER_OWNER); 9607 } catch (RemoteException e) { 9608 } 9609 } 9610 } 9611 9612 @Override 9613 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9614 int installFlags, String installerPackageName, VerificationParams verificationParams, 9615 String packageAbiOverride) { 9616 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9617 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9618 } 9619 9620 @Override 9621 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9622 int installFlags, String installerPackageName, VerificationParams verificationParams, 9623 String packageAbiOverride, int userId) { 9624 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9625 9626 final int callingUid = Binder.getCallingUid(); 9627 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9628 9629 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9630 try { 9631 if (observer != null) { 9632 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9633 } 9634 } catch (RemoteException re) { 9635 } 9636 return; 9637 } 9638 9639 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9640 installFlags |= PackageManager.INSTALL_FROM_ADB; 9641 9642 } else { 9643 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9644 // about installerPackageName. 9645 9646 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9647 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9648 } 9649 9650 UserHandle user; 9651 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9652 user = UserHandle.ALL; 9653 } else { 9654 user = new UserHandle(userId); 9655 } 9656 9657 // Only system components can circumvent runtime permissions when installing. 9658 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9659 && mContext.checkCallingOrSelfPermission(Manifest.permission 9660 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9661 throw new SecurityException("You need the " 9662 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9663 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9664 } 9665 9666 verificationParams.setInstallerUid(callingUid); 9667 9668 final File originFile = new File(originPath); 9669 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9670 9671 final Message msg = mHandler.obtainMessage(INIT_COPY); 9672 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9673 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9674 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9675 msg.obj = params; 9676 9677 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9678 System.identityHashCode(msg.obj)); 9679 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9680 System.identityHashCode(msg.obj)); 9681 9682 mHandler.sendMessage(msg); 9683 } 9684 9685 void installStage(String packageName, File stagedDir, String stagedCid, 9686 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9687 String installerPackageName, int installerUid, UserHandle user) { 9688 final VerificationParams verifParams = new VerificationParams( 9689 null, sessionParams.originatingUri, sessionParams.referrerUri, 9690 sessionParams.originatingUid, null); 9691 verifParams.setInstallerUid(installerUid); 9692 9693 final OriginInfo origin; 9694 if (stagedDir != null) { 9695 origin = OriginInfo.fromStagedFile(stagedDir); 9696 } else { 9697 origin = OriginInfo.fromStagedContainer(stagedCid); 9698 } 9699 9700 final Message msg = mHandler.obtainMessage(INIT_COPY); 9701 final InstallParams params = new InstallParams(origin, null, observer, 9702 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9703 verifParams, user, sessionParams.abiOverride, 9704 sessionParams.grantedRuntimePermissions); 9705 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9706 msg.obj = params; 9707 9708 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9709 System.identityHashCode(msg.obj)); 9710 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9711 System.identityHashCode(msg.obj)); 9712 9713 mHandler.sendMessage(msg); 9714 } 9715 9716 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9717 Bundle extras = new Bundle(1); 9718 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9719 9720 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9721 packageName, extras, null, null, new int[] {userId}); 9722 try { 9723 IActivityManager am = ActivityManagerNative.getDefault(); 9724 final boolean isSystem = 9725 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9726 if (isSystem && am.isUserRunning(userId, false)) { 9727 // The just-installed/enabled app is bundled on the system, so presumed 9728 // to be able to run automatically without needing an explicit launch. 9729 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9730 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9731 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9732 .setPackage(packageName); 9733 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9734 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9735 } 9736 } catch (RemoteException e) { 9737 // shouldn't happen 9738 Slog.w(TAG, "Unable to bootstrap installed package", e); 9739 } 9740 } 9741 9742 @Override 9743 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9744 int userId) { 9745 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9746 PackageSetting pkgSetting; 9747 final int uid = Binder.getCallingUid(); 9748 enforceCrossUserPermission(uid, userId, true, true, 9749 "setApplicationHiddenSetting for user " + userId); 9750 9751 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9752 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9753 return false; 9754 } 9755 9756 long callingId = Binder.clearCallingIdentity(); 9757 try { 9758 boolean sendAdded = false; 9759 boolean sendRemoved = false; 9760 // writer 9761 synchronized (mPackages) { 9762 pkgSetting = mSettings.mPackages.get(packageName); 9763 if (pkgSetting == null) { 9764 return false; 9765 } 9766 if (pkgSetting.getHidden(userId) != hidden) { 9767 pkgSetting.setHidden(hidden, userId); 9768 mSettings.writePackageRestrictionsLPr(userId); 9769 if (hidden) { 9770 sendRemoved = true; 9771 } else { 9772 sendAdded = true; 9773 } 9774 } 9775 } 9776 if (sendAdded) { 9777 sendPackageAddedForUser(packageName, pkgSetting, userId); 9778 return true; 9779 } 9780 if (sendRemoved) { 9781 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9782 "hiding pkg"); 9783 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9784 return true; 9785 } 9786 } finally { 9787 Binder.restoreCallingIdentity(callingId); 9788 } 9789 return false; 9790 } 9791 9792 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9793 int userId) { 9794 final PackageRemovedInfo info = new PackageRemovedInfo(); 9795 info.removedPackage = packageName; 9796 info.removedUsers = new int[] {userId}; 9797 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9798 info.sendBroadcast(false, false, false); 9799 } 9800 9801 /** 9802 * Returns true if application is not found or there was an error. Otherwise it returns 9803 * the hidden state of the package for the given user. 9804 */ 9805 @Override 9806 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9807 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9808 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9809 false, "getApplicationHidden for user " + userId); 9810 PackageSetting pkgSetting; 9811 long callingId = Binder.clearCallingIdentity(); 9812 try { 9813 // writer 9814 synchronized (mPackages) { 9815 pkgSetting = mSettings.mPackages.get(packageName); 9816 if (pkgSetting == null) { 9817 return true; 9818 } 9819 return pkgSetting.getHidden(userId); 9820 } 9821 } finally { 9822 Binder.restoreCallingIdentity(callingId); 9823 } 9824 } 9825 9826 /** 9827 * @hide 9828 */ 9829 @Override 9830 public int installExistingPackageAsUser(String packageName, int userId) { 9831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9832 null); 9833 PackageSetting pkgSetting; 9834 final int uid = Binder.getCallingUid(); 9835 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9836 + userId); 9837 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9838 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9839 } 9840 9841 long callingId = Binder.clearCallingIdentity(); 9842 try { 9843 boolean sendAdded = false; 9844 9845 // writer 9846 synchronized (mPackages) { 9847 pkgSetting = mSettings.mPackages.get(packageName); 9848 if (pkgSetting == null) { 9849 return PackageManager.INSTALL_FAILED_INVALID_URI; 9850 } 9851 if (!pkgSetting.getInstalled(userId)) { 9852 pkgSetting.setInstalled(true, userId); 9853 pkgSetting.setHidden(false, userId); 9854 mSettings.writePackageRestrictionsLPr(userId); 9855 sendAdded = true; 9856 } 9857 } 9858 9859 if (sendAdded) { 9860 sendPackageAddedForUser(packageName, pkgSetting, userId); 9861 } 9862 } finally { 9863 Binder.restoreCallingIdentity(callingId); 9864 } 9865 9866 return PackageManager.INSTALL_SUCCEEDED; 9867 } 9868 9869 boolean isUserRestricted(int userId, String restrictionKey) { 9870 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9871 if (restrictions.getBoolean(restrictionKey, false)) { 9872 Log.w(TAG, "User is restricted: " + restrictionKey); 9873 return true; 9874 } 9875 return false; 9876 } 9877 9878 @Override 9879 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9880 mContext.enforceCallingOrSelfPermission( 9881 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9882 "Only package verification agents can verify applications"); 9883 9884 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9885 final PackageVerificationResponse response = new PackageVerificationResponse( 9886 verificationCode, Binder.getCallingUid()); 9887 msg.arg1 = id; 9888 msg.obj = response; 9889 mHandler.sendMessage(msg); 9890 } 9891 9892 @Override 9893 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9894 long millisecondsToDelay) { 9895 mContext.enforceCallingOrSelfPermission( 9896 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9897 "Only package verification agents can extend verification timeouts"); 9898 9899 final PackageVerificationState state = mPendingVerification.get(id); 9900 final PackageVerificationResponse response = new PackageVerificationResponse( 9901 verificationCodeAtTimeout, Binder.getCallingUid()); 9902 9903 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9904 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9905 } 9906 if (millisecondsToDelay < 0) { 9907 millisecondsToDelay = 0; 9908 } 9909 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9910 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9911 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9912 } 9913 9914 if ((state != null) && !state.timeoutExtended()) { 9915 state.extendTimeout(); 9916 9917 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9918 msg.arg1 = id; 9919 msg.obj = response; 9920 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9921 } 9922 } 9923 9924 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9925 int verificationCode, UserHandle user) { 9926 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9927 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9928 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9929 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9930 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9931 9932 mContext.sendBroadcastAsUser(intent, user, 9933 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9934 } 9935 9936 private ComponentName matchComponentForVerifier(String packageName, 9937 List<ResolveInfo> receivers) { 9938 ActivityInfo targetReceiver = null; 9939 9940 final int NR = receivers.size(); 9941 for (int i = 0; i < NR; i++) { 9942 final ResolveInfo info = receivers.get(i); 9943 if (info.activityInfo == null) { 9944 continue; 9945 } 9946 9947 if (packageName.equals(info.activityInfo.packageName)) { 9948 targetReceiver = info.activityInfo; 9949 break; 9950 } 9951 } 9952 9953 if (targetReceiver == null) { 9954 return null; 9955 } 9956 9957 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9958 } 9959 9960 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9961 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9962 if (pkgInfo.verifiers.length == 0) { 9963 return null; 9964 } 9965 9966 final int N = pkgInfo.verifiers.length; 9967 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9968 for (int i = 0; i < N; i++) { 9969 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9970 9971 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9972 receivers); 9973 if (comp == null) { 9974 continue; 9975 } 9976 9977 final int verifierUid = getUidForVerifier(verifierInfo); 9978 if (verifierUid == -1) { 9979 continue; 9980 } 9981 9982 if (DEBUG_VERIFY) { 9983 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9984 + " with the correct signature"); 9985 } 9986 sufficientVerifiers.add(comp); 9987 verificationState.addSufficientVerifier(verifierUid); 9988 } 9989 9990 return sufficientVerifiers; 9991 } 9992 9993 private int getUidForVerifier(VerifierInfo verifierInfo) { 9994 synchronized (mPackages) { 9995 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9996 if (pkg == null) { 9997 return -1; 9998 } else if (pkg.mSignatures.length != 1) { 9999 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10000 + " has more than one signature; ignoring"); 10001 return -1; 10002 } 10003 10004 /* 10005 * If the public key of the package's signature does not match 10006 * our expected public key, then this is a different package and 10007 * we should skip. 10008 */ 10009 10010 final byte[] expectedPublicKey; 10011 try { 10012 final Signature verifierSig = pkg.mSignatures[0]; 10013 final PublicKey publicKey = verifierSig.getPublicKey(); 10014 expectedPublicKey = publicKey.getEncoded(); 10015 } catch (CertificateException e) { 10016 return -1; 10017 } 10018 10019 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10020 10021 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10022 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10023 + " does not have the expected public key; ignoring"); 10024 return -1; 10025 } 10026 10027 return pkg.applicationInfo.uid; 10028 } 10029 } 10030 10031 @Override 10032 public void finishPackageInstall(int token) { 10033 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10034 10035 if (DEBUG_INSTALL) { 10036 Slog.v(TAG, "BM finishing package install for " + token); 10037 } 10038 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10039 10040 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10041 mHandler.sendMessage(msg); 10042 } 10043 10044 /** 10045 * Get the verification agent timeout. 10046 * 10047 * @return verification timeout in milliseconds 10048 */ 10049 private long getVerificationTimeout() { 10050 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10051 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10052 DEFAULT_VERIFICATION_TIMEOUT); 10053 } 10054 10055 /** 10056 * Get the default verification agent response code. 10057 * 10058 * @return default verification response code 10059 */ 10060 private int getDefaultVerificationResponse() { 10061 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10062 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10063 DEFAULT_VERIFICATION_RESPONSE); 10064 } 10065 10066 /** 10067 * Check whether or not package verification has been enabled. 10068 * 10069 * @return true if verification should be performed 10070 */ 10071 private boolean isVerificationEnabled(int userId, int installFlags) { 10072 if (!DEFAULT_VERIFY_ENABLE) { 10073 return false; 10074 } 10075 10076 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10077 10078 // Check if installing from ADB 10079 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10080 // Do not run verification in a test harness environment 10081 if (ActivityManager.isRunningInTestHarness()) { 10082 return false; 10083 } 10084 if (ensureVerifyAppsEnabled) { 10085 return true; 10086 } 10087 // Check if the developer does not want package verification for ADB installs 10088 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10089 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10090 return false; 10091 } 10092 } 10093 10094 if (ensureVerifyAppsEnabled) { 10095 return true; 10096 } 10097 10098 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10099 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10100 } 10101 10102 @Override 10103 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10104 throws RemoteException { 10105 mContext.enforceCallingOrSelfPermission( 10106 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10107 "Only intentfilter verification agents can verify applications"); 10108 10109 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10110 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10111 Binder.getCallingUid(), verificationCode, failedDomains); 10112 msg.arg1 = id; 10113 msg.obj = response; 10114 mHandler.sendMessage(msg); 10115 } 10116 10117 @Override 10118 public int getIntentVerificationStatus(String packageName, int userId) { 10119 synchronized (mPackages) { 10120 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10121 } 10122 } 10123 10124 @Override 10125 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10126 mContext.enforceCallingOrSelfPermission( 10127 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10128 10129 boolean result = false; 10130 synchronized (mPackages) { 10131 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10132 } 10133 if (result) { 10134 scheduleWritePackageRestrictionsLocked(userId); 10135 } 10136 return result; 10137 } 10138 10139 @Override 10140 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10141 synchronized (mPackages) { 10142 return mSettings.getIntentFilterVerificationsLPr(packageName); 10143 } 10144 } 10145 10146 @Override 10147 public List<IntentFilter> getAllIntentFilters(String packageName) { 10148 if (TextUtils.isEmpty(packageName)) { 10149 return Collections.<IntentFilter>emptyList(); 10150 } 10151 synchronized (mPackages) { 10152 PackageParser.Package pkg = mPackages.get(packageName); 10153 if (pkg == null || pkg.activities == null) { 10154 return Collections.<IntentFilter>emptyList(); 10155 } 10156 final int count = pkg.activities.size(); 10157 ArrayList<IntentFilter> result = new ArrayList<>(); 10158 for (int n=0; n<count; n++) { 10159 PackageParser.Activity activity = pkg.activities.get(n); 10160 if (activity.intents != null || activity.intents.size() > 0) { 10161 result.addAll(activity.intents); 10162 } 10163 } 10164 return result; 10165 } 10166 } 10167 10168 @Override 10169 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10170 mContext.enforceCallingOrSelfPermission( 10171 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10172 10173 synchronized (mPackages) { 10174 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10175 if (packageName != null) { 10176 result |= updateIntentVerificationStatus(packageName, 10177 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10178 userId); 10179 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10180 packageName, userId); 10181 } 10182 return result; 10183 } 10184 } 10185 10186 @Override 10187 public String getDefaultBrowserPackageName(int userId) { 10188 synchronized (mPackages) { 10189 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10190 } 10191 } 10192 10193 /** 10194 * Get the "allow unknown sources" setting. 10195 * 10196 * @return the current "allow unknown sources" setting 10197 */ 10198 private int getUnknownSourcesSettings() { 10199 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10200 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10201 -1); 10202 } 10203 10204 @Override 10205 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10206 final int uid = Binder.getCallingUid(); 10207 // writer 10208 synchronized (mPackages) { 10209 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10210 if (targetPackageSetting == null) { 10211 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10212 } 10213 10214 PackageSetting installerPackageSetting; 10215 if (installerPackageName != null) { 10216 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10217 if (installerPackageSetting == null) { 10218 throw new IllegalArgumentException("Unknown installer package: " 10219 + installerPackageName); 10220 } 10221 } else { 10222 installerPackageSetting = null; 10223 } 10224 10225 Signature[] callerSignature; 10226 Object obj = mSettings.getUserIdLPr(uid); 10227 if (obj != null) { 10228 if (obj instanceof SharedUserSetting) { 10229 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10230 } else if (obj instanceof PackageSetting) { 10231 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10232 } else { 10233 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10234 } 10235 } else { 10236 throw new SecurityException("Unknown calling uid " + uid); 10237 } 10238 10239 // Verify: can't set installerPackageName to a package that is 10240 // not signed with the same cert as the caller. 10241 if (installerPackageSetting != null) { 10242 if (compareSignatures(callerSignature, 10243 installerPackageSetting.signatures.mSignatures) 10244 != PackageManager.SIGNATURE_MATCH) { 10245 throw new SecurityException( 10246 "Caller does not have same cert as new installer package " 10247 + installerPackageName); 10248 } 10249 } 10250 10251 // Verify: if target already has an installer package, it must 10252 // be signed with the same cert as the caller. 10253 if (targetPackageSetting.installerPackageName != null) { 10254 PackageSetting setting = mSettings.mPackages.get( 10255 targetPackageSetting.installerPackageName); 10256 // If the currently set package isn't valid, then it's always 10257 // okay to change it. 10258 if (setting != null) { 10259 if (compareSignatures(callerSignature, 10260 setting.signatures.mSignatures) 10261 != PackageManager.SIGNATURE_MATCH) { 10262 throw new SecurityException( 10263 "Caller does not have same cert as old installer package " 10264 + targetPackageSetting.installerPackageName); 10265 } 10266 } 10267 } 10268 10269 // Okay! 10270 targetPackageSetting.installerPackageName = installerPackageName; 10271 scheduleWriteSettingsLocked(); 10272 } 10273 } 10274 10275 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10276 // Queue up an async operation since the package installation may take a little while. 10277 mHandler.post(new Runnable() { 10278 public void run() { 10279 mHandler.removeCallbacks(this); 10280 // Result object to be returned 10281 PackageInstalledInfo res = new PackageInstalledInfo(); 10282 res.returnCode = currentStatus; 10283 res.uid = -1; 10284 res.pkg = null; 10285 res.removedInfo = new PackageRemovedInfo(); 10286 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10287 args.doPreInstall(res.returnCode); 10288 synchronized (mInstallLock) { 10289 installPackageTracedLI(args, res); 10290 } 10291 args.doPostInstall(res.returnCode, res.uid); 10292 } 10293 10294 // A restore should be performed at this point if (a) the install 10295 // succeeded, (b) the operation is not an update, and (c) the new 10296 // package has not opted out of backup participation. 10297 final boolean update = res.removedInfo.removedPackage != null; 10298 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10299 boolean doRestore = !update 10300 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10301 10302 // Set up the post-install work request bookkeeping. This will be used 10303 // and cleaned up by the post-install event handling regardless of whether 10304 // there's a restore pass performed. Token values are >= 1. 10305 int token; 10306 if (mNextInstallToken < 0) mNextInstallToken = 1; 10307 token = mNextInstallToken++; 10308 10309 PostInstallData data = new PostInstallData(args, res); 10310 mRunningInstalls.put(token, data); 10311 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10312 10313 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10314 // Pass responsibility to the Backup Manager. It will perform a 10315 // restore if appropriate, then pass responsibility back to the 10316 // Package Manager to run the post-install observer callbacks 10317 // and broadcasts. 10318 IBackupManager bm = IBackupManager.Stub.asInterface( 10319 ServiceManager.getService(Context.BACKUP_SERVICE)); 10320 if (bm != null) { 10321 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10322 + " to BM for possible restore"); 10323 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10324 try { 10325 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10326 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10327 } else { 10328 doRestore = false; 10329 } 10330 } catch (RemoteException e) { 10331 // can't happen; the backup manager is local 10332 } catch (Exception e) { 10333 Slog.e(TAG, "Exception trying to enqueue restore", e); 10334 doRestore = false; 10335 } 10336 } else { 10337 Slog.e(TAG, "Backup Manager not found!"); 10338 doRestore = false; 10339 } 10340 } 10341 10342 if (!doRestore) { 10343 // No restore possible, or the Backup Manager was mysteriously not 10344 // available -- just fire the post-install work request directly. 10345 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10346 10347 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10348 10349 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10350 mHandler.sendMessage(msg); 10351 } 10352 } 10353 }); 10354 } 10355 10356 private abstract class HandlerParams { 10357 private static final int MAX_RETRIES = 4; 10358 10359 /** 10360 * Number of times startCopy() has been attempted and had a non-fatal 10361 * error. 10362 */ 10363 private int mRetries = 0; 10364 10365 /** User handle for the user requesting the information or installation. */ 10366 private final UserHandle mUser; 10367 String traceMethod; 10368 int traceCookie; 10369 10370 HandlerParams(UserHandle user) { 10371 mUser = user; 10372 } 10373 10374 UserHandle getUser() { 10375 return mUser; 10376 } 10377 10378 HandlerParams setTraceMethod(String traceMethod) { 10379 this.traceMethod = traceMethod; 10380 return this; 10381 } 10382 10383 HandlerParams setTraceCookie(int traceCookie) { 10384 this.traceCookie = traceCookie; 10385 return this; 10386 } 10387 10388 final boolean startCopy() { 10389 boolean res; 10390 try { 10391 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10392 10393 if (++mRetries > MAX_RETRIES) { 10394 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10395 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10396 handleServiceError(); 10397 return false; 10398 } else { 10399 handleStartCopy(); 10400 res = true; 10401 } 10402 } catch (RemoteException e) { 10403 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10404 mHandler.sendEmptyMessage(MCS_RECONNECT); 10405 res = false; 10406 } 10407 handleReturnCode(); 10408 return res; 10409 } 10410 10411 final void serviceError() { 10412 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10413 handleServiceError(); 10414 handleReturnCode(); 10415 } 10416 10417 abstract void handleStartCopy() throws RemoteException; 10418 abstract void handleServiceError(); 10419 abstract void handleReturnCode(); 10420 } 10421 10422 class MeasureParams extends HandlerParams { 10423 private final PackageStats mStats; 10424 private boolean mSuccess; 10425 10426 private final IPackageStatsObserver mObserver; 10427 10428 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10429 super(new UserHandle(stats.userHandle)); 10430 mObserver = observer; 10431 mStats = stats; 10432 } 10433 10434 @Override 10435 public String toString() { 10436 return "MeasureParams{" 10437 + Integer.toHexString(System.identityHashCode(this)) 10438 + " " + mStats.packageName + "}"; 10439 } 10440 10441 @Override 10442 void handleStartCopy() throws RemoteException { 10443 synchronized (mInstallLock) { 10444 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10445 } 10446 10447 if (mSuccess) { 10448 final boolean mounted; 10449 if (Environment.isExternalStorageEmulated()) { 10450 mounted = true; 10451 } else { 10452 final String status = Environment.getExternalStorageState(); 10453 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10454 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10455 } 10456 10457 if (mounted) { 10458 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10459 10460 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10461 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10462 10463 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10464 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10465 10466 // Always subtract cache size, since it's a subdirectory 10467 mStats.externalDataSize -= mStats.externalCacheSize; 10468 10469 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10470 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10471 10472 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10473 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10474 } 10475 } 10476 } 10477 10478 @Override 10479 void handleReturnCode() { 10480 if (mObserver != null) { 10481 try { 10482 mObserver.onGetStatsCompleted(mStats, mSuccess); 10483 } catch (RemoteException e) { 10484 Slog.i(TAG, "Observer no longer exists."); 10485 } 10486 } 10487 } 10488 10489 @Override 10490 void handleServiceError() { 10491 Slog.e(TAG, "Could not measure application " + mStats.packageName 10492 + " external storage"); 10493 } 10494 } 10495 10496 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10497 throws RemoteException { 10498 long result = 0; 10499 for (File path : paths) { 10500 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10501 } 10502 return result; 10503 } 10504 10505 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10506 for (File path : paths) { 10507 try { 10508 mcs.clearDirectory(path.getAbsolutePath()); 10509 } catch (RemoteException e) { 10510 } 10511 } 10512 } 10513 10514 static class OriginInfo { 10515 /** 10516 * Location where install is coming from, before it has been 10517 * copied/renamed into place. This could be a single monolithic APK 10518 * file, or a cluster directory. This location may be untrusted. 10519 */ 10520 final File file; 10521 final String cid; 10522 10523 /** 10524 * Flag indicating that {@link #file} or {@link #cid} has already been 10525 * staged, meaning downstream users don't need to defensively copy the 10526 * contents. 10527 */ 10528 final boolean staged; 10529 10530 /** 10531 * Flag indicating that {@link #file} or {@link #cid} is an already 10532 * installed app that is being moved. 10533 */ 10534 final boolean existing; 10535 10536 final String resolvedPath; 10537 final File resolvedFile; 10538 10539 static OriginInfo fromNothing() { 10540 return new OriginInfo(null, null, false, false); 10541 } 10542 10543 static OriginInfo fromUntrustedFile(File file) { 10544 return new OriginInfo(file, null, false, false); 10545 } 10546 10547 static OriginInfo fromExistingFile(File file) { 10548 return new OriginInfo(file, null, false, true); 10549 } 10550 10551 static OriginInfo fromStagedFile(File file) { 10552 return new OriginInfo(file, null, true, false); 10553 } 10554 10555 static OriginInfo fromStagedContainer(String cid) { 10556 return new OriginInfo(null, cid, true, false); 10557 } 10558 10559 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10560 this.file = file; 10561 this.cid = cid; 10562 this.staged = staged; 10563 this.existing = existing; 10564 10565 if (cid != null) { 10566 resolvedPath = PackageHelper.getSdDir(cid); 10567 resolvedFile = new File(resolvedPath); 10568 } else if (file != null) { 10569 resolvedPath = file.getAbsolutePath(); 10570 resolvedFile = file; 10571 } else { 10572 resolvedPath = null; 10573 resolvedFile = null; 10574 } 10575 } 10576 } 10577 10578 class MoveInfo { 10579 final int moveId; 10580 final String fromUuid; 10581 final String toUuid; 10582 final String packageName; 10583 final String dataAppName; 10584 final int appId; 10585 final String seinfo; 10586 10587 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10588 String dataAppName, int appId, String seinfo) { 10589 this.moveId = moveId; 10590 this.fromUuid = fromUuid; 10591 this.toUuid = toUuid; 10592 this.packageName = packageName; 10593 this.dataAppName = dataAppName; 10594 this.appId = appId; 10595 this.seinfo = seinfo; 10596 } 10597 } 10598 10599 class InstallParams extends HandlerParams { 10600 final OriginInfo origin; 10601 final MoveInfo move; 10602 final IPackageInstallObserver2 observer; 10603 int installFlags; 10604 final String installerPackageName; 10605 final String volumeUuid; 10606 final VerificationParams verificationParams; 10607 private InstallArgs mArgs; 10608 private int mRet; 10609 final String packageAbiOverride; 10610 final String[] grantedRuntimePermissions; 10611 10612 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10613 int installFlags, String installerPackageName, String volumeUuid, 10614 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10615 String[] grantedPermissions) { 10616 super(user); 10617 this.origin = origin; 10618 this.move = move; 10619 this.observer = observer; 10620 this.installFlags = installFlags; 10621 this.installerPackageName = installerPackageName; 10622 this.volumeUuid = volumeUuid; 10623 this.verificationParams = verificationParams; 10624 this.packageAbiOverride = packageAbiOverride; 10625 this.grantedRuntimePermissions = grantedPermissions; 10626 } 10627 10628 @Override 10629 public String toString() { 10630 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10631 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10632 } 10633 10634 public ManifestDigest getManifestDigest() { 10635 if (verificationParams == null) { 10636 return null; 10637 } 10638 return verificationParams.getManifestDigest(); 10639 } 10640 10641 private int installLocationPolicy(PackageInfoLite pkgLite) { 10642 String packageName = pkgLite.packageName; 10643 int installLocation = pkgLite.installLocation; 10644 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10645 // reader 10646 synchronized (mPackages) { 10647 PackageParser.Package pkg = mPackages.get(packageName); 10648 if (pkg != null) { 10649 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10650 // Check for downgrading. 10651 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10652 try { 10653 checkDowngrade(pkg, pkgLite); 10654 } catch (PackageManagerException e) { 10655 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10656 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10657 } 10658 } 10659 // Check for updated system application. 10660 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10661 if (onSd) { 10662 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10663 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10664 } 10665 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10666 } else { 10667 if (onSd) { 10668 // Install flag overrides everything. 10669 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10670 } 10671 // If current upgrade specifies particular preference 10672 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10673 // Application explicitly specified internal. 10674 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10675 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10676 // App explictly prefers external. Let policy decide 10677 } else { 10678 // Prefer previous location 10679 if (isExternal(pkg)) { 10680 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10681 } 10682 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10683 } 10684 } 10685 } else { 10686 // Invalid install. Return error code 10687 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10688 } 10689 } 10690 } 10691 // All the special cases have been taken care of. 10692 // Return result based on recommended install location. 10693 if (onSd) { 10694 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10695 } 10696 return pkgLite.recommendedInstallLocation; 10697 } 10698 10699 /* 10700 * Invoke remote method to get package information and install 10701 * location values. Override install location based on default 10702 * policy if needed and then create install arguments based 10703 * on the install location. 10704 */ 10705 public void handleStartCopy() throws RemoteException { 10706 int ret = PackageManager.INSTALL_SUCCEEDED; 10707 10708 // If we're already staged, we've firmly committed to an install location 10709 if (origin.staged) { 10710 if (origin.file != null) { 10711 installFlags |= PackageManager.INSTALL_INTERNAL; 10712 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10713 } else if (origin.cid != null) { 10714 installFlags |= PackageManager.INSTALL_EXTERNAL; 10715 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10716 } else { 10717 throw new IllegalStateException("Invalid stage location"); 10718 } 10719 } 10720 10721 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10722 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10723 PackageInfoLite pkgLite = null; 10724 10725 if (onInt && onSd) { 10726 // Check if both bits are set. 10727 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10728 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10729 } else { 10730 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10731 packageAbiOverride); 10732 10733 /* 10734 * If we have too little free space, try to free cache 10735 * before giving up. 10736 */ 10737 if (!origin.staged && pkgLite.recommendedInstallLocation 10738 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10739 // TODO: focus freeing disk space on the target device 10740 final StorageManager storage = StorageManager.from(mContext); 10741 final long lowThreshold = storage.getStorageLowBytes( 10742 Environment.getDataDirectory()); 10743 10744 final long sizeBytes = mContainerService.calculateInstalledSize( 10745 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10746 10747 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10748 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10749 installFlags, packageAbiOverride); 10750 } 10751 10752 /* 10753 * The cache free must have deleted the file we 10754 * downloaded to install. 10755 * 10756 * TODO: fix the "freeCache" call to not delete 10757 * the file we care about. 10758 */ 10759 if (pkgLite.recommendedInstallLocation 10760 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10761 pkgLite.recommendedInstallLocation 10762 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10763 } 10764 } 10765 } 10766 10767 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10768 int loc = pkgLite.recommendedInstallLocation; 10769 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10770 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10771 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10772 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10773 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10774 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10775 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10776 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10777 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10778 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10779 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10780 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10781 } else { 10782 // Override with defaults if needed. 10783 loc = installLocationPolicy(pkgLite); 10784 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10785 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10786 } else if (!onSd && !onInt) { 10787 // Override install location with flags 10788 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10789 // Set the flag to install on external media. 10790 installFlags |= PackageManager.INSTALL_EXTERNAL; 10791 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10792 } else { 10793 // Make sure the flag for installing on external 10794 // media is unset 10795 installFlags |= PackageManager.INSTALL_INTERNAL; 10796 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10797 } 10798 } 10799 } 10800 } 10801 10802 final InstallArgs args = createInstallArgs(this); 10803 mArgs = args; 10804 10805 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10806 /* 10807 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10808 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10809 */ 10810 int userIdentifier = getUser().getIdentifier(); 10811 if (userIdentifier == UserHandle.USER_ALL 10812 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10813 userIdentifier = UserHandle.USER_OWNER; 10814 } 10815 10816 /* 10817 * Determine if we have any installed package verifiers. If we 10818 * do, then we'll defer to them to verify the packages. 10819 */ 10820 final int requiredUid = mRequiredVerifierPackage == null ? -1 10821 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10822 if (!origin.existing && requiredUid != -1 10823 && isVerificationEnabled(userIdentifier, installFlags)) { 10824 final Intent verification = new Intent( 10825 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10826 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10827 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10828 PACKAGE_MIME_TYPE); 10829 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10830 10831 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10832 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10833 0 /* TODO: Which userId? */); 10834 10835 if (DEBUG_VERIFY) { 10836 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10837 + verification.toString() + " with " + pkgLite.verifiers.length 10838 + " optional verifiers"); 10839 } 10840 10841 final int verificationId = mPendingVerificationToken++; 10842 10843 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10844 10845 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10846 installerPackageName); 10847 10848 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10849 installFlags); 10850 10851 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10852 pkgLite.packageName); 10853 10854 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10855 pkgLite.versionCode); 10856 10857 if (verificationParams != null) { 10858 if (verificationParams.getVerificationURI() != null) { 10859 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10860 verificationParams.getVerificationURI()); 10861 } 10862 if (verificationParams.getOriginatingURI() != null) { 10863 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10864 verificationParams.getOriginatingURI()); 10865 } 10866 if (verificationParams.getReferrer() != null) { 10867 verification.putExtra(Intent.EXTRA_REFERRER, 10868 verificationParams.getReferrer()); 10869 } 10870 if (verificationParams.getOriginatingUid() >= 0) { 10871 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10872 verificationParams.getOriginatingUid()); 10873 } 10874 if (verificationParams.getInstallerUid() >= 0) { 10875 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10876 verificationParams.getInstallerUid()); 10877 } 10878 } 10879 10880 final PackageVerificationState verificationState = new PackageVerificationState( 10881 requiredUid, args); 10882 10883 mPendingVerification.append(verificationId, verificationState); 10884 10885 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10886 receivers, verificationState); 10887 10888 // Apps installed for "all" users use the device owner to verify the app 10889 UserHandle verifierUser = getUser(); 10890 if (verifierUser == UserHandle.ALL) { 10891 verifierUser = UserHandle.OWNER; 10892 } 10893 10894 /* 10895 * If any sufficient verifiers were listed in the package 10896 * manifest, attempt to ask them. 10897 */ 10898 if (sufficientVerifiers != null) { 10899 final int N = sufficientVerifiers.size(); 10900 if (N == 0) { 10901 Slog.i(TAG, "Additional verifiers required, but none installed."); 10902 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10903 } else { 10904 for (int i = 0; i < N; i++) { 10905 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10906 10907 final Intent sufficientIntent = new Intent(verification); 10908 sufficientIntent.setComponent(verifierComponent); 10909 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10910 } 10911 } 10912 } 10913 10914 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10915 mRequiredVerifierPackage, receivers); 10916 if (ret == PackageManager.INSTALL_SUCCEEDED 10917 && mRequiredVerifierPackage != null) { 10918 Trace.asyncTraceBegin( 10919 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10920 /* 10921 * Send the intent to the required verification agent, 10922 * but only start the verification timeout after the 10923 * target BroadcastReceivers have run. 10924 */ 10925 verification.setComponent(requiredVerifierComponent); 10926 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10927 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10928 new BroadcastReceiver() { 10929 @Override 10930 public void onReceive(Context context, Intent intent) { 10931 final Message msg = mHandler 10932 .obtainMessage(CHECK_PENDING_VERIFICATION); 10933 msg.arg1 = verificationId; 10934 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10935 } 10936 }, null, 0, null, null); 10937 10938 /* 10939 * We don't want the copy to proceed until verification 10940 * succeeds, so null out this field. 10941 */ 10942 mArgs = null; 10943 } 10944 } else { 10945 /* 10946 * No package verification is enabled, so immediately start 10947 * the remote call to initiate copy using temporary file. 10948 */ 10949 ret = args.copyApk(mContainerService, true); 10950 } 10951 } 10952 10953 mRet = ret; 10954 } 10955 10956 @Override 10957 void handleReturnCode() { 10958 // If mArgs is null, then MCS couldn't be reached. When it 10959 // reconnects, it will try again to install. At that point, this 10960 // will succeed. 10961 if (mArgs != null) { 10962 processPendingInstall(mArgs, mRet); 10963 } 10964 } 10965 10966 @Override 10967 void handleServiceError() { 10968 mArgs = createInstallArgs(this); 10969 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10970 } 10971 10972 public boolean isForwardLocked() { 10973 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10974 } 10975 } 10976 10977 /** 10978 * Used during creation of InstallArgs 10979 * 10980 * @param installFlags package installation flags 10981 * @return true if should be installed on external storage 10982 */ 10983 private static boolean installOnExternalAsec(int installFlags) { 10984 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10985 return false; 10986 } 10987 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10988 return true; 10989 } 10990 return false; 10991 } 10992 10993 /** 10994 * Used during creation of InstallArgs 10995 * 10996 * @param installFlags package installation flags 10997 * @return true if should be installed as forward locked 10998 */ 10999 private static boolean installForwardLocked(int installFlags) { 11000 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11001 } 11002 11003 private InstallArgs createInstallArgs(InstallParams params) { 11004 if (params.move != null) { 11005 return new MoveInstallArgs(params); 11006 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11007 return new AsecInstallArgs(params); 11008 } else { 11009 return new FileInstallArgs(params); 11010 } 11011 } 11012 11013 /** 11014 * Create args that describe an existing installed package. Typically used 11015 * when cleaning up old installs, or used as a move source. 11016 */ 11017 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11018 String resourcePath, String[] instructionSets) { 11019 final boolean isInAsec; 11020 if (installOnExternalAsec(installFlags)) { 11021 /* Apps on SD card are always in ASEC containers. */ 11022 isInAsec = true; 11023 } else if (installForwardLocked(installFlags) 11024 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11025 /* 11026 * Forward-locked apps are only in ASEC containers if they're the 11027 * new style 11028 */ 11029 isInAsec = true; 11030 } else { 11031 isInAsec = false; 11032 } 11033 11034 if (isInAsec) { 11035 return new AsecInstallArgs(codePath, instructionSets, 11036 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11037 } else { 11038 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11039 } 11040 } 11041 11042 static abstract class InstallArgs { 11043 /** @see InstallParams#origin */ 11044 final OriginInfo origin; 11045 /** @see InstallParams#move */ 11046 final MoveInfo move; 11047 11048 final IPackageInstallObserver2 observer; 11049 // Always refers to PackageManager flags only 11050 final int installFlags; 11051 final String installerPackageName; 11052 final String volumeUuid; 11053 final ManifestDigest manifestDigest; 11054 final UserHandle user; 11055 final String abiOverride; 11056 final String[] installGrantPermissions; 11057 /** If non-null, drop an async trace when the install completes */ 11058 final String traceMethod; 11059 final int traceCookie; 11060 11061 // The list of instruction sets supported by this app. This is currently 11062 // only used during the rmdex() phase to clean up resources. We can get rid of this 11063 // if we move dex files under the common app path. 11064 /* nullable */ String[] instructionSets; 11065 11066 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11067 int installFlags, String installerPackageName, String volumeUuid, 11068 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11069 String abiOverride, String[] installGrantPermissions, 11070 String traceMethod, int traceCookie) { 11071 this.origin = origin; 11072 this.move = move; 11073 this.installFlags = installFlags; 11074 this.observer = observer; 11075 this.installerPackageName = installerPackageName; 11076 this.volumeUuid = volumeUuid; 11077 this.manifestDigest = manifestDigest; 11078 this.user = user; 11079 this.instructionSets = instructionSets; 11080 this.abiOverride = abiOverride; 11081 this.installGrantPermissions = installGrantPermissions; 11082 this.traceMethod = traceMethod; 11083 this.traceCookie = traceCookie; 11084 } 11085 11086 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11087 abstract int doPreInstall(int status); 11088 11089 /** 11090 * Rename package into final resting place. All paths on the given 11091 * scanned package should be updated to reflect the rename. 11092 */ 11093 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11094 abstract int doPostInstall(int status, int uid); 11095 11096 /** @see PackageSettingBase#codePathString */ 11097 abstract String getCodePath(); 11098 /** @see PackageSettingBase#resourcePathString */ 11099 abstract String getResourcePath(); 11100 11101 // Need installer lock especially for dex file removal. 11102 abstract void cleanUpResourcesLI(); 11103 abstract boolean doPostDeleteLI(boolean delete); 11104 11105 /** 11106 * Called before the source arguments are copied. This is used mostly 11107 * for MoveParams when it needs to read the source file to put it in the 11108 * destination. 11109 */ 11110 int doPreCopy() { 11111 return PackageManager.INSTALL_SUCCEEDED; 11112 } 11113 11114 /** 11115 * Called after the source arguments are copied. This is used mostly for 11116 * MoveParams when it needs to read the source file to put it in the 11117 * destination. 11118 * 11119 * @return 11120 */ 11121 int doPostCopy(int uid) { 11122 return PackageManager.INSTALL_SUCCEEDED; 11123 } 11124 11125 protected boolean isFwdLocked() { 11126 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11127 } 11128 11129 protected boolean isExternalAsec() { 11130 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11131 } 11132 11133 UserHandle getUser() { 11134 return user; 11135 } 11136 } 11137 11138 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11139 if (!allCodePaths.isEmpty()) { 11140 if (instructionSets == null) { 11141 throw new IllegalStateException("instructionSet == null"); 11142 } 11143 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11144 for (String codePath : allCodePaths) { 11145 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11146 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11147 if (retCode < 0) { 11148 Slog.w(TAG, "Couldn't remove dex file for package: " 11149 + " at location " + codePath + ", retcode=" + retCode); 11150 // we don't consider this to be a failure of the core package deletion 11151 } 11152 } 11153 } 11154 } 11155 } 11156 11157 /** 11158 * Logic to handle installation of non-ASEC applications, including copying 11159 * and renaming logic. 11160 */ 11161 class FileInstallArgs extends InstallArgs { 11162 private File codeFile; 11163 private File resourceFile; 11164 11165 // Example topology: 11166 // /data/app/com.example/base.apk 11167 // /data/app/com.example/split_foo.apk 11168 // /data/app/com.example/lib/arm/libfoo.so 11169 // /data/app/com.example/lib/arm64/libfoo.so 11170 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11171 11172 /** New install */ 11173 FileInstallArgs(InstallParams params) { 11174 super(params.origin, params.move, params.observer, params.installFlags, 11175 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11176 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11177 params.grantedRuntimePermissions, 11178 params.traceMethod, params.traceCookie); 11179 if (isFwdLocked()) { 11180 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11181 } 11182 } 11183 11184 /** Existing install */ 11185 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11186 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11187 null, null, null, 0); 11188 this.codeFile = (codePath != null) ? new File(codePath) : null; 11189 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11190 } 11191 11192 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11193 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11194 try { 11195 return doCopyApk(imcs, temp); 11196 } finally { 11197 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11198 } 11199 } 11200 11201 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11202 if (origin.staged) { 11203 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11204 codeFile = origin.file; 11205 resourceFile = origin.file; 11206 return PackageManager.INSTALL_SUCCEEDED; 11207 } 11208 11209 try { 11210 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11211 codeFile = tempDir; 11212 resourceFile = tempDir; 11213 } catch (IOException e) { 11214 Slog.w(TAG, "Failed to create copy file: " + e); 11215 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11216 } 11217 11218 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11219 @Override 11220 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11221 if (!FileUtils.isValidExtFilename(name)) { 11222 throw new IllegalArgumentException("Invalid filename: " + name); 11223 } 11224 try { 11225 final File file = new File(codeFile, name); 11226 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11227 O_RDWR | O_CREAT, 0644); 11228 Os.chmod(file.getAbsolutePath(), 0644); 11229 return new ParcelFileDescriptor(fd); 11230 } catch (ErrnoException e) { 11231 throw new RemoteException("Failed to open: " + e.getMessage()); 11232 } 11233 } 11234 }; 11235 11236 int ret = PackageManager.INSTALL_SUCCEEDED; 11237 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11238 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11239 Slog.e(TAG, "Failed to copy package"); 11240 return ret; 11241 } 11242 11243 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11244 NativeLibraryHelper.Handle handle = null; 11245 try { 11246 handle = NativeLibraryHelper.Handle.create(codeFile); 11247 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11248 abiOverride); 11249 } catch (IOException e) { 11250 Slog.e(TAG, "Copying native libraries failed", e); 11251 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11252 } finally { 11253 IoUtils.closeQuietly(handle); 11254 } 11255 11256 return ret; 11257 } 11258 11259 int doPreInstall(int status) { 11260 if (status != PackageManager.INSTALL_SUCCEEDED) { 11261 cleanUp(); 11262 } 11263 return status; 11264 } 11265 11266 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11267 if (status != PackageManager.INSTALL_SUCCEEDED) { 11268 cleanUp(); 11269 return false; 11270 } 11271 11272 final File targetDir = codeFile.getParentFile(); 11273 final File beforeCodeFile = codeFile; 11274 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11275 11276 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11277 try { 11278 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11279 } catch (ErrnoException e) { 11280 Slog.w(TAG, "Failed to rename", e); 11281 return false; 11282 } 11283 11284 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11285 Slog.w(TAG, "Failed to restorecon"); 11286 return false; 11287 } 11288 11289 // Reflect the rename internally 11290 codeFile = afterCodeFile; 11291 resourceFile = afterCodeFile; 11292 11293 // Reflect the rename in scanned details 11294 pkg.codePath = afterCodeFile.getAbsolutePath(); 11295 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11296 pkg.baseCodePath); 11297 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11298 pkg.splitCodePaths); 11299 11300 // Reflect the rename in app info 11301 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11302 pkg.applicationInfo.setCodePath(pkg.codePath); 11303 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11304 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11305 pkg.applicationInfo.setResourcePath(pkg.codePath); 11306 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11307 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11308 11309 return true; 11310 } 11311 11312 int doPostInstall(int status, int uid) { 11313 if (status != PackageManager.INSTALL_SUCCEEDED) { 11314 cleanUp(); 11315 } 11316 return status; 11317 } 11318 11319 @Override 11320 String getCodePath() { 11321 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11322 } 11323 11324 @Override 11325 String getResourcePath() { 11326 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11327 } 11328 11329 private boolean cleanUp() { 11330 if (codeFile == null || !codeFile.exists()) { 11331 return false; 11332 } 11333 11334 if (codeFile.isDirectory()) { 11335 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11336 } else { 11337 codeFile.delete(); 11338 } 11339 11340 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11341 resourceFile.delete(); 11342 } 11343 11344 return true; 11345 } 11346 11347 void cleanUpResourcesLI() { 11348 // Try enumerating all code paths before deleting 11349 List<String> allCodePaths = Collections.EMPTY_LIST; 11350 if (codeFile != null && codeFile.exists()) { 11351 try { 11352 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11353 allCodePaths = pkg.getAllCodePaths(); 11354 } catch (PackageParserException e) { 11355 // Ignored; we tried our best 11356 } 11357 } 11358 11359 cleanUp(); 11360 removeDexFiles(allCodePaths, instructionSets); 11361 } 11362 11363 boolean doPostDeleteLI(boolean delete) { 11364 // XXX err, shouldn't we respect the delete flag? 11365 cleanUpResourcesLI(); 11366 return true; 11367 } 11368 } 11369 11370 private boolean isAsecExternal(String cid) { 11371 final String asecPath = PackageHelper.getSdFilesystem(cid); 11372 return !asecPath.startsWith(mAsecInternalPath); 11373 } 11374 11375 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11376 PackageManagerException { 11377 if (copyRet < 0) { 11378 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11379 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11380 throw new PackageManagerException(copyRet, message); 11381 } 11382 } 11383 } 11384 11385 /** 11386 * Extract the MountService "container ID" from the full code path of an 11387 * .apk. 11388 */ 11389 static String cidFromCodePath(String fullCodePath) { 11390 int eidx = fullCodePath.lastIndexOf("/"); 11391 String subStr1 = fullCodePath.substring(0, eidx); 11392 int sidx = subStr1.lastIndexOf("/"); 11393 return subStr1.substring(sidx+1, eidx); 11394 } 11395 11396 /** 11397 * Logic to handle installation of ASEC applications, including copying and 11398 * renaming logic. 11399 */ 11400 class AsecInstallArgs extends InstallArgs { 11401 static final String RES_FILE_NAME = "pkg.apk"; 11402 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11403 11404 String cid; 11405 String packagePath; 11406 String resourcePath; 11407 11408 /** New install */ 11409 AsecInstallArgs(InstallParams params) { 11410 super(params.origin, params.move, params.observer, params.installFlags, 11411 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11412 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11413 params.grantedRuntimePermissions, 11414 params.traceMethod, params.traceCookie); 11415 } 11416 11417 /** Existing install */ 11418 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11419 boolean isExternal, boolean isForwardLocked) { 11420 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11421 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11422 instructionSets, null, null, null, 0); 11423 // Hackily pretend we're still looking at a full code path 11424 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11425 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11426 } 11427 11428 // Extract cid from fullCodePath 11429 int eidx = fullCodePath.lastIndexOf("/"); 11430 String subStr1 = fullCodePath.substring(0, eidx); 11431 int sidx = subStr1.lastIndexOf("/"); 11432 cid = subStr1.substring(sidx+1, eidx); 11433 setMountPath(subStr1); 11434 } 11435 11436 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11437 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11438 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11439 instructionSets, null, null, null, 0); 11440 this.cid = cid; 11441 setMountPath(PackageHelper.getSdDir(cid)); 11442 } 11443 11444 void createCopyFile() { 11445 cid = mInstallerService.allocateExternalStageCidLegacy(); 11446 } 11447 11448 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11449 if (origin.staged) { 11450 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11451 cid = origin.cid; 11452 setMountPath(PackageHelper.getSdDir(cid)); 11453 return PackageManager.INSTALL_SUCCEEDED; 11454 } 11455 11456 if (temp) { 11457 createCopyFile(); 11458 } else { 11459 /* 11460 * Pre-emptively destroy the container since it's destroyed if 11461 * copying fails due to it existing anyway. 11462 */ 11463 PackageHelper.destroySdDir(cid); 11464 } 11465 11466 final String newMountPath = imcs.copyPackageToContainer( 11467 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11468 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11469 11470 if (newMountPath != null) { 11471 setMountPath(newMountPath); 11472 return PackageManager.INSTALL_SUCCEEDED; 11473 } else { 11474 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11475 } 11476 } 11477 11478 @Override 11479 String getCodePath() { 11480 return packagePath; 11481 } 11482 11483 @Override 11484 String getResourcePath() { 11485 return resourcePath; 11486 } 11487 11488 int doPreInstall(int status) { 11489 if (status != PackageManager.INSTALL_SUCCEEDED) { 11490 // Destroy container 11491 PackageHelper.destroySdDir(cid); 11492 } else { 11493 boolean mounted = PackageHelper.isContainerMounted(cid); 11494 if (!mounted) { 11495 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11496 Process.SYSTEM_UID); 11497 if (newMountPath != null) { 11498 setMountPath(newMountPath); 11499 } else { 11500 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11501 } 11502 } 11503 } 11504 return status; 11505 } 11506 11507 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11508 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11509 String newMountPath = null; 11510 if (PackageHelper.isContainerMounted(cid)) { 11511 // Unmount the container 11512 if (!PackageHelper.unMountSdDir(cid)) { 11513 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11514 return false; 11515 } 11516 } 11517 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11518 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11519 " which might be stale. Will try to clean up."); 11520 // Clean up the stale container and proceed to recreate. 11521 if (!PackageHelper.destroySdDir(newCacheId)) { 11522 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11523 return false; 11524 } 11525 // Successfully cleaned up stale container. Try to rename again. 11526 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11527 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11528 + " inspite of cleaning it up."); 11529 return false; 11530 } 11531 } 11532 if (!PackageHelper.isContainerMounted(newCacheId)) { 11533 Slog.w(TAG, "Mounting container " + newCacheId); 11534 newMountPath = PackageHelper.mountSdDir(newCacheId, 11535 getEncryptKey(), Process.SYSTEM_UID); 11536 } else { 11537 newMountPath = PackageHelper.getSdDir(newCacheId); 11538 } 11539 if (newMountPath == null) { 11540 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11541 return false; 11542 } 11543 Log.i(TAG, "Succesfully renamed " + cid + 11544 " to " + newCacheId + 11545 " at new path: " + newMountPath); 11546 cid = newCacheId; 11547 11548 final File beforeCodeFile = new File(packagePath); 11549 setMountPath(newMountPath); 11550 final File afterCodeFile = new File(packagePath); 11551 11552 // Reflect the rename in scanned details 11553 pkg.codePath = afterCodeFile.getAbsolutePath(); 11554 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11555 pkg.baseCodePath); 11556 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11557 pkg.splitCodePaths); 11558 11559 // Reflect the rename in app info 11560 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11561 pkg.applicationInfo.setCodePath(pkg.codePath); 11562 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11563 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11564 pkg.applicationInfo.setResourcePath(pkg.codePath); 11565 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11566 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11567 11568 return true; 11569 } 11570 11571 private void setMountPath(String mountPath) { 11572 final File mountFile = new File(mountPath); 11573 11574 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11575 if (monolithicFile.exists()) { 11576 packagePath = monolithicFile.getAbsolutePath(); 11577 if (isFwdLocked()) { 11578 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11579 } else { 11580 resourcePath = packagePath; 11581 } 11582 } else { 11583 packagePath = mountFile.getAbsolutePath(); 11584 resourcePath = packagePath; 11585 } 11586 } 11587 11588 int doPostInstall(int status, int uid) { 11589 if (status != PackageManager.INSTALL_SUCCEEDED) { 11590 cleanUp(); 11591 } else { 11592 final int groupOwner; 11593 final String protectedFile; 11594 if (isFwdLocked()) { 11595 groupOwner = UserHandle.getSharedAppGid(uid); 11596 protectedFile = RES_FILE_NAME; 11597 } else { 11598 groupOwner = -1; 11599 protectedFile = null; 11600 } 11601 11602 if (uid < Process.FIRST_APPLICATION_UID 11603 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11604 Slog.e(TAG, "Failed to finalize " + cid); 11605 PackageHelper.destroySdDir(cid); 11606 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11607 } 11608 11609 boolean mounted = PackageHelper.isContainerMounted(cid); 11610 if (!mounted) { 11611 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11612 } 11613 } 11614 return status; 11615 } 11616 11617 private void cleanUp() { 11618 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11619 11620 // Destroy secure container 11621 PackageHelper.destroySdDir(cid); 11622 } 11623 11624 private List<String> getAllCodePaths() { 11625 final File codeFile = new File(getCodePath()); 11626 if (codeFile != null && codeFile.exists()) { 11627 try { 11628 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11629 return pkg.getAllCodePaths(); 11630 } catch (PackageParserException e) { 11631 // Ignored; we tried our best 11632 } 11633 } 11634 return Collections.EMPTY_LIST; 11635 } 11636 11637 void cleanUpResourcesLI() { 11638 // Enumerate all code paths before deleting 11639 cleanUpResourcesLI(getAllCodePaths()); 11640 } 11641 11642 private void cleanUpResourcesLI(List<String> allCodePaths) { 11643 cleanUp(); 11644 removeDexFiles(allCodePaths, instructionSets); 11645 } 11646 11647 String getPackageName() { 11648 return getAsecPackageName(cid); 11649 } 11650 11651 boolean doPostDeleteLI(boolean delete) { 11652 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11653 final List<String> allCodePaths = getAllCodePaths(); 11654 boolean mounted = PackageHelper.isContainerMounted(cid); 11655 if (mounted) { 11656 // Unmount first 11657 if (PackageHelper.unMountSdDir(cid)) { 11658 mounted = false; 11659 } 11660 } 11661 if (!mounted && delete) { 11662 cleanUpResourcesLI(allCodePaths); 11663 } 11664 return !mounted; 11665 } 11666 11667 @Override 11668 int doPreCopy() { 11669 if (isFwdLocked()) { 11670 if (!PackageHelper.fixSdPermissions(cid, 11671 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11672 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11673 } 11674 } 11675 11676 return PackageManager.INSTALL_SUCCEEDED; 11677 } 11678 11679 @Override 11680 int doPostCopy(int uid) { 11681 if (isFwdLocked()) { 11682 if (uid < Process.FIRST_APPLICATION_UID 11683 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11684 RES_FILE_NAME)) { 11685 Slog.e(TAG, "Failed to finalize " + cid); 11686 PackageHelper.destroySdDir(cid); 11687 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11688 } 11689 } 11690 11691 return PackageManager.INSTALL_SUCCEEDED; 11692 } 11693 } 11694 11695 /** 11696 * Logic to handle movement of existing installed applications. 11697 */ 11698 class MoveInstallArgs extends InstallArgs { 11699 private File codeFile; 11700 private File resourceFile; 11701 11702 /** New install */ 11703 MoveInstallArgs(InstallParams params) { 11704 super(params.origin, params.move, params.observer, params.installFlags, 11705 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11706 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11707 params.grantedRuntimePermissions, 11708 params.traceMethod, params.traceCookie); 11709 } 11710 11711 int copyApk(IMediaContainerService imcs, boolean temp) { 11712 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11713 + move.fromUuid + " to " + move.toUuid); 11714 synchronized (mInstaller) { 11715 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11716 move.dataAppName, move.appId, move.seinfo) != 0) { 11717 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11718 } 11719 } 11720 11721 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11722 resourceFile = codeFile; 11723 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11724 11725 return PackageManager.INSTALL_SUCCEEDED; 11726 } 11727 11728 int doPreInstall(int status) { 11729 if (status != PackageManager.INSTALL_SUCCEEDED) { 11730 cleanUp(move.toUuid); 11731 } 11732 return status; 11733 } 11734 11735 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11736 if (status != PackageManager.INSTALL_SUCCEEDED) { 11737 cleanUp(move.toUuid); 11738 return false; 11739 } 11740 11741 // Reflect the move in app info 11742 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11743 pkg.applicationInfo.setCodePath(pkg.codePath); 11744 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11745 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11746 pkg.applicationInfo.setResourcePath(pkg.codePath); 11747 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11748 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11749 11750 return true; 11751 } 11752 11753 int doPostInstall(int status, int uid) { 11754 if (status == PackageManager.INSTALL_SUCCEEDED) { 11755 cleanUp(move.fromUuid); 11756 } else { 11757 cleanUp(move.toUuid); 11758 } 11759 return status; 11760 } 11761 11762 @Override 11763 String getCodePath() { 11764 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11765 } 11766 11767 @Override 11768 String getResourcePath() { 11769 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11770 } 11771 11772 private boolean cleanUp(String volumeUuid) { 11773 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11774 move.dataAppName); 11775 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11776 synchronized (mInstallLock) { 11777 // Clean up both app data and code 11778 removeDataDirsLI(volumeUuid, move.packageName); 11779 if (codeFile.isDirectory()) { 11780 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11781 } else { 11782 codeFile.delete(); 11783 } 11784 } 11785 return true; 11786 } 11787 11788 void cleanUpResourcesLI() { 11789 throw new UnsupportedOperationException(); 11790 } 11791 11792 boolean doPostDeleteLI(boolean delete) { 11793 throw new UnsupportedOperationException(); 11794 } 11795 } 11796 11797 static String getAsecPackageName(String packageCid) { 11798 int idx = packageCid.lastIndexOf("-"); 11799 if (idx == -1) { 11800 return packageCid; 11801 } 11802 return packageCid.substring(0, idx); 11803 } 11804 11805 // Utility method used to create code paths based on package name and available index. 11806 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11807 String idxStr = ""; 11808 int idx = 1; 11809 // Fall back to default value of idx=1 if prefix is not 11810 // part of oldCodePath 11811 if (oldCodePath != null) { 11812 String subStr = oldCodePath; 11813 // Drop the suffix right away 11814 if (suffix != null && subStr.endsWith(suffix)) { 11815 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11816 } 11817 // If oldCodePath already contains prefix find out the 11818 // ending index to either increment or decrement. 11819 int sidx = subStr.lastIndexOf(prefix); 11820 if (sidx != -1) { 11821 subStr = subStr.substring(sidx + prefix.length()); 11822 if (subStr != null) { 11823 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11824 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11825 } 11826 try { 11827 idx = Integer.parseInt(subStr); 11828 if (idx <= 1) { 11829 idx++; 11830 } else { 11831 idx--; 11832 } 11833 } catch(NumberFormatException e) { 11834 } 11835 } 11836 } 11837 } 11838 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11839 return prefix + idxStr; 11840 } 11841 11842 private File getNextCodePath(File targetDir, String packageName) { 11843 int suffix = 1; 11844 File result; 11845 do { 11846 result = new File(targetDir, packageName + "-" + suffix); 11847 suffix++; 11848 } while (result.exists()); 11849 return result; 11850 } 11851 11852 // Utility method that returns the relative package path with respect 11853 // to the installation directory. Like say for /data/data/com.test-1.apk 11854 // string com.test-1 is returned. 11855 static String deriveCodePathName(String codePath) { 11856 if (codePath == null) { 11857 return null; 11858 } 11859 final File codeFile = new File(codePath); 11860 final String name = codeFile.getName(); 11861 if (codeFile.isDirectory()) { 11862 return name; 11863 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11864 final int lastDot = name.lastIndexOf('.'); 11865 return name.substring(0, lastDot); 11866 } else { 11867 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11868 return null; 11869 } 11870 } 11871 11872 class PackageInstalledInfo { 11873 String name; 11874 int uid; 11875 // The set of users that originally had this package installed. 11876 int[] origUsers; 11877 // The set of users that now have this package installed. 11878 int[] newUsers; 11879 PackageParser.Package pkg; 11880 int returnCode; 11881 String returnMsg; 11882 PackageRemovedInfo removedInfo; 11883 11884 public void setError(int code, String msg) { 11885 returnCode = code; 11886 returnMsg = msg; 11887 Slog.w(TAG, msg); 11888 } 11889 11890 public void setError(String msg, PackageParserException e) { 11891 returnCode = e.error; 11892 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11893 Slog.w(TAG, msg, e); 11894 } 11895 11896 public void setError(String msg, PackageManagerException e) { 11897 returnCode = e.error; 11898 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11899 Slog.w(TAG, msg, e); 11900 } 11901 11902 // In some error cases we want to convey more info back to the observer 11903 String origPackage; 11904 String origPermission; 11905 } 11906 11907 /* 11908 * Install a non-existing package. 11909 */ 11910 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11911 UserHandle user, String installerPackageName, String volumeUuid, 11912 PackageInstalledInfo res) { 11913 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11914 11915 // Remember this for later, in case we need to rollback this install 11916 String pkgName = pkg.packageName; 11917 11918 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11919 // TODO: b/23350563 11920 final boolean dataDirExists = Environment 11921 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11922 11923 synchronized(mPackages) { 11924 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11925 // A package with the same name is already installed, though 11926 // it has been renamed to an older name. The package we 11927 // are trying to install should be installed as an update to 11928 // the existing one, but that has not been requested, so bail. 11929 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11930 + " without first uninstalling package running as " 11931 + mSettings.mRenamedPackages.get(pkgName)); 11932 return; 11933 } 11934 if (mPackages.containsKey(pkgName)) { 11935 // Don't allow installation over an existing package with the same name. 11936 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11937 + " without first uninstalling."); 11938 return; 11939 } 11940 } 11941 11942 try { 11943 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11944 System.currentTimeMillis(), user); 11945 11946 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11947 // delete the partially installed application. the data directory will have to be 11948 // restored if it was already existing 11949 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11950 // remove package from internal structures. Note that we want deletePackageX to 11951 // delete the package data and cache directories that it created in 11952 // scanPackageLocked, unless those directories existed before we even tried to 11953 // install. 11954 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11955 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11956 res.removedInfo, true); 11957 } 11958 11959 } catch (PackageManagerException e) { 11960 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11961 } 11962 11963 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11964 } 11965 11966 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11967 // Can't rotate keys during boot or if sharedUser. 11968 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11969 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11970 return false; 11971 } 11972 // app is using upgradeKeySets; make sure all are valid 11973 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11974 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11975 for (int i = 0; i < upgradeKeySets.length; i++) { 11976 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11977 Slog.wtf(TAG, "Package " 11978 + (oldPs.name != null ? oldPs.name : "<null>") 11979 + " contains upgrade-key-set reference to unknown key-set: " 11980 + upgradeKeySets[i] 11981 + " reverting to signatures check."); 11982 return false; 11983 } 11984 } 11985 return true; 11986 } 11987 11988 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11989 // Upgrade keysets are being used. Determine if new package has a superset of the 11990 // required keys. 11991 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11992 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11993 for (int i = 0; i < upgradeKeySets.length; i++) { 11994 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11995 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11996 return true; 11997 } 11998 } 11999 return false; 12000 } 12001 12002 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12003 UserHandle user, String installerPackageName, String volumeUuid, 12004 PackageInstalledInfo res) { 12005 final PackageParser.Package oldPackage; 12006 final String pkgName = pkg.packageName; 12007 final int[] allUsers; 12008 final boolean[] perUserInstalled; 12009 12010 // First find the old package info and check signatures 12011 synchronized(mPackages) { 12012 oldPackage = mPackages.get(pkgName); 12013 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12014 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12015 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12016 if(!checkUpgradeKeySetLP(ps, pkg)) { 12017 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12018 "New package not signed by keys specified by upgrade-keysets: " 12019 + pkgName); 12020 return; 12021 } 12022 } else { 12023 // default to original signature matching 12024 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12025 != PackageManager.SIGNATURE_MATCH) { 12026 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12027 "New package has a different signature: " + pkgName); 12028 return; 12029 } 12030 } 12031 12032 // In case of rollback, remember per-user/profile install state 12033 allUsers = sUserManager.getUserIds(); 12034 perUserInstalled = new boolean[allUsers.length]; 12035 for (int i = 0; i < allUsers.length; i++) { 12036 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12037 } 12038 } 12039 12040 boolean sysPkg = (isSystemApp(oldPackage)); 12041 if (sysPkg) { 12042 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12043 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12044 } else { 12045 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12046 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12047 } 12048 } 12049 12050 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12051 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12052 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12053 String volumeUuid, PackageInstalledInfo res) { 12054 String pkgName = deletedPackage.packageName; 12055 boolean deletedPkg = true; 12056 boolean updatedSettings = false; 12057 12058 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12059 + deletedPackage); 12060 long origUpdateTime; 12061 if (pkg.mExtras != null) { 12062 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12063 } else { 12064 origUpdateTime = 0; 12065 } 12066 12067 // First delete the existing package while retaining the data directory 12068 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12069 res.removedInfo, true)) { 12070 // If the existing package wasn't successfully deleted 12071 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12072 deletedPkg = false; 12073 } else { 12074 // Successfully deleted the old package; proceed with replace. 12075 12076 // If deleted package lived in a container, give users a chance to 12077 // relinquish resources before killing. 12078 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12079 if (DEBUG_INSTALL) { 12080 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12081 } 12082 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12083 final ArrayList<String> pkgList = new ArrayList<String>(1); 12084 pkgList.add(deletedPackage.applicationInfo.packageName); 12085 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12086 } 12087 12088 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12089 try { 12090 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12091 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12092 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12093 perUserInstalled, res, user); 12094 updatedSettings = true; 12095 } catch (PackageManagerException e) { 12096 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12097 } 12098 } 12099 12100 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12101 // remove package from internal structures. Note that we want deletePackageX to 12102 // delete the package data and cache directories that it created in 12103 // scanPackageLocked, unless those directories existed before we even tried to 12104 // install. 12105 if(updatedSettings) { 12106 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12107 deletePackageLI( 12108 pkgName, null, true, allUsers, perUserInstalled, 12109 PackageManager.DELETE_KEEP_DATA, 12110 res.removedInfo, true); 12111 } 12112 // Since we failed to install the new package we need to restore the old 12113 // package that we deleted. 12114 if (deletedPkg) { 12115 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12116 File restoreFile = new File(deletedPackage.codePath); 12117 // Parse old package 12118 boolean oldExternal = isExternal(deletedPackage); 12119 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12120 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12121 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12122 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12123 try { 12124 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 12125 } catch (PackageManagerException e) { 12126 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12127 + e.getMessage()); 12128 return; 12129 } 12130 // Restore of old package succeeded. Update permissions. 12131 // writer 12132 synchronized (mPackages) { 12133 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12134 UPDATE_PERMISSIONS_ALL); 12135 // can downgrade to reader 12136 mSettings.writeLPr(); 12137 } 12138 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12139 } 12140 } 12141 } 12142 12143 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12144 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12145 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12146 String volumeUuid, PackageInstalledInfo res) { 12147 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12148 + ", old=" + deletedPackage); 12149 boolean disabledSystem = false; 12150 boolean updatedSettings = false; 12151 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12152 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12153 != 0) { 12154 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12155 } 12156 String packageName = deletedPackage.packageName; 12157 if (packageName == null) { 12158 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12159 "Attempt to delete null packageName."); 12160 return; 12161 } 12162 PackageParser.Package oldPkg; 12163 PackageSetting oldPkgSetting; 12164 // reader 12165 synchronized (mPackages) { 12166 oldPkg = mPackages.get(packageName); 12167 oldPkgSetting = mSettings.mPackages.get(packageName); 12168 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12169 (oldPkgSetting == null)) { 12170 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12171 "Couldn't find package:" + packageName + " information"); 12172 return; 12173 } 12174 } 12175 12176 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12177 12178 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12179 res.removedInfo.removedPackage = packageName; 12180 // Remove existing system package 12181 removePackageLI(oldPkgSetting, true); 12182 // writer 12183 synchronized (mPackages) { 12184 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12185 if (!disabledSystem && deletedPackage != null) { 12186 // We didn't need to disable the .apk as a current system package, 12187 // which means we are replacing another update that is already 12188 // installed. We need to make sure to delete the older one's .apk. 12189 res.removedInfo.args = createInstallArgsForExisting(0, 12190 deletedPackage.applicationInfo.getCodePath(), 12191 deletedPackage.applicationInfo.getResourcePath(), 12192 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12193 } else { 12194 res.removedInfo.args = null; 12195 } 12196 } 12197 12198 // Successfully disabled the old package. Now proceed with re-installation 12199 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12200 12201 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12202 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12203 12204 PackageParser.Package newPackage = null; 12205 try { 12206 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12207 if (newPackage.mExtras != null) { 12208 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12209 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12210 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12211 12212 // is the update attempting to change shared user? that isn't going to work... 12213 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12214 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12215 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12216 + " to " + newPkgSetting.sharedUser); 12217 updatedSettings = true; 12218 } 12219 } 12220 12221 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12222 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12223 perUserInstalled, res, user); 12224 updatedSettings = true; 12225 } 12226 12227 } catch (PackageManagerException e) { 12228 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12229 } 12230 12231 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12232 // Re installation failed. Restore old information 12233 // Remove new pkg information 12234 if (newPackage != null) { 12235 removeInstalledPackageLI(newPackage, true); 12236 } 12237 // Add back the old system package 12238 try { 12239 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12240 } catch (PackageManagerException e) { 12241 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12242 } 12243 // Restore the old system information in Settings 12244 synchronized (mPackages) { 12245 if (disabledSystem) { 12246 mSettings.enableSystemPackageLPw(packageName); 12247 } 12248 if (updatedSettings) { 12249 mSettings.setInstallerPackageName(packageName, 12250 oldPkgSetting.installerPackageName); 12251 } 12252 mSettings.writeLPr(); 12253 } 12254 } 12255 } 12256 12257 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12258 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12259 UserHandle user) { 12260 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12261 12262 String pkgName = newPackage.packageName; 12263 synchronized (mPackages) { 12264 //write settings. the installStatus will be incomplete at this stage. 12265 //note that the new package setting would have already been 12266 //added to mPackages. It hasn't been persisted yet. 12267 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12269 mSettings.writeLPr(); 12270 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12271 } 12272 12273 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12274 synchronized (mPackages) { 12275 updatePermissionsLPw(newPackage.packageName, newPackage, 12276 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12277 ? UPDATE_PERMISSIONS_ALL : 0)); 12278 // For system-bundled packages, we assume that installing an upgraded version 12279 // of the package implies that the user actually wants to run that new code, 12280 // so we enable the package. 12281 PackageSetting ps = mSettings.mPackages.get(pkgName); 12282 if (ps != null) { 12283 if (isSystemApp(newPackage)) { 12284 // NB: implicit assumption that system package upgrades apply to all users 12285 if (DEBUG_INSTALL) { 12286 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12287 } 12288 if (res.origUsers != null) { 12289 for (int userHandle : res.origUsers) { 12290 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12291 userHandle, installerPackageName); 12292 } 12293 } 12294 // Also convey the prior install/uninstall state 12295 if (allUsers != null && perUserInstalled != null) { 12296 for (int i = 0; i < allUsers.length; i++) { 12297 if (DEBUG_INSTALL) { 12298 Slog.d(TAG, " user " + allUsers[i] 12299 + " => " + perUserInstalled[i]); 12300 } 12301 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12302 } 12303 // these install state changes will be persisted in the 12304 // upcoming call to mSettings.writeLPr(). 12305 } 12306 } 12307 // It's implied that when a user requests installation, they want the app to be 12308 // installed and enabled. 12309 int userId = user.getIdentifier(); 12310 if (userId != UserHandle.USER_ALL) { 12311 ps.setInstalled(true, userId); 12312 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12313 } 12314 } 12315 res.name = pkgName; 12316 res.uid = newPackage.applicationInfo.uid; 12317 res.pkg = newPackage; 12318 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12319 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12320 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12321 //to update install status 12322 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12323 mSettings.writeLPr(); 12324 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12325 } 12326 12327 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12328 } 12329 12330 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12331 try { 12332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12333 installPackageLI(args, res); 12334 } finally { 12335 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12336 } 12337 } 12338 12339 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12340 final int installFlags = args.installFlags; 12341 final String installerPackageName = args.installerPackageName; 12342 final String volumeUuid = args.volumeUuid; 12343 final File tmpPackageFile = new File(args.getCodePath()); 12344 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12345 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12346 || (args.volumeUuid != null)); 12347 boolean replace = false; 12348 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12349 if (args.move != null) { 12350 // moving a complete application; perfom an initial scan on the new install location 12351 scanFlags |= SCAN_INITIAL; 12352 } 12353 // Result object to be returned 12354 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12355 12356 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12357 12358 // Retrieve PackageSettings and parse package 12359 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12360 | PackageParser.PARSE_ENFORCE_CODE 12361 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12362 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12363 PackageParser pp = new PackageParser(); 12364 pp.setSeparateProcesses(mSeparateProcesses); 12365 pp.setDisplayMetrics(mMetrics); 12366 12367 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12368 final PackageParser.Package pkg; 12369 try { 12370 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12371 } catch (PackageParserException e) { 12372 res.setError("Failed parse during installPackageLI", e); 12373 return; 12374 } finally { 12375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12376 } 12377 12378 // Mark that we have an install time CPU ABI override. 12379 pkg.cpuAbiOverride = args.abiOverride; 12380 12381 String pkgName = res.name = pkg.packageName; 12382 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12383 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12384 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12385 return; 12386 } 12387 } 12388 12389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12390 try { 12391 pp.collectCertificates(pkg, parseFlags); 12392 pp.collectManifestDigest(pkg); 12393 } catch (PackageParserException e) { 12394 res.setError("Failed collect during installPackageLI", e); 12395 return; 12396 } finally { 12397 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12398 } 12399 12400 /* If the installer passed in a manifest digest, compare it now. */ 12401 if (args.manifestDigest != null) { 12402 if (DEBUG_INSTALL) { 12403 final String parsedManifest = pkg.manifestDigest == null ? "null" 12404 : pkg.manifestDigest.toString(); 12405 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12406 + parsedManifest); 12407 } 12408 12409 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12410 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12411 return; 12412 } 12413 } else if (DEBUG_INSTALL) { 12414 final String parsedManifest = pkg.manifestDigest == null 12415 ? "null" : pkg.manifestDigest.toString(); 12416 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12417 } 12418 12419 // Get rid of all references to package scan path via parser. 12420 pp = null; 12421 String oldCodePath = null; 12422 boolean systemApp = false; 12423 synchronized (mPackages) { 12424 // Check if installing already existing package 12425 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12426 String oldName = mSettings.mRenamedPackages.get(pkgName); 12427 if (pkg.mOriginalPackages != null 12428 && pkg.mOriginalPackages.contains(oldName) 12429 && mPackages.containsKey(oldName)) { 12430 // This package is derived from an original package, 12431 // and this device has been updating from that original 12432 // name. We must continue using the original name, so 12433 // rename the new package here. 12434 pkg.setPackageName(oldName); 12435 pkgName = pkg.packageName; 12436 replace = true; 12437 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12438 + oldName + " pkgName=" + pkgName); 12439 } else if (mPackages.containsKey(pkgName)) { 12440 // This package, under its official name, already exists 12441 // on the device; we should replace it. 12442 replace = true; 12443 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12444 } 12445 12446 // Prevent apps opting out from runtime permissions 12447 if (replace) { 12448 PackageParser.Package oldPackage = mPackages.get(pkgName); 12449 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12450 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12451 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12452 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12453 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12454 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12455 + " doesn't support runtime permissions but the old" 12456 + " target SDK " + oldTargetSdk + " does."); 12457 return; 12458 } 12459 } 12460 } 12461 12462 PackageSetting ps = mSettings.mPackages.get(pkgName); 12463 if (ps != null) { 12464 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12465 12466 // Quick sanity check that we're signed correctly if updating; 12467 // we'll check this again later when scanning, but we want to 12468 // bail early here before tripping over redefined permissions. 12469 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12470 if (!checkUpgradeKeySetLP(ps, pkg)) { 12471 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12472 + pkg.packageName + " upgrade keys do not match the " 12473 + "previously installed version"); 12474 return; 12475 } 12476 } else { 12477 try { 12478 verifySignaturesLP(ps, pkg); 12479 } catch (PackageManagerException e) { 12480 res.setError(e.error, e.getMessage()); 12481 return; 12482 } 12483 } 12484 12485 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12486 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12487 systemApp = (ps.pkg.applicationInfo.flags & 12488 ApplicationInfo.FLAG_SYSTEM) != 0; 12489 } 12490 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12491 } 12492 12493 // Check whether the newly-scanned package wants to define an already-defined perm 12494 int N = pkg.permissions.size(); 12495 for (int i = N-1; i >= 0; i--) { 12496 PackageParser.Permission perm = pkg.permissions.get(i); 12497 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12498 if (bp != null) { 12499 // If the defining package is signed with our cert, it's okay. This 12500 // also includes the "updating the same package" case, of course. 12501 // "updating same package" could also involve key-rotation. 12502 final boolean sigsOk; 12503 if (bp.sourcePackage.equals(pkg.packageName) 12504 && (bp.packageSetting instanceof PackageSetting) 12505 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12506 scanFlags))) { 12507 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12508 } else { 12509 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12510 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12511 } 12512 if (!sigsOk) { 12513 // If the owning package is the system itself, we log but allow 12514 // install to proceed; we fail the install on all other permission 12515 // redefinitions. 12516 if (!bp.sourcePackage.equals("android")) { 12517 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12518 + pkg.packageName + " attempting to redeclare permission " 12519 + perm.info.name + " already owned by " + bp.sourcePackage); 12520 res.origPermission = perm.info.name; 12521 res.origPackage = bp.sourcePackage; 12522 return; 12523 } else { 12524 Slog.w(TAG, "Package " + pkg.packageName 12525 + " attempting to redeclare system permission " 12526 + perm.info.name + "; ignoring new declaration"); 12527 pkg.permissions.remove(i); 12528 } 12529 } 12530 } 12531 } 12532 12533 } 12534 12535 if (systemApp && onExternal) { 12536 // Disable updates to system apps on sdcard 12537 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12538 "Cannot install updates to system apps on sdcard"); 12539 return; 12540 } 12541 12542 if (args.move != null) { 12543 // We did an in-place move, so dex is ready to roll 12544 scanFlags |= SCAN_NO_DEX; 12545 scanFlags |= SCAN_MOVE; 12546 12547 synchronized (mPackages) { 12548 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12549 if (ps == null) { 12550 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12551 "Missing settings for moved package " + pkgName); 12552 } 12553 12554 // We moved the entire application as-is, so bring over the 12555 // previously derived ABI information. 12556 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12557 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12558 } 12559 12560 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12561 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12562 scanFlags |= SCAN_NO_DEX; 12563 12564 try { 12565 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12566 true /* extract libs */); 12567 } catch (PackageManagerException pme) { 12568 Slog.e(TAG, "Error deriving application ABI", pme); 12569 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12570 return; 12571 } 12572 12573 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12574 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12575 12576 int result = mPackageDexOptimizer 12577 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12578 false /* defer */, false /* inclDependencies */, 12579 true /*bootComplete*/, false /*useJit*/); 12580 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12581 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12582 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12583 return; 12584 } 12585 } 12586 12587 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12588 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12589 return; 12590 } 12591 12592 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12593 12594 if (replace) { 12595 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12596 installerPackageName, volumeUuid, res); 12597 } else { 12598 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12599 args.user, installerPackageName, volumeUuid, res); 12600 } 12601 synchronized (mPackages) { 12602 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12603 if (ps != null) { 12604 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12605 } 12606 } 12607 } 12608 12609 private void startIntentFilterVerifications(int userId, boolean replacing, 12610 PackageParser.Package pkg) { 12611 if (mIntentFilterVerifierComponent == null) { 12612 Slog.w(TAG, "No IntentFilter verification will not be done as " 12613 + "there is no IntentFilterVerifier available!"); 12614 return; 12615 } 12616 12617 final int verifierUid = getPackageUid( 12618 mIntentFilterVerifierComponent.getPackageName(), 12619 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12620 12621 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12622 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12623 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12624 mHandler.sendMessage(msg); 12625 } 12626 12627 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12628 PackageParser.Package pkg) { 12629 int size = pkg.activities.size(); 12630 if (size == 0) { 12631 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12632 "No activity, so no need to verify any IntentFilter!"); 12633 return; 12634 } 12635 12636 final boolean hasDomainURLs = hasDomainURLs(pkg); 12637 if (!hasDomainURLs) { 12638 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12639 "No domain URLs, so no need to verify any IntentFilter!"); 12640 return; 12641 } 12642 12643 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12644 + " if any IntentFilter from the " + size 12645 + " Activities needs verification ..."); 12646 12647 int count = 0; 12648 final String packageName = pkg.packageName; 12649 12650 synchronized (mPackages) { 12651 // If this is a new install and we see that we've already run verification for this 12652 // package, we have nothing to do: it means the state was restored from backup. 12653 if (!replacing) { 12654 IntentFilterVerificationInfo ivi = 12655 mSettings.getIntentFilterVerificationLPr(packageName); 12656 if (ivi != null) { 12657 if (DEBUG_DOMAIN_VERIFICATION) { 12658 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12659 + ivi.getStatusString()); 12660 } 12661 return; 12662 } 12663 } 12664 12665 // If any filters need to be verified, then all need to be. 12666 boolean needToVerify = false; 12667 for (PackageParser.Activity a : pkg.activities) { 12668 for (ActivityIntentInfo filter : a.intents) { 12669 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12670 if (DEBUG_DOMAIN_VERIFICATION) { 12671 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12672 } 12673 needToVerify = true; 12674 break; 12675 } 12676 } 12677 } 12678 12679 if (needToVerify) { 12680 final int verificationId = mIntentFilterVerificationToken++; 12681 for (PackageParser.Activity a : pkg.activities) { 12682 for (ActivityIntentInfo filter : a.intents) { 12683 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12685 "Verification needed for IntentFilter:" + filter.toString()); 12686 mIntentFilterVerifier.addOneIntentFilterVerification( 12687 verifierUid, userId, verificationId, filter, packageName); 12688 count++; 12689 } 12690 } 12691 } 12692 } 12693 } 12694 12695 if (count > 0) { 12696 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12697 + " IntentFilter verification" + (count > 1 ? "s" : "") 12698 + " for userId:" + userId); 12699 mIntentFilterVerifier.startVerifications(userId); 12700 } else { 12701 if (DEBUG_DOMAIN_VERIFICATION) { 12702 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12703 } 12704 } 12705 } 12706 12707 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12708 final ComponentName cn = filter.activity.getComponentName(); 12709 final String packageName = cn.getPackageName(); 12710 12711 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12712 packageName); 12713 if (ivi == null) { 12714 return true; 12715 } 12716 int status = ivi.getStatus(); 12717 switch (status) { 12718 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12719 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12720 return true; 12721 12722 default: 12723 // Nothing to do 12724 return false; 12725 } 12726 } 12727 12728 private static boolean isMultiArch(PackageSetting ps) { 12729 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12730 } 12731 12732 private static boolean isMultiArch(ApplicationInfo info) { 12733 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12734 } 12735 12736 private static boolean isExternal(PackageParser.Package pkg) { 12737 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12738 } 12739 12740 private static boolean isExternal(PackageSetting ps) { 12741 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12742 } 12743 12744 private static boolean isExternal(ApplicationInfo info) { 12745 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12746 } 12747 12748 private static boolean isSystemApp(PackageParser.Package pkg) { 12749 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12750 } 12751 12752 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12753 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12754 } 12755 12756 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12757 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12758 } 12759 12760 private static boolean isSystemApp(PackageSetting ps) { 12761 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12762 } 12763 12764 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12765 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12766 } 12767 12768 private int packageFlagsToInstallFlags(PackageSetting ps) { 12769 int installFlags = 0; 12770 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12771 // This existing package was an external ASEC install when we have 12772 // the external flag without a UUID 12773 installFlags |= PackageManager.INSTALL_EXTERNAL; 12774 } 12775 if (ps.isForwardLocked()) { 12776 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12777 } 12778 return installFlags; 12779 } 12780 12781 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12782 if (isExternal(pkg)) { 12783 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12784 return mSettings.getExternalVersion(); 12785 } else { 12786 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12787 } 12788 } else { 12789 return mSettings.getInternalVersion(); 12790 } 12791 } 12792 12793 private void deleteTempPackageFiles() { 12794 final FilenameFilter filter = new FilenameFilter() { 12795 public boolean accept(File dir, String name) { 12796 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12797 } 12798 }; 12799 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12800 file.delete(); 12801 } 12802 } 12803 12804 @Override 12805 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12806 int flags) { 12807 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12808 flags); 12809 } 12810 12811 @Override 12812 public void deletePackage(final String packageName, 12813 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12814 mContext.enforceCallingOrSelfPermission( 12815 android.Manifest.permission.DELETE_PACKAGES, null); 12816 Preconditions.checkNotNull(packageName); 12817 Preconditions.checkNotNull(observer); 12818 final int uid = Binder.getCallingUid(); 12819 if (UserHandle.getUserId(uid) != userId) { 12820 mContext.enforceCallingPermission( 12821 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12822 "deletePackage for user " + userId); 12823 } 12824 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12825 try { 12826 observer.onPackageDeleted(packageName, 12827 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12828 } catch (RemoteException re) { 12829 } 12830 return; 12831 } 12832 12833 boolean uninstallBlocked = false; 12834 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12835 int[] users = sUserManager.getUserIds(); 12836 for (int i = 0; i < users.length; ++i) { 12837 if (getBlockUninstallForUser(packageName, users[i])) { 12838 uninstallBlocked = true; 12839 break; 12840 } 12841 } 12842 } else { 12843 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12844 } 12845 if (uninstallBlocked) { 12846 try { 12847 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12848 null); 12849 } catch (RemoteException re) { 12850 } 12851 return; 12852 } 12853 12854 if (DEBUG_REMOVE) { 12855 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12856 } 12857 // Queue up an async operation since the package deletion may take a little while. 12858 mHandler.post(new Runnable() { 12859 public void run() { 12860 mHandler.removeCallbacks(this); 12861 final int returnCode = deletePackageX(packageName, userId, flags); 12862 if (observer != null) { 12863 try { 12864 observer.onPackageDeleted(packageName, returnCode, null); 12865 } catch (RemoteException e) { 12866 Log.i(TAG, "Observer no longer exists."); 12867 } //end catch 12868 } //end if 12869 } //end run 12870 }); 12871 } 12872 12873 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12874 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12875 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12876 try { 12877 if (dpm != null) { 12878 if (dpm.isDeviceOwner(packageName)) { 12879 return true; 12880 } 12881 int[] users; 12882 if (userId == UserHandle.USER_ALL) { 12883 users = sUserManager.getUserIds(); 12884 } else { 12885 users = new int[]{userId}; 12886 } 12887 for (int i = 0; i < users.length; ++i) { 12888 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12889 return true; 12890 } 12891 } 12892 } 12893 } catch (RemoteException e) { 12894 } 12895 return false; 12896 } 12897 12898 /** 12899 * This method is an internal method that could be get invoked either 12900 * to delete an installed package or to clean up a failed installation. 12901 * After deleting an installed package, a broadcast is sent to notify any 12902 * listeners that the package has been installed. For cleaning up a failed 12903 * installation, the broadcast is not necessary since the package's 12904 * installation wouldn't have sent the initial broadcast either 12905 * The key steps in deleting a package are 12906 * deleting the package information in internal structures like mPackages, 12907 * deleting the packages base directories through installd 12908 * updating mSettings to reflect current status 12909 * persisting settings for later use 12910 * sending a broadcast if necessary 12911 */ 12912 private int deletePackageX(String packageName, int userId, int flags) { 12913 final PackageRemovedInfo info = new PackageRemovedInfo(); 12914 final boolean res; 12915 12916 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12917 ? UserHandle.ALL : new UserHandle(userId); 12918 12919 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12920 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12921 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12922 } 12923 12924 boolean removedForAllUsers = false; 12925 boolean systemUpdate = false; 12926 12927 // for the uninstall-updates case and restricted profiles, remember the per- 12928 // userhandle installed state 12929 int[] allUsers; 12930 boolean[] perUserInstalled; 12931 synchronized (mPackages) { 12932 PackageSetting ps = mSettings.mPackages.get(packageName); 12933 allUsers = sUserManager.getUserIds(); 12934 perUserInstalled = new boolean[allUsers.length]; 12935 for (int i = 0; i < allUsers.length; i++) { 12936 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12937 } 12938 } 12939 12940 synchronized (mInstallLock) { 12941 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12942 res = deletePackageLI(packageName, removeForUser, 12943 true, allUsers, perUserInstalled, 12944 flags | REMOVE_CHATTY, info, true); 12945 systemUpdate = info.isRemovedPackageSystemUpdate; 12946 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12947 removedForAllUsers = true; 12948 } 12949 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12950 + " removedForAllUsers=" + removedForAllUsers); 12951 } 12952 12953 if (res) { 12954 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12955 12956 // If the removed package was a system update, the old system package 12957 // was re-enabled; we need to broadcast this information 12958 if (systemUpdate) { 12959 Bundle extras = new Bundle(1); 12960 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12961 ? info.removedAppId : info.uid); 12962 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12963 12964 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12965 extras, null, null, null); 12966 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12967 extras, null, null, null); 12968 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12969 null, packageName, null, null); 12970 } 12971 } 12972 // Force a gc here. 12973 Runtime.getRuntime().gc(); 12974 // Delete the resources here after sending the broadcast to let 12975 // other processes clean up before deleting resources. 12976 if (info.args != null) { 12977 synchronized (mInstallLock) { 12978 info.args.doPostDeleteLI(true); 12979 } 12980 } 12981 12982 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12983 } 12984 12985 class PackageRemovedInfo { 12986 String removedPackage; 12987 int uid = -1; 12988 int removedAppId = -1; 12989 int[] removedUsers = null; 12990 boolean isRemovedPackageSystemUpdate = false; 12991 // Clean up resources deleted packages. 12992 InstallArgs args = null; 12993 12994 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12995 Bundle extras = new Bundle(1); 12996 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12997 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12998 if (replacing) { 12999 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13000 } 13001 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13002 if (removedPackage != null) { 13003 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13004 extras, null, null, removedUsers); 13005 if (fullRemove && !replacing) { 13006 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13007 extras, null, null, removedUsers); 13008 } 13009 } 13010 if (removedAppId >= 0) { 13011 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13012 removedUsers); 13013 } 13014 } 13015 } 13016 13017 /* 13018 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13019 * flag is not set, the data directory is removed as well. 13020 * make sure this flag is set for partially installed apps. If not its meaningless to 13021 * delete a partially installed application. 13022 */ 13023 private void removePackageDataLI(PackageSetting ps, 13024 int[] allUserHandles, boolean[] perUserInstalled, 13025 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13026 String packageName = ps.name; 13027 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13028 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13029 // Retrieve object to delete permissions for shared user later on 13030 final PackageSetting deletedPs; 13031 // reader 13032 synchronized (mPackages) { 13033 deletedPs = mSettings.mPackages.get(packageName); 13034 if (outInfo != null) { 13035 outInfo.removedPackage = packageName; 13036 outInfo.removedUsers = deletedPs != null 13037 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13038 : null; 13039 } 13040 } 13041 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13042 removeDataDirsLI(ps.volumeUuid, packageName); 13043 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13044 } 13045 // writer 13046 synchronized (mPackages) { 13047 if (deletedPs != null) { 13048 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13049 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13050 clearDefaultBrowserIfNeeded(packageName); 13051 if (outInfo != null) { 13052 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13053 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13054 } 13055 updatePermissionsLPw(deletedPs.name, null, 0); 13056 if (deletedPs.sharedUser != null) { 13057 // Remove permissions associated with package. Since runtime 13058 // permissions are per user we have to kill the removed package 13059 // or packages running under the shared user of the removed 13060 // package if revoking the permissions requested only by the removed 13061 // package is successful and this causes a change in gids. 13062 for (int userId : UserManagerService.getInstance().getUserIds()) { 13063 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13064 userId); 13065 if (userIdToKill == UserHandle.USER_ALL 13066 || userIdToKill >= UserHandle.USER_OWNER) { 13067 // If gids changed for this user, kill all affected packages. 13068 mHandler.post(new Runnable() { 13069 @Override 13070 public void run() { 13071 // This has to happen with no lock held. 13072 killApplication(deletedPs.name, deletedPs.appId, 13073 KILL_APP_REASON_GIDS_CHANGED); 13074 } 13075 }); 13076 break; 13077 } 13078 } 13079 } 13080 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13081 } 13082 // make sure to preserve per-user disabled state if this removal was just 13083 // a downgrade of a system app to the factory package 13084 if (allUserHandles != null && perUserInstalled != null) { 13085 if (DEBUG_REMOVE) { 13086 Slog.d(TAG, "Propagating install state across downgrade"); 13087 } 13088 for (int i = 0; i < allUserHandles.length; i++) { 13089 if (DEBUG_REMOVE) { 13090 Slog.d(TAG, " user " + allUserHandles[i] 13091 + " => " + perUserInstalled[i]); 13092 } 13093 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13094 } 13095 } 13096 } 13097 // can downgrade to reader 13098 if (writeSettings) { 13099 // Save settings now 13100 mSettings.writeLPr(); 13101 } 13102 } 13103 if (outInfo != null) { 13104 // A user ID was deleted here. Go through all users and remove it 13105 // from KeyStore. 13106 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13107 } 13108 } 13109 13110 static boolean locationIsPrivileged(File path) { 13111 try { 13112 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13113 .getCanonicalPath(); 13114 return path.getCanonicalPath().startsWith(privilegedAppDir); 13115 } catch (IOException e) { 13116 Slog.e(TAG, "Unable to access code path " + path); 13117 } 13118 return false; 13119 } 13120 13121 /* 13122 * Tries to delete system package. 13123 */ 13124 private boolean deleteSystemPackageLI(PackageSetting newPs, 13125 int[] allUserHandles, boolean[] perUserInstalled, 13126 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13127 final boolean applyUserRestrictions 13128 = (allUserHandles != null) && (perUserInstalled != null); 13129 PackageSetting disabledPs = null; 13130 // Confirm if the system package has been updated 13131 // An updated system app can be deleted. This will also have to restore 13132 // the system pkg from system partition 13133 // reader 13134 synchronized (mPackages) { 13135 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13136 } 13137 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13138 + " disabledPs=" + disabledPs); 13139 if (disabledPs == null) { 13140 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13141 return false; 13142 } else if (DEBUG_REMOVE) { 13143 Slog.d(TAG, "Deleting system pkg from data partition"); 13144 } 13145 if (DEBUG_REMOVE) { 13146 if (applyUserRestrictions) { 13147 Slog.d(TAG, "Remembering install states:"); 13148 for (int i = 0; i < allUserHandles.length; i++) { 13149 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13150 } 13151 } 13152 } 13153 // Delete the updated package 13154 outInfo.isRemovedPackageSystemUpdate = true; 13155 if (disabledPs.versionCode < newPs.versionCode) { 13156 // Delete data for downgrades 13157 flags &= ~PackageManager.DELETE_KEEP_DATA; 13158 } else { 13159 // Preserve data by setting flag 13160 flags |= PackageManager.DELETE_KEEP_DATA; 13161 } 13162 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13163 allUserHandles, perUserInstalled, outInfo, writeSettings); 13164 if (!ret) { 13165 return false; 13166 } 13167 // writer 13168 synchronized (mPackages) { 13169 // Reinstate the old system package 13170 mSettings.enableSystemPackageLPw(newPs.name); 13171 // Remove any native libraries from the upgraded package. 13172 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13173 } 13174 // Install the system package 13175 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13176 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13177 if (locationIsPrivileged(disabledPs.codePath)) { 13178 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13179 } 13180 13181 final PackageParser.Package newPkg; 13182 try { 13183 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13184 } catch (PackageManagerException e) { 13185 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13186 return false; 13187 } 13188 13189 // writer 13190 synchronized (mPackages) { 13191 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13192 13193 // Propagate the permissions state as we do not want to drop on the floor 13194 // runtime permissions. The update permissions method below will take 13195 // care of removing obsolete permissions and grant install permissions. 13196 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13197 updatePermissionsLPw(newPkg.packageName, newPkg, 13198 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13199 13200 if (applyUserRestrictions) { 13201 if (DEBUG_REMOVE) { 13202 Slog.d(TAG, "Propagating install state across reinstall"); 13203 } 13204 for (int i = 0; i < allUserHandles.length; i++) { 13205 if (DEBUG_REMOVE) { 13206 Slog.d(TAG, " user " + allUserHandles[i] 13207 + " => " + perUserInstalled[i]); 13208 } 13209 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13210 13211 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13212 } 13213 // Regardless of writeSettings we need to ensure that this restriction 13214 // state propagation is persisted 13215 mSettings.writeAllUsersPackageRestrictionsLPr(); 13216 } 13217 // can downgrade to reader here 13218 if (writeSettings) { 13219 mSettings.writeLPr(); 13220 } 13221 } 13222 return true; 13223 } 13224 13225 private boolean deleteInstalledPackageLI(PackageSetting ps, 13226 boolean deleteCodeAndResources, int flags, 13227 int[] allUserHandles, boolean[] perUserInstalled, 13228 PackageRemovedInfo outInfo, boolean writeSettings) { 13229 if (outInfo != null) { 13230 outInfo.uid = ps.appId; 13231 } 13232 13233 // Delete package data from internal structures and also remove data if flag is set 13234 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13235 13236 // Delete application code and resources 13237 if (deleteCodeAndResources && (outInfo != null)) { 13238 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13239 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13240 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13241 } 13242 return true; 13243 } 13244 13245 @Override 13246 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13247 int userId) { 13248 mContext.enforceCallingOrSelfPermission( 13249 android.Manifest.permission.DELETE_PACKAGES, null); 13250 synchronized (mPackages) { 13251 PackageSetting ps = mSettings.mPackages.get(packageName); 13252 if (ps == null) { 13253 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13254 return false; 13255 } 13256 if (!ps.getInstalled(userId)) { 13257 // Can't block uninstall for an app that is not installed or enabled. 13258 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13259 return false; 13260 } 13261 ps.setBlockUninstall(blockUninstall, userId); 13262 mSettings.writePackageRestrictionsLPr(userId); 13263 } 13264 return true; 13265 } 13266 13267 @Override 13268 public boolean getBlockUninstallForUser(String packageName, int userId) { 13269 synchronized (mPackages) { 13270 PackageSetting ps = mSettings.mPackages.get(packageName); 13271 if (ps == null) { 13272 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13273 return false; 13274 } 13275 return ps.getBlockUninstall(userId); 13276 } 13277 } 13278 13279 /* 13280 * This method handles package deletion in general 13281 */ 13282 private boolean deletePackageLI(String packageName, UserHandle user, 13283 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13284 int flags, PackageRemovedInfo outInfo, 13285 boolean writeSettings) { 13286 if (packageName == null) { 13287 Slog.w(TAG, "Attempt to delete null packageName."); 13288 return false; 13289 } 13290 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13291 PackageSetting ps; 13292 boolean dataOnly = false; 13293 int removeUser = -1; 13294 int appId = -1; 13295 synchronized (mPackages) { 13296 ps = mSettings.mPackages.get(packageName); 13297 if (ps == null) { 13298 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13299 return false; 13300 } 13301 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13302 && user.getIdentifier() != UserHandle.USER_ALL) { 13303 // The caller is asking that the package only be deleted for a single 13304 // user. To do this, we just mark its uninstalled state and delete 13305 // its data. If this is a system app, we only allow this to happen if 13306 // they have set the special DELETE_SYSTEM_APP which requests different 13307 // semantics than normal for uninstalling system apps. 13308 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13309 final int userId = user.getIdentifier(); 13310 ps.setUserState(userId, 13311 COMPONENT_ENABLED_STATE_DEFAULT, 13312 false, //installed 13313 true, //stopped 13314 true, //notLaunched 13315 false, //hidden 13316 null, null, null, 13317 false, // blockUninstall 13318 ps.readUserState(userId).domainVerificationStatus, 0); 13319 if (!isSystemApp(ps)) { 13320 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13321 // Other user still have this package installed, so all 13322 // we need to do is clear this user's data and save that 13323 // it is uninstalled. 13324 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13325 removeUser = user.getIdentifier(); 13326 appId = ps.appId; 13327 scheduleWritePackageRestrictionsLocked(removeUser); 13328 } else { 13329 // We need to set it back to 'installed' so the uninstall 13330 // broadcasts will be sent correctly. 13331 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13332 ps.setInstalled(true, user.getIdentifier()); 13333 } 13334 } else { 13335 // This is a system app, so we assume that the 13336 // other users still have this package installed, so all 13337 // we need to do is clear this user's data and save that 13338 // it is uninstalled. 13339 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13340 removeUser = user.getIdentifier(); 13341 appId = ps.appId; 13342 scheduleWritePackageRestrictionsLocked(removeUser); 13343 } 13344 } 13345 } 13346 13347 if (removeUser >= 0) { 13348 // From above, we determined that we are deleting this only 13349 // for a single user. Continue the work here. 13350 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13351 if (outInfo != null) { 13352 outInfo.removedPackage = packageName; 13353 outInfo.removedAppId = appId; 13354 outInfo.removedUsers = new int[] {removeUser}; 13355 } 13356 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13357 removeKeystoreDataIfNeeded(removeUser, appId); 13358 schedulePackageCleaning(packageName, removeUser, false); 13359 synchronized (mPackages) { 13360 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13361 scheduleWritePackageRestrictionsLocked(removeUser); 13362 } 13363 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13364 } 13365 return true; 13366 } 13367 13368 if (dataOnly) { 13369 // Delete application data first 13370 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13371 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13372 return true; 13373 } 13374 13375 boolean ret = false; 13376 if (isSystemApp(ps)) { 13377 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13378 // When an updated system application is deleted we delete the existing resources as well and 13379 // fall back to existing code in system partition 13380 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13381 flags, outInfo, writeSettings); 13382 } else { 13383 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13384 // Kill application pre-emptively especially for apps on sd. 13385 killApplication(packageName, ps.appId, "uninstall pkg"); 13386 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13387 allUserHandles, perUserInstalled, 13388 outInfo, writeSettings); 13389 } 13390 13391 return ret; 13392 } 13393 13394 private final class ClearStorageConnection implements ServiceConnection { 13395 IMediaContainerService mContainerService; 13396 13397 @Override 13398 public void onServiceConnected(ComponentName name, IBinder service) { 13399 synchronized (this) { 13400 mContainerService = IMediaContainerService.Stub.asInterface(service); 13401 notifyAll(); 13402 } 13403 } 13404 13405 @Override 13406 public void onServiceDisconnected(ComponentName name) { 13407 } 13408 } 13409 13410 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13411 final boolean mounted; 13412 if (Environment.isExternalStorageEmulated()) { 13413 mounted = true; 13414 } else { 13415 final String status = Environment.getExternalStorageState(); 13416 13417 mounted = status.equals(Environment.MEDIA_MOUNTED) 13418 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13419 } 13420 13421 if (!mounted) { 13422 return; 13423 } 13424 13425 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13426 int[] users; 13427 if (userId == UserHandle.USER_ALL) { 13428 users = sUserManager.getUserIds(); 13429 } else { 13430 users = new int[] { userId }; 13431 } 13432 final ClearStorageConnection conn = new ClearStorageConnection(); 13433 if (mContext.bindServiceAsUser( 13434 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13435 try { 13436 for (int curUser : users) { 13437 long timeout = SystemClock.uptimeMillis() + 5000; 13438 synchronized (conn) { 13439 long now = SystemClock.uptimeMillis(); 13440 while (conn.mContainerService == null && now < timeout) { 13441 try { 13442 conn.wait(timeout - now); 13443 } catch (InterruptedException e) { 13444 } 13445 } 13446 } 13447 if (conn.mContainerService == null) { 13448 return; 13449 } 13450 13451 final UserEnvironment userEnv = new UserEnvironment(curUser); 13452 clearDirectory(conn.mContainerService, 13453 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13454 if (allData) { 13455 clearDirectory(conn.mContainerService, 13456 userEnv.buildExternalStorageAppDataDirs(packageName)); 13457 clearDirectory(conn.mContainerService, 13458 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13459 } 13460 } 13461 } finally { 13462 mContext.unbindService(conn); 13463 } 13464 } 13465 } 13466 13467 @Override 13468 public void clearApplicationUserData(final String packageName, 13469 final IPackageDataObserver observer, final int userId) { 13470 mContext.enforceCallingOrSelfPermission( 13471 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13472 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13473 // Queue up an async operation since the package deletion may take a little while. 13474 mHandler.post(new Runnable() { 13475 public void run() { 13476 mHandler.removeCallbacks(this); 13477 final boolean succeeded; 13478 synchronized (mInstallLock) { 13479 succeeded = clearApplicationUserDataLI(packageName, userId); 13480 } 13481 clearExternalStorageDataSync(packageName, userId, true); 13482 if (succeeded) { 13483 // invoke DeviceStorageMonitor's update method to clear any notifications 13484 DeviceStorageMonitorInternal 13485 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13486 if (dsm != null) { 13487 dsm.checkMemory(); 13488 } 13489 } 13490 if(observer != null) { 13491 try { 13492 observer.onRemoveCompleted(packageName, succeeded); 13493 } catch (RemoteException e) { 13494 Log.i(TAG, "Observer no longer exists."); 13495 } 13496 } //end if observer 13497 } //end run 13498 }); 13499 } 13500 13501 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13502 if (packageName == null) { 13503 Slog.w(TAG, "Attempt to delete null packageName."); 13504 return false; 13505 } 13506 13507 // Try finding details about the requested package 13508 PackageParser.Package pkg; 13509 synchronized (mPackages) { 13510 pkg = mPackages.get(packageName); 13511 if (pkg == null) { 13512 final PackageSetting ps = mSettings.mPackages.get(packageName); 13513 if (ps != null) { 13514 pkg = ps.pkg; 13515 } 13516 } 13517 13518 if (pkg == null) { 13519 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13520 return false; 13521 } 13522 13523 PackageSetting ps = (PackageSetting) pkg.mExtras; 13524 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13525 } 13526 13527 // Always delete data directories for package, even if we found no other 13528 // record of app. This helps users recover from UID mismatches without 13529 // resorting to a full data wipe. 13530 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13531 if (retCode < 0) { 13532 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13533 return false; 13534 } 13535 13536 final int appId = pkg.applicationInfo.uid; 13537 removeKeystoreDataIfNeeded(userId, appId); 13538 13539 // Create a native library symlink only if we have native libraries 13540 // and if the native libraries are 32 bit libraries. We do not provide 13541 // this symlink for 64 bit libraries. 13542 if (pkg.applicationInfo.primaryCpuAbi != null && 13543 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13544 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13545 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13546 nativeLibPath, userId) < 0) { 13547 Slog.w(TAG, "Failed linking native library dir"); 13548 return false; 13549 } 13550 } 13551 13552 return true; 13553 } 13554 13555 /** 13556 * Reverts user permission state changes (permissions and flags) in 13557 * all packages for a given user. 13558 * 13559 * @param userId The device user for which to do a reset. 13560 */ 13561 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13562 final int packageCount = mPackages.size(); 13563 for (int i = 0; i < packageCount; i++) { 13564 PackageParser.Package pkg = mPackages.valueAt(i); 13565 PackageSetting ps = (PackageSetting) pkg.mExtras; 13566 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13567 } 13568 } 13569 13570 /** 13571 * Reverts user permission state changes (permissions and flags). 13572 * 13573 * @param ps The package for which to reset. 13574 * @param userId The device user for which to do a reset. 13575 */ 13576 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13577 final PackageSetting ps, final int userId) { 13578 if (ps.pkg == null) { 13579 return; 13580 } 13581 13582 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13583 | FLAG_PERMISSION_USER_FIXED 13584 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13585 13586 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13587 | FLAG_PERMISSION_POLICY_FIXED; 13588 13589 boolean writeInstallPermissions = false; 13590 boolean writeRuntimePermissions = false; 13591 13592 final int permissionCount = ps.pkg.requestedPermissions.size(); 13593 for (int i = 0; i < permissionCount; i++) { 13594 String permission = ps.pkg.requestedPermissions.get(i); 13595 13596 BasePermission bp = mSettings.mPermissions.get(permission); 13597 if (bp == null) { 13598 continue; 13599 } 13600 13601 // If shared user we just reset the state to which only this app contributed. 13602 if (ps.sharedUser != null) { 13603 boolean used = false; 13604 final int packageCount = ps.sharedUser.packages.size(); 13605 for (int j = 0; j < packageCount; j++) { 13606 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13607 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13608 && pkg.pkg.requestedPermissions.contains(permission)) { 13609 used = true; 13610 break; 13611 } 13612 } 13613 if (used) { 13614 continue; 13615 } 13616 } 13617 13618 PermissionsState permissionsState = ps.getPermissionsState(); 13619 13620 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13621 13622 // Always clear the user settable flags. 13623 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13624 bp.name) != null; 13625 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13626 if (hasInstallState) { 13627 writeInstallPermissions = true; 13628 } else { 13629 writeRuntimePermissions = true; 13630 } 13631 } 13632 13633 // Below is only runtime permission handling. 13634 if (!bp.isRuntime()) { 13635 continue; 13636 } 13637 13638 // Never clobber system or policy. 13639 if ((oldFlags & policyOrSystemFlags) != 0) { 13640 continue; 13641 } 13642 13643 // If this permission was granted by default, make sure it is. 13644 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13645 if (permissionsState.grantRuntimePermission(bp, userId) 13646 != PERMISSION_OPERATION_FAILURE) { 13647 writeRuntimePermissions = true; 13648 } 13649 } else { 13650 // Otherwise, reset the permission. 13651 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13652 switch (revokeResult) { 13653 case PERMISSION_OPERATION_SUCCESS: { 13654 writeRuntimePermissions = true; 13655 } break; 13656 13657 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13658 writeRuntimePermissions = true; 13659 final int appId = ps.appId; 13660 mHandler.post(new Runnable() { 13661 @Override 13662 public void run() { 13663 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13664 } 13665 }); 13666 } break; 13667 } 13668 } 13669 } 13670 13671 // Synchronously write as we are taking permissions away. 13672 if (writeRuntimePermissions) { 13673 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13674 } 13675 13676 // Synchronously write as we are taking permissions away. 13677 if (writeInstallPermissions) { 13678 mSettings.writeLPr(); 13679 } 13680 } 13681 13682 /** 13683 * Remove entries from the keystore daemon. Will only remove it if the 13684 * {@code appId} is valid. 13685 */ 13686 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13687 if (appId < 0) { 13688 return; 13689 } 13690 13691 final KeyStore keyStore = KeyStore.getInstance(); 13692 if (keyStore != null) { 13693 if (userId == UserHandle.USER_ALL) { 13694 for (final int individual : sUserManager.getUserIds()) { 13695 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13696 } 13697 } else { 13698 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13699 } 13700 } else { 13701 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13702 } 13703 } 13704 13705 @Override 13706 public void deleteApplicationCacheFiles(final String packageName, 13707 final IPackageDataObserver observer) { 13708 mContext.enforceCallingOrSelfPermission( 13709 android.Manifest.permission.DELETE_CACHE_FILES, null); 13710 // Queue up an async operation since the package deletion may take a little while. 13711 final int userId = UserHandle.getCallingUserId(); 13712 mHandler.post(new Runnable() { 13713 public void run() { 13714 mHandler.removeCallbacks(this); 13715 final boolean succeded; 13716 synchronized (mInstallLock) { 13717 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13718 } 13719 clearExternalStorageDataSync(packageName, userId, false); 13720 if (observer != null) { 13721 try { 13722 observer.onRemoveCompleted(packageName, succeded); 13723 } catch (RemoteException e) { 13724 Log.i(TAG, "Observer no longer exists."); 13725 } 13726 } //end if observer 13727 } //end run 13728 }); 13729 } 13730 13731 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13732 if (packageName == null) { 13733 Slog.w(TAG, "Attempt to delete null packageName."); 13734 return false; 13735 } 13736 PackageParser.Package p; 13737 synchronized (mPackages) { 13738 p = mPackages.get(packageName); 13739 } 13740 if (p == null) { 13741 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13742 return false; 13743 } 13744 final ApplicationInfo applicationInfo = p.applicationInfo; 13745 if (applicationInfo == null) { 13746 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13747 return false; 13748 } 13749 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13750 if (retCode < 0) { 13751 Slog.w(TAG, "Couldn't remove cache files for package: " 13752 + packageName + " u" + userId); 13753 return false; 13754 } 13755 return true; 13756 } 13757 13758 @Override 13759 public void getPackageSizeInfo(final String packageName, int userHandle, 13760 final IPackageStatsObserver observer) { 13761 mContext.enforceCallingOrSelfPermission( 13762 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13763 if (packageName == null) { 13764 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13765 } 13766 13767 PackageStats stats = new PackageStats(packageName, userHandle); 13768 13769 /* 13770 * Queue up an async operation since the package measurement may take a 13771 * little while. 13772 */ 13773 Message msg = mHandler.obtainMessage(INIT_COPY); 13774 msg.obj = new MeasureParams(stats, observer); 13775 mHandler.sendMessage(msg); 13776 } 13777 13778 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13779 PackageStats pStats) { 13780 if (packageName == null) { 13781 Slog.w(TAG, "Attempt to get size of null packageName."); 13782 return false; 13783 } 13784 PackageParser.Package p; 13785 boolean dataOnly = false; 13786 String libDirRoot = null; 13787 String asecPath = null; 13788 PackageSetting ps = null; 13789 synchronized (mPackages) { 13790 p = mPackages.get(packageName); 13791 ps = mSettings.mPackages.get(packageName); 13792 if(p == null) { 13793 dataOnly = true; 13794 if((ps == null) || (ps.pkg == null)) { 13795 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13796 return false; 13797 } 13798 p = ps.pkg; 13799 } 13800 if (ps != null) { 13801 libDirRoot = ps.legacyNativeLibraryPathString; 13802 } 13803 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13804 final long token = Binder.clearCallingIdentity(); 13805 try { 13806 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13807 if (secureContainerId != null) { 13808 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13809 } 13810 } finally { 13811 Binder.restoreCallingIdentity(token); 13812 } 13813 } 13814 } 13815 String publicSrcDir = null; 13816 if(!dataOnly) { 13817 final ApplicationInfo applicationInfo = p.applicationInfo; 13818 if (applicationInfo == null) { 13819 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13820 return false; 13821 } 13822 if (p.isForwardLocked()) { 13823 publicSrcDir = applicationInfo.getBaseResourcePath(); 13824 } 13825 } 13826 // TODO: extend to measure size of split APKs 13827 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13828 // not just the first level. 13829 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13830 // just the primary. 13831 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13832 13833 String apkPath; 13834 File packageDir = new File(p.codePath); 13835 13836 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13837 apkPath = packageDir.getAbsolutePath(); 13838 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13839 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13840 libDirRoot = null; 13841 } 13842 } else { 13843 apkPath = p.baseCodePath; 13844 } 13845 13846 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13847 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13848 if (res < 0) { 13849 return false; 13850 } 13851 13852 // Fix-up for forward-locked applications in ASEC containers. 13853 if (!isExternal(p)) { 13854 pStats.codeSize += pStats.externalCodeSize; 13855 pStats.externalCodeSize = 0L; 13856 } 13857 13858 return true; 13859 } 13860 13861 13862 @Override 13863 public void addPackageToPreferred(String packageName) { 13864 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13865 } 13866 13867 @Override 13868 public void removePackageFromPreferred(String packageName) { 13869 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13870 } 13871 13872 @Override 13873 public List<PackageInfo> getPreferredPackages(int flags) { 13874 return new ArrayList<PackageInfo>(); 13875 } 13876 13877 private int getUidTargetSdkVersionLockedLPr(int uid) { 13878 Object obj = mSettings.getUserIdLPr(uid); 13879 if (obj instanceof SharedUserSetting) { 13880 final SharedUserSetting sus = (SharedUserSetting) obj; 13881 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13882 final Iterator<PackageSetting> it = sus.packages.iterator(); 13883 while (it.hasNext()) { 13884 final PackageSetting ps = it.next(); 13885 if (ps.pkg != null) { 13886 int v = ps.pkg.applicationInfo.targetSdkVersion; 13887 if (v < vers) vers = v; 13888 } 13889 } 13890 return vers; 13891 } else if (obj instanceof PackageSetting) { 13892 final PackageSetting ps = (PackageSetting) obj; 13893 if (ps.pkg != null) { 13894 return ps.pkg.applicationInfo.targetSdkVersion; 13895 } 13896 } 13897 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13898 } 13899 13900 @Override 13901 public void addPreferredActivity(IntentFilter filter, int match, 13902 ComponentName[] set, ComponentName activity, int userId) { 13903 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13904 "Adding preferred"); 13905 } 13906 13907 private void addPreferredActivityInternal(IntentFilter filter, int match, 13908 ComponentName[] set, ComponentName activity, boolean always, int userId, 13909 String opname) { 13910 // writer 13911 int callingUid = Binder.getCallingUid(); 13912 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13913 if (filter.countActions() == 0) { 13914 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13915 return; 13916 } 13917 synchronized (mPackages) { 13918 if (mContext.checkCallingOrSelfPermission( 13919 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13920 != PackageManager.PERMISSION_GRANTED) { 13921 if (getUidTargetSdkVersionLockedLPr(callingUid) 13922 < Build.VERSION_CODES.FROYO) { 13923 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13924 + callingUid); 13925 return; 13926 } 13927 mContext.enforceCallingOrSelfPermission( 13928 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13929 } 13930 13931 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13932 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13933 + userId + ":"); 13934 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13935 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13936 scheduleWritePackageRestrictionsLocked(userId); 13937 } 13938 } 13939 13940 @Override 13941 public void replacePreferredActivity(IntentFilter filter, int match, 13942 ComponentName[] set, ComponentName activity, int userId) { 13943 if (filter.countActions() != 1) { 13944 throw new IllegalArgumentException( 13945 "replacePreferredActivity expects filter to have only 1 action."); 13946 } 13947 if (filter.countDataAuthorities() != 0 13948 || filter.countDataPaths() != 0 13949 || filter.countDataSchemes() > 1 13950 || filter.countDataTypes() != 0) { 13951 throw new IllegalArgumentException( 13952 "replacePreferredActivity expects filter to have no data authorities, " + 13953 "paths, or types; and at most one scheme."); 13954 } 13955 13956 final int callingUid = Binder.getCallingUid(); 13957 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13958 synchronized (mPackages) { 13959 if (mContext.checkCallingOrSelfPermission( 13960 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13961 != PackageManager.PERMISSION_GRANTED) { 13962 if (getUidTargetSdkVersionLockedLPr(callingUid) 13963 < Build.VERSION_CODES.FROYO) { 13964 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13965 + Binder.getCallingUid()); 13966 return; 13967 } 13968 mContext.enforceCallingOrSelfPermission( 13969 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13970 } 13971 13972 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13973 if (pir != null) { 13974 // Get all of the existing entries that exactly match this filter. 13975 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13976 if (existing != null && existing.size() == 1) { 13977 PreferredActivity cur = existing.get(0); 13978 if (DEBUG_PREFERRED) { 13979 Slog.i(TAG, "Checking replace of preferred:"); 13980 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13981 if (!cur.mPref.mAlways) { 13982 Slog.i(TAG, " -- CUR; not mAlways!"); 13983 } else { 13984 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13985 Slog.i(TAG, " -- CUR: mSet=" 13986 + Arrays.toString(cur.mPref.mSetComponents)); 13987 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13988 Slog.i(TAG, " -- NEW: mMatch=" 13989 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13990 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13991 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13992 } 13993 } 13994 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13995 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13996 && cur.mPref.sameSet(set)) { 13997 // Setting the preferred activity to what it happens to be already 13998 if (DEBUG_PREFERRED) { 13999 Slog.i(TAG, "Replacing with same preferred activity " 14000 + cur.mPref.mShortComponent + " for user " 14001 + userId + ":"); 14002 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14003 } 14004 return; 14005 } 14006 } 14007 14008 if (existing != null) { 14009 if (DEBUG_PREFERRED) { 14010 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14011 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14012 } 14013 for (int i = 0; i < existing.size(); i++) { 14014 PreferredActivity pa = existing.get(i); 14015 if (DEBUG_PREFERRED) { 14016 Slog.i(TAG, "Removing existing preferred activity " 14017 + pa.mPref.mComponent + ":"); 14018 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14019 } 14020 pir.removeFilter(pa); 14021 } 14022 } 14023 } 14024 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14025 "Replacing preferred"); 14026 } 14027 } 14028 14029 @Override 14030 public void clearPackagePreferredActivities(String packageName) { 14031 final int uid = Binder.getCallingUid(); 14032 // writer 14033 synchronized (mPackages) { 14034 PackageParser.Package pkg = mPackages.get(packageName); 14035 if (pkg == null || pkg.applicationInfo.uid != uid) { 14036 if (mContext.checkCallingOrSelfPermission( 14037 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14038 != PackageManager.PERMISSION_GRANTED) { 14039 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14040 < Build.VERSION_CODES.FROYO) { 14041 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14042 + Binder.getCallingUid()); 14043 return; 14044 } 14045 mContext.enforceCallingOrSelfPermission( 14046 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14047 } 14048 } 14049 14050 int user = UserHandle.getCallingUserId(); 14051 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14052 scheduleWritePackageRestrictionsLocked(user); 14053 } 14054 } 14055 } 14056 14057 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14058 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14059 ArrayList<PreferredActivity> removed = null; 14060 boolean changed = false; 14061 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14062 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14063 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14064 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14065 continue; 14066 } 14067 Iterator<PreferredActivity> it = pir.filterIterator(); 14068 while (it.hasNext()) { 14069 PreferredActivity pa = it.next(); 14070 // Mark entry for removal only if it matches the package name 14071 // and the entry is of type "always". 14072 if (packageName == null || 14073 (pa.mPref.mComponent.getPackageName().equals(packageName) 14074 && pa.mPref.mAlways)) { 14075 if (removed == null) { 14076 removed = new ArrayList<PreferredActivity>(); 14077 } 14078 removed.add(pa); 14079 } 14080 } 14081 if (removed != null) { 14082 for (int j=0; j<removed.size(); j++) { 14083 PreferredActivity pa = removed.get(j); 14084 pir.removeFilter(pa); 14085 } 14086 changed = true; 14087 } 14088 } 14089 return changed; 14090 } 14091 14092 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14093 private void clearIntentFilterVerificationsLPw(int userId) { 14094 final int packageCount = mPackages.size(); 14095 for (int i = 0; i < packageCount; i++) { 14096 PackageParser.Package pkg = mPackages.valueAt(i); 14097 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14098 } 14099 } 14100 14101 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14102 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14103 if (userId == UserHandle.USER_ALL) { 14104 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14105 sUserManager.getUserIds())) { 14106 for (int oneUserId : sUserManager.getUserIds()) { 14107 scheduleWritePackageRestrictionsLocked(oneUserId); 14108 } 14109 } 14110 } else { 14111 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14112 scheduleWritePackageRestrictionsLocked(userId); 14113 } 14114 } 14115 } 14116 14117 void clearDefaultBrowserIfNeeded(String packageName) { 14118 for (int oneUserId : sUserManager.getUserIds()) { 14119 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14120 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14121 if (packageName.equals(defaultBrowserPackageName)) { 14122 setDefaultBrowserPackageName(null, oneUserId); 14123 } 14124 } 14125 } 14126 14127 @Override 14128 public void resetApplicationPreferences(int userId) { 14129 mContext.enforceCallingOrSelfPermission( 14130 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14131 // writer 14132 synchronized (mPackages) { 14133 final long identity = Binder.clearCallingIdentity(); 14134 try { 14135 clearPackagePreferredActivitiesLPw(null, userId); 14136 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14137 // TODO: We have to reset the default SMS and Phone. This requires 14138 // significant refactoring to keep all default apps in the package 14139 // manager (cleaner but more work) or have the services provide 14140 // callbacks to the package manager to request a default app reset. 14141 applyFactoryDefaultBrowserLPw(userId); 14142 clearIntentFilterVerificationsLPw(userId); 14143 primeDomainVerificationsLPw(userId); 14144 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14145 scheduleWritePackageRestrictionsLocked(userId); 14146 } finally { 14147 Binder.restoreCallingIdentity(identity); 14148 } 14149 } 14150 } 14151 14152 @Override 14153 public int getPreferredActivities(List<IntentFilter> outFilters, 14154 List<ComponentName> outActivities, String packageName) { 14155 14156 int num = 0; 14157 final int userId = UserHandle.getCallingUserId(); 14158 // reader 14159 synchronized (mPackages) { 14160 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14161 if (pir != null) { 14162 final Iterator<PreferredActivity> it = pir.filterIterator(); 14163 while (it.hasNext()) { 14164 final PreferredActivity pa = it.next(); 14165 if (packageName == null 14166 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14167 && pa.mPref.mAlways)) { 14168 if (outFilters != null) { 14169 outFilters.add(new IntentFilter(pa)); 14170 } 14171 if (outActivities != null) { 14172 outActivities.add(pa.mPref.mComponent); 14173 } 14174 } 14175 } 14176 } 14177 } 14178 14179 return num; 14180 } 14181 14182 @Override 14183 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14184 int userId) { 14185 int callingUid = Binder.getCallingUid(); 14186 if (callingUid != Process.SYSTEM_UID) { 14187 throw new SecurityException( 14188 "addPersistentPreferredActivity can only be run by the system"); 14189 } 14190 if (filter.countActions() == 0) { 14191 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14192 return; 14193 } 14194 synchronized (mPackages) { 14195 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14196 " :"); 14197 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14198 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14199 new PersistentPreferredActivity(filter, activity)); 14200 scheduleWritePackageRestrictionsLocked(userId); 14201 } 14202 } 14203 14204 @Override 14205 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14206 int callingUid = Binder.getCallingUid(); 14207 if (callingUid != Process.SYSTEM_UID) { 14208 throw new SecurityException( 14209 "clearPackagePersistentPreferredActivities can only be run by the system"); 14210 } 14211 ArrayList<PersistentPreferredActivity> removed = null; 14212 boolean changed = false; 14213 synchronized (mPackages) { 14214 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14215 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14216 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14217 .valueAt(i); 14218 if (userId != thisUserId) { 14219 continue; 14220 } 14221 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14222 while (it.hasNext()) { 14223 PersistentPreferredActivity ppa = it.next(); 14224 // Mark entry for removal only if it matches the package name. 14225 if (ppa.mComponent.getPackageName().equals(packageName)) { 14226 if (removed == null) { 14227 removed = new ArrayList<PersistentPreferredActivity>(); 14228 } 14229 removed.add(ppa); 14230 } 14231 } 14232 if (removed != null) { 14233 for (int j=0; j<removed.size(); j++) { 14234 PersistentPreferredActivity ppa = removed.get(j); 14235 ppir.removeFilter(ppa); 14236 } 14237 changed = true; 14238 } 14239 } 14240 14241 if (changed) { 14242 scheduleWritePackageRestrictionsLocked(userId); 14243 } 14244 } 14245 } 14246 14247 /** 14248 * Common machinery for picking apart a restored XML blob and passing 14249 * it to a caller-supplied functor to be applied to the running system. 14250 */ 14251 private void restoreFromXml(XmlPullParser parser, int userId, 14252 String expectedStartTag, BlobXmlRestorer functor) 14253 throws IOException, XmlPullParserException { 14254 int type; 14255 while ((type = parser.next()) != XmlPullParser.START_TAG 14256 && type != XmlPullParser.END_DOCUMENT) { 14257 } 14258 if (type != XmlPullParser.START_TAG) { 14259 // oops didn't find a start tag?! 14260 if (DEBUG_BACKUP) { 14261 Slog.e(TAG, "Didn't find start tag during restore"); 14262 } 14263 return; 14264 } 14265 14266 // this is supposed to be TAG_PREFERRED_BACKUP 14267 if (!expectedStartTag.equals(parser.getName())) { 14268 if (DEBUG_BACKUP) { 14269 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14270 } 14271 return; 14272 } 14273 14274 // skip interfering stuff, then we're aligned with the backing implementation 14275 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14276 functor.apply(parser, userId); 14277 } 14278 14279 private interface BlobXmlRestorer { 14280 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14281 } 14282 14283 /** 14284 * Non-Binder method, support for the backup/restore mechanism: write the 14285 * full set of preferred activities in its canonical XML format. Returns the 14286 * XML output as a byte array, or null if there is none. 14287 */ 14288 @Override 14289 public byte[] getPreferredActivityBackup(int userId) { 14290 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14291 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14292 } 14293 14294 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14295 try { 14296 final XmlSerializer serializer = new FastXmlSerializer(); 14297 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14298 serializer.startDocument(null, true); 14299 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14300 14301 synchronized (mPackages) { 14302 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14303 } 14304 14305 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14306 serializer.endDocument(); 14307 serializer.flush(); 14308 } catch (Exception e) { 14309 if (DEBUG_BACKUP) { 14310 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14311 } 14312 return null; 14313 } 14314 14315 return dataStream.toByteArray(); 14316 } 14317 14318 @Override 14319 public void restorePreferredActivities(byte[] backup, int userId) { 14320 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14321 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14322 } 14323 14324 try { 14325 final XmlPullParser parser = Xml.newPullParser(); 14326 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14327 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14328 new BlobXmlRestorer() { 14329 @Override 14330 public void apply(XmlPullParser parser, int userId) 14331 throws XmlPullParserException, IOException { 14332 synchronized (mPackages) { 14333 mSettings.readPreferredActivitiesLPw(parser, userId); 14334 } 14335 } 14336 } ); 14337 } catch (Exception e) { 14338 if (DEBUG_BACKUP) { 14339 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14340 } 14341 } 14342 } 14343 14344 /** 14345 * Non-Binder method, support for the backup/restore mechanism: write the 14346 * default browser (etc) settings in its canonical XML format. Returns the default 14347 * browser XML representation as a byte array, or null if there is none. 14348 */ 14349 @Override 14350 public byte[] getDefaultAppsBackup(int userId) { 14351 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14352 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14353 } 14354 14355 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14356 try { 14357 final XmlSerializer serializer = new FastXmlSerializer(); 14358 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14359 serializer.startDocument(null, true); 14360 serializer.startTag(null, TAG_DEFAULT_APPS); 14361 14362 synchronized (mPackages) { 14363 mSettings.writeDefaultAppsLPr(serializer, userId); 14364 } 14365 14366 serializer.endTag(null, TAG_DEFAULT_APPS); 14367 serializer.endDocument(); 14368 serializer.flush(); 14369 } catch (Exception e) { 14370 if (DEBUG_BACKUP) { 14371 Slog.e(TAG, "Unable to write default apps for backup", e); 14372 } 14373 return null; 14374 } 14375 14376 return dataStream.toByteArray(); 14377 } 14378 14379 @Override 14380 public void restoreDefaultApps(byte[] backup, int userId) { 14381 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14382 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14383 } 14384 14385 try { 14386 final XmlPullParser parser = Xml.newPullParser(); 14387 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14388 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14389 new BlobXmlRestorer() { 14390 @Override 14391 public void apply(XmlPullParser parser, int userId) 14392 throws XmlPullParserException, IOException { 14393 synchronized (mPackages) { 14394 mSettings.readDefaultAppsLPw(parser, userId); 14395 } 14396 } 14397 } ); 14398 } catch (Exception e) { 14399 if (DEBUG_BACKUP) { 14400 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14401 } 14402 } 14403 } 14404 14405 @Override 14406 public byte[] getIntentFilterVerificationBackup(int userId) { 14407 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14408 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14409 } 14410 14411 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14412 try { 14413 final XmlSerializer serializer = new FastXmlSerializer(); 14414 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14415 serializer.startDocument(null, true); 14416 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14417 14418 synchronized (mPackages) { 14419 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14420 } 14421 14422 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14423 serializer.endDocument(); 14424 serializer.flush(); 14425 } catch (Exception e) { 14426 if (DEBUG_BACKUP) { 14427 Slog.e(TAG, "Unable to write default apps for backup", e); 14428 } 14429 return null; 14430 } 14431 14432 return dataStream.toByteArray(); 14433 } 14434 14435 @Override 14436 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14437 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14438 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14439 } 14440 14441 try { 14442 final XmlPullParser parser = Xml.newPullParser(); 14443 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14444 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14445 new BlobXmlRestorer() { 14446 @Override 14447 public void apply(XmlPullParser parser, int userId) 14448 throws XmlPullParserException, IOException { 14449 synchronized (mPackages) { 14450 mSettings.readAllDomainVerificationsLPr(parser, userId); 14451 mSettings.writeLPr(); 14452 } 14453 } 14454 } ); 14455 } catch (Exception e) { 14456 if (DEBUG_BACKUP) { 14457 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14458 } 14459 } 14460 } 14461 14462 @Override 14463 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14464 int sourceUserId, int targetUserId, int flags) { 14465 mContext.enforceCallingOrSelfPermission( 14466 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14467 int callingUid = Binder.getCallingUid(); 14468 enforceOwnerRights(ownerPackage, callingUid); 14469 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14470 if (intentFilter.countActions() == 0) { 14471 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14472 return; 14473 } 14474 synchronized (mPackages) { 14475 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14476 ownerPackage, targetUserId, flags); 14477 CrossProfileIntentResolver resolver = 14478 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14479 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14480 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14481 if (existing != null) { 14482 int size = existing.size(); 14483 for (int i = 0; i < size; i++) { 14484 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14485 return; 14486 } 14487 } 14488 } 14489 resolver.addFilter(newFilter); 14490 scheduleWritePackageRestrictionsLocked(sourceUserId); 14491 } 14492 } 14493 14494 @Override 14495 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14496 mContext.enforceCallingOrSelfPermission( 14497 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14498 int callingUid = Binder.getCallingUid(); 14499 enforceOwnerRights(ownerPackage, callingUid); 14500 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14501 synchronized (mPackages) { 14502 CrossProfileIntentResolver resolver = 14503 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14504 ArraySet<CrossProfileIntentFilter> set = 14505 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14506 for (CrossProfileIntentFilter filter : set) { 14507 if (filter.getOwnerPackage().equals(ownerPackage)) { 14508 resolver.removeFilter(filter); 14509 } 14510 } 14511 scheduleWritePackageRestrictionsLocked(sourceUserId); 14512 } 14513 } 14514 14515 // Enforcing that callingUid is owning pkg on userId 14516 private void enforceOwnerRights(String pkg, int callingUid) { 14517 // The system owns everything. 14518 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14519 return; 14520 } 14521 int callingUserId = UserHandle.getUserId(callingUid); 14522 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14523 if (pi == null) { 14524 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14525 + callingUserId); 14526 } 14527 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14528 throw new SecurityException("Calling uid " + callingUid 14529 + " does not own package " + pkg); 14530 } 14531 } 14532 14533 @Override 14534 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14535 Intent intent = new Intent(Intent.ACTION_MAIN); 14536 intent.addCategory(Intent.CATEGORY_HOME); 14537 14538 final int callingUserId = UserHandle.getCallingUserId(); 14539 List<ResolveInfo> list = queryIntentActivities(intent, null, 14540 PackageManager.GET_META_DATA, callingUserId); 14541 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14542 true, false, false, callingUserId); 14543 14544 allHomeCandidates.clear(); 14545 if (list != null) { 14546 for (ResolveInfo ri : list) { 14547 allHomeCandidates.add(ri); 14548 } 14549 } 14550 return (preferred == null || preferred.activityInfo == null) 14551 ? null 14552 : new ComponentName(preferred.activityInfo.packageName, 14553 preferred.activityInfo.name); 14554 } 14555 14556 @Override 14557 public void setApplicationEnabledSetting(String appPackageName, 14558 int newState, int flags, int userId, String callingPackage) { 14559 if (!sUserManager.exists(userId)) return; 14560 if (callingPackage == null) { 14561 callingPackage = Integer.toString(Binder.getCallingUid()); 14562 } 14563 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14564 } 14565 14566 @Override 14567 public void setComponentEnabledSetting(ComponentName componentName, 14568 int newState, int flags, int userId) { 14569 if (!sUserManager.exists(userId)) return; 14570 setEnabledSetting(componentName.getPackageName(), 14571 componentName.getClassName(), newState, flags, userId, null); 14572 } 14573 14574 private void setEnabledSetting(final String packageName, String className, int newState, 14575 final int flags, int userId, String callingPackage) { 14576 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14577 || newState == COMPONENT_ENABLED_STATE_ENABLED 14578 || newState == COMPONENT_ENABLED_STATE_DISABLED 14579 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14580 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14581 throw new IllegalArgumentException("Invalid new component state: " 14582 + newState); 14583 } 14584 PackageSetting pkgSetting; 14585 final int uid = Binder.getCallingUid(); 14586 final int permission = mContext.checkCallingOrSelfPermission( 14587 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14588 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14589 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14590 boolean sendNow = false; 14591 boolean isApp = (className == null); 14592 String componentName = isApp ? packageName : className; 14593 int packageUid = -1; 14594 ArrayList<String> components; 14595 14596 // writer 14597 synchronized (mPackages) { 14598 pkgSetting = mSettings.mPackages.get(packageName); 14599 if (pkgSetting == null) { 14600 if (className == null) { 14601 throw new IllegalArgumentException( 14602 "Unknown package: " + packageName); 14603 } 14604 throw new IllegalArgumentException( 14605 "Unknown component: " + packageName 14606 + "/" + className); 14607 } 14608 // Allow root and verify that userId is not being specified by a different user 14609 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14610 throw new SecurityException( 14611 "Permission Denial: attempt to change component state from pid=" 14612 + Binder.getCallingPid() 14613 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14614 } 14615 if (className == null) { 14616 // We're dealing with an application/package level state change 14617 if (pkgSetting.getEnabled(userId) == newState) { 14618 // Nothing to do 14619 return; 14620 } 14621 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14622 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14623 // Don't care about who enables an app. 14624 callingPackage = null; 14625 } 14626 pkgSetting.setEnabled(newState, userId, callingPackage); 14627 // pkgSetting.pkg.mSetEnabled = newState; 14628 } else { 14629 // We're dealing with a component level state change 14630 // First, verify that this is a valid class name. 14631 PackageParser.Package pkg = pkgSetting.pkg; 14632 if (pkg == null || !pkg.hasComponentClassName(className)) { 14633 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14634 throw new IllegalArgumentException("Component class " + className 14635 + " does not exist in " + packageName); 14636 } else { 14637 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14638 + className + " does not exist in " + packageName); 14639 } 14640 } 14641 switch (newState) { 14642 case COMPONENT_ENABLED_STATE_ENABLED: 14643 if (!pkgSetting.enableComponentLPw(className, userId)) { 14644 return; 14645 } 14646 break; 14647 case COMPONENT_ENABLED_STATE_DISABLED: 14648 if (!pkgSetting.disableComponentLPw(className, userId)) { 14649 return; 14650 } 14651 break; 14652 case COMPONENT_ENABLED_STATE_DEFAULT: 14653 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14654 return; 14655 } 14656 break; 14657 default: 14658 Slog.e(TAG, "Invalid new component state: " + newState); 14659 return; 14660 } 14661 } 14662 scheduleWritePackageRestrictionsLocked(userId); 14663 components = mPendingBroadcasts.get(userId, packageName); 14664 final boolean newPackage = components == null; 14665 if (newPackage) { 14666 components = new ArrayList<String>(); 14667 } 14668 if (!components.contains(componentName)) { 14669 components.add(componentName); 14670 } 14671 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14672 sendNow = true; 14673 // Purge entry from pending broadcast list if another one exists already 14674 // since we are sending one right away. 14675 mPendingBroadcasts.remove(userId, packageName); 14676 } else { 14677 if (newPackage) { 14678 mPendingBroadcasts.put(userId, packageName, components); 14679 } 14680 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14681 // Schedule a message 14682 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14683 } 14684 } 14685 } 14686 14687 long callingId = Binder.clearCallingIdentity(); 14688 try { 14689 if (sendNow) { 14690 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14691 sendPackageChangedBroadcast(packageName, 14692 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14693 } 14694 } finally { 14695 Binder.restoreCallingIdentity(callingId); 14696 } 14697 } 14698 14699 private void sendPackageChangedBroadcast(String packageName, 14700 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14701 if (DEBUG_INSTALL) 14702 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14703 + componentNames); 14704 Bundle extras = new Bundle(4); 14705 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14706 String nameList[] = new String[componentNames.size()]; 14707 componentNames.toArray(nameList); 14708 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14709 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14710 extras.putInt(Intent.EXTRA_UID, packageUid); 14711 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14712 new int[] {UserHandle.getUserId(packageUid)}); 14713 } 14714 14715 @Override 14716 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14717 if (!sUserManager.exists(userId)) return; 14718 final int uid = Binder.getCallingUid(); 14719 final int permission = mContext.checkCallingOrSelfPermission( 14720 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14721 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14722 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14723 // writer 14724 synchronized (mPackages) { 14725 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14726 allowedByPermission, uid, userId)) { 14727 scheduleWritePackageRestrictionsLocked(userId); 14728 } 14729 } 14730 } 14731 14732 @Override 14733 public String getInstallerPackageName(String packageName) { 14734 // reader 14735 synchronized (mPackages) { 14736 return mSettings.getInstallerPackageNameLPr(packageName); 14737 } 14738 } 14739 14740 @Override 14741 public int getApplicationEnabledSetting(String packageName, int userId) { 14742 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14743 int uid = Binder.getCallingUid(); 14744 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14745 // reader 14746 synchronized (mPackages) { 14747 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14748 } 14749 } 14750 14751 @Override 14752 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14753 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14754 int uid = Binder.getCallingUid(); 14755 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14756 // reader 14757 synchronized (mPackages) { 14758 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14759 } 14760 } 14761 14762 @Override 14763 public void enterSafeMode() { 14764 enforceSystemOrRoot("Only the system can request entering safe mode"); 14765 14766 if (!mSystemReady) { 14767 mSafeMode = true; 14768 } 14769 } 14770 14771 @Override 14772 public void systemReady() { 14773 mSystemReady = true; 14774 14775 // Read the compatibilty setting when the system is ready. 14776 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14777 mContext.getContentResolver(), 14778 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14779 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14780 if (DEBUG_SETTINGS) { 14781 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14782 } 14783 14784 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14785 14786 synchronized (mPackages) { 14787 // Verify that all of the preferred activity components actually 14788 // exist. It is possible for applications to be updated and at 14789 // that point remove a previously declared activity component that 14790 // had been set as a preferred activity. We try to clean this up 14791 // the next time we encounter that preferred activity, but it is 14792 // possible for the user flow to never be able to return to that 14793 // situation so here we do a sanity check to make sure we haven't 14794 // left any junk around. 14795 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14796 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14797 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14798 removed.clear(); 14799 for (PreferredActivity pa : pir.filterSet()) { 14800 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14801 removed.add(pa); 14802 } 14803 } 14804 if (removed.size() > 0) { 14805 for (int r=0; r<removed.size(); r++) { 14806 PreferredActivity pa = removed.get(r); 14807 Slog.w(TAG, "Removing dangling preferred activity: " 14808 + pa.mPref.mComponent); 14809 pir.removeFilter(pa); 14810 } 14811 mSettings.writePackageRestrictionsLPr( 14812 mSettings.mPreferredActivities.keyAt(i)); 14813 } 14814 } 14815 14816 for (int userId : UserManagerService.getInstance().getUserIds()) { 14817 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14818 grantPermissionsUserIds = ArrayUtils.appendInt( 14819 grantPermissionsUserIds, userId); 14820 } 14821 } 14822 } 14823 sUserManager.systemReady(); 14824 14825 // If we upgraded grant all default permissions before kicking off. 14826 for (int userId : grantPermissionsUserIds) { 14827 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14828 } 14829 14830 // Kick off any messages waiting for system ready 14831 if (mPostSystemReadyMessages != null) { 14832 for (Message msg : mPostSystemReadyMessages) { 14833 msg.sendToTarget(); 14834 } 14835 mPostSystemReadyMessages = null; 14836 } 14837 14838 // Watch for external volumes that come and go over time 14839 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14840 storage.registerListener(mStorageListener); 14841 14842 mInstallerService.systemReady(); 14843 mPackageDexOptimizer.systemReady(); 14844 14845 MountServiceInternal mountServiceInternal = LocalServices.getService( 14846 MountServiceInternal.class); 14847 mountServiceInternal.addExternalStoragePolicy( 14848 new MountServiceInternal.ExternalStorageMountPolicy() { 14849 @Override 14850 public int getMountMode(int uid, String packageName) { 14851 if (Process.isIsolated(uid)) { 14852 return Zygote.MOUNT_EXTERNAL_NONE; 14853 } 14854 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14855 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14856 } 14857 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14858 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14859 } 14860 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14861 return Zygote.MOUNT_EXTERNAL_READ; 14862 } 14863 return Zygote.MOUNT_EXTERNAL_WRITE; 14864 } 14865 14866 @Override 14867 public boolean hasExternalStorage(int uid, String packageName) { 14868 return true; 14869 } 14870 }); 14871 } 14872 14873 @Override 14874 public boolean isSafeMode() { 14875 return mSafeMode; 14876 } 14877 14878 @Override 14879 public boolean hasSystemUidErrors() { 14880 return mHasSystemUidErrors; 14881 } 14882 14883 static String arrayToString(int[] array) { 14884 StringBuffer buf = new StringBuffer(128); 14885 buf.append('['); 14886 if (array != null) { 14887 for (int i=0; i<array.length; i++) { 14888 if (i > 0) buf.append(", "); 14889 buf.append(array[i]); 14890 } 14891 } 14892 buf.append(']'); 14893 return buf.toString(); 14894 } 14895 14896 static class DumpState { 14897 public static final int DUMP_LIBS = 1 << 0; 14898 public static final int DUMP_FEATURES = 1 << 1; 14899 public static final int DUMP_RESOLVERS = 1 << 2; 14900 public static final int DUMP_PERMISSIONS = 1 << 3; 14901 public static final int DUMP_PACKAGES = 1 << 4; 14902 public static final int DUMP_SHARED_USERS = 1 << 5; 14903 public static final int DUMP_MESSAGES = 1 << 6; 14904 public static final int DUMP_PROVIDERS = 1 << 7; 14905 public static final int DUMP_VERIFIERS = 1 << 8; 14906 public static final int DUMP_PREFERRED = 1 << 9; 14907 public static final int DUMP_PREFERRED_XML = 1 << 10; 14908 public static final int DUMP_KEYSETS = 1 << 11; 14909 public static final int DUMP_VERSION = 1 << 12; 14910 public static final int DUMP_INSTALLS = 1 << 13; 14911 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14912 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14913 14914 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14915 14916 private int mTypes; 14917 14918 private int mOptions; 14919 14920 private boolean mTitlePrinted; 14921 14922 private SharedUserSetting mSharedUser; 14923 14924 public boolean isDumping(int type) { 14925 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14926 return true; 14927 } 14928 14929 return (mTypes & type) != 0; 14930 } 14931 14932 public void setDump(int type) { 14933 mTypes |= type; 14934 } 14935 14936 public boolean isOptionEnabled(int option) { 14937 return (mOptions & option) != 0; 14938 } 14939 14940 public void setOptionEnabled(int option) { 14941 mOptions |= option; 14942 } 14943 14944 public boolean onTitlePrinted() { 14945 final boolean printed = mTitlePrinted; 14946 mTitlePrinted = true; 14947 return printed; 14948 } 14949 14950 public boolean getTitlePrinted() { 14951 return mTitlePrinted; 14952 } 14953 14954 public void setTitlePrinted(boolean enabled) { 14955 mTitlePrinted = enabled; 14956 } 14957 14958 public SharedUserSetting getSharedUser() { 14959 return mSharedUser; 14960 } 14961 14962 public void setSharedUser(SharedUserSetting user) { 14963 mSharedUser = user; 14964 } 14965 } 14966 14967 @Override 14968 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14969 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14970 != PackageManager.PERMISSION_GRANTED) { 14971 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14972 + Binder.getCallingPid() 14973 + ", uid=" + Binder.getCallingUid() 14974 + " without permission " 14975 + android.Manifest.permission.DUMP); 14976 return; 14977 } 14978 14979 DumpState dumpState = new DumpState(); 14980 boolean fullPreferred = false; 14981 boolean checkin = false; 14982 14983 String packageName = null; 14984 ArraySet<String> permissionNames = null; 14985 14986 int opti = 0; 14987 while (opti < args.length) { 14988 String opt = args[opti]; 14989 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14990 break; 14991 } 14992 opti++; 14993 14994 if ("-a".equals(opt)) { 14995 // Right now we only know how to print all. 14996 } else if ("-h".equals(opt)) { 14997 pw.println("Package manager dump options:"); 14998 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14999 pw.println(" --checkin: dump for a checkin"); 15000 pw.println(" -f: print details of intent filters"); 15001 pw.println(" -h: print this help"); 15002 pw.println(" cmd may be one of:"); 15003 pw.println(" l[ibraries]: list known shared libraries"); 15004 pw.println(" f[ibraries]: list device features"); 15005 pw.println(" k[eysets]: print known keysets"); 15006 pw.println(" r[esolvers]: dump intent resolvers"); 15007 pw.println(" perm[issions]: dump permissions"); 15008 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15009 pw.println(" pref[erred]: print preferred package settings"); 15010 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15011 pw.println(" prov[iders]: dump content providers"); 15012 pw.println(" p[ackages]: dump installed packages"); 15013 pw.println(" s[hared-users]: dump shared user IDs"); 15014 pw.println(" m[essages]: print collected runtime messages"); 15015 pw.println(" v[erifiers]: print package verifier info"); 15016 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15017 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15018 pw.println(" version: print database version info"); 15019 pw.println(" write: write current settings now"); 15020 pw.println(" installs: details about install sessions"); 15021 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15022 pw.println(" <package.name>: info about given package"); 15023 return; 15024 } else if ("--checkin".equals(opt)) { 15025 checkin = true; 15026 } else if ("-f".equals(opt)) { 15027 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15028 } else { 15029 pw.println("Unknown argument: " + opt + "; use -h for help"); 15030 } 15031 } 15032 15033 // Is the caller requesting to dump a particular piece of data? 15034 if (opti < args.length) { 15035 String cmd = args[opti]; 15036 opti++; 15037 // Is this a package name? 15038 if ("android".equals(cmd) || cmd.contains(".")) { 15039 packageName = cmd; 15040 // When dumping a single package, we always dump all of its 15041 // filter information since the amount of data will be reasonable. 15042 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15043 } else if ("check-permission".equals(cmd)) { 15044 if (opti >= args.length) { 15045 pw.println("Error: check-permission missing permission argument"); 15046 return; 15047 } 15048 String perm = args[opti]; 15049 opti++; 15050 if (opti >= args.length) { 15051 pw.println("Error: check-permission missing package argument"); 15052 return; 15053 } 15054 String pkg = args[opti]; 15055 opti++; 15056 int user = UserHandle.getUserId(Binder.getCallingUid()); 15057 if (opti < args.length) { 15058 try { 15059 user = Integer.parseInt(args[opti]); 15060 } catch (NumberFormatException e) { 15061 pw.println("Error: check-permission user argument is not a number: " 15062 + args[opti]); 15063 return; 15064 } 15065 } 15066 pw.println(checkPermission(perm, pkg, user)); 15067 return; 15068 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15069 dumpState.setDump(DumpState.DUMP_LIBS); 15070 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15071 dumpState.setDump(DumpState.DUMP_FEATURES); 15072 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15073 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15074 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15075 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15076 } else if ("permission".equals(cmd)) { 15077 if (opti >= args.length) { 15078 pw.println("Error: permission requires permission name"); 15079 return; 15080 } 15081 permissionNames = new ArraySet<>(); 15082 while (opti < args.length) { 15083 permissionNames.add(args[opti]); 15084 opti++; 15085 } 15086 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15087 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15088 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15089 dumpState.setDump(DumpState.DUMP_PREFERRED); 15090 } else if ("preferred-xml".equals(cmd)) { 15091 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15092 if (opti < args.length && "--full".equals(args[opti])) { 15093 fullPreferred = true; 15094 opti++; 15095 } 15096 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15097 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15098 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15099 dumpState.setDump(DumpState.DUMP_PACKAGES); 15100 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15101 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15102 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15103 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15104 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15105 dumpState.setDump(DumpState.DUMP_MESSAGES); 15106 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15107 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15108 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15109 || "intent-filter-verifiers".equals(cmd)) { 15110 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15111 } else if ("version".equals(cmd)) { 15112 dumpState.setDump(DumpState.DUMP_VERSION); 15113 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15114 dumpState.setDump(DumpState.DUMP_KEYSETS); 15115 } else if ("installs".equals(cmd)) { 15116 dumpState.setDump(DumpState.DUMP_INSTALLS); 15117 } else if ("write".equals(cmd)) { 15118 synchronized (mPackages) { 15119 mSettings.writeLPr(); 15120 pw.println("Settings written."); 15121 return; 15122 } 15123 } 15124 } 15125 15126 if (checkin) { 15127 pw.println("vers,1"); 15128 } 15129 15130 // reader 15131 synchronized (mPackages) { 15132 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15133 if (!checkin) { 15134 if (dumpState.onTitlePrinted()) 15135 pw.println(); 15136 pw.println("Database versions:"); 15137 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15138 } 15139 } 15140 15141 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15142 if (!checkin) { 15143 if (dumpState.onTitlePrinted()) 15144 pw.println(); 15145 pw.println("Verifiers:"); 15146 pw.print(" Required: "); 15147 pw.print(mRequiredVerifierPackage); 15148 pw.print(" (uid="); 15149 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15150 pw.println(")"); 15151 } else if (mRequiredVerifierPackage != null) { 15152 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15153 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15154 } 15155 } 15156 15157 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15158 packageName == null) { 15159 if (mIntentFilterVerifierComponent != null) { 15160 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15161 if (!checkin) { 15162 if (dumpState.onTitlePrinted()) 15163 pw.println(); 15164 pw.println("Intent Filter Verifier:"); 15165 pw.print(" Using: "); 15166 pw.print(verifierPackageName); 15167 pw.print(" (uid="); 15168 pw.print(getPackageUid(verifierPackageName, 0)); 15169 pw.println(")"); 15170 } else if (verifierPackageName != null) { 15171 pw.print("ifv,"); pw.print(verifierPackageName); 15172 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15173 } 15174 } else { 15175 pw.println(); 15176 pw.println("No Intent Filter Verifier available!"); 15177 } 15178 } 15179 15180 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15181 boolean printedHeader = false; 15182 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15183 while (it.hasNext()) { 15184 String name = it.next(); 15185 SharedLibraryEntry ent = mSharedLibraries.get(name); 15186 if (!checkin) { 15187 if (!printedHeader) { 15188 if (dumpState.onTitlePrinted()) 15189 pw.println(); 15190 pw.println("Libraries:"); 15191 printedHeader = true; 15192 } 15193 pw.print(" "); 15194 } else { 15195 pw.print("lib,"); 15196 } 15197 pw.print(name); 15198 if (!checkin) { 15199 pw.print(" -> "); 15200 } 15201 if (ent.path != null) { 15202 if (!checkin) { 15203 pw.print("(jar) "); 15204 pw.print(ent.path); 15205 } else { 15206 pw.print(",jar,"); 15207 pw.print(ent.path); 15208 } 15209 } else { 15210 if (!checkin) { 15211 pw.print("(apk) "); 15212 pw.print(ent.apk); 15213 } else { 15214 pw.print(",apk,"); 15215 pw.print(ent.apk); 15216 } 15217 } 15218 pw.println(); 15219 } 15220 } 15221 15222 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15223 if (dumpState.onTitlePrinted()) 15224 pw.println(); 15225 if (!checkin) { 15226 pw.println("Features:"); 15227 } 15228 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15229 while (it.hasNext()) { 15230 String name = it.next(); 15231 if (!checkin) { 15232 pw.print(" "); 15233 } else { 15234 pw.print("feat,"); 15235 } 15236 pw.println(name); 15237 } 15238 } 15239 15240 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15241 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15242 : "Activity Resolver Table:", " ", packageName, 15243 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15244 dumpState.setTitlePrinted(true); 15245 } 15246 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15247 : "Receiver Resolver Table:", " ", packageName, 15248 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15249 dumpState.setTitlePrinted(true); 15250 } 15251 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15252 : "Service Resolver Table:", " ", packageName, 15253 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15254 dumpState.setTitlePrinted(true); 15255 } 15256 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15257 : "Provider Resolver Table:", " ", packageName, 15258 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15259 dumpState.setTitlePrinted(true); 15260 } 15261 } 15262 15263 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15264 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15265 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15266 int user = mSettings.mPreferredActivities.keyAt(i); 15267 if (pir.dump(pw, 15268 dumpState.getTitlePrinted() 15269 ? "\nPreferred Activities User " + user + ":" 15270 : "Preferred Activities User " + user + ":", " ", 15271 packageName, true, false)) { 15272 dumpState.setTitlePrinted(true); 15273 } 15274 } 15275 } 15276 15277 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15278 pw.flush(); 15279 FileOutputStream fout = new FileOutputStream(fd); 15280 BufferedOutputStream str = new BufferedOutputStream(fout); 15281 XmlSerializer serializer = new FastXmlSerializer(); 15282 try { 15283 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15284 serializer.startDocument(null, true); 15285 serializer.setFeature( 15286 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15287 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15288 serializer.endDocument(); 15289 serializer.flush(); 15290 } catch (IllegalArgumentException e) { 15291 pw.println("Failed writing: " + e); 15292 } catch (IllegalStateException e) { 15293 pw.println("Failed writing: " + e); 15294 } catch (IOException e) { 15295 pw.println("Failed writing: " + e); 15296 } 15297 } 15298 15299 if (!checkin 15300 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15301 && packageName == null) { 15302 pw.println(); 15303 int count = mSettings.mPackages.size(); 15304 if (count == 0) { 15305 pw.println("No applications!"); 15306 pw.println(); 15307 } else { 15308 final String prefix = " "; 15309 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15310 if (allPackageSettings.size() == 0) { 15311 pw.println("No domain preferred apps!"); 15312 pw.println(); 15313 } else { 15314 pw.println("App verification status:"); 15315 pw.println(); 15316 count = 0; 15317 for (PackageSetting ps : allPackageSettings) { 15318 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15319 if (ivi == null || ivi.getPackageName() == null) continue; 15320 pw.println(prefix + "Package: " + ivi.getPackageName()); 15321 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15322 pw.println(prefix + "Status: " + ivi.getStatusString()); 15323 pw.println(); 15324 count++; 15325 } 15326 if (count == 0) { 15327 pw.println(prefix + "No app verification established."); 15328 pw.println(); 15329 } 15330 for (int userId : sUserManager.getUserIds()) { 15331 pw.println("App linkages for user " + userId + ":"); 15332 pw.println(); 15333 count = 0; 15334 for (PackageSetting ps : allPackageSettings) { 15335 final long status = ps.getDomainVerificationStatusForUser(userId); 15336 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15337 continue; 15338 } 15339 pw.println(prefix + "Package: " + ps.name); 15340 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15341 String statusStr = IntentFilterVerificationInfo. 15342 getStatusStringFromValue(status); 15343 pw.println(prefix + "Status: " + statusStr); 15344 pw.println(); 15345 count++; 15346 } 15347 if (count == 0) { 15348 pw.println(prefix + "No configured app linkages."); 15349 pw.println(); 15350 } 15351 } 15352 } 15353 } 15354 } 15355 15356 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15357 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15358 if (packageName == null && permissionNames == null) { 15359 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15360 if (iperm == 0) { 15361 if (dumpState.onTitlePrinted()) 15362 pw.println(); 15363 pw.println("AppOp Permissions:"); 15364 } 15365 pw.print(" AppOp Permission "); 15366 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15367 pw.println(":"); 15368 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15369 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15370 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15371 } 15372 } 15373 } 15374 } 15375 15376 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15377 boolean printedSomething = false; 15378 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15379 if (packageName != null && !packageName.equals(p.info.packageName)) { 15380 continue; 15381 } 15382 if (!printedSomething) { 15383 if (dumpState.onTitlePrinted()) 15384 pw.println(); 15385 pw.println("Registered ContentProviders:"); 15386 printedSomething = true; 15387 } 15388 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15389 pw.print(" "); pw.println(p.toString()); 15390 } 15391 printedSomething = false; 15392 for (Map.Entry<String, PackageParser.Provider> entry : 15393 mProvidersByAuthority.entrySet()) { 15394 PackageParser.Provider p = entry.getValue(); 15395 if (packageName != null && !packageName.equals(p.info.packageName)) { 15396 continue; 15397 } 15398 if (!printedSomething) { 15399 if (dumpState.onTitlePrinted()) 15400 pw.println(); 15401 pw.println("ContentProvider Authorities:"); 15402 printedSomething = true; 15403 } 15404 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15405 pw.print(" "); pw.println(p.toString()); 15406 if (p.info != null && p.info.applicationInfo != null) { 15407 final String appInfo = p.info.applicationInfo.toString(); 15408 pw.print(" applicationInfo="); pw.println(appInfo); 15409 } 15410 } 15411 } 15412 15413 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15414 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15415 } 15416 15417 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15418 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15419 } 15420 15421 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15422 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15423 } 15424 15425 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15426 // XXX should handle packageName != null by dumping only install data that 15427 // the given package is involved with. 15428 if (dumpState.onTitlePrinted()) pw.println(); 15429 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15430 } 15431 15432 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15433 if (dumpState.onTitlePrinted()) pw.println(); 15434 mSettings.dumpReadMessagesLPr(pw, dumpState); 15435 15436 pw.println(); 15437 pw.println("Package warning messages:"); 15438 BufferedReader in = null; 15439 String line = null; 15440 try { 15441 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15442 while ((line = in.readLine()) != null) { 15443 if (line.contains("ignored: updated version")) continue; 15444 pw.println(line); 15445 } 15446 } catch (IOException ignored) { 15447 } finally { 15448 IoUtils.closeQuietly(in); 15449 } 15450 } 15451 15452 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15453 BufferedReader in = null; 15454 String line = null; 15455 try { 15456 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15457 while ((line = in.readLine()) != null) { 15458 if (line.contains("ignored: updated version")) continue; 15459 pw.print("msg,"); 15460 pw.println(line); 15461 } 15462 } catch (IOException ignored) { 15463 } finally { 15464 IoUtils.closeQuietly(in); 15465 } 15466 } 15467 } 15468 } 15469 15470 private String dumpDomainString(String packageName) { 15471 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15472 List<IntentFilter> filters = getAllIntentFilters(packageName); 15473 15474 ArraySet<String> result = new ArraySet<>(); 15475 if (iviList.size() > 0) { 15476 for (IntentFilterVerificationInfo ivi : iviList) { 15477 for (String host : ivi.getDomains()) { 15478 result.add(host); 15479 } 15480 } 15481 } 15482 if (filters != null && filters.size() > 0) { 15483 for (IntentFilter filter : filters) { 15484 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15485 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15486 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15487 result.addAll(filter.getHostsList()); 15488 } 15489 } 15490 } 15491 15492 StringBuilder sb = new StringBuilder(result.size() * 16); 15493 for (String domain : result) { 15494 if (sb.length() > 0) sb.append(" "); 15495 sb.append(domain); 15496 } 15497 return sb.toString(); 15498 } 15499 15500 // ------- apps on sdcard specific code ------- 15501 static final boolean DEBUG_SD_INSTALL = false; 15502 15503 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15504 15505 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15506 15507 private boolean mMediaMounted = false; 15508 15509 static String getEncryptKey() { 15510 try { 15511 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15512 SD_ENCRYPTION_KEYSTORE_NAME); 15513 if (sdEncKey == null) { 15514 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15515 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15516 if (sdEncKey == null) { 15517 Slog.e(TAG, "Failed to create encryption keys"); 15518 return null; 15519 } 15520 } 15521 return sdEncKey; 15522 } catch (NoSuchAlgorithmException nsae) { 15523 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15524 return null; 15525 } catch (IOException ioe) { 15526 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15527 return null; 15528 } 15529 } 15530 15531 /* 15532 * Update media status on PackageManager. 15533 */ 15534 @Override 15535 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15536 int callingUid = Binder.getCallingUid(); 15537 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15538 throw new SecurityException("Media status can only be updated by the system"); 15539 } 15540 // reader; this apparently protects mMediaMounted, but should probably 15541 // be a different lock in that case. 15542 synchronized (mPackages) { 15543 Log.i(TAG, "Updating external media status from " 15544 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15545 + (mediaStatus ? "mounted" : "unmounted")); 15546 if (DEBUG_SD_INSTALL) 15547 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15548 + ", mMediaMounted=" + mMediaMounted); 15549 if (mediaStatus == mMediaMounted) { 15550 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15551 : 0, -1); 15552 mHandler.sendMessage(msg); 15553 return; 15554 } 15555 mMediaMounted = mediaStatus; 15556 } 15557 // Queue up an async operation since the package installation may take a 15558 // little while. 15559 mHandler.post(new Runnable() { 15560 public void run() { 15561 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15562 } 15563 }); 15564 } 15565 15566 /** 15567 * Called by MountService when the initial ASECs to scan are available. 15568 * Should block until all the ASEC containers are finished being scanned. 15569 */ 15570 public void scanAvailableAsecs() { 15571 updateExternalMediaStatusInner(true, false, false); 15572 if (mShouldRestoreconData) { 15573 SELinuxMMAC.setRestoreconDone(); 15574 mShouldRestoreconData = false; 15575 } 15576 } 15577 15578 /* 15579 * Collect information of applications on external media, map them against 15580 * existing containers and update information based on current mount status. 15581 * Please note that we always have to report status if reportStatus has been 15582 * set to true especially when unloading packages. 15583 */ 15584 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15585 boolean externalStorage) { 15586 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15587 int[] uidArr = EmptyArray.INT; 15588 15589 final String[] list = PackageHelper.getSecureContainerList(); 15590 if (ArrayUtils.isEmpty(list)) { 15591 Log.i(TAG, "No secure containers found"); 15592 } else { 15593 // Process list of secure containers and categorize them 15594 // as active or stale based on their package internal state. 15595 15596 // reader 15597 synchronized (mPackages) { 15598 for (String cid : list) { 15599 // Leave stages untouched for now; installer service owns them 15600 if (PackageInstallerService.isStageName(cid)) continue; 15601 15602 if (DEBUG_SD_INSTALL) 15603 Log.i(TAG, "Processing container " + cid); 15604 String pkgName = getAsecPackageName(cid); 15605 if (pkgName == null) { 15606 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15607 continue; 15608 } 15609 if (DEBUG_SD_INSTALL) 15610 Log.i(TAG, "Looking for pkg : " + pkgName); 15611 15612 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15613 if (ps == null) { 15614 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15615 continue; 15616 } 15617 15618 /* 15619 * Skip packages that are not external if we're unmounting 15620 * external storage. 15621 */ 15622 if (externalStorage && !isMounted && !isExternal(ps)) { 15623 continue; 15624 } 15625 15626 final AsecInstallArgs args = new AsecInstallArgs(cid, 15627 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15628 // The package status is changed only if the code path 15629 // matches between settings and the container id. 15630 if (ps.codePathString != null 15631 && ps.codePathString.startsWith(args.getCodePath())) { 15632 if (DEBUG_SD_INSTALL) { 15633 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15634 + " at code path: " + ps.codePathString); 15635 } 15636 15637 // We do have a valid package installed on sdcard 15638 processCids.put(args, ps.codePathString); 15639 final int uid = ps.appId; 15640 if (uid != -1) { 15641 uidArr = ArrayUtils.appendInt(uidArr, uid); 15642 } 15643 } else { 15644 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15645 + ps.codePathString); 15646 } 15647 } 15648 } 15649 15650 Arrays.sort(uidArr); 15651 } 15652 15653 // Process packages with valid entries. 15654 if (isMounted) { 15655 if (DEBUG_SD_INSTALL) 15656 Log.i(TAG, "Loading packages"); 15657 loadMediaPackages(processCids, uidArr); 15658 startCleaningPackages(); 15659 mInstallerService.onSecureContainersAvailable(); 15660 } else { 15661 if (DEBUG_SD_INSTALL) 15662 Log.i(TAG, "Unloading packages"); 15663 unloadMediaPackages(processCids, uidArr, reportStatus); 15664 } 15665 } 15666 15667 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15668 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15669 final int size = infos.size(); 15670 final String[] packageNames = new String[size]; 15671 final int[] packageUids = new int[size]; 15672 for (int i = 0; i < size; i++) { 15673 final ApplicationInfo info = infos.get(i); 15674 packageNames[i] = info.packageName; 15675 packageUids[i] = info.uid; 15676 } 15677 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15678 finishedReceiver); 15679 } 15680 15681 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15682 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15683 sendResourcesChangedBroadcast(mediaStatus, replacing, 15684 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15685 } 15686 15687 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15688 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15689 int size = pkgList.length; 15690 if (size > 0) { 15691 // Send broadcasts here 15692 Bundle extras = new Bundle(); 15693 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15694 if (uidArr != null) { 15695 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15696 } 15697 if (replacing) { 15698 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15699 } 15700 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15701 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15702 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15703 } 15704 } 15705 15706 /* 15707 * Look at potentially valid container ids from processCids If package 15708 * information doesn't match the one on record or package scanning fails, 15709 * the cid is added to list of removeCids. We currently don't delete stale 15710 * containers. 15711 */ 15712 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15713 ArrayList<String> pkgList = new ArrayList<String>(); 15714 Set<AsecInstallArgs> keys = processCids.keySet(); 15715 15716 for (AsecInstallArgs args : keys) { 15717 String codePath = processCids.get(args); 15718 if (DEBUG_SD_INSTALL) 15719 Log.i(TAG, "Loading container : " + args.cid); 15720 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15721 try { 15722 // Make sure there are no container errors first. 15723 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15724 Slog.e(TAG, "Failed to mount cid : " + args.cid 15725 + " when installing from sdcard"); 15726 continue; 15727 } 15728 // Check code path here. 15729 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15730 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15731 + " does not match one in settings " + codePath); 15732 continue; 15733 } 15734 // Parse package 15735 int parseFlags = mDefParseFlags; 15736 if (args.isExternalAsec()) { 15737 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15738 } 15739 if (args.isFwdLocked()) { 15740 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15741 } 15742 15743 synchronized (mInstallLock) { 15744 PackageParser.Package pkg = null; 15745 try { 15746 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15747 } catch (PackageManagerException e) { 15748 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15749 } 15750 // Scan the package 15751 if (pkg != null) { 15752 /* 15753 * TODO why is the lock being held? doPostInstall is 15754 * called in other places without the lock. This needs 15755 * to be straightened out. 15756 */ 15757 // writer 15758 synchronized (mPackages) { 15759 retCode = PackageManager.INSTALL_SUCCEEDED; 15760 pkgList.add(pkg.packageName); 15761 // Post process args 15762 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15763 pkg.applicationInfo.uid); 15764 } 15765 } else { 15766 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15767 } 15768 } 15769 15770 } finally { 15771 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15772 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15773 } 15774 } 15775 } 15776 // writer 15777 synchronized (mPackages) { 15778 // If the platform SDK has changed since the last time we booted, 15779 // we need to re-grant app permission to catch any new ones that 15780 // appear. This is really a hack, and means that apps can in some 15781 // cases get permissions that the user didn't initially explicitly 15782 // allow... it would be nice to have some better way to handle 15783 // this situation. 15784 final VersionInfo ver = mSettings.getExternalVersion(); 15785 15786 int updateFlags = UPDATE_PERMISSIONS_ALL; 15787 if (ver.sdkVersion != mSdkVersion) { 15788 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15789 + mSdkVersion + "; regranting permissions for external"); 15790 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15791 } 15792 updatePermissionsLPw(null, null, updateFlags); 15793 15794 // Yay, everything is now upgraded 15795 ver.forceCurrent(); 15796 15797 // can downgrade to reader 15798 // Persist settings 15799 mSettings.writeLPr(); 15800 } 15801 // Send a broadcast to let everyone know we are done processing 15802 if (pkgList.size() > 0) { 15803 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15804 } 15805 } 15806 15807 /* 15808 * Utility method to unload a list of specified containers 15809 */ 15810 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15811 // Just unmount all valid containers. 15812 for (AsecInstallArgs arg : cidArgs) { 15813 synchronized (mInstallLock) { 15814 arg.doPostDeleteLI(false); 15815 } 15816 } 15817 } 15818 15819 /* 15820 * Unload packages mounted on external media. This involves deleting package 15821 * data from internal structures, sending broadcasts about diabled packages, 15822 * gc'ing to free up references, unmounting all secure containers 15823 * corresponding to packages on external media, and posting a 15824 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15825 * that we always have to post this message if status has been requested no 15826 * matter what. 15827 */ 15828 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15829 final boolean reportStatus) { 15830 if (DEBUG_SD_INSTALL) 15831 Log.i(TAG, "unloading media packages"); 15832 ArrayList<String> pkgList = new ArrayList<String>(); 15833 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15834 final Set<AsecInstallArgs> keys = processCids.keySet(); 15835 for (AsecInstallArgs args : keys) { 15836 String pkgName = args.getPackageName(); 15837 if (DEBUG_SD_INSTALL) 15838 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15839 // Delete package internally 15840 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15841 synchronized (mInstallLock) { 15842 boolean res = deletePackageLI(pkgName, null, false, null, null, 15843 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15844 if (res) { 15845 pkgList.add(pkgName); 15846 } else { 15847 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15848 failedList.add(args); 15849 } 15850 } 15851 } 15852 15853 // reader 15854 synchronized (mPackages) { 15855 // We didn't update the settings after removing each package; 15856 // write them now for all packages. 15857 mSettings.writeLPr(); 15858 } 15859 15860 // We have to absolutely send UPDATED_MEDIA_STATUS only 15861 // after confirming that all the receivers processed the ordered 15862 // broadcast when packages get disabled, force a gc to clean things up. 15863 // and unload all the containers. 15864 if (pkgList.size() > 0) { 15865 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15866 new IIntentReceiver.Stub() { 15867 public void performReceive(Intent intent, int resultCode, String data, 15868 Bundle extras, boolean ordered, boolean sticky, 15869 int sendingUser) throws RemoteException { 15870 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15871 reportStatus ? 1 : 0, 1, keys); 15872 mHandler.sendMessage(msg); 15873 } 15874 }); 15875 } else { 15876 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15877 keys); 15878 mHandler.sendMessage(msg); 15879 } 15880 } 15881 15882 private void loadPrivatePackages(final VolumeInfo vol) { 15883 mHandler.post(new Runnable() { 15884 @Override 15885 public void run() { 15886 loadPrivatePackagesInner(vol); 15887 } 15888 }); 15889 } 15890 15891 private void loadPrivatePackagesInner(VolumeInfo vol) { 15892 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15893 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15894 15895 final VersionInfo ver; 15896 final List<PackageSetting> packages; 15897 synchronized (mPackages) { 15898 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15899 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15900 } 15901 15902 for (PackageSetting ps : packages) { 15903 synchronized (mInstallLock) { 15904 final PackageParser.Package pkg; 15905 try { 15906 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15907 loaded.add(pkg.applicationInfo); 15908 } catch (PackageManagerException e) { 15909 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15910 } 15911 15912 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15913 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15914 } 15915 } 15916 } 15917 15918 synchronized (mPackages) { 15919 int updateFlags = UPDATE_PERMISSIONS_ALL; 15920 if (ver.sdkVersion != mSdkVersion) { 15921 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15922 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15923 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15924 } 15925 updatePermissionsLPw(null, null, updateFlags); 15926 15927 // Yay, everything is now upgraded 15928 ver.forceCurrent(); 15929 15930 mSettings.writeLPr(); 15931 } 15932 15933 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15934 sendResourcesChangedBroadcast(true, false, loaded, null); 15935 } 15936 15937 private void unloadPrivatePackages(final VolumeInfo vol) { 15938 mHandler.post(new Runnable() { 15939 @Override 15940 public void run() { 15941 unloadPrivatePackagesInner(vol); 15942 } 15943 }); 15944 } 15945 15946 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15947 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15948 synchronized (mInstallLock) { 15949 synchronized (mPackages) { 15950 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15951 for (PackageSetting ps : packages) { 15952 if (ps.pkg == null) continue; 15953 15954 final ApplicationInfo info = ps.pkg.applicationInfo; 15955 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15956 if (deletePackageLI(ps.name, null, false, null, null, 15957 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15958 unloaded.add(info); 15959 } else { 15960 Slog.w(TAG, "Failed to unload " + ps.codePath); 15961 } 15962 } 15963 15964 mSettings.writeLPr(); 15965 } 15966 } 15967 15968 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15969 sendResourcesChangedBroadcast(false, false, unloaded, null); 15970 } 15971 15972 /** 15973 * Examine all users present on given mounted volume, and destroy data 15974 * belonging to users that are no longer valid, or whose user ID has been 15975 * recycled. 15976 */ 15977 private void reconcileUsers(String volumeUuid) { 15978 final File[] files = FileUtils 15979 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15980 for (File file : files) { 15981 if (!file.isDirectory()) continue; 15982 15983 final int userId; 15984 final UserInfo info; 15985 try { 15986 userId = Integer.parseInt(file.getName()); 15987 info = sUserManager.getUserInfo(userId); 15988 } catch (NumberFormatException e) { 15989 Slog.w(TAG, "Invalid user directory " + file); 15990 continue; 15991 } 15992 15993 boolean destroyUser = false; 15994 if (info == null) { 15995 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15996 + " because no matching user was found"); 15997 destroyUser = true; 15998 } else { 15999 try { 16000 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16001 } catch (IOException e) { 16002 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16003 + " because we failed to enforce serial number: " + e); 16004 destroyUser = true; 16005 } 16006 } 16007 16008 if (destroyUser) { 16009 synchronized (mInstallLock) { 16010 mInstaller.removeUserDataDirs(volumeUuid, userId); 16011 } 16012 } 16013 } 16014 16015 final UserManager um = mContext.getSystemService(UserManager.class); 16016 for (UserInfo user : um.getUsers()) { 16017 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16018 if (userDir.exists()) continue; 16019 16020 try { 16021 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16022 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16023 } catch (IOException e) { 16024 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16025 } 16026 } 16027 } 16028 16029 /** 16030 * Examine all apps present on given mounted volume, and destroy apps that 16031 * aren't expected, either due to uninstallation or reinstallation on 16032 * another volume. 16033 */ 16034 private void reconcileApps(String volumeUuid) { 16035 final File[] files = FileUtils 16036 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16037 for (File file : files) { 16038 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16039 && !PackageInstallerService.isStageName(file.getName()); 16040 if (!isPackage) { 16041 // Ignore entries which are not packages 16042 continue; 16043 } 16044 16045 boolean destroyApp = false; 16046 String packageName = null; 16047 try { 16048 final PackageLite pkg = PackageParser.parsePackageLite(file, 16049 PackageParser.PARSE_MUST_BE_APK); 16050 packageName = pkg.packageName; 16051 16052 synchronized (mPackages) { 16053 final PackageSetting ps = mSettings.mPackages.get(packageName); 16054 if (ps == null) { 16055 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16056 + volumeUuid + " because we found no install record"); 16057 destroyApp = true; 16058 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16059 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16060 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16061 destroyApp = true; 16062 } 16063 } 16064 16065 } catch (PackageParserException e) { 16066 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16067 destroyApp = true; 16068 } 16069 16070 if (destroyApp) { 16071 synchronized (mInstallLock) { 16072 if (packageName != null) { 16073 removeDataDirsLI(volumeUuid, packageName); 16074 } 16075 if (file.isDirectory()) { 16076 mInstaller.rmPackageDir(file.getAbsolutePath()); 16077 } else { 16078 file.delete(); 16079 } 16080 } 16081 } 16082 } 16083 } 16084 16085 private void unfreezePackage(String packageName) { 16086 synchronized (mPackages) { 16087 final PackageSetting ps = mSettings.mPackages.get(packageName); 16088 if (ps != null) { 16089 ps.frozen = false; 16090 } 16091 } 16092 } 16093 16094 @Override 16095 public int movePackage(final String packageName, final String volumeUuid) { 16096 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16097 16098 final int moveId = mNextMoveId.getAndIncrement(); 16099 try { 16100 movePackageInternal(packageName, volumeUuid, moveId); 16101 } catch (PackageManagerException e) { 16102 Slog.w(TAG, "Failed to move " + packageName, e); 16103 mMoveCallbacks.notifyStatusChanged(moveId, 16104 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16105 } 16106 return moveId; 16107 } 16108 16109 private void movePackageInternal(final String packageName, final String volumeUuid, 16110 final int moveId) throws PackageManagerException { 16111 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16112 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16113 final PackageManager pm = mContext.getPackageManager(); 16114 16115 final boolean currentAsec; 16116 final String currentVolumeUuid; 16117 final File codeFile; 16118 final String installerPackageName; 16119 final String packageAbiOverride; 16120 final int appId; 16121 final String seinfo; 16122 final String label; 16123 16124 // reader 16125 synchronized (mPackages) { 16126 final PackageParser.Package pkg = mPackages.get(packageName); 16127 final PackageSetting ps = mSettings.mPackages.get(packageName); 16128 if (pkg == null || ps == null) { 16129 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16130 } 16131 16132 if (pkg.applicationInfo.isSystemApp()) { 16133 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16134 "Cannot move system application"); 16135 } 16136 16137 if (pkg.applicationInfo.isExternalAsec()) { 16138 currentAsec = true; 16139 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16140 } else if (pkg.applicationInfo.isForwardLocked()) { 16141 currentAsec = true; 16142 currentVolumeUuid = "forward_locked"; 16143 } else { 16144 currentAsec = false; 16145 currentVolumeUuid = ps.volumeUuid; 16146 16147 final File probe = new File(pkg.codePath); 16148 final File probeOat = new File(probe, "oat"); 16149 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16150 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16151 "Move only supported for modern cluster style installs"); 16152 } 16153 } 16154 16155 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16156 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16157 "Package already moved to " + volumeUuid); 16158 } 16159 16160 if (ps.frozen) { 16161 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16162 "Failed to move already frozen package"); 16163 } 16164 ps.frozen = true; 16165 16166 codeFile = new File(pkg.codePath); 16167 installerPackageName = ps.installerPackageName; 16168 packageAbiOverride = ps.cpuAbiOverrideString; 16169 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16170 seinfo = pkg.applicationInfo.seinfo; 16171 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16172 } 16173 16174 // Now that we're guarded by frozen state, kill app during move 16175 final long token = Binder.clearCallingIdentity(); 16176 try { 16177 killApplication(packageName, appId, "move pkg"); 16178 } finally { 16179 Binder.restoreCallingIdentity(token); 16180 } 16181 16182 final Bundle extras = new Bundle(); 16183 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16184 extras.putString(Intent.EXTRA_TITLE, label); 16185 mMoveCallbacks.notifyCreated(moveId, extras); 16186 16187 int installFlags; 16188 final boolean moveCompleteApp; 16189 final File measurePath; 16190 16191 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16192 installFlags = INSTALL_INTERNAL; 16193 moveCompleteApp = !currentAsec; 16194 measurePath = Environment.getDataAppDirectory(volumeUuid); 16195 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16196 installFlags = INSTALL_EXTERNAL; 16197 moveCompleteApp = false; 16198 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16199 } else { 16200 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16201 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16202 || !volume.isMountedWritable()) { 16203 unfreezePackage(packageName); 16204 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16205 "Move location not mounted private volume"); 16206 } 16207 16208 Preconditions.checkState(!currentAsec); 16209 16210 installFlags = INSTALL_INTERNAL; 16211 moveCompleteApp = true; 16212 measurePath = Environment.getDataAppDirectory(volumeUuid); 16213 } 16214 16215 final PackageStats stats = new PackageStats(null, -1); 16216 synchronized (mInstaller) { 16217 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16218 unfreezePackage(packageName); 16219 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16220 "Failed to measure package size"); 16221 } 16222 } 16223 16224 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16225 + stats.dataSize); 16226 16227 final long startFreeBytes = measurePath.getFreeSpace(); 16228 final long sizeBytes; 16229 if (moveCompleteApp) { 16230 sizeBytes = stats.codeSize + stats.dataSize; 16231 } else { 16232 sizeBytes = stats.codeSize; 16233 } 16234 16235 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16236 unfreezePackage(packageName); 16237 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16238 "Not enough free space to move"); 16239 } 16240 16241 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16242 16243 final CountDownLatch installedLatch = new CountDownLatch(1); 16244 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16245 @Override 16246 public void onUserActionRequired(Intent intent) throws RemoteException { 16247 throw new IllegalStateException(); 16248 } 16249 16250 @Override 16251 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16252 Bundle extras) throws RemoteException { 16253 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16254 + PackageManager.installStatusToString(returnCode, msg)); 16255 16256 installedLatch.countDown(); 16257 16258 // Regardless of success or failure of the move operation, 16259 // always unfreeze the package 16260 unfreezePackage(packageName); 16261 16262 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16263 switch (status) { 16264 case PackageInstaller.STATUS_SUCCESS: 16265 mMoveCallbacks.notifyStatusChanged(moveId, 16266 PackageManager.MOVE_SUCCEEDED); 16267 break; 16268 case PackageInstaller.STATUS_FAILURE_STORAGE: 16269 mMoveCallbacks.notifyStatusChanged(moveId, 16270 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16271 break; 16272 default: 16273 mMoveCallbacks.notifyStatusChanged(moveId, 16274 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16275 break; 16276 } 16277 } 16278 }; 16279 16280 final MoveInfo move; 16281 if (moveCompleteApp) { 16282 // Kick off a thread to report progress estimates 16283 new Thread() { 16284 @Override 16285 public void run() { 16286 while (true) { 16287 try { 16288 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16289 break; 16290 } 16291 } catch (InterruptedException ignored) { 16292 } 16293 16294 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16295 final int progress = 10 + (int) MathUtils.constrain( 16296 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16297 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16298 } 16299 } 16300 }.start(); 16301 16302 final String dataAppName = codeFile.getName(); 16303 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16304 dataAppName, appId, seinfo); 16305 } else { 16306 move = null; 16307 } 16308 16309 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16310 16311 final Message msg = mHandler.obtainMessage(INIT_COPY); 16312 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16313 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16314 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16315 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16316 msg.obj = params; 16317 16318 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16319 System.identityHashCode(msg.obj)); 16320 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16321 System.identityHashCode(msg.obj)); 16322 16323 mHandler.sendMessage(msg); 16324 } 16325 16326 @Override 16327 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16328 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16329 16330 final int realMoveId = mNextMoveId.getAndIncrement(); 16331 final Bundle extras = new Bundle(); 16332 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16333 mMoveCallbacks.notifyCreated(realMoveId, extras); 16334 16335 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16336 @Override 16337 public void onCreated(int moveId, Bundle extras) { 16338 // Ignored 16339 } 16340 16341 @Override 16342 public void onStatusChanged(int moveId, int status, long estMillis) { 16343 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16344 } 16345 }; 16346 16347 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16348 storage.setPrimaryStorageUuid(volumeUuid, callback); 16349 return realMoveId; 16350 } 16351 16352 @Override 16353 public int getMoveStatus(int moveId) { 16354 mContext.enforceCallingOrSelfPermission( 16355 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16356 return mMoveCallbacks.mLastStatus.get(moveId); 16357 } 16358 16359 @Override 16360 public void registerMoveCallback(IPackageMoveObserver callback) { 16361 mContext.enforceCallingOrSelfPermission( 16362 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16363 mMoveCallbacks.register(callback); 16364 } 16365 16366 @Override 16367 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16368 mContext.enforceCallingOrSelfPermission( 16369 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16370 mMoveCallbacks.unregister(callback); 16371 } 16372 16373 @Override 16374 public boolean setInstallLocation(int loc) { 16375 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16376 null); 16377 if (getInstallLocation() == loc) { 16378 return true; 16379 } 16380 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16381 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16382 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16383 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16384 return true; 16385 } 16386 return false; 16387 } 16388 16389 @Override 16390 public int getInstallLocation() { 16391 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16392 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16393 PackageHelper.APP_INSTALL_AUTO); 16394 } 16395 16396 /** Called by UserManagerService */ 16397 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16398 mDirtyUsers.remove(userHandle); 16399 mSettings.removeUserLPw(userHandle); 16400 mPendingBroadcasts.remove(userHandle); 16401 if (mInstaller != null) { 16402 // Technically, we shouldn't be doing this with the package lock 16403 // held. However, this is very rare, and there is already so much 16404 // other disk I/O going on, that we'll let it slide for now. 16405 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16406 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16407 final String volumeUuid = vol.getFsUuid(); 16408 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16409 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16410 } 16411 } 16412 mUserNeedsBadging.delete(userHandle); 16413 removeUnusedPackagesLILPw(userManager, userHandle); 16414 } 16415 16416 /** 16417 * We're removing userHandle and would like to remove any downloaded packages 16418 * that are no longer in use by any other user. 16419 * @param userHandle the user being removed 16420 */ 16421 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16422 final boolean DEBUG_CLEAN_APKS = false; 16423 int [] users = userManager.getUserIdsLPr(); 16424 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16425 while (psit.hasNext()) { 16426 PackageSetting ps = psit.next(); 16427 if (ps.pkg == null) { 16428 continue; 16429 } 16430 final String packageName = ps.pkg.packageName; 16431 // Skip over if system app 16432 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16433 continue; 16434 } 16435 if (DEBUG_CLEAN_APKS) { 16436 Slog.i(TAG, "Checking package " + packageName); 16437 } 16438 boolean keep = false; 16439 for (int i = 0; i < users.length; i++) { 16440 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16441 keep = true; 16442 if (DEBUG_CLEAN_APKS) { 16443 Slog.i(TAG, " Keeping package " + packageName + " for user " 16444 + users[i]); 16445 } 16446 break; 16447 } 16448 } 16449 if (!keep) { 16450 if (DEBUG_CLEAN_APKS) { 16451 Slog.i(TAG, " Removing package " + packageName); 16452 } 16453 mHandler.post(new Runnable() { 16454 public void run() { 16455 deletePackageX(packageName, userHandle, 0); 16456 } //end run 16457 }); 16458 } 16459 } 16460 } 16461 16462 /** Called by UserManagerService */ 16463 void createNewUserLILPw(int userHandle) { 16464 if (mInstaller != null) { 16465 mInstaller.createUserConfig(userHandle); 16466 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16467 applyFactoryDefaultBrowserLPw(userHandle); 16468 primeDomainVerificationsLPw(userHandle); 16469 } 16470 } 16471 16472 void newUserCreated(final int userHandle) { 16473 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16474 } 16475 16476 @Override 16477 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16478 mContext.enforceCallingOrSelfPermission( 16479 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16480 "Only package verification agents can read the verifier device identity"); 16481 16482 synchronized (mPackages) { 16483 return mSettings.getVerifierDeviceIdentityLPw(); 16484 } 16485 } 16486 16487 @Override 16488 public void setPermissionEnforced(String permission, boolean enforced) { 16489 // TODO: Now that we no longer change GID for storage, this should to away. 16490 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16491 "setPermissionEnforced"); 16492 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16493 synchronized (mPackages) { 16494 if (mSettings.mReadExternalStorageEnforced == null 16495 || mSettings.mReadExternalStorageEnforced != enforced) { 16496 mSettings.mReadExternalStorageEnforced = enforced; 16497 mSettings.writeLPr(); 16498 } 16499 } 16500 // kill any non-foreground processes so we restart them and 16501 // grant/revoke the GID. 16502 final IActivityManager am = ActivityManagerNative.getDefault(); 16503 if (am != null) { 16504 final long token = Binder.clearCallingIdentity(); 16505 try { 16506 am.killProcessesBelowForeground("setPermissionEnforcement"); 16507 } catch (RemoteException e) { 16508 } finally { 16509 Binder.restoreCallingIdentity(token); 16510 } 16511 } 16512 } else { 16513 throw new IllegalArgumentException("No selective enforcement for " + permission); 16514 } 16515 } 16516 16517 @Override 16518 @Deprecated 16519 public boolean isPermissionEnforced(String permission) { 16520 return true; 16521 } 16522 16523 @Override 16524 public boolean isStorageLow() { 16525 final long token = Binder.clearCallingIdentity(); 16526 try { 16527 final DeviceStorageMonitorInternal 16528 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16529 if (dsm != null) { 16530 return dsm.isMemoryLow(); 16531 } else { 16532 return false; 16533 } 16534 } finally { 16535 Binder.restoreCallingIdentity(token); 16536 } 16537 } 16538 16539 @Override 16540 public IPackageInstaller getPackageInstaller() { 16541 return mInstallerService; 16542 } 16543 16544 private boolean userNeedsBadging(int userId) { 16545 int index = mUserNeedsBadging.indexOfKey(userId); 16546 if (index < 0) { 16547 final UserInfo userInfo; 16548 final long token = Binder.clearCallingIdentity(); 16549 try { 16550 userInfo = sUserManager.getUserInfo(userId); 16551 } finally { 16552 Binder.restoreCallingIdentity(token); 16553 } 16554 final boolean b; 16555 if (userInfo != null && userInfo.isManagedProfile()) { 16556 b = true; 16557 } else { 16558 b = false; 16559 } 16560 mUserNeedsBadging.put(userId, b); 16561 return b; 16562 } 16563 return mUserNeedsBadging.valueAt(index); 16564 } 16565 16566 @Override 16567 public KeySet getKeySetByAlias(String packageName, String alias) { 16568 if (packageName == null || alias == null) { 16569 return null; 16570 } 16571 synchronized(mPackages) { 16572 final PackageParser.Package pkg = mPackages.get(packageName); 16573 if (pkg == null) { 16574 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16575 throw new IllegalArgumentException("Unknown package: " + packageName); 16576 } 16577 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16578 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16579 } 16580 } 16581 16582 @Override 16583 public KeySet getSigningKeySet(String packageName) { 16584 if (packageName == null) { 16585 return null; 16586 } 16587 synchronized(mPackages) { 16588 final PackageParser.Package pkg = mPackages.get(packageName); 16589 if (pkg == null) { 16590 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16591 throw new IllegalArgumentException("Unknown package: " + packageName); 16592 } 16593 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16594 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16595 throw new SecurityException("May not access signing KeySet of other apps."); 16596 } 16597 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16598 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16599 } 16600 } 16601 16602 @Override 16603 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16604 if (packageName == null || ks == null) { 16605 return false; 16606 } 16607 synchronized(mPackages) { 16608 final PackageParser.Package pkg = mPackages.get(packageName); 16609 if (pkg == null) { 16610 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16611 throw new IllegalArgumentException("Unknown package: " + packageName); 16612 } 16613 IBinder ksh = ks.getToken(); 16614 if (ksh instanceof KeySetHandle) { 16615 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16616 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16617 } 16618 return false; 16619 } 16620 } 16621 16622 @Override 16623 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16624 if (packageName == null || ks == null) { 16625 return false; 16626 } 16627 synchronized(mPackages) { 16628 final PackageParser.Package pkg = mPackages.get(packageName); 16629 if (pkg == null) { 16630 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16631 throw new IllegalArgumentException("Unknown package: " + packageName); 16632 } 16633 IBinder ksh = ks.getToken(); 16634 if (ksh instanceof KeySetHandle) { 16635 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16636 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16637 } 16638 return false; 16639 } 16640 } 16641 16642 public void getUsageStatsIfNoPackageUsageInfo() { 16643 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16644 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16645 if (usm == null) { 16646 throw new IllegalStateException("UsageStatsManager must be initialized"); 16647 } 16648 long now = System.currentTimeMillis(); 16649 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16650 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16651 String packageName = entry.getKey(); 16652 PackageParser.Package pkg = mPackages.get(packageName); 16653 if (pkg == null) { 16654 continue; 16655 } 16656 UsageStats usage = entry.getValue(); 16657 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16658 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16659 } 16660 } 16661 } 16662 16663 /** 16664 * Check and throw if the given before/after packages would be considered a 16665 * downgrade. 16666 */ 16667 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16668 throws PackageManagerException { 16669 if (after.versionCode < before.mVersionCode) { 16670 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16671 "Update version code " + after.versionCode + " is older than current " 16672 + before.mVersionCode); 16673 } else if (after.versionCode == before.mVersionCode) { 16674 if (after.baseRevisionCode < before.baseRevisionCode) { 16675 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16676 "Update base revision code " + after.baseRevisionCode 16677 + " is older than current " + before.baseRevisionCode); 16678 } 16679 16680 if (!ArrayUtils.isEmpty(after.splitNames)) { 16681 for (int i = 0; i < after.splitNames.length; i++) { 16682 final String splitName = after.splitNames[i]; 16683 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16684 if (j != -1) { 16685 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16686 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16687 "Update split " + splitName + " revision code " 16688 + after.splitRevisionCodes[i] + " is older than current " 16689 + before.splitRevisionCodes[j]); 16690 } 16691 } 16692 } 16693 } 16694 } 16695 } 16696 16697 private static class MoveCallbacks extends Handler { 16698 private static final int MSG_CREATED = 1; 16699 private static final int MSG_STATUS_CHANGED = 2; 16700 16701 private final RemoteCallbackList<IPackageMoveObserver> 16702 mCallbacks = new RemoteCallbackList<>(); 16703 16704 private final SparseIntArray mLastStatus = new SparseIntArray(); 16705 16706 public MoveCallbacks(Looper looper) { 16707 super(looper); 16708 } 16709 16710 public void register(IPackageMoveObserver callback) { 16711 mCallbacks.register(callback); 16712 } 16713 16714 public void unregister(IPackageMoveObserver callback) { 16715 mCallbacks.unregister(callback); 16716 } 16717 16718 @Override 16719 public void handleMessage(Message msg) { 16720 final SomeArgs args = (SomeArgs) msg.obj; 16721 final int n = mCallbacks.beginBroadcast(); 16722 for (int i = 0; i < n; i++) { 16723 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16724 try { 16725 invokeCallback(callback, msg.what, args); 16726 } catch (RemoteException ignored) { 16727 } 16728 } 16729 mCallbacks.finishBroadcast(); 16730 args.recycle(); 16731 } 16732 16733 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16734 throws RemoteException { 16735 switch (what) { 16736 case MSG_CREATED: { 16737 callback.onCreated(args.argi1, (Bundle) args.arg2); 16738 break; 16739 } 16740 case MSG_STATUS_CHANGED: { 16741 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16742 break; 16743 } 16744 } 16745 } 16746 16747 private void notifyCreated(int moveId, Bundle extras) { 16748 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16749 16750 final SomeArgs args = SomeArgs.obtain(); 16751 args.argi1 = moveId; 16752 args.arg2 = extras; 16753 obtainMessage(MSG_CREATED, args).sendToTarget(); 16754 } 16755 16756 private void notifyStatusChanged(int moveId, int status) { 16757 notifyStatusChanged(moveId, status, -1); 16758 } 16759 16760 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16761 Slog.v(TAG, "Move " + moveId + " status " + status); 16762 16763 final SomeArgs args = SomeArgs.obtain(); 16764 args.argi1 = moveId; 16765 args.argi2 = status; 16766 args.arg3 = estMillis; 16767 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16768 16769 synchronized (mLastStatus) { 16770 mLastStatus.put(moveId, status); 16771 } 16772 } 16773 } 16774 16775 private final class OnPermissionChangeListeners extends Handler { 16776 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16777 16778 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16779 new RemoteCallbackList<>(); 16780 16781 public OnPermissionChangeListeners(Looper looper) { 16782 super(looper); 16783 } 16784 16785 @Override 16786 public void handleMessage(Message msg) { 16787 switch (msg.what) { 16788 case MSG_ON_PERMISSIONS_CHANGED: { 16789 final int uid = msg.arg1; 16790 handleOnPermissionsChanged(uid); 16791 } break; 16792 } 16793 } 16794 16795 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16796 mPermissionListeners.register(listener); 16797 16798 } 16799 16800 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16801 mPermissionListeners.unregister(listener); 16802 } 16803 16804 public void onPermissionsChanged(int uid) { 16805 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16806 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16807 } 16808 } 16809 16810 private void handleOnPermissionsChanged(int uid) { 16811 final int count = mPermissionListeners.beginBroadcast(); 16812 try { 16813 for (int i = 0; i < count; i++) { 16814 IOnPermissionsChangeListener callback = mPermissionListeners 16815 .getBroadcastItem(i); 16816 try { 16817 callback.onPermissionsChanged(uid); 16818 } catch (RemoteException e) { 16819 Log.e(TAG, "Permission listener is dead", e); 16820 } 16821 } 16822 } finally { 16823 mPermissionListeners.finishBroadcast(); 16824 } 16825 } 16826 } 16827 16828 private class PackageManagerInternalImpl extends PackageManagerInternal { 16829 @Override 16830 public void setLocationPackagesProvider(PackagesProvider provider) { 16831 synchronized (mPackages) { 16832 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16833 } 16834 } 16835 16836 @Override 16837 public void setImePackagesProvider(PackagesProvider provider) { 16838 synchronized (mPackages) { 16839 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16840 } 16841 } 16842 16843 @Override 16844 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16845 synchronized (mPackages) { 16846 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16847 } 16848 } 16849 16850 @Override 16851 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16852 synchronized (mPackages) { 16853 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16854 } 16855 } 16856 16857 @Override 16858 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16859 synchronized (mPackages) { 16860 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16861 } 16862 } 16863 16864 @Override 16865 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16866 synchronized (mPackages) { 16867 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16868 } 16869 } 16870 16871 @Override 16872 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16873 synchronized (mPackages) { 16874 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16875 } 16876 } 16877 16878 @Override 16879 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16880 synchronized (mPackages) { 16881 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16882 packageName, userId); 16883 } 16884 } 16885 16886 @Override 16887 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16888 synchronized (mPackages) { 16889 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16890 packageName, userId); 16891 } 16892 } 16893 @Override 16894 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16895 synchronized (mPackages) { 16896 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16897 packageName, userId); 16898 } 16899 } 16900 } 16901 16902 @Override 16903 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16904 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16905 synchronized (mPackages) { 16906 final long identity = Binder.clearCallingIdentity(); 16907 try { 16908 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16909 packageNames, userId); 16910 } finally { 16911 Binder.restoreCallingIdentity(identity); 16912 } 16913 } 16914 } 16915 16916 private static void enforceSystemOrPhoneCaller(String tag) { 16917 int callingUid = Binder.getCallingUid(); 16918 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16919 throw new SecurityException( 16920 "Cannot call " + tag + " from UID " + callingUid); 16921 } 16922 } 16923} 16924