PackageManagerService.java revision 27c073796978106746e4a51f2100b29068ab37f6
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.ResultReceiver; 166import android.os.SELinux; 167import android.os.ServiceManager; 168import android.os.SystemClock; 169import android.os.SystemProperties; 170import android.os.Trace; 171import android.os.UserHandle; 172import android.os.UserManager; 173import android.os.storage.IMountService; 174import android.os.storage.MountServiceInternal; 175import android.os.storage.StorageEventListener; 176import android.os.storage.StorageManager; 177import android.os.storage.VolumeInfo; 178import android.os.storage.VolumeRecord; 179import android.security.KeyStore; 180import android.security.SystemKeyStore; 181import android.system.ErrnoException; 182import android.system.Os; 183import android.system.StructStat; 184import android.text.TextUtils; 185import android.text.format.DateUtils; 186import android.util.ArrayMap; 187import android.util.ArraySet; 188import android.util.AtomicFile; 189import android.util.DisplayMetrics; 190import android.util.EventLog; 191import android.util.ExceptionUtils; 192import android.util.Log; 193import android.util.LogPrinter; 194import android.util.MathUtils; 195import android.util.PrintStreamPrinter; 196import android.util.Slog; 197import android.util.SparseArray; 198import android.util.SparseBooleanArray; 199import android.util.SparseIntArray; 200import android.util.Xml; 201import android.view.Display; 202 203import dalvik.system.DexFile; 204import dalvik.system.VMRuntime; 205 206import libcore.io.IoUtils; 207import libcore.util.EmptyArray; 208 209import com.android.internal.R; 210import com.android.internal.annotations.GuardedBy; 211import com.android.internal.app.IMediaContainerService; 212import com.android.internal.app.ResolverActivity; 213import com.android.internal.content.NativeLibraryHelper; 214import com.android.internal.content.PackageHelper; 215import com.android.internal.os.IParcelFileDescriptorFactory; 216import com.android.internal.os.SomeArgs; 217import com.android.internal.os.Zygote; 218import com.android.internal.util.ArrayUtils; 219import com.android.internal.util.FastPrintWriter; 220import com.android.internal.util.FastXmlSerializer; 221import com.android.internal.util.IndentingPrintWriter; 222import com.android.internal.util.Preconditions; 223import com.android.server.EventLogTags; 224import com.android.server.FgThread; 225import com.android.server.IntentResolver; 226import com.android.server.LocalServices; 227import com.android.server.ServiceThread; 228import com.android.server.SystemConfig; 229import com.android.server.Watchdog; 230import com.android.server.pm.PermissionsState.PermissionState; 231import com.android.server.pm.Settings.DatabaseVersion; 232import com.android.server.pm.Settings.VersionInfo; 233import com.android.server.storage.DeviceStorageMonitorInternal; 234 235import org.xmlpull.v1.XmlPullParser; 236import org.xmlpull.v1.XmlPullParserException; 237import org.xmlpull.v1.XmlSerializer; 238 239import java.io.BufferedInputStream; 240import java.io.BufferedOutputStream; 241import java.io.BufferedReader; 242import java.io.ByteArrayInputStream; 243import java.io.ByteArrayOutputStream; 244import java.io.File; 245import java.io.FileDescriptor; 246import java.io.FileNotFoundException; 247import java.io.FileOutputStream; 248import java.io.FileReader; 249import java.io.FilenameFilter; 250import java.io.IOException; 251import java.io.InputStream; 252import java.io.PrintWriter; 253import java.nio.charset.StandardCharsets; 254import java.security.NoSuchAlgorithmException; 255import java.security.PublicKey; 256import java.security.cert.CertificateEncodingException; 257import java.security.cert.CertificateException; 258import java.text.SimpleDateFormat; 259import java.util.ArrayList; 260import java.util.Arrays; 261import java.util.Collection; 262import java.util.Collections; 263import java.util.Comparator; 264import java.util.Date; 265import java.util.Iterator; 266import java.util.List; 267import java.util.Map; 268import java.util.Objects; 269import java.util.Set; 270import java.util.concurrent.CountDownLatch; 271import java.util.concurrent.TimeUnit; 272import java.util.concurrent.atomic.AtomicBoolean; 273import java.util.concurrent.atomic.AtomicInteger; 274import java.util.concurrent.atomic.AtomicLong; 275 276/** 277 * Keep track of all those .apks everywhere. 278 * 279 * This is very central to the platform's security; please run the unit 280 * tests whenever making modifications here: 281 * 282runtest -c android.content.pm.PackageManagerTests frameworks-core 283 * 284 * {@hide} 285 */ 286public class PackageManagerService extends IPackageManager.Stub { 287 static final String TAG = "PackageManager"; 288 static final boolean DEBUG_SETTINGS = false; 289 static final boolean DEBUG_PREFERRED = false; 290 static final boolean DEBUG_UPGRADE = false; 291 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 292 private static final boolean DEBUG_BACKUP = false; 293 private static final boolean DEBUG_INSTALL = false; 294 private static final boolean DEBUG_REMOVE = false; 295 private static final boolean DEBUG_BROADCASTS = false; 296 private static final boolean DEBUG_SHOW_INFO = false; 297 private static final boolean DEBUG_PACKAGE_INFO = false; 298 private static final boolean DEBUG_INTENT_MATCHING = false; 299 private static final boolean DEBUG_PACKAGE_SCANNING = false; 300 private static final boolean DEBUG_VERIFY = false; 301 private static final boolean DEBUG_DEXOPT = false; 302 private static final boolean DEBUG_ABI_SELECTION = false; 303 304 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 305 306 private static final int RADIO_UID = Process.PHONE_UID; 307 private static final int LOG_UID = Process.LOG_UID; 308 private static final int NFC_UID = Process.NFC_UID; 309 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 310 private static final int SHELL_UID = Process.SHELL_UID; 311 312 // Cap the size of permission trees that 3rd party apps can define 313 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 314 315 // Suffix used during package installation when copying/moving 316 // package apks to install directory. 317 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 318 319 static final int SCAN_NO_DEX = 1<<1; 320 static final int SCAN_FORCE_DEX = 1<<2; 321 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 322 static final int SCAN_NEW_INSTALL = 1<<4; 323 static final int SCAN_NO_PATHS = 1<<5; 324 static final int SCAN_UPDATE_TIME = 1<<6; 325 static final int SCAN_DEFER_DEX = 1<<7; 326 static final int SCAN_BOOTING = 1<<8; 327 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 328 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 329 static final int SCAN_REPLACING = 1<<11; 330 static final int SCAN_REQUIRE_KNOWN = 1<<12; 331 static final int SCAN_MOVE = 1<<13; 332 static final int SCAN_INITIAL = 1<<14; 333 334 static final int REMOVE_CHATTY = 1<<16; 335 336 private static final int[] EMPTY_INT_ARRAY = new int[0]; 337 338 /** 339 * Timeout (in milliseconds) after which the watchdog should declare that 340 * our handler thread is wedged. The usual default for such things is one 341 * minute but we sometimes do very lengthy I/O operations on this thread, 342 * such as installing multi-gigabyte applications, so ours needs to be longer. 343 */ 344 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 345 346 /** 347 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 348 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 349 * settings entry if available, otherwise we use the hardcoded default. If it's been 350 * more than this long since the last fstrim, we force one during the boot sequence. 351 * 352 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 353 * one gets run at the next available charging+idle time. This final mandatory 354 * no-fstrim check kicks in only of the other scheduling criteria is never met. 355 */ 356 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 357 358 /** 359 * Whether verification is enabled by default. 360 */ 361 private static final boolean DEFAULT_VERIFY_ENABLE = true; 362 363 /** 364 * The default maximum time to wait for the verification agent to return in 365 * milliseconds. 366 */ 367 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 368 369 /** 370 * The default response for package verification timeout. 371 * 372 * This can be either PackageManager.VERIFICATION_ALLOW or 373 * PackageManager.VERIFICATION_REJECT. 374 */ 375 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 376 377 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 378 379 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 380 DEFAULT_CONTAINER_PACKAGE, 381 "com.android.defcontainer.DefaultContainerService"); 382 383 private static final String KILL_APP_REASON_GIDS_CHANGED = 384 "permission grant or revoke changed gids"; 385 386 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 387 "permissions revoked"; 388 389 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 390 391 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 392 393 /** Permission grant: not grant the permission. */ 394 private static final int GRANT_DENIED = 1; 395 396 /** Permission grant: grant the permission as an install permission. */ 397 private static final int GRANT_INSTALL = 2; 398 399 /** Permission grant: grant the permission as an install permission for a legacy app. */ 400 private static final int GRANT_INSTALL_LEGACY = 3; 401 402 /** Permission grant: grant the permission as a runtime one. */ 403 private static final int GRANT_RUNTIME = 4; 404 405 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 406 private static final int GRANT_UPGRADE = 5; 407 408 /** Canonical intent used to identify what counts as a "web browser" app */ 409 private static final Intent sBrowserIntent; 410 static { 411 sBrowserIntent = new Intent(); 412 sBrowserIntent.setAction(Intent.ACTION_VIEW); 413 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 414 sBrowserIntent.setData(Uri.parse("http:")); 415 } 416 417 final ServiceThread mHandlerThread; 418 419 final PackageHandler mHandler; 420 421 /** 422 * Messages for {@link #mHandler} that need to wait for system ready before 423 * being dispatched. 424 */ 425 private ArrayList<Message> mPostSystemReadyMessages; 426 427 final int mSdkVersion = Build.VERSION.SDK_INT; 428 429 final Context mContext; 430 final boolean mFactoryTest; 431 final boolean mOnlyCore; 432 final DisplayMetrics mMetrics; 433 final int mDefParseFlags; 434 final String[] mSeparateProcesses; 435 final boolean mIsUpgrade; 436 437 // This is where all application persistent data goes. 438 final File mAppDataDir; 439 440 // This is where all application persistent data goes for secondary users. 441 final File mUserAppDataDir; 442 443 /** The location for ASEC container files on internal storage. */ 444 final String mAsecInternalPath; 445 446 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 447 // LOCK HELD. Can be called with mInstallLock held. 448 @GuardedBy("mInstallLock") 449 final Installer mInstaller; 450 451 /** Directory where installed third-party apps stored */ 452 final File mAppInstallDir; 453 454 /** 455 * Directory to which applications installed internally have their 456 * 32 bit native libraries copied. 457 */ 458 private File mAppLib32InstallDir; 459 460 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 461 // apps. 462 final File mDrmAppPrivateInstallDir; 463 464 // ---------------------------------------------------------------- 465 466 // Lock for state used when installing and doing other long running 467 // operations. Methods that must be called with this lock held have 468 // the suffix "LI". 469 final Object mInstallLock = new Object(); 470 471 // ---------------------------------------------------------------- 472 473 // Keys are String (package name), values are Package. This also serves 474 // as the lock for the global state. Methods that must be called with 475 // this lock held have the prefix "LP". 476 @GuardedBy("mPackages") 477 final ArrayMap<String, PackageParser.Package> mPackages = 478 new ArrayMap<String, PackageParser.Package>(); 479 480 // Tracks available target package names -> overlay package paths. 481 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 482 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 483 484 /** 485 * Tracks new system packages [received in an OTA] that we expect to 486 * find updated user-installed versions. Keys are package name, values 487 * are package location. 488 */ 489 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 490 491 /** 492 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 493 */ 494 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 495 /** 496 * Whether or not system app permissions should be promoted from install to runtime. 497 */ 498 boolean mPromoteSystemApps; 499 500 final Settings mSettings; 501 boolean mRestoredSettings; 502 503 // System configuration read by SystemConfig. 504 final int[] mGlobalGids; 505 final SparseArray<ArraySet<String>> mSystemPermissions; 506 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 507 508 // If mac_permissions.xml was found for seinfo labeling. 509 boolean mFoundPolicyFile; 510 511 // If a recursive restorecon of /data/data/<pkg> is needed. 512 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 513 514 public static final class SharedLibraryEntry { 515 public final String path; 516 public final String apk; 517 518 SharedLibraryEntry(String _path, String _apk) { 519 path = _path; 520 apk = _apk; 521 } 522 } 523 524 // Currently known shared libraries. 525 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 526 new ArrayMap<String, SharedLibraryEntry>(); 527 528 // All available activities, for your resolving pleasure. 529 final ActivityIntentResolver mActivities = 530 new ActivityIntentResolver(); 531 532 // All available receivers, for your resolving pleasure. 533 final ActivityIntentResolver mReceivers = 534 new ActivityIntentResolver(); 535 536 // All available services, for your resolving pleasure. 537 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 538 539 // All available providers, for your resolving pleasure. 540 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 541 542 // Mapping from provider base names (first directory in content URI codePath) 543 // to the provider information. 544 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 545 new ArrayMap<String, PackageParser.Provider>(); 546 547 // Mapping from instrumentation class names to info about them. 548 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 549 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 550 551 // Mapping from permission names to info about them. 552 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 553 new ArrayMap<String, PackageParser.PermissionGroup>(); 554 555 // Packages whose data we have transfered into another package, thus 556 // should no longer exist. 557 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 558 559 // Broadcast actions that are only available to the system. 560 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 561 562 /** List of packages waiting for verification. */ 563 final SparseArray<PackageVerificationState> mPendingVerification 564 = new SparseArray<PackageVerificationState>(); 565 566 /** Set of packages associated with each app op permission. */ 567 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 568 569 final PackageInstallerService mInstallerService; 570 571 private final PackageDexOptimizer mPackageDexOptimizer; 572 573 private AtomicInteger mNextMoveId = new AtomicInteger(); 574 private final MoveCallbacks mMoveCallbacks; 575 576 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 577 578 // Cache of users who need badging. 579 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 580 581 /** Token for keys in mPendingVerification. */ 582 private int mPendingVerificationToken = 0; 583 584 volatile boolean mSystemReady; 585 volatile boolean mSafeMode; 586 volatile boolean mHasSystemUidErrors; 587 588 ApplicationInfo mAndroidApplication; 589 final ActivityInfo mResolveActivity = new ActivityInfo(); 590 final ResolveInfo mResolveInfo = new ResolveInfo(); 591 ComponentName mResolveComponentName; 592 PackageParser.Package mPlatformPackage; 593 ComponentName mCustomResolverComponentName; 594 595 boolean mResolverReplaced = false; 596 597 private final ComponentName mIntentFilterVerifierComponent; 598 private int mIntentFilterVerificationToken = 0; 599 600 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 601 = new SparseArray<IntentFilterVerificationState>(); 602 603 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 604 new DefaultPermissionGrantPolicy(this); 605 606 private static class IFVerificationParams { 607 PackageParser.Package pkg; 608 boolean replacing; 609 int userId; 610 int verifierUid; 611 612 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 613 int _userId, int _verifierUid) { 614 pkg = _pkg; 615 replacing = _replacing; 616 userId = _userId; 617 replacing = _replacing; 618 verifierUid = _verifierUid; 619 } 620 } 621 622 private interface IntentFilterVerifier<T extends IntentFilter> { 623 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 624 T filter, String packageName); 625 void startVerifications(int userId); 626 void receiveVerificationResponse(int verificationId); 627 } 628 629 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 630 private Context mContext; 631 private ComponentName mIntentFilterVerifierComponent; 632 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 633 634 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 635 mContext = context; 636 mIntentFilterVerifierComponent = verifierComponent; 637 } 638 639 private String getDefaultScheme() { 640 return IntentFilter.SCHEME_HTTPS; 641 } 642 643 @Override 644 public void startVerifications(int userId) { 645 // Launch verifications requests 646 int count = mCurrentIntentFilterVerifications.size(); 647 for (int n=0; n<count; n++) { 648 int verificationId = mCurrentIntentFilterVerifications.get(n); 649 final IntentFilterVerificationState ivs = 650 mIntentFilterVerificationStates.get(verificationId); 651 652 String packageName = ivs.getPackageName(); 653 654 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 655 final int filterCount = filters.size(); 656 ArraySet<String> domainsSet = new ArraySet<>(); 657 for (int m=0; m<filterCount; m++) { 658 PackageParser.ActivityIntentInfo filter = filters.get(m); 659 domainsSet.addAll(filter.getHostsList()); 660 } 661 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 662 synchronized (mPackages) { 663 if (mSettings.createIntentFilterVerificationIfNeededLPw( 664 packageName, domainsList) != null) { 665 scheduleWriteSettingsLocked(); 666 } 667 } 668 sendVerificationRequest(userId, verificationId, ivs); 669 } 670 mCurrentIntentFilterVerifications.clear(); 671 } 672 673 private void sendVerificationRequest(int userId, int verificationId, 674 IntentFilterVerificationState ivs) { 675 676 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 677 verificationIntent.putExtra( 678 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 679 verificationId); 680 verificationIntent.putExtra( 681 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 682 getDefaultScheme()); 683 verificationIntent.putExtra( 684 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 685 ivs.getHostsString()); 686 verificationIntent.putExtra( 687 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 688 ivs.getPackageName()); 689 verificationIntent.setComponent(mIntentFilterVerifierComponent); 690 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 691 692 UserHandle user = new UserHandle(userId); 693 mContext.sendBroadcastAsUser(verificationIntent, user); 694 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 695 "Sending IntentFilter verification broadcast"); 696 } 697 698 public void receiveVerificationResponse(int verificationId) { 699 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 700 701 final boolean verified = ivs.isVerified(); 702 703 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 704 final int count = filters.size(); 705 if (DEBUG_DOMAIN_VERIFICATION) { 706 Slog.i(TAG, "Received verification response " + verificationId 707 + " for " + count + " filters, verified=" + verified); 708 } 709 for (int n=0; n<count; n++) { 710 PackageParser.ActivityIntentInfo filter = filters.get(n); 711 filter.setVerified(verified); 712 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 714 + " verified with result:" + verified + " and hosts:" 715 + ivs.getHostsString()); 716 } 717 718 mIntentFilterVerificationStates.remove(verificationId); 719 720 final String packageName = ivs.getPackageName(); 721 IntentFilterVerificationInfo ivi = null; 722 723 synchronized (mPackages) { 724 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 725 } 726 if (ivi == null) { 727 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 728 + verificationId + " packageName:" + packageName); 729 return; 730 } 731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 732 "Updating IntentFilterVerificationInfo for package " + packageName 733 +" verificationId:" + verificationId); 734 735 synchronized (mPackages) { 736 if (verified) { 737 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 738 } else { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 740 } 741 scheduleWriteSettingsLocked(); 742 743 final int userId = ivs.getUserId(); 744 if (userId != UserHandle.USER_ALL) { 745 final int userStatus = 746 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 747 748 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 749 boolean needUpdate = false; 750 751 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 752 // already been set by the User thru the Disambiguation dialog 753 switch (userStatus) { 754 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 755 if (verified) { 756 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 757 } else { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 759 } 760 needUpdate = true; 761 break; 762 763 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 764 if (verified) { 765 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 766 needUpdate = true; 767 } 768 break; 769 770 default: 771 // Nothing to do 772 } 773 774 if (needUpdate) { 775 mSettings.updateIntentFilterVerificationStatusLPw( 776 packageName, updatedStatus, userId); 777 scheduleWritePackageRestrictionsLocked(userId); 778 } 779 } 780 } 781 } 782 783 @Override 784 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 785 ActivityIntentInfo filter, String packageName) { 786 if (!hasValidDomains(filter)) { 787 return false; 788 } 789 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 790 if (ivs == null) { 791 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 792 packageName); 793 } 794 if (DEBUG_DOMAIN_VERIFICATION) { 795 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 796 } 797 ivs.addFilter(filter); 798 return true; 799 } 800 801 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 802 int userId, int verificationId, String packageName) { 803 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 804 verifierUid, userId, packageName); 805 ivs.setPendingState(); 806 synchronized (mPackages) { 807 mIntentFilterVerificationStates.append(verificationId, ivs); 808 mCurrentIntentFilterVerifications.add(verificationId); 809 } 810 return ivs; 811 } 812 } 813 814 private static boolean hasValidDomains(ActivityIntentInfo filter) { 815 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 816 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 817 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 818 } 819 820 private IntentFilterVerifier mIntentFilterVerifier; 821 822 // Set of pending broadcasts for aggregating enable/disable of components. 823 static class PendingPackageBroadcasts { 824 // for each user id, a map of <package name -> components within that package> 825 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 826 827 public PendingPackageBroadcasts() { 828 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 829 } 830 831 public ArrayList<String> get(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 833 return packages.get(packageName); 834 } 835 836 public void put(int userId, String packageName, ArrayList<String> components) { 837 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 838 packages.put(packageName, components); 839 } 840 841 public void remove(int userId, String packageName) { 842 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 843 if (packages != null) { 844 packages.remove(packageName); 845 } 846 } 847 848 public void remove(int userId) { 849 mUidMap.remove(userId); 850 } 851 852 public int userIdCount() { 853 return mUidMap.size(); 854 } 855 856 public int userIdAt(int n) { 857 return mUidMap.keyAt(n); 858 } 859 860 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 861 return mUidMap.get(userId); 862 } 863 864 public int size() { 865 // total number of pending broadcast entries across all userIds 866 int num = 0; 867 for (int i = 0; i< mUidMap.size(); i++) { 868 num += mUidMap.valueAt(i).size(); 869 } 870 return num; 871 } 872 873 public void clear() { 874 mUidMap.clear(); 875 } 876 877 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 878 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 879 if (map == null) { 880 map = new ArrayMap<String, ArrayList<String>>(); 881 mUidMap.put(userId, map); 882 } 883 return map; 884 } 885 } 886 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 887 888 // Service Connection to remote media container service to copy 889 // package uri's from external media onto secure containers 890 // or internal storage. 891 private IMediaContainerService mContainerService = null; 892 893 static final int SEND_PENDING_BROADCAST = 1; 894 static final int MCS_BOUND = 3; 895 static final int END_COPY = 4; 896 static final int INIT_COPY = 5; 897 static final int MCS_UNBIND = 6; 898 static final int START_CLEANING_PACKAGE = 7; 899 static final int FIND_INSTALL_LOC = 8; 900 static final int POST_INSTALL = 9; 901 static final int MCS_RECONNECT = 10; 902 static final int MCS_GIVE_UP = 11; 903 static final int UPDATED_MEDIA_STATUS = 12; 904 static final int WRITE_SETTINGS = 13; 905 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 906 static final int PACKAGE_VERIFIED = 15; 907 static final int CHECK_PENDING_VERIFICATION = 16; 908 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 909 static final int INTENT_FILTER_VERIFIED = 18; 910 911 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 912 913 // Delay time in millisecs 914 static final int BROADCAST_DELAY = 10 * 1000; 915 916 static UserManagerService sUserManager; 917 918 // Stores a list of users whose package restrictions file needs to be updated 919 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 920 921 final private DefaultContainerConnection mDefContainerConn = 922 new DefaultContainerConnection(); 923 class DefaultContainerConnection implements ServiceConnection { 924 public void onServiceConnected(ComponentName name, IBinder service) { 925 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 926 IMediaContainerService imcs = 927 IMediaContainerService.Stub.asInterface(service); 928 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 929 } 930 931 public void onServiceDisconnected(ComponentName name) { 932 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 933 } 934 } 935 936 // Recordkeeping of restore-after-install operations that are currently in flight 937 // between the Package Manager and the Backup Manager 938 class PostInstallData { 939 public InstallArgs args; 940 public PackageInstalledInfo res; 941 942 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 943 args = _a; 944 res = _r; 945 } 946 } 947 948 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 949 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 950 951 // XML tags for backup/restore of various bits of state 952 private static final String TAG_PREFERRED_BACKUP = "pa"; 953 private static final String TAG_DEFAULT_APPS = "da"; 954 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 955 956 final String mRequiredVerifierPackage; 957 final String mRequiredInstallerPackage; 958 959 private final PackageUsage mPackageUsage = new PackageUsage(); 960 961 private class PackageUsage { 962 private static final int WRITE_INTERVAL 963 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 964 965 private final Object mFileLock = new Object(); 966 private final AtomicLong mLastWritten = new AtomicLong(0); 967 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 968 969 private boolean mIsHistoricalPackageUsageAvailable = true; 970 971 boolean isHistoricalPackageUsageAvailable() { 972 return mIsHistoricalPackageUsageAvailable; 973 } 974 975 void write(boolean force) { 976 if (force) { 977 writeInternal(); 978 return; 979 } 980 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 981 && !DEBUG_DEXOPT) { 982 return; 983 } 984 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 985 new Thread("PackageUsage_DiskWriter") { 986 @Override 987 public void run() { 988 try { 989 writeInternal(); 990 } finally { 991 mBackgroundWriteRunning.set(false); 992 } 993 } 994 }.start(); 995 } 996 } 997 998 private void writeInternal() { 999 synchronized (mPackages) { 1000 synchronized (mFileLock) { 1001 AtomicFile file = getFile(); 1002 FileOutputStream f = null; 1003 try { 1004 f = file.startWrite(); 1005 BufferedOutputStream out = new BufferedOutputStream(f); 1006 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1007 StringBuilder sb = new StringBuilder(); 1008 for (PackageParser.Package pkg : mPackages.values()) { 1009 if (pkg.mLastPackageUsageTimeInMills == 0) { 1010 continue; 1011 } 1012 sb.setLength(0); 1013 sb.append(pkg.packageName); 1014 sb.append(' '); 1015 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1016 sb.append('\n'); 1017 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1018 } 1019 out.flush(); 1020 file.finishWrite(f); 1021 } catch (IOException e) { 1022 if (f != null) { 1023 file.failWrite(f); 1024 } 1025 Log.e(TAG, "Failed to write package usage times", e); 1026 } 1027 } 1028 } 1029 mLastWritten.set(SystemClock.elapsedRealtime()); 1030 } 1031 1032 void readLP() { 1033 synchronized (mFileLock) { 1034 AtomicFile file = getFile(); 1035 BufferedInputStream in = null; 1036 try { 1037 in = new BufferedInputStream(file.openRead()); 1038 StringBuffer sb = new StringBuffer(); 1039 while (true) { 1040 String packageName = readToken(in, sb, ' '); 1041 if (packageName == null) { 1042 break; 1043 } 1044 String timeInMillisString = readToken(in, sb, '\n'); 1045 if (timeInMillisString == null) { 1046 throw new IOException("Failed to find last usage time for package " 1047 + packageName); 1048 } 1049 PackageParser.Package pkg = mPackages.get(packageName); 1050 if (pkg == null) { 1051 continue; 1052 } 1053 long timeInMillis; 1054 try { 1055 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1056 } catch (NumberFormatException e) { 1057 throw new IOException("Failed to parse " + timeInMillisString 1058 + " as a long.", e); 1059 } 1060 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1061 } 1062 } catch (FileNotFoundException expected) { 1063 mIsHistoricalPackageUsageAvailable = false; 1064 } catch (IOException e) { 1065 Log.w(TAG, "Failed to read package usage times", e); 1066 } finally { 1067 IoUtils.closeQuietly(in); 1068 } 1069 } 1070 mLastWritten.set(SystemClock.elapsedRealtime()); 1071 } 1072 1073 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1074 throws IOException { 1075 sb.setLength(0); 1076 while (true) { 1077 int ch = in.read(); 1078 if (ch == -1) { 1079 if (sb.length() == 0) { 1080 return null; 1081 } 1082 throw new IOException("Unexpected EOF"); 1083 } 1084 if (ch == endOfToken) { 1085 return sb.toString(); 1086 } 1087 sb.append((char)ch); 1088 } 1089 } 1090 1091 private AtomicFile getFile() { 1092 File dataDir = Environment.getDataDirectory(); 1093 File systemDir = new File(dataDir, "system"); 1094 File fname = new File(systemDir, "package-usage.list"); 1095 return new AtomicFile(fname); 1096 } 1097 } 1098 1099 class PackageHandler extends Handler { 1100 private boolean mBound = false; 1101 final ArrayList<HandlerParams> mPendingInstalls = 1102 new ArrayList<HandlerParams>(); 1103 1104 private boolean connectToService() { 1105 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1106 " DefaultContainerService"); 1107 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1110 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 mBound = true; 1113 return true; 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 return false; 1117 } 1118 1119 private void disconnectService() { 1120 mContainerService = null; 1121 mBound = false; 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1123 mContext.unbindService(mDefContainerConn); 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1125 } 1126 1127 PackageHandler(Looper looper) { 1128 super(looper); 1129 } 1130 1131 public void handleMessage(Message msg) { 1132 try { 1133 doHandleMessage(msg); 1134 } finally { 1135 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1136 } 1137 } 1138 1139 void doHandleMessage(Message msg) { 1140 switch (msg.what) { 1141 case INIT_COPY: { 1142 HandlerParams params = (HandlerParams) msg.obj; 1143 int idx = mPendingInstalls.size(); 1144 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1145 // If a bind was already initiated we dont really 1146 // need to do anything. The pending install 1147 // will be processed later on. 1148 if (!mBound) { 1149 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1150 System.identityHashCode(mHandler)); 1151 // If this is the only one pending we might 1152 // have to bind to the service again. 1153 if (!connectToService()) { 1154 Slog.e(TAG, "Failed to bind to media container service"); 1155 params.serviceError(); 1156 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1157 System.identityHashCode(mHandler)); 1158 if (params.traceMethod != null) { 1159 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1160 params.traceCookie); 1161 } 1162 return; 1163 } else { 1164 // Once we bind to the service, the first 1165 // pending request will be processed. 1166 mPendingInstalls.add(idx, params); 1167 } 1168 } else { 1169 mPendingInstalls.add(idx, params); 1170 // Already bound to the service. Just make 1171 // sure we trigger off processing the first request. 1172 if (idx == 0) { 1173 mHandler.sendEmptyMessage(MCS_BOUND); 1174 } 1175 } 1176 break; 1177 } 1178 case MCS_BOUND: { 1179 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1180 if (msg.obj != null) { 1181 mContainerService = (IMediaContainerService) msg.obj; 1182 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1183 System.identityHashCode(mHandler)); 1184 } 1185 if (mContainerService == null) { 1186 if (!mBound) { 1187 // Something seriously wrong since we are not bound and we are not 1188 // waiting for connection. Bail out. 1189 Slog.e(TAG, "Cannot bind to media container service"); 1190 for (HandlerParams params : mPendingInstalls) { 1191 // Indicate service bind error 1192 params.serviceError(); 1193 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1194 System.identityHashCode(params)); 1195 if (params.traceMethod != null) { 1196 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1197 params.traceMethod, params.traceCookie); 1198 } 1199 return; 1200 } 1201 mPendingInstalls.clear(); 1202 } else { 1203 Slog.w(TAG, "Waiting to connect to media container service"); 1204 } 1205 } else if (mPendingInstalls.size() > 0) { 1206 HandlerParams params = mPendingInstalls.get(0); 1207 if (params != null) { 1208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1209 System.identityHashCode(params)); 1210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1211 if (params.startCopy()) { 1212 // We are done... look for more work or to 1213 // go idle. 1214 if (DEBUG_SD_INSTALL) Log.i(TAG, 1215 "Checking for more work or unbind..."); 1216 // Delete pending install 1217 if (mPendingInstalls.size() > 0) { 1218 mPendingInstalls.remove(0); 1219 } 1220 if (mPendingInstalls.size() == 0) { 1221 if (mBound) { 1222 if (DEBUG_SD_INSTALL) Log.i(TAG, 1223 "Posting delayed MCS_UNBIND"); 1224 removeMessages(MCS_UNBIND); 1225 Message ubmsg = obtainMessage(MCS_UNBIND); 1226 // Unbind after a little delay, to avoid 1227 // continual thrashing. 1228 sendMessageDelayed(ubmsg, 10000); 1229 } 1230 } else { 1231 // There are more pending requests in queue. 1232 // Just post MCS_BOUND message to trigger processing 1233 // of next pending install. 1234 if (DEBUG_SD_INSTALL) Log.i(TAG, 1235 "Posting MCS_BOUND for next work"); 1236 mHandler.sendEmptyMessage(MCS_BOUND); 1237 } 1238 } 1239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1240 } 1241 } else { 1242 // Should never happen ideally. 1243 Slog.w(TAG, "Empty queue"); 1244 } 1245 break; 1246 } 1247 case MCS_RECONNECT: { 1248 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1249 if (mPendingInstalls.size() > 0) { 1250 if (mBound) { 1251 disconnectService(); 1252 } 1253 if (!connectToService()) { 1254 Slog.e(TAG, "Failed to bind to media container service"); 1255 for (HandlerParams params : mPendingInstalls) { 1256 // Indicate service bind error 1257 params.serviceError(); 1258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1259 System.identityHashCode(params)); 1260 } 1261 mPendingInstalls.clear(); 1262 } 1263 } 1264 break; 1265 } 1266 case MCS_UNBIND: { 1267 // If there is no actual work left, then time to unbind. 1268 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1269 1270 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1271 if (mBound) { 1272 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1273 1274 disconnectService(); 1275 } 1276 } else if (mPendingInstalls.size() > 0) { 1277 // There are more pending requests in queue. 1278 // Just post MCS_BOUND message to trigger processing 1279 // of next pending install. 1280 mHandler.sendEmptyMessage(MCS_BOUND); 1281 } 1282 1283 break; 1284 } 1285 case MCS_GIVE_UP: { 1286 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1287 HandlerParams params = mPendingInstalls.remove(0); 1288 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1289 System.identityHashCode(params)); 1290 break; 1291 } 1292 case SEND_PENDING_BROADCAST: { 1293 String packages[]; 1294 ArrayList<String> components[]; 1295 int size = 0; 1296 int uids[]; 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1298 synchronized (mPackages) { 1299 if (mPendingBroadcasts == null) { 1300 return; 1301 } 1302 size = mPendingBroadcasts.size(); 1303 if (size <= 0) { 1304 // Nothing to be done. Just return 1305 return; 1306 } 1307 packages = new String[size]; 1308 components = new ArrayList[size]; 1309 uids = new int[size]; 1310 int i = 0; // filling out the above arrays 1311 1312 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1313 int packageUserId = mPendingBroadcasts.userIdAt(n); 1314 Iterator<Map.Entry<String, ArrayList<String>>> it 1315 = mPendingBroadcasts.packagesForUserId(packageUserId) 1316 .entrySet().iterator(); 1317 while (it.hasNext() && i < size) { 1318 Map.Entry<String, ArrayList<String>> ent = it.next(); 1319 packages[i] = ent.getKey(); 1320 components[i] = ent.getValue(); 1321 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1322 uids[i] = (ps != null) 1323 ? UserHandle.getUid(packageUserId, ps.appId) 1324 : -1; 1325 i++; 1326 } 1327 } 1328 size = i; 1329 mPendingBroadcasts.clear(); 1330 } 1331 // Send broadcasts 1332 for (int i = 0; i < size; i++) { 1333 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1334 } 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 break; 1337 } 1338 case START_CLEANING_PACKAGE: { 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1340 final String packageName = (String)msg.obj; 1341 final int userId = msg.arg1; 1342 final boolean andCode = msg.arg2 != 0; 1343 synchronized (mPackages) { 1344 if (userId == UserHandle.USER_ALL) { 1345 int[] users = sUserManager.getUserIds(); 1346 for (int user : users) { 1347 mSettings.addPackageToCleanLPw( 1348 new PackageCleanItem(user, packageName, andCode)); 1349 } 1350 } else { 1351 mSettings.addPackageToCleanLPw( 1352 new PackageCleanItem(userId, packageName, andCode)); 1353 } 1354 } 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1356 startCleaningPackages(); 1357 } break; 1358 case POST_INSTALL: { 1359 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1360 PostInstallData data = mRunningInstalls.get(msg.arg1); 1361 mRunningInstalls.delete(msg.arg1); 1362 boolean deleteOld = false; 1363 1364 if (data != null) { 1365 InstallArgs args = data.args; 1366 PackageInstalledInfo res = data.res; 1367 1368 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1369 final String packageName = res.pkg.applicationInfo.packageName; 1370 res.removedInfo.sendBroadcast(false, true, false); 1371 Bundle extras = new Bundle(1); 1372 extras.putInt(Intent.EXTRA_UID, res.uid); 1373 1374 // Now that we successfully installed the package, grant runtime 1375 // permissions if requested before broadcasting the install. 1376 if ((args.installFlags 1377 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1378 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1379 args.installGrantPermissions); 1380 } 1381 1382 // Determine the set of users who are adding this 1383 // package for the first time vs. those who are seeing 1384 // an update. 1385 int[] firstUsers; 1386 int[] updateUsers = new int[0]; 1387 if (res.origUsers == null || res.origUsers.length == 0) { 1388 firstUsers = res.newUsers; 1389 } else { 1390 firstUsers = new int[0]; 1391 for (int i=0; i<res.newUsers.length; i++) { 1392 int user = res.newUsers[i]; 1393 boolean isNew = true; 1394 for (int j=0; j<res.origUsers.length; j++) { 1395 if (res.origUsers[j] == user) { 1396 isNew = false; 1397 break; 1398 } 1399 } 1400 if (isNew) { 1401 int[] newFirst = new int[firstUsers.length+1]; 1402 System.arraycopy(firstUsers, 0, newFirst, 0, 1403 firstUsers.length); 1404 newFirst[firstUsers.length] = user; 1405 firstUsers = newFirst; 1406 } else { 1407 int[] newUpdate = new int[updateUsers.length+1]; 1408 System.arraycopy(updateUsers, 0, newUpdate, 0, 1409 updateUsers.length); 1410 newUpdate[updateUsers.length] = user; 1411 updateUsers = newUpdate; 1412 } 1413 } 1414 } 1415 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1416 packageName, extras, null, null, firstUsers); 1417 final boolean update = res.removedInfo.removedPackage != null; 1418 if (update) { 1419 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1420 } 1421 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1422 packageName, extras, null, null, updateUsers); 1423 if (update) { 1424 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1425 packageName, extras, null, null, updateUsers); 1426 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1427 null, null, packageName, null, updateUsers); 1428 1429 // treat asec-hosted packages like removable media on upgrade 1430 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1431 if (DEBUG_INSTALL) { 1432 Slog.i(TAG, "upgrading pkg " + res.pkg 1433 + " is ASEC-hosted -> AVAILABLE"); 1434 } 1435 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1436 ArrayList<String> pkgList = new ArrayList<String>(1); 1437 pkgList.add(packageName); 1438 sendResourcesChangedBroadcast(true, true, 1439 pkgList,uidArray, null); 1440 } 1441 } 1442 if (res.removedInfo.args != null) { 1443 // Remove the replaced package's older resources safely now 1444 deleteOld = true; 1445 } 1446 1447 // If this app is a browser and it's newly-installed for some 1448 // users, clear any default-browser state in those users 1449 if (firstUsers.length > 0) { 1450 // the app's nature doesn't depend on the user, so we can just 1451 // check its browser nature in any user and generalize. 1452 if (packageIsBrowser(packageName, firstUsers[0])) { 1453 synchronized (mPackages) { 1454 for (int userId : firstUsers) { 1455 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1456 } 1457 } 1458 } 1459 } 1460 // Log current value of "unknown sources" setting 1461 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1462 getUnknownSourcesSettings()); 1463 } 1464 // Force a gc to clear up things 1465 Runtime.getRuntime().gc(); 1466 // We delete after a gc for applications on sdcard. 1467 if (deleteOld) { 1468 synchronized (mInstallLock) { 1469 res.removedInfo.args.doPostDeleteLI(true); 1470 } 1471 } 1472 if (args.observer != null) { 1473 try { 1474 Bundle extras = extrasForInstallResult(res); 1475 args.observer.onPackageInstalled(res.name, res.returnCode, 1476 res.returnMsg, extras); 1477 } catch (RemoteException e) { 1478 Slog.i(TAG, "Observer no longer exists."); 1479 } 1480 } 1481 if (args.traceMethod != null) { 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1483 args.traceCookie); 1484 } 1485 return; 1486 } else { 1487 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1488 } 1489 1490 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1491 } break; 1492 case UPDATED_MEDIA_STATUS: { 1493 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1494 boolean reportStatus = msg.arg1 == 1; 1495 boolean doGc = msg.arg2 == 1; 1496 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1497 if (doGc) { 1498 // Force a gc to clear up stale containers. 1499 Runtime.getRuntime().gc(); 1500 } 1501 if (msg.obj != null) { 1502 @SuppressWarnings("unchecked") 1503 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1504 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1505 // Unload containers 1506 unloadAllContainers(args); 1507 } 1508 if (reportStatus) { 1509 try { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1511 PackageHelper.getMountService().finishMediaUpdate(); 1512 } catch (RemoteException e) { 1513 Log.e(TAG, "MountService not running?"); 1514 } 1515 } 1516 } break; 1517 case WRITE_SETTINGS: { 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 removeMessages(WRITE_SETTINGS); 1521 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1522 mSettings.writeLPr(); 1523 mDirtyUsers.clear(); 1524 } 1525 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1526 } break; 1527 case WRITE_PACKAGE_RESTRICTIONS: { 1528 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1529 synchronized (mPackages) { 1530 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1531 for (int userId : mDirtyUsers) { 1532 mSettings.writePackageRestrictionsLPr(userId); 1533 } 1534 mDirtyUsers.clear(); 1535 } 1536 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1537 } break; 1538 case CHECK_PENDING_VERIFICATION: { 1539 final int verificationId = msg.arg1; 1540 final PackageVerificationState state = mPendingVerification.get(verificationId); 1541 1542 if ((state != null) && !state.timeoutExtended()) { 1543 final InstallArgs args = state.getInstallArgs(); 1544 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1545 1546 Slog.i(TAG, "Verification timed out for " + originUri); 1547 mPendingVerification.remove(verificationId); 1548 1549 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1550 1551 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1552 Slog.i(TAG, "Continuing with installation of " + originUri); 1553 state.setVerifierResponse(Binder.getCallingUid(), 1554 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1555 broadcastPackageVerified(verificationId, originUri, 1556 PackageManager.VERIFICATION_ALLOW, 1557 state.getInstallArgs().getUser()); 1558 try { 1559 ret = args.copyApk(mContainerService, true); 1560 } catch (RemoteException e) { 1561 Slog.e(TAG, "Could not contact the ContainerService"); 1562 } 1563 } else { 1564 broadcastPackageVerified(verificationId, originUri, 1565 PackageManager.VERIFICATION_REJECT, 1566 state.getInstallArgs().getUser()); 1567 } 1568 1569 Trace.asyncTraceEnd( 1570 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1571 1572 processPendingInstall(args, ret); 1573 mHandler.sendEmptyMessage(MCS_UNBIND); 1574 } 1575 break; 1576 } 1577 case PACKAGE_VERIFIED: { 1578 final int verificationId = msg.arg1; 1579 1580 final PackageVerificationState state = mPendingVerification.get(verificationId); 1581 if (state == null) { 1582 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1583 break; 1584 } 1585 1586 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1587 1588 state.setVerifierResponse(response.callerUid, response.code); 1589 1590 if (state.isVerificationComplete()) { 1591 mPendingVerification.remove(verificationId); 1592 1593 final InstallArgs args = state.getInstallArgs(); 1594 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1595 1596 int ret; 1597 if (state.isInstallAllowed()) { 1598 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1599 broadcastPackageVerified(verificationId, originUri, 1600 response.code, state.getInstallArgs().getUser()); 1601 try { 1602 ret = args.copyApk(mContainerService, true); 1603 } catch (RemoteException e) { 1604 Slog.e(TAG, "Could not contact the ContainerService"); 1605 } 1606 } else { 1607 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1608 } 1609 1610 Trace.asyncTraceEnd( 1611 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1612 1613 processPendingInstall(args, ret); 1614 mHandler.sendEmptyMessage(MCS_UNBIND); 1615 } 1616 1617 break; 1618 } 1619 case START_INTENT_FILTER_VERIFICATIONS: { 1620 IFVerificationParams params = (IFVerificationParams) msg.obj; 1621 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1622 params.replacing, params.pkg); 1623 break; 1624 } 1625 case INTENT_FILTER_VERIFIED: { 1626 final int verificationId = msg.arg1; 1627 1628 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1629 verificationId); 1630 if (state == null) { 1631 Slog.w(TAG, "Invalid IntentFilter verification token " 1632 + verificationId + " received"); 1633 break; 1634 } 1635 1636 final int userId = state.getUserId(); 1637 1638 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1639 "Processing IntentFilter verification with token:" 1640 + verificationId + " and userId:" + userId); 1641 1642 final IntentFilterVerificationResponse response = 1643 (IntentFilterVerificationResponse) msg.obj; 1644 1645 state.setVerifierResponse(response.callerUid, response.code); 1646 1647 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1648 "IntentFilter verification with token:" + verificationId 1649 + " and userId:" + userId 1650 + " is settings verifier response with response code:" 1651 + response.code); 1652 1653 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1654 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1655 + response.getFailedDomainsString()); 1656 } 1657 1658 if (state.isVerificationComplete()) { 1659 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1660 } else { 1661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1662 "IntentFilter verification with token:" + verificationId 1663 + " was not said to be complete"); 1664 } 1665 1666 break; 1667 } 1668 } 1669 } 1670 } 1671 1672 private StorageEventListener mStorageListener = new StorageEventListener() { 1673 @Override 1674 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1675 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1676 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1677 final String volumeUuid = vol.getFsUuid(); 1678 1679 // Clean up any users or apps that were removed or recreated 1680 // while this volume was missing 1681 reconcileUsers(volumeUuid); 1682 reconcileApps(volumeUuid); 1683 1684 // Clean up any install sessions that expired or were 1685 // cancelled while this volume was missing 1686 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1687 1688 loadPrivatePackages(vol); 1689 1690 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1691 unloadPrivatePackages(vol); 1692 } 1693 } 1694 1695 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1696 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1697 updateExternalMediaStatus(true, false); 1698 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1699 updateExternalMediaStatus(false, false); 1700 } 1701 } 1702 } 1703 1704 @Override 1705 public void onVolumeForgotten(String fsUuid) { 1706 if (TextUtils.isEmpty(fsUuid)) { 1707 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1708 return; 1709 } 1710 1711 // Remove any apps installed on the forgotten volume 1712 synchronized (mPackages) { 1713 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1714 for (PackageSetting ps : packages) { 1715 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1716 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1717 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1718 } 1719 1720 mSettings.onVolumeForgotten(fsUuid); 1721 mSettings.writeLPr(); 1722 } 1723 } 1724 }; 1725 1726 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1727 String[] grantedPermissions) { 1728 if (userId >= UserHandle.USER_SYSTEM) { 1729 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1730 } else if (userId == UserHandle.USER_ALL) { 1731 final int[] userIds; 1732 synchronized (mPackages) { 1733 userIds = UserManagerService.getInstance().getUserIds(); 1734 } 1735 for (int someUserId : userIds) { 1736 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1737 } 1738 } 1739 1740 // We could have touched GID membership, so flush out packages.list 1741 synchronized (mPackages) { 1742 mSettings.writePackageListLPr(); 1743 } 1744 } 1745 1746 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1747 String[] grantedPermissions) { 1748 SettingBase sb = (SettingBase) pkg.mExtras; 1749 if (sb == null) { 1750 return; 1751 } 1752 1753 PermissionsState permissionsState = sb.getPermissionsState(); 1754 1755 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1756 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1757 1758 synchronized (mPackages) { 1759 for (String permission : pkg.requestedPermissions) { 1760 BasePermission bp = mSettings.mPermissions.get(permission); 1761 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1762 && (grantedPermissions == null 1763 || ArrayUtils.contains(grantedPermissions, permission))) { 1764 final int flags = permissionsState.getPermissionFlags(permission, userId); 1765 // Installer cannot change immutable permissions. 1766 if ((flags & immutableFlags) == 0) { 1767 grantRuntimePermission(pkg.packageName, permission, userId); 1768 } 1769 } 1770 } 1771 } 1772 } 1773 1774 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1775 Bundle extras = null; 1776 switch (res.returnCode) { 1777 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1778 extras = new Bundle(); 1779 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1780 res.origPermission); 1781 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1782 res.origPackage); 1783 break; 1784 } 1785 case PackageManager.INSTALL_SUCCEEDED: { 1786 extras = new Bundle(); 1787 extras.putBoolean(Intent.EXTRA_REPLACING, 1788 res.removedInfo != null && res.removedInfo.removedPackage != null); 1789 break; 1790 } 1791 } 1792 return extras; 1793 } 1794 1795 void scheduleWriteSettingsLocked() { 1796 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1797 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1798 } 1799 } 1800 1801 void scheduleWritePackageRestrictionsLocked(int userId) { 1802 if (!sUserManager.exists(userId)) return; 1803 mDirtyUsers.add(userId); 1804 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1805 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1806 } 1807 } 1808 1809 public static PackageManagerService main(Context context, Installer installer, 1810 boolean factoryTest, boolean onlyCore) { 1811 PackageManagerService m = new PackageManagerService(context, installer, 1812 factoryTest, onlyCore); 1813 ServiceManager.addService("package", m); 1814 return m; 1815 } 1816 1817 static String[] splitString(String str, char sep) { 1818 int count = 1; 1819 int i = 0; 1820 while ((i=str.indexOf(sep, i)) >= 0) { 1821 count++; 1822 i++; 1823 } 1824 1825 String[] res = new String[count]; 1826 i=0; 1827 count = 0; 1828 int lastI=0; 1829 while ((i=str.indexOf(sep, i)) >= 0) { 1830 res[count] = str.substring(lastI, i); 1831 count++; 1832 i++; 1833 lastI = i; 1834 } 1835 res[count] = str.substring(lastI, str.length()); 1836 return res; 1837 } 1838 1839 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1840 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1841 Context.DISPLAY_SERVICE); 1842 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1843 } 1844 1845 public PackageManagerService(Context context, Installer installer, 1846 boolean factoryTest, boolean onlyCore) { 1847 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1848 SystemClock.uptimeMillis()); 1849 1850 if (mSdkVersion <= 0) { 1851 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1852 } 1853 1854 mContext = context; 1855 mFactoryTest = factoryTest; 1856 mOnlyCore = onlyCore; 1857 mMetrics = new DisplayMetrics(); 1858 mSettings = new Settings(mPackages); 1859 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1860 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1861 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1862 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1863 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1864 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1865 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1866 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1867 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1868 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1869 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1870 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1871 1872 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1873 if (separateProcesses != null && separateProcesses.length() > 0) { 1874 if ("*".equals(separateProcesses)) { 1875 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1876 mSeparateProcesses = null; 1877 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1878 } else { 1879 mDefParseFlags = 0; 1880 mSeparateProcesses = separateProcesses.split(","); 1881 Slog.w(TAG, "Running with debug.separate_processes: " 1882 + separateProcesses); 1883 } 1884 } else { 1885 mDefParseFlags = 0; 1886 mSeparateProcesses = null; 1887 } 1888 1889 mInstaller = installer; 1890 mPackageDexOptimizer = new PackageDexOptimizer(this); 1891 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1892 1893 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1894 FgThread.get().getLooper()); 1895 1896 getDefaultDisplayMetrics(context, mMetrics); 1897 1898 SystemConfig systemConfig = SystemConfig.getInstance(); 1899 mGlobalGids = systemConfig.getGlobalGids(); 1900 mSystemPermissions = systemConfig.getSystemPermissions(); 1901 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1902 1903 synchronized (mInstallLock) { 1904 // writer 1905 synchronized (mPackages) { 1906 mHandlerThread = new ServiceThread(TAG, 1907 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1908 mHandlerThread.start(); 1909 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1910 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1911 1912 File dataDir = Environment.getDataDirectory(); 1913 mAppDataDir = new File(dataDir, "data"); 1914 mAppInstallDir = new File(dataDir, "app"); 1915 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1916 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1917 mUserAppDataDir = new File(dataDir, "user"); 1918 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1919 1920 sUserManager = new UserManagerService(context, this, 1921 mInstallLock, mPackages); 1922 1923 // Propagate permission configuration in to package manager. 1924 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1925 = systemConfig.getPermissions(); 1926 for (int i=0; i<permConfig.size(); i++) { 1927 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1928 BasePermission bp = mSettings.mPermissions.get(perm.name); 1929 if (bp == null) { 1930 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1931 mSettings.mPermissions.put(perm.name, bp); 1932 } 1933 if (perm.gids != null) { 1934 bp.setGids(perm.gids, perm.perUser); 1935 } 1936 } 1937 1938 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1939 for (int i=0; i<libConfig.size(); i++) { 1940 mSharedLibraries.put(libConfig.keyAt(i), 1941 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1942 } 1943 1944 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1945 1946 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1947 1948 String customResolverActivity = Resources.getSystem().getString( 1949 R.string.config_customResolverActivity); 1950 if (TextUtils.isEmpty(customResolverActivity)) { 1951 customResolverActivity = null; 1952 } else { 1953 mCustomResolverComponentName = ComponentName.unflattenFromString( 1954 customResolverActivity); 1955 } 1956 1957 long startTime = SystemClock.uptimeMillis(); 1958 1959 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1960 startTime); 1961 1962 // Set flag to monitor and not change apk file paths when 1963 // scanning install directories. 1964 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1965 1966 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1967 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1968 1969 if (bootClassPath == null) { 1970 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1971 } 1972 1973 if (systemServerClassPath == null) { 1974 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1975 } 1976 1977 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1978 final String[] dexCodeInstructionSets = 1979 getDexCodeInstructionSets( 1980 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1981 1982 /** 1983 * Ensure all external libraries have had dexopt run on them. 1984 */ 1985 if (mSharedLibraries.size() > 0) { 1986 // NOTE: For now, we're compiling these system "shared libraries" 1987 // (and framework jars) into all available architectures. It's possible 1988 // to compile them only when we come across an app that uses them (there's 1989 // already logic for that in scanPackageLI) but that adds some complexity. 1990 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1991 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1992 final String lib = libEntry.path; 1993 if (lib == null) { 1994 continue; 1995 } 1996 1997 try { 1998 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1999 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2000 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2001 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2002 } 2003 } catch (FileNotFoundException e) { 2004 Slog.w(TAG, "Library not found: " + lib); 2005 } catch (IOException e) { 2006 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2007 + e.getMessage()); 2008 } 2009 } 2010 } 2011 } 2012 2013 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2014 2015 final VersionInfo ver = mSettings.getInternalVersion(); 2016 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2017 // when upgrading from pre-M, promote system app permissions from install to runtime 2018 mPromoteSystemApps = 2019 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2020 2021 // save off the names of pre-existing system packages prior to scanning; we don't 2022 // want to automatically grant runtime permissions for new system apps 2023 if (mPromoteSystemApps) { 2024 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2025 while (pkgSettingIter.hasNext()) { 2026 PackageSetting ps = pkgSettingIter.next(); 2027 if (isSystemApp(ps)) { 2028 mExistingSystemPackages.add(ps.name); 2029 } 2030 } 2031 } 2032 2033 // Collect vendor overlay packages. 2034 // (Do this before scanning any apps.) 2035 // For security and version matching reason, only consider 2036 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2037 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2038 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2039 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2040 2041 // Find base frameworks (resource packages without code). 2042 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2043 | PackageParser.PARSE_IS_SYSTEM_DIR 2044 | PackageParser.PARSE_IS_PRIVILEGED, 2045 scanFlags | SCAN_NO_DEX, 0); 2046 2047 // Collected privileged system packages. 2048 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2049 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2050 | PackageParser.PARSE_IS_SYSTEM_DIR 2051 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2052 2053 // Collect ordinary system packages. 2054 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2055 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2057 2058 // Collect all vendor packages. 2059 File vendorAppDir = new File("/vendor/app"); 2060 try { 2061 vendorAppDir = vendorAppDir.getCanonicalFile(); 2062 } catch (IOException e) { 2063 // failed to look up canonical path, continue with original one 2064 } 2065 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2066 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2067 2068 // Collect all OEM packages. 2069 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2070 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2071 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2072 2073 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2074 mInstaller.moveFiles(); 2075 2076 // Prune any system packages that no longer exist. 2077 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2078 if (!mOnlyCore) { 2079 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2080 while (psit.hasNext()) { 2081 PackageSetting ps = psit.next(); 2082 2083 /* 2084 * If this is not a system app, it can't be a 2085 * disable system app. 2086 */ 2087 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2088 continue; 2089 } 2090 2091 /* 2092 * If the package is scanned, it's not erased. 2093 */ 2094 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2095 if (scannedPkg != null) { 2096 /* 2097 * If the system app is both scanned and in the 2098 * disabled packages list, then it must have been 2099 * added via OTA. Remove it from the currently 2100 * scanned package so the previously user-installed 2101 * application can be scanned. 2102 */ 2103 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2104 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2105 + ps.name + "; removing system app. Last known codePath=" 2106 + ps.codePathString + ", installStatus=" + ps.installStatus 2107 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2108 + scannedPkg.mVersionCode); 2109 removePackageLI(ps, true); 2110 mExpectingBetter.put(ps.name, ps.codePath); 2111 } 2112 2113 continue; 2114 } 2115 2116 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2117 psit.remove(); 2118 logCriticalInfo(Log.WARN, "System package " + ps.name 2119 + " no longer exists; wiping its data"); 2120 removeDataDirsLI(null, ps.name); 2121 } else { 2122 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2123 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2124 possiblyDeletedUpdatedSystemApps.add(ps.name); 2125 } 2126 } 2127 } 2128 } 2129 2130 //look for any incomplete package installations 2131 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2132 //clean up list 2133 for(int i = 0; i < deletePkgsList.size(); i++) { 2134 //clean up here 2135 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2136 } 2137 //delete tmp files 2138 deleteTempPackageFiles(); 2139 2140 // Remove any shared userIDs that have no associated packages 2141 mSettings.pruneSharedUsersLPw(); 2142 2143 if (!mOnlyCore) { 2144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2145 SystemClock.uptimeMillis()); 2146 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2147 2148 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2149 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2150 2151 /** 2152 * Remove disable package settings for any updated system 2153 * apps that were removed via an OTA. If they're not a 2154 * previously-updated app, remove them completely. 2155 * Otherwise, just revoke their system-level permissions. 2156 */ 2157 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2158 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2159 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2160 2161 String msg; 2162 if (deletedPkg == null) { 2163 msg = "Updated system package " + deletedAppName 2164 + " no longer exists; wiping its data"; 2165 removeDataDirsLI(null, deletedAppName); 2166 } else { 2167 msg = "Updated system app + " + deletedAppName 2168 + " no longer present; removing system privileges for " 2169 + deletedAppName; 2170 2171 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2172 2173 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2174 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2175 } 2176 logCriticalInfo(Log.WARN, msg); 2177 } 2178 2179 /** 2180 * Make sure all system apps that we expected to appear on 2181 * the userdata partition actually showed up. If they never 2182 * appeared, crawl back and revive the system version. 2183 */ 2184 for (int i = 0; i < mExpectingBetter.size(); i++) { 2185 final String packageName = mExpectingBetter.keyAt(i); 2186 if (!mPackages.containsKey(packageName)) { 2187 final File scanFile = mExpectingBetter.valueAt(i); 2188 2189 logCriticalInfo(Log.WARN, "Expected better " + packageName 2190 + " but never showed up; reverting to system"); 2191 2192 final int reparseFlags; 2193 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2194 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2195 | PackageParser.PARSE_IS_SYSTEM_DIR 2196 | PackageParser.PARSE_IS_PRIVILEGED; 2197 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2198 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2199 | PackageParser.PARSE_IS_SYSTEM_DIR; 2200 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2201 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2202 | PackageParser.PARSE_IS_SYSTEM_DIR; 2203 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2204 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2205 | PackageParser.PARSE_IS_SYSTEM_DIR; 2206 } else { 2207 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2208 continue; 2209 } 2210 2211 mSettings.enableSystemPackageLPw(packageName); 2212 2213 try { 2214 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2215 } catch (PackageManagerException e) { 2216 Slog.e(TAG, "Failed to parse original system package: " 2217 + e.getMessage()); 2218 } 2219 } 2220 } 2221 } 2222 mExpectingBetter.clear(); 2223 2224 // Now that we know all of the shared libraries, update all clients to have 2225 // the correct library paths. 2226 updateAllSharedLibrariesLPw(); 2227 2228 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2229 // NOTE: We ignore potential failures here during a system scan (like 2230 // the rest of the commands above) because there's precious little we 2231 // can do about it. A settings error is reported, though. 2232 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2233 false /* boot complete */); 2234 } 2235 2236 // Now that we know all the packages we are keeping, 2237 // read and update their last usage times. 2238 mPackageUsage.readLP(); 2239 2240 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2241 SystemClock.uptimeMillis()); 2242 Slog.i(TAG, "Time to scan packages: " 2243 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2244 + " seconds"); 2245 2246 // If the platform SDK has changed since the last time we booted, 2247 // we need to re-grant app permission to catch any new ones that 2248 // appear. This is really a hack, and means that apps can in some 2249 // cases get permissions that the user didn't initially explicitly 2250 // allow... it would be nice to have some better way to handle 2251 // this situation. 2252 int updateFlags = UPDATE_PERMISSIONS_ALL; 2253 if (ver.sdkVersion != mSdkVersion) { 2254 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2255 + mSdkVersion + "; regranting permissions for internal storage"); 2256 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2257 } 2258 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2259 ver.sdkVersion = mSdkVersion; 2260 2261 // If this is the first boot or an update from pre-M, and it is a normal 2262 // boot, then we need to initialize the default preferred apps across 2263 // all defined users. 2264 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2265 for (UserInfo user : sUserManager.getUsers(true)) { 2266 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2267 applyFactoryDefaultBrowserLPw(user.id); 2268 primeDomainVerificationsLPw(user.id); 2269 } 2270 } 2271 2272 // If this is first boot after an OTA, and a normal boot, then 2273 // we need to clear code cache directories. 2274 if (mIsUpgrade && !onlyCore) { 2275 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2276 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2277 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2278 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2279 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2280 } 2281 } 2282 ver.fingerprint = Build.FINGERPRINT; 2283 } 2284 2285 checkDefaultBrowser(); 2286 2287 // clear only after permissions and other defaults have been updated 2288 mExistingSystemPackages.clear(); 2289 mPromoteSystemApps = false; 2290 2291 // All the changes are done during package scanning. 2292 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2293 2294 // can downgrade to reader 2295 mSettings.writeLPr(); 2296 2297 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2298 SystemClock.uptimeMillis()); 2299 2300 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2301 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2302 2303 mInstallerService = new PackageInstallerService(context, this); 2304 2305 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2306 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2307 mIntentFilterVerifierComponent); 2308 2309 } // synchronized (mPackages) 2310 } // synchronized (mInstallLock) 2311 2312 // Now after opening every single application zip, make sure they 2313 // are all flushed. Not really needed, but keeps things nice and 2314 // tidy. 2315 Runtime.getRuntime().gc(); 2316 2317 // The initial scanning above does many calls into installd while 2318 // holding the mPackages lock, but we're mostly interested in yelling 2319 // once we have a booted system. 2320 mInstaller.setWarnIfHeld(mPackages); 2321 2322 // Expose private service for system components to use. 2323 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2324 } 2325 2326 @Override 2327 public boolean isFirstBoot() { 2328 return !mRestoredSettings; 2329 } 2330 2331 @Override 2332 public boolean isOnlyCoreApps() { 2333 return mOnlyCore; 2334 } 2335 2336 @Override 2337 public boolean isUpgrade() { 2338 return mIsUpgrade; 2339 } 2340 2341 private String getRequiredVerifierLPr() { 2342 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2343 // We only care about verifier that's installed under system user. 2344 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2345 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2346 2347 String requiredVerifier = null; 2348 2349 final int N = receivers.size(); 2350 for (int i = 0; i < N; i++) { 2351 final ResolveInfo info = receivers.get(i); 2352 2353 if (info.activityInfo == null) { 2354 continue; 2355 } 2356 2357 final String packageName = info.activityInfo.packageName; 2358 2359 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2360 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2361 continue; 2362 } 2363 2364 if (requiredVerifier != null) { 2365 throw new RuntimeException("There can be only one required verifier"); 2366 } 2367 2368 requiredVerifier = packageName; 2369 } 2370 2371 return requiredVerifier; 2372 } 2373 2374 private String getRequiredInstallerLPr() { 2375 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2376 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2377 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2378 2379 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2380 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2381 2382 String requiredInstaller = null; 2383 2384 final int N = installers.size(); 2385 for (int i = 0; i < N; i++) { 2386 final ResolveInfo info = installers.get(i); 2387 final String packageName = info.activityInfo.packageName; 2388 2389 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2390 continue; 2391 } 2392 2393 if (requiredInstaller != null) { 2394 throw new RuntimeException("There must be one required installer"); 2395 } 2396 2397 requiredInstaller = packageName; 2398 } 2399 2400 if (requiredInstaller == null) { 2401 throw new RuntimeException("There must be one required installer"); 2402 } 2403 2404 return requiredInstaller; 2405 } 2406 2407 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2408 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2409 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2410 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2411 2412 ComponentName verifierComponentName = null; 2413 2414 int priority = -1000; 2415 final int N = receivers.size(); 2416 for (int i = 0; i < N; i++) { 2417 final ResolveInfo info = receivers.get(i); 2418 2419 if (info.activityInfo == null) { 2420 continue; 2421 } 2422 2423 final String packageName = info.activityInfo.packageName; 2424 2425 final PackageSetting ps = mSettings.mPackages.get(packageName); 2426 if (ps == null) { 2427 continue; 2428 } 2429 2430 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2431 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2432 continue; 2433 } 2434 2435 // Select the IntentFilterVerifier with the highest priority 2436 if (priority < info.priority) { 2437 priority = info.priority; 2438 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2439 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2440 + verifierComponentName + " with priority: " + info.priority); 2441 } 2442 } 2443 2444 return verifierComponentName; 2445 } 2446 2447 private void primeDomainVerificationsLPw(int userId) { 2448 if (DEBUG_DOMAIN_VERIFICATION) { 2449 Slog.d(TAG, "Priming domain verifications in user " + userId); 2450 } 2451 2452 SystemConfig systemConfig = SystemConfig.getInstance(); 2453 ArraySet<String> packages = systemConfig.getLinkedApps(); 2454 ArraySet<String> domains = new ArraySet<String>(); 2455 2456 for (String packageName : packages) { 2457 PackageParser.Package pkg = mPackages.get(packageName); 2458 if (pkg != null) { 2459 if (!pkg.isSystemApp()) { 2460 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2461 continue; 2462 } 2463 2464 domains.clear(); 2465 for (PackageParser.Activity a : pkg.activities) { 2466 for (ActivityIntentInfo filter : a.intents) { 2467 if (hasValidDomains(filter)) { 2468 domains.addAll(filter.getHostsList()); 2469 } 2470 } 2471 } 2472 2473 if (domains.size() > 0) { 2474 if (DEBUG_DOMAIN_VERIFICATION) { 2475 Slog.v(TAG, " + " + packageName); 2476 } 2477 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2478 // state w.r.t. the formal app-linkage "no verification attempted" state; 2479 // and then 'always' in the per-user state actually used for intent resolution. 2480 final IntentFilterVerificationInfo ivi; 2481 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2482 new ArrayList<String>(domains)); 2483 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2484 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2485 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2486 } else { 2487 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2488 + "' does not handle web links"); 2489 } 2490 } else { 2491 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2492 } 2493 } 2494 2495 scheduleWritePackageRestrictionsLocked(userId); 2496 scheduleWriteSettingsLocked(); 2497 } 2498 2499 private void applyFactoryDefaultBrowserLPw(int userId) { 2500 // The default browser app's package name is stored in a string resource, 2501 // with a product-specific overlay used for vendor customization. 2502 String browserPkg = mContext.getResources().getString( 2503 com.android.internal.R.string.default_browser); 2504 if (!TextUtils.isEmpty(browserPkg)) { 2505 // non-empty string => required to be a known package 2506 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2507 if (ps == null) { 2508 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2509 browserPkg = null; 2510 } else { 2511 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2512 } 2513 } 2514 2515 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2516 // default. If there's more than one, just leave everything alone. 2517 if (browserPkg == null) { 2518 calculateDefaultBrowserLPw(userId); 2519 } 2520 } 2521 2522 private void calculateDefaultBrowserLPw(int userId) { 2523 List<String> allBrowsers = resolveAllBrowserApps(userId); 2524 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2525 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2526 } 2527 2528 private List<String> resolveAllBrowserApps(int userId) { 2529 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2530 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2531 PackageManager.MATCH_ALL, userId); 2532 2533 final int count = list.size(); 2534 List<String> result = new ArrayList<String>(count); 2535 for (int i=0; i<count; i++) { 2536 ResolveInfo info = list.get(i); 2537 if (info.activityInfo == null 2538 || !info.handleAllWebDataURI 2539 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2540 || result.contains(info.activityInfo.packageName)) { 2541 continue; 2542 } 2543 result.add(info.activityInfo.packageName); 2544 } 2545 2546 return result; 2547 } 2548 2549 private boolean packageIsBrowser(String packageName, int userId) { 2550 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2551 PackageManager.MATCH_ALL, userId); 2552 final int N = list.size(); 2553 for (int i = 0; i < N; i++) { 2554 ResolveInfo info = list.get(i); 2555 if (packageName.equals(info.activityInfo.packageName)) { 2556 return true; 2557 } 2558 } 2559 return false; 2560 } 2561 2562 private void checkDefaultBrowser() { 2563 final int myUserId = UserHandle.myUserId(); 2564 final String packageName = getDefaultBrowserPackageName(myUserId); 2565 if (packageName != null) { 2566 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2567 if (info == null) { 2568 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2569 synchronized (mPackages) { 2570 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2571 } 2572 } 2573 } 2574 } 2575 2576 @Override 2577 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2578 throws RemoteException { 2579 try { 2580 return super.onTransact(code, data, reply, flags); 2581 } catch (RuntimeException e) { 2582 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2583 Slog.wtf(TAG, "Package Manager Crash", e); 2584 } 2585 throw e; 2586 } 2587 } 2588 2589 void cleanupInstallFailedPackage(PackageSetting ps) { 2590 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2591 2592 removeDataDirsLI(ps.volumeUuid, ps.name); 2593 if (ps.codePath != null) { 2594 if (ps.codePath.isDirectory()) { 2595 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2596 } else { 2597 ps.codePath.delete(); 2598 } 2599 } 2600 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2601 if (ps.resourcePath.isDirectory()) { 2602 FileUtils.deleteContents(ps.resourcePath); 2603 } 2604 ps.resourcePath.delete(); 2605 } 2606 mSettings.removePackageLPw(ps.name); 2607 } 2608 2609 static int[] appendInts(int[] cur, int[] add) { 2610 if (add == null) return cur; 2611 if (cur == null) return add; 2612 final int N = add.length; 2613 for (int i=0; i<N; i++) { 2614 cur = appendInt(cur, add[i]); 2615 } 2616 return cur; 2617 } 2618 2619 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2620 if (!sUserManager.exists(userId)) return null; 2621 final PackageSetting ps = (PackageSetting) p.mExtras; 2622 if (ps == null) { 2623 return null; 2624 } 2625 2626 final PermissionsState permissionsState = ps.getPermissionsState(); 2627 2628 final int[] gids = permissionsState.computeGids(userId); 2629 final Set<String> permissions = permissionsState.getPermissions(userId); 2630 final PackageUserState state = ps.readUserState(userId); 2631 2632 return PackageParser.generatePackageInfo(p, gids, flags, 2633 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2634 } 2635 2636 @Override 2637 public boolean isPackageFrozen(String packageName) { 2638 synchronized (mPackages) { 2639 final PackageSetting ps = mSettings.mPackages.get(packageName); 2640 if (ps != null) { 2641 return ps.frozen; 2642 } 2643 } 2644 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2645 return true; 2646 } 2647 2648 @Override 2649 public boolean isPackageAvailable(String packageName, int userId) { 2650 if (!sUserManager.exists(userId)) return false; 2651 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2652 synchronized (mPackages) { 2653 PackageParser.Package p = mPackages.get(packageName); 2654 if (p != null) { 2655 final PackageSetting ps = (PackageSetting) p.mExtras; 2656 if (ps != null) { 2657 final PackageUserState state = ps.readUserState(userId); 2658 if (state != null) { 2659 return PackageParser.isAvailable(state); 2660 } 2661 } 2662 } 2663 } 2664 return false; 2665 } 2666 2667 @Override 2668 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2669 if (!sUserManager.exists(userId)) return null; 2670 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2671 // reader 2672 synchronized (mPackages) { 2673 PackageParser.Package p = mPackages.get(packageName); 2674 if (DEBUG_PACKAGE_INFO) 2675 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2676 if (p != null) { 2677 return generatePackageInfo(p, flags, userId); 2678 } 2679 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2680 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2681 } 2682 } 2683 return null; 2684 } 2685 2686 @Override 2687 public String[] currentToCanonicalPackageNames(String[] names) { 2688 String[] out = new String[names.length]; 2689 // reader 2690 synchronized (mPackages) { 2691 for (int i=names.length-1; i>=0; i--) { 2692 PackageSetting ps = mSettings.mPackages.get(names[i]); 2693 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2694 } 2695 } 2696 return out; 2697 } 2698 2699 @Override 2700 public String[] canonicalToCurrentPackageNames(String[] names) { 2701 String[] out = new String[names.length]; 2702 // reader 2703 synchronized (mPackages) { 2704 for (int i=names.length-1; i>=0; i--) { 2705 String cur = mSettings.mRenamedPackages.get(names[i]); 2706 out[i] = cur != null ? cur : names[i]; 2707 } 2708 } 2709 return out; 2710 } 2711 2712 @Override 2713 public int getPackageUid(String packageName, int userId) { 2714 return getPackageUidEtc(packageName, 0, userId); 2715 } 2716 2717 @Override 2718 public int getPackageUidEtc(String packageName, int flags, int userId) { 2719 if (!sUserManager.exists(userId)) return -1; 2720 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2721 2722 // reader 2723 synchronized (mPackages) { 2724 final PackageParser.Package p = mPackages.get(packageName); 2725 if (p != null) { 2726 return UserHandle.getUid(userId, p.applicationInfo.uid); 2727 } 2728 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2729 final PackageSetting ps = mSettings.mPackages.get(packageName); 2730 if (ps != null) { 2731 return UserHandle.getUid(userId, ps.appId); 2732 } 2733 } 2734 } 2735 2736 return -1; 2737 } 2738 2739 @Override 2740 public int[] getPackageGids(String packageName, int userId) { 2741 return getPackageGidsEtc(packageName, 0, userId); 2742 } 2743 2744 @Override 2745 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2746 if (!sUserManager.exists(userId)) { 2747 return null; 2748 } 2749 2750 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2751 "getPackageGids"); 2752 2753 // reader 2754 synchronized (mPackages) { 2755 final PackageParser.Package p = mPackages.get(packageName); 2756 if (p != null) { 2757 PackageSetting ps = (PackageSetting) p.mExtras; 2758 return ps.getPermissionsState().computeGids(userId); 2759 } 2760 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2761 final PackageSetting ps = mSettings.mPackages.get(packageName); 2762 if (ps != null) { 2763 return ps.getPermissionsState().computeGids(userId); 2764 } 2765 } 2766 } 2767 2768 return null; 2769 } 2770 2771 static PermissionInfo generatePermissionInfo( 2772 BasePermission bp, int flags) { 2773 if (bp.perm != null) { 2774 return PackageParser.generatePermissionInfo(bp.perm, flags); 2775 } 2776 PermissionInfo pi = new PermissionInfo(); 2777 pi.name = bp.name; 2778 pi.packageName = bp.sourcePackage; 2779 pi.nonLocalizedLabel = bp.name; 2780 pi.protectionLevel = bp.protectionLevel; 2781 return pi; 2782 } 2783 2784 @Override 2785 public PermissionInfo getPermissionInfo(String name, int flags) { 2786 // reader 2787 synchronized (mPackages) { 2788 final BasePermission p = mSettings.mPermissions.get(name); 2789 if (p != null) { 2790 return generatePermissionInfo(p, flags); 2791 } 2792 return null; 2793 } 2794 } 2795 2796 @Override 2797 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2798 // reader 2799 synchronized (mPackages) { 2800 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2801 for (BasePermission p : mSettings.mPermissions.values()) { 2802 if (group == null) { 2803 if (p.perm == null || p.perm.info.group == null) { 2804 out.add(generatePermissionInfo(p, flags)); 2805 } 2806 } else { 2807 if (p.perm != null && group.equals(p.perm.info.group)) { 2808 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2809 } 2810 } 2811 } 2812 2813 if (out.size() > 0) { 2814 return out; 2815 } 2816 return mPermissionGroups.containsKey(group) ? out : null; 2817 } 2818 } 2819 2820 @Override 2821 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2822 // reader 2823 synchronized (mPackages) { 2824 return PackageParser.generatePermissionGroupInfo( 2825 mPermissionGroups.get(name), flags); 2826 } 2827 } 2828 2829 @Override 2830 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2831 // reader 2832 synchronized (mPackages) { 2833 final int N = mPermissionGroups.size(); 2834 ArrayList<PermissionGroupInfo> out 2835 = new ArrayList<PermissionGroupInfo>(N); 2836 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2837 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2838 } 2839 return out; 2840 } 2841 } 2842 2843 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2844 int userId) { 2845 if (!sUserManager.exists(userId)) return null; 2846 PackageSetting ps = mSettings.mPackages.get(packageName); 2847 if (ps != null) { 2848 if (ps.pkg == null) { 2849 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2850 flags, userId); 2851 if (pInfo != null) { 2852 return pInfo.applicationInfo; 2853 } 2854 return null; 2855 } 2856 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2857 ps.readUserState(userId), userId); 2858 } 2859 return null; 2860 } 2861 2862 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2863 int userId) { 2864 if (!sUserManager.exists(userId)) return null; 2865 PackageSetting ps = mSettings.mPackages.get(packageName); 2866 if (ps != null) { 2867 PackageParser.Package pkg = ps.pkg; 2868 if (pkg == null) { 2869 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2870 return null; 2871 } 2872 // Only data remains, so we aren't worried about code paths 2873 pkg = new PackageParser.Package(packageName); 2874 pkg.applicationInfo.packageName = packageName; 2875 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2876 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2877 pkg.applicationInfo.dataDir = Environment 2878 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2879 .getAbsolutePath(); 2880 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2881 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2882 } 2883 return generatePackageInfo(pkg, flags, userId); 2884 } 2885 return null; 2886 } 2887 2888 @Override 2889 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2892 // writer 2893 synchronized (mPackages) { 2894 PackageParser.Package p = mPackages.get(packageName); 2895 if (DEBUG_PACKAGE_INFO) Log.v( 2896 TAG, "getApplicationInfo " + packageName 2897 + ": " + p); 2898 if (p != null) { 2899 PackageSetting ps = mSettings.mPackages.get(packageName); 2900 if (ps == null) return null; 2901 // Note: isEnabledLP() does not apply here - always return info 2902 return PackageParser.generateApplicationInfo( 2903 p, flags, ps.readUserState(userId), userId); 2904 } 2905 if ("android".equals(packageName)||"system".equals(packageName)) { 2906 return mAndroidApplication; 2907 } 2908 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2909 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2910 } 2911 } 2912 return null; 2913 } 2914 2915 @Override 2916 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2917 final IPackageDataObserver observer) { 2918 mContext.enforceCallingOrSelfPermission( 2919 android.Manifest.permission.CLEAR_APP_CACHE, null); 2920 // Queue up an async operation since clearing cache may take a little while. 2921 mHandler.post(new Runnable() { 2922 public void run() { 2923 mHandler.removeCallbacks(this); 2924 int retCode = -1; 2925 synchronized (mInstallLock) { 2926 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2927 if (retCode < 0) { 2928 Slog.w(TAG, "Couldn't clear application caches"); 2929 } 2930 } 2931 if (observer != null) { 2932 try { 2933 observer.onRemoveCompleted(null, (retCode >= 0)); 2934 } catch (RemoteException e) { 2935 Slog.w(TAG, "RemoveException when invoking call back"); 2936 } 2937 } 2938 } 2939 }); 2940 } 2941 2942 @Override 2943 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2944 final IntentSender pi) { 2945 mContext.enforceCallingOrSelfPermission( 2946 android.Manifest.permission.CLEAR_APP_CACHE, null); 2947 // Queue up an async operation since clearing cache may take a little while. 2948 mHandler.post(new Runnable() { 2949 public void run() { 2950 mHandler.removeCallbacks(this); 2951 int retCode = -1; 2952 synchronized (mInstallLock) { 2953 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2954 if (retCode < 0) { 2955 Slog.w(TAG, "Couldn't clear application caches"); 2956 } 2957 } 2958 if(pi != null) { 2959 try { 2960 // Callback via pending intent 2961 int code = (retCode >= 0) ? 1 : 0; 2962 pi.sendIntent(null, code, null, 2963 null, null); 2964 } catch (SendIntentException e1) { 2965 Slog.i(TAG, "Failed to send pending intent"); 2966 } 2967 } 2968 } 2969 }); 2970 } 2971 2972 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2973 synchronized (mInstallLock) { 2974 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2975 throw new IOException("Failed to free enough space"); 2976 } 2977 } 2978 } 2979 2980 @Override 2981 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2982 if (!sUserManager.exists(userId)) return null; 2983 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2984 synchronized (mPackages) { 2985 PackageParser.Activity a = mActivities.mActivities.get(component); 2986 2987 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2988 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2989 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2990 if (ps == null) return null; 2991 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2992 userId); 2993 } 2994 if (mResolveComponentName.equals(component)) { 2995 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2996 new PackageUserState(), userId); 2997 } 2998 } 2999 return null; 3000 } 3001 3002 @Override 3003 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3004 String resolvedType) { 3005 synchronized (mPackages) { 3006 if (component.equals(mResolveComponentName)) { 3007 // The resolver supports EVERYTHING! 3008 return true; 3009 } 3010 PackageParser.Activity a = mActivities.mActivities.get(component); 3011 if (a == null) { 3012 return false; 3013 } 3014 for (int i=0; i<a.intents.size(); i++) { 3015 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3016 intent.getData(), intent.getCategories(), TAG) >= 0) { 3017 return true; 3018 } 3019 } 3020 return false; 3021 } 3022 } 3023 3024 @Override 3025 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3026 if (!sUserManager.exists(userId)) return null; 3027 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3028 synchronized (mPackages) { 3029 PackageParser.Activity a = mReceivers.mActivities.get(component); 3030 if (DEBUG_PACKAGE_INFO) Log.v( 3031 TAG, "getReceiverInfo " + component + ": " + a); 3032 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3033 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3034 if (ps == null) return null; 3035 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3036 userId); 3037 } 3038 } 3039 return null; 3040 } 3041 3042 @Override 3043 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3044 if (!sUserManager.exists(userId)) return null; 3045 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3046 synchronized (mPackages) { 3047 PackageParser.Service s = mServices.mServices.get(component); 3048 if (DEBUG_PACKAGE_INFO) Log.v( 3049 TAG, "getServiceInfo " + component + ": " + s); 3050 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3051 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3052 if (ps == null) return null; 3053 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3054 userId); 3055 } 3056 } 3057 return null; 3058 } 3059 3060 @Override 3061 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3062 if (!sUserManager.exists(userId)) return null; 3063 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3064 synchronized (mPackages) { 3065 PackageParser.Provider p = mProviders.mProviders.get(component); 3066 if (DEBUG_PACKAGE_INFO) Log.v( 3067 TAG, "getProviderInfo " + component + ": " + p); 3068 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3069 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3070 if (ps == null) return null; 3071 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3072 userId); 3073 } 3074 } 3075 return null; 3076 } 3077 3078 @Override 3079 public String[] getSystemSharedLibraryNames() { 3080 Set<String> libSet; 3081 synchronized (mPackages) { 3082 libSet = mSharedLibraries.keySet(); 3083 int size = libSet.size(); 3084 if (size > 0) { 3085 String[] libs = new String[size]; 3086 libSet.toArray(libs); 3087 return libs; 3088 } 3089 } 3090 return null; 3091 } 3092 3093 /** 3094 * @hide 3095 */ 3096 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3097 synchronized (mPackages) { 3098 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3099 if (lib != null && lib.apk != null) { 3100 return mPackages.get(lib.apk); 3101 } 3102 } 3103 return null; 3104 } 3105 3106 @Override 3107 public FeatureInfo[] getSystemAvailableFeatures() { 3108 Collection<FeatureInfo> featSet; 3109 synchronized (mPackages) { 3110 featSet = mAvailableFeatures.values(); 3111 int size = featSet.size(); 3112 if (size > 0) { 3113 FeatureInfo[] features = new FeatureInfo[size+1]; 3114 featSet.toArray(features); 3115 FeatureInfo fi = new FeatureInfo(); 3116 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3117 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3118 features[size] = fi; 3119 return features; 3120 } 3121 } 3122 return null; 3123 } 3124 3125 @Override 3126 public boolean hasSystemFeature(String name) { 3127 synchronized (mPackages) { 3128 return mAvailableFeatures.containsKey(name); 3129 } 3130 } 3131 3132 private void checkValidCaller(int uid, int userId) { 3133 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3134 return; 3135 3136 throw new SecurityException("Caller uid=" + uid 3137 + " is not privileged to communicate with user=" + userId); 3138 } 3139 3140 @Override 3141 public int checkPermission(String permName, String pkgName, int userId) { 3142 if (!sUserManager.exists(userId)) { 3143 return PackageManager.PERMISSION_DENIED; 3144 } 3145 3146 synchronized (mPackages) { 3147 final PackageParser.Package p = mPackages.get(pkgName); 3148 if (p != null && p.mExtras != null) { 3149 final PackageSetting ps = (PackageSetting) p.mExtras; 3150 final PermissionsState permissionsState = ps.getPermissionsState(); 3151 if (permissionsState.hasPermission(permName, userId)) { 3152 return PackageManager.PERMISSION_GRANTED; 3153 } 3154 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3155 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3156 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3157 return PackageManager.PERMISSION_GRANTED; 3158 } 3159 } 3160 } 3161 3162 return PackageManager.PERMISSION_DENIED; 3163 } 3164 3165 @Override 3166 public int checkUidPermission(String permName, int uid) { 3167 final int userId = UserHandle.getUserId(uid); 3168 3169 if (!sUserManager.exists(userId)) { 3170 return PackageManager.PERMISSION_DENIED; 3171 } 3172 3173 synchronized (mPackages) { 3174 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3175 if (obj != null) { 3176 final SettingBase ps = (SettingBase) obj; 3177 final PermissionsState permissionsState = ps.getPermissionsState(); 3178 if (permissionsState.hasPermission(permName, userId)) { 3179 return PackageManager.PERMISSION_GRANTED; 3180 } 3181 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3182 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3183 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3184 return PackageManager.PERMISSION_GRANTED; 3185 } 3186 } else { 3187 ArraySet<String> perms = mSystemPermissions.get(uid); 3188 if (perms != null) { 3189 if (perms.contains(permName)) { 3190 return PackageManager.PERMISSION_GRANTED; 3191 } 3192 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3193 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3194 return PackageManager.PERMISSION_GRANTED; 3195 } 3196 } 3197 } 3198 } 3199 3200 return PackageManager.PERMISSION_DENIED; 3201 } 3202 3203 @Override 3204 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3205 if (UserHandle.getCallingUserId() != userId) { 3206 mContext.enforceCallingPermission( 3207 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3208 "isPermissionRevokedByPolicy for user " + userId); 3209 } 3210 3211 if (checkPermission(permission, packageName, userId) 3212 == PackageManager.PERMISSION_GRANTED) { 3213 return false; 3214 } 3215 3216 final long identity = Binder.clearCallingIdentity(); 3217 try { 3218 final int flags = getPermissionFlags(permission, packageName, userId); 3219 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3220 } finally { 3221 Binder.restoreCallingIdentity(identity); 3222 } 3223 } 3224 3225 @Override 3226 public String getPermissionControllerPackageName() { 3227 synchronized (mPackages) { 3228 return mRequiredInstallerPackage; 3229 } 3230 } 3231 3232 /** 3233 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3234 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3235 * @param checkShell TODO(yamasani): 3236 * @param message the message to log on security exception 3237 */ 3238 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3239 boolean checkShell, String message) { 3240 if (userId < 0) { 3241 throw new IllegalArgumentException("Invalid userId " + userId); 3242 } 3243 if (checkShell) { 3244 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3245 } 3246 if (userId == UserHandle.getUserId(callingUid)) return; 3247 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3248 if (requireFullPermission) { 3249 mContext.enforceCallingOrSelfPermission( 3250 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3251 } else { 3252 try { 3253 mContext.enforceCallingOrSelfPermission( 3254 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3255 } catch (SecurityException se) { 3256 mContext.enforceCallingOrSelfPermission( 3257 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3258 } 3259 } 3260 } 3261 } 3262 3263 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3264 if (callingUid == Process.SHELL_UID) { 3265 if (userHandle >= 0 3266 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3267 throw new SecurityException("Shell does not have permission to access user " 3268 + userHandle); 3269 } else if (userHandle < 0) { 3270 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3271 + Debug.getCallers(3)); 3272 } 3273 } 3274 } 3275 3276 private BasePermission findPermissionTreeLP(String permName) { 3277 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3278 if (permName.startsWith(bp.name) && 3279 permName.length() > bp.name.length() && 3280 permName.charAt(bp.name.length()) == '.') { 3281 return bp; 3282 } 3283 } 3284 return null; 3285 } 3286 3287 private BasePermission checkPermissionTreeLP(String permName) { 3288 if (permName != null) { 3289 BasePermission bp = findPermissionTreeLP(permName); 3290 if (bp != null) { 3291 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3292 return bp; 3293 } 3294 throw new SecurityException("Calling uid " 3295 + Binder.getCallingUid() 3296 + " is not allowed to add to permission tree " 3297 + bp.name + " owned by uid " + bp.uid); 3298 } 3299 } 3300 throw new SecurityException("No permission tree found for " + permName); 3301 } 3302 3303 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3304 if (s1 == null) { 3305 return s2 == null; 3306 } 3307 if (s2 == null) { 3308 return false; 3309 } 3310 if (s1.getClass() != s2.getClass()) { 3311 return false; 3312 } 3313 return s1.equals(s2); 3314 } 3315 3316 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3317 if (pi1.icon != pi2.icon) return false; 3318 if (pi1.logo != pi2.logo) return false; 3319 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3320 if (!compareStrings(pi1.name, pi2.name)) return false; 3321 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3322 // We'll take care of setting this one. 3323 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3324 // These are not currently stored in settings. 3325 //if (!compareStrings(pi1.group, pi2.group)) return false; 3326 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3327 //if (pi1.labelRes != pi2.labelRes) return false; 3328 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3329 return true; 3330 } 3331 3332 int permissionInfoFootprint(PermissionInfo info) { 3333 int size = info.name.length(); 3334 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3335 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3336 return size; 3337 } 3338 3339 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3340 int size = 0; 3341 for (BasePermission perm : mSettings.mPermissions.values()) { 3342 if (perm.uid == tree.uid) { 3343 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3344 } 3345 } 3346 return size; 3347 } 3348 3349 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3350 // We calculate the max size of permissions defined by this uid and throw 3351 // if that plus the size of 'info' would exceed our stated maximum. 3352 if (tree.uid != Process.SYSTEM_UID) { 3353 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3354 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3355 throw new SecurityException("Permission tree size cap exceeded"); 3356 } 3357 } 3358 } 3359 3360 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3361 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3362 throw new SecurityException("Label must be specified in permission"); 3363 } 3364 BasePermission tree = checkPermissionTreeLP(info.name); 3365 BasePermission bp = mSettings.mPermissions.get(info.name); 3366 boolean added = bp == null; 3367 boolean changed = true; 3368 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3369 if (added) { 3370 enforcePermissionCapLocked(info, tree); 3371 bp = new BasePermission(info.name, tree.sourcePackage, 3372 BasePermission.TYPE_DYNAMIC); 3373 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3374 throw new SecurityException( 3375 "Not allowed to modify non-dynamic permission " 3376 + info.name); 3377 } else { 3378 if (bp.protectionLevel == fixedLevel 3379 && bp.perm.owner.equals(tree.perm.owner) 3380 && bp.uid == tree.uid 3381 && comparePermissionInfos(bp.perm.info, info)) { 3382 changed = false; 3383 } 3384 } 3385 bp.protectionLevel = fixedLevel; 3386 info = new PermissionInfo(info); 3387 info.protectionLevel = fixedLevel; 3388 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3389 bp.perm.info.packageName = tree.perm.info.packageName; 3390 bp.uid = tree.uid; 3391 if (added) { 3392 mSettings.mPermissions.put(info.name, bp); 3393 } 3394 if (changed) { 3395 if (!async) { 3396 mSettings.writeLPr(); 3397 } else { 3398 scheduleWriteSettingsLocked(); 3399 } 3400 } 3401 return added; 3402 } 3403 3404 @Override 3405 public boolean addPermission(PermissionInfo info) { 3406 synchronized (mPackages) { 3407 return addPermissionLocked(info, false); 3408 } 3409 } 3410 3411 @Override 3412 public boolean addPermissionAsync(PermissionInfo info) { 3413 synchronized (mPackages) { 3414 return addPermissionLocked(info, true); 3415 } 3416 } 3417 3418 @Override 3419 public void removePermission(String name) { 3420 synchronized (mPackages) { 3421 checkPermissionTreeLP(name); 3422 BasePermission bp = mSettings.mPermissions.get(name); 3423 if (bp != null) { 3424 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3425 throw new SecurityException( 3426 "Not allowed to modify non-dynamic permission " 3427 + name); 3428 } 3429 mSettings.mPermissions.remove(name); 3430 mSettings.writeLPr(); 3431 } 3432 } 3433 } 3434 3435 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3436 BasePermission bp) { 3437 int index = pkg.requestedPermissions.indexOf(bp.name); 3438 if (index == -1) { 3439 throw new SecurityException("Package " + pkg.packageName 3440 + " has not requested permission " + bp.name); 3441 } 3442 if (!bp.isRuntime() && !bp.isDevelopment()) { 3443 throw new SecurityException("Permission " + bp.name 3444 + " is not a changeable permission type"); 3445 } 3446 } 3447 3448 @Override 3449 public void grantRuntimePermission(String packageName, String name, final int userId) { 3450 if (!sUserManager.exists(userId)) { 3451 Log.e(TAG, "No such user:" + userId); 3452 return; 3453 } 3454 3455 mContext.enforceCallingOrSelfPermission( 3456 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3457 "grantRuntimePermission"); 3458 3459 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3460 "grantRuntimePermission"); 3461 3462 final int uid; 3463 final SettingBase sb; 3464 3465 synchronized (mPackages) { 3466 final PackageParser.Package pkg = mPackages.get(packageName); 3467 if (pkg == null) { 3468 throw new IllegalArgumentException("Unknown package: " + packageName); 3469 } 3470 3471 final BasePermission bp = mSettings.mPermissions.get(name); 3472 if (bp == null) { 3473 throw new IllegalArgumentException("Unknown permission: " + name); 3474 } 3475 3476 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3477 3478 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3479 sb = (SettingBase) pkg.mExtras; 3480 if (sb == null) { 3481 throw new IllegalArgumentException("Unknown package: " + packageName); 3482 } 3483 3484 final PermissionsState permissionsState = sb.getPermissionsState(); 3485 3486 final int flags = permissionsState.getPermissionFlags(name, userId); 3487 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3488 throw new SecurityException("Cannot grant system fixed permission: " 3489 + name + " for package: " + packageName); 3490 } 3491 3492 if (bp.isDevelopment()) { 3493 // Development permissions must be handled specially, since they are not 3494 // normal runtime permissions. For now they apply to all users. 3495 if (permissionsState.grantInstallPermission(bp) != 3496 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3497 scheduleWriteSettingsLocked(); 3498 } 3499 return; 3500 } 3501 3502 final int result = permissionsState.grantRuntimePermission(bp, userId); 3503 switch (result) { 3504 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3505 return; 3506 } 3507 3508 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3509 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3510 mHandler.post(new Runnable() { 3511 @Override 3512 public void run() { 3513 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3514 } 3515 }); 3516 } 3517 break; 3518 } 3519 3520 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3521 3522 // Not critical if that is lost - app has to request again. 3523 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3524 } 3525 3526 // Only need to do this if user is initialized. Otherwise it's a new user 3527 // and there are no processes running as the user yet and there's no need 3528 // to make an expensive call to remount processes for the changed permissions. 3529 if (READ_EXTERNAL_STORAGE.equals(name) 3530 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3531 final long token = Binder.clearCallingIdentity(); 3532 try { 3533 if (sUserManager.isInitialized(userId)) { 3534 MountServiceInternal mountServiceInternal = LocalServices.getService( 3535 MountServiceInternal.class); 3536 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3537 } 3538 } finally { 3539 Binder.restoreCallingIdentity(token); 3540 } 3541 } 3542 } 3543 3544 @Override 3545 public void revokeRuntimePermission(String packageName, String name, int userId) { 3546 if (!sUserManager.exists(userId)) { 3547 Log.e(TAG, "No such user:" + userId); 3548 return; 3549 } 3550 3551 mContext.enforceCallingOrSelfPermission( 3552 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3553 "revokeRuntimePermission"); 3554 3555 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3556 "revokeRuntimePermission"); 3557 3558 final int appId; 3559 3560 synchronized (mPackages) { 3561 final PackageParser.Package pkg = mPackages.get(packageName); 3562 if (pkg == null) { 3563 throw new IllegalArgumentException("Unknown package: " + packageName); 3564 } 3565 3566 final BasePermission bp = mSettings.mPermissions.get(name); 3567 if (bp == null) { 3568 throw new IllegalArgumentException("Unknown permission: " + name); 3569 } 3570 3571 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3572 3573 SettingBase sb = (SettingBase) pkg.mExtras; 3574 if (sb == null) { 3575 throw new IllegalArgumentException("Unknown package: " + packageName); 3576 } 3577 3578 final PermissionsState permissionsState = sb.getPermissionsState(); 3579 3580 final int flags = permissionsState.getPermissionFlags(name, userId); 3581 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3582 throw new SecurityException("Cannot revoke system fixed permission: " 3583 + name + " for package: " + packageName); 3584 } 3585 3586 if (bp.isDevelopment()) { 3587 // Development permissions must be handled specially, since they are not 3588 // normal runtime permissions. For now they apply to all users. 3589 if (permissionsState.revokeInstallPermission(bp) != 3590 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3591 scheduleWriteSettingsLocked(); 3592 } 3593 return; 3594 } 3595 3596 if (permissionsState.revokeRuntimePermission(bp, userId) == 3597 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3598 return; 3599 } 3600 3601 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3602 3603 // Critical, after this call app should never have the permission. 3604 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3605 3606 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3607 } 3608 3609 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3610 } 3611 3612 @Override 3613 public void resetRuntimePermissions() { 3614 mContext.enforceCallingOrSelfPermission( 3615 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3616 "revokeRuntimePermission"); 3617 3618 int callingUid = Binder.getCallingUid(); 3619 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3620 mContext.enforceCallingOrSelfPermission( 3621 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3622 "resetRuntimePermissions"); 3623 } 3624 3625 synchronized (mPackages) { 3626 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3627 for (int userId : UserManagerService.getInstance().getUserIds()) { 3628 final int packageCount = mPackages.size(); 3629 for (int i = 0; i < packageCount; i++) { 3630 PackageParser.Package pkg = mPackages.valueAt(i); 3631 if (!(pkg.mExtras instanceof PackageSetting)) { 3632 continue; 3633 } 3634 PackageSetting ps = (PackageSetting) pkg.mExtras; 3635 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3636 } 3637 } 3638 } 3639 } 3640 3641 @Override 3642 public int getPermissionFlags(String name, String packageName, int userId) { 3643 if (!sUserManager.exists(userId)) { 3644 return 0; 3645 } 3646 3647 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3648 3649 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3650 "getPermissionFlags"); 3651 3652 synchronized (mPackages) { 3653 final PackageParser.Package pkg = mPackages.get(packageName); 3654 if (pkg == null) { 3655 throw new IllegalArgumentException("Unknown package: " + packageName); 3656 } 3657 3658 final BasePermission bp = mSettings.mPermissions.get(name); 3659 if (bp == null) { 3660 throw new IllegalArgumentException("Unknown permission: " + name); 3661 } 3662 3663 SettingBase sb = (SettingBase) pkg.mExtras; 3664 if (sb == null) { 3665 throw new IllegalArgumentException("Unknown package: " + packageName); 3666 } 3667 3668 PermissionsState permissionsState = sb.getPermissionsState(); 3669 return permissionsState.getPermissionFlags(name, userId); 3670 } 3671 } 3672 3673 @Override 3674 public void updatePermissionFlags(String name, String packageName, int flagMask, 3675 int flagValues, int userId) { 3676 if (!sUserManager.exists(userId)) { 3677 return; 3678 } 3679 3680 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3681 3682 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3683 "updatePermissionFlags"); 3684 3685 // Only the system can change these flags and nothing else. 3686 if (getCallingUid() != Process.SYSTEM_UID) { 3687 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3688 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3689 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3690 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3691 } 3692 3693 synchronized (mPackages) { 3694 final PackageParser.Package pkg = mPackages.get(packageName); 3695 if (pkg == null) { 3696 throw new IllegalArgumentException("Unknown package: " + packageName); 3697 } 3698 3699 final BasePermission bp = mSettings.mPermissions.get(name); 3700 if (bp == null) { 3701 throw new IllegalArgumentException("Unknown permission: " + name); 3702 } 3703 3704 SettingBase sb = (SettingBase) pkg.mExtras; 3705 if (sb == null) { 3706 throw new IllegalArgumentException("Unknown package: " + packageName); 3707 } 3708 3709 PermissionsState permissionsState = sb.getPermissionsState(); 3710 3711 // Only the package manager can change flags for system component permissions. 3712 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3713 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3714 return; 3715 } 3716 3717 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3718 3719 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3720 // Install and runtime permissions are stored in different places, 3721 // so figure out what permission changed and persist the change. 3722 if (permissionsState.getInstallPermissionState(name) != null) { 3723 scheduleWriteSettingsLocked(); 3724 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3725 || hadState) { 3726 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3727 } 3728 } 3729 } 3730 } 3731 3732 /** 3733 * Update the permission flags for all packages and runtime permissions of a user in order 3734 * to allow device or profile owner to remove POLICY_FIXED. 3735 */ 3736 @Override 3737 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3738 if (!sUserManager.exists(userId)) { 3739 return; 3740 } 3741 3742 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3743 3744 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3745 "updatePermissionFlagsForAllApps"); 3746 3747 // Only the system can change system fixed flags. 3748 if (getCallingUid() != Process.SYSTEM_UID) { 3749 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3750 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3751 } 3752 3753 synchronized (mPackages) { 3754 boolean changed = false; 3755 final int packageCount = mPackages.size(); 3756 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3757 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3758 SettingBase sb = (SettingBase) pkg.mExtras; 3759 if (sb == null) { 3760 continue; 3761 } 3762 PermissionsState permissionsState = sb.getPermissionsState(); 3763 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3764 userId, flagMask, flagValues); 3765 } 3766 if (changed) { 3767 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3768 } 3769 } 3770 } 3771 3772 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3773 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3774 != PackageManager.PERMISSION_GRANTED 3775 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3776 != PackageManager.PERMISSION_GRANTED) { 3777 throw new SecurityException(message + " requires " 3778 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3779 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3780 } 3781 } 3782 3783 @Override 3784 public boolean shouldShowRequestPermissionRationale(String permissionName, 3785 String packageName, int userId) { 3786 if (UserHandle.getCallingUserId() != userId) { 3787 mContext.enforceCallingPermission( 3788 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3789 "canShowRequestPermissionRationale for user " + userId); 3790 } 3791 3792 final int uid = getPackageUid(packageName, userId); 3793 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3794 return false; 3795 } 3796 3797 if (checkPermission(permissionName, packageName, userId) 3798 == PackageManager.PERMISSION_GRANTED) { 3799 return false; 3800 } 3801 3802 final int flags; 3803 3804 final long identity = Binder.clearCallingIdentity(); 3805 try { 3806 flags = getPermissionFlags(permissionName, 3807 packageName, userId); 3808 } finally { 3809 Binder.restoreCallingIdentity(identity); 3810 } 3811 3812 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3813 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3814 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3815 3816 if ((flags & fixedFlags) != 0) { 3817 return false; 3818 } 3819 3820 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3821 } 3822 3823 @Override 3824 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3825 mContext.enforceCallingOrSelfPermission( 3826 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3827 "addOnPermissionsChangeListener"); 3828 3829 synchronized (mPackages) { 3830 mOnPermissionChangeListeners.addListenerLocked(listener); 3831 } 3832 } 3833 3834 @Override 3835 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3836 synchronized (mPackages) { 3837 mOnPermissionChangeListeners.removeListenerLocked(listener); 3838 } 3839 } 3840 3841 @Override 3842 public boolean isProtectedBroadcast(String actionName) { 3843 synchronized (mPackages) { 3844 return mProtectedBroadcasts.contains(actionName); 3845 } 3846 } 3847 3848 @Override 3849 public int checkSignatures(String pkg1, String pkg2) { 3850 synchronized (mPackages) { 3851 final PackageParser.Package p1 = mPackages.get(pkg1); 3852 final PackageParser.Package p2 = mPackages.get(pkg2); 3853 if (p1 == null || p1.mExtras == null 3854 || p2 == null || p2.mExtras == null) { 3855 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3856 } 3857 return compareSignatures(p1.mSignatures, p2.mSignatures); 3858 } 3859 } 3860 3861 @Override 3862 public int checkUidSignatures(int uid1, int uid2) { 3863 // Map to base uids. 3864 uid1 = UserHandle.getAppId(uid1); 3865 uid2 = UserHandle.getAppId(uid2); 3866 // reader 3867 synchronized (mPackages) { 3868 Signature[] s1; 3869 Signature[] s2; 3870 Object obj = mSettings.getUserIdLPr(uid1); 3871 if (obj != null) { 3872 if (obj instanceof SharedUserSetting) { 3873 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3874 } else if (obj instanceof PackageSetting) { 3875 s1 = ((PackageSetting)obj).signatures.mSignatures; 3876 } else { 3877 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3878 } 3879 } else { 3880 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3881 } 3882 obj = mSettings.getUserIdLPr(uid2); 3883 if (obj != null) { 3884 if (obj instanceof SharedUserSetting) { 3885 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3886 } else if (obj instanceof PackageSetting) { 3887 s2 = ((PackageSetting)obj).signatures.mSignatures; 3888 } else { 3889 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3890 } 3891 } else { 3892 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3893 } 3894 return compareSignatures(s1, s2); 3895 } 3896 } 3897 3898 private void killUid(int appId, int userId, String reason) { 3899 final long identity = Binder.clearCallingIdentity(); 3900 try { 3901 IActivityManager am = ActivityManagerNative.getDefault(); 3902 if (am != null) { 3903 try { 3904 am.killUid(appId, userId, reason); 3905 } catch (RemoteException e) { 3906 /* ignore - same process */ 3907 } 3908 } 3909 } finally { 3910 Binder.restoreCallingIdentity(identity); 3911 } 3912 } 3913 3914 /** 3915 * Compares two sets of signatures. Returns: 3916 * <br /> 3917 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3918 * <br /> 3919 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3920 * <br /> 3921 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3922 * <br /> 3923 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3924 * <br /> 3925 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3926 */ 3927 static int compareSignatures(Signature[] s1, Signature[] s2) { 3928 if (s1 == null) { 3929 return s2 == null 3930 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3931 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3932 } 3933 3934 if (s2 == null) { 3935 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3936 } 3937 3938 if (s1.length != s2.length) { 3939 return PackageManager.SIGNATURE_NO_MATCH; 3940 } 3941 3942 // Since both signature sets are of size 1, we can compare without HashSets. 3943 if (s1.length == 1) { 3944 return s1[0].equals(s2[0]) ? 3945 PackageManager.SIGNATURE_MATCH : 3946 PackageManager.SIGNATURE_NO_MATCH; 3947 } 3948 3949 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3950 for (Signature sig : s1) { 3951 set1.add(sig); 3952 } 3953 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3954 for (Signature sig : s2) { 3955 set2.add(sig); 3956 } 3957 // Make sure s2 contains all signatures in s1. 3958 if (set1.equals(set2)) { 3959 return PackageManager.SIGNATURE_MATCH; 3960 } 3961 return PackageManager.SIGNATURE_NO_MATCH; 3962 } 3963 3964 /** 3965 * If the database version for this type of package (internal storage or 3966 * external storage) is less than the version where package signatures 3967 * were updated, return true. 3968 */ 3969 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3970 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3971 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3972 } 3973 3974 /** 3975 * Used for backward compatibility to make sure any packages with 3976 * certificate chains get upgraded to the new style. {@code existingSigs} 3977 * will be in the old format (since they were stored on disk from before the 3978 * system upgrade) and {@code scannedSigs} will be in the newer format. 3979 */ 3980 private int compareSignaturesCompat(PackageSignatures existingSigs, 3981 PackageParser.Package scannedPkg) { 3982 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3983 return PackageManager.SIGNATURE_NO_MATCH; 3984 } 3985 3986 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3987 for (Signature sig : existingSigs.mSignatures) { 3988 existingSet.add(sig); 3989 } 3990 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3991 for (Signature sig : scannedPkg.mSignatures) { 3992 try { 3993 Signature[] chainSignatures = sig.getChainSignatures(); 3994 for (Signature chainSig : chainSignatures) { 3995 scannedCompatSet.add(chainSig); 3996 } 3997 } catch (CertificateEncodingException e) { 3998 scannedCompatSet.add(sig); 3999 } 4000 } 4001 /* 4002 * Make sure the expanded scanned set contains all signatures in the 4003 * existing one. 4004 */ 4005 if (scannedCompatSet.equals(existingSet)) { 4006 // Migrate the old signatures to the new scheme. 4007 existingSigs.assignSignatures(scannedPkg.mSignatures); 4008 // The new KeySets will be re-added later in the scanning process. 4009 synchronized (mPackages) { 4010 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4011 } 4012 return PackageManager.SIGNATURE_MATCH; 4013 } 4014 return PackageManager.SIGNATURE_NO_MATCH; 4015 } 4016 4017 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4018 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4019 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4020 } 4021 4022 private int compareSignaturesRecover(PackageSignatures existingSigs, 4023 PackageParser.Package scannedPkg) { 4024 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4025 return PackageManager.SIGNATURE_NO_MATCH; 4026 } 4027 4028 String msg = null; 4029 try { 4030 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4031 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4032 + scannedPkg.packageName); 4033 return PackageManager.SIGNATURE_MATCH; 4034 } 4035 } catch (CertificateException e) { 4036 msg = e.getMessage(); 4037 } 4038 4039 logCriticalInfo(Log.INFO, 4040 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4041 return PackageManager.SIGNATURE_NO_MATCH; 4042 } 4043 4044 @Override 4045 public String[] getPackagesForUid(int uid) { 4046 uid = UserHandle.getAppId(uid); 4047 // reader 4048 synchronized (mPackages) { 4049 Object obj = mSettings.getUserIdLPr(uid); 4050 if (obj instanceof SharedUserSetting) { 4051 final SharedUserSetting sus = (SharedUserSetting) obj; 4052 final int N = sus.packages.size(); 4053 final String[] res = new String[N]; 4054 final Iterator<PackageSetting> it = sus.packages.iterator(); 4055 int i = 0; 4056 while (it.hasNext()) { 4057 res[i++] = it.next().name; 4058 } 4059 return res; 4060 } else if (obj instanceof PackageSetting) { 4061 final PackageSetting ps = (PackageSetting) obj; 4062 return new String[] { ps.name }; 4063 } 4064 } 4065 return null; 4066 } 4067 4068 @Override 4069 public String getNameForUid(int uid) { 4070 // reader 4071 synchronized (mPackages) { 4072 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4073 if (obj instanceof SharedUserSetting) { 4074 final SharedUserSetting sus = (SharedUserSetting) obj; 4075 return sus.name + ":" + sus.userId; 4076 } else if (obj instanceof PackageSetting) { 4077 final PackageSetting ps = (PackageSetting) obj; 4078 return ps.name; 4079 } 4080 } 4081 return null; 4082 } 4083 4084 @Override 4085 public int getUidForSharedUser(String sharedUserName) { 4086 if(sharedUserName == null) { 4087 return -1; 4088 } 4089 // reader 4090 synchronized (mPackages) { 4091 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4092 if (suid == null) { 4093 return -1; 4094 } 4095 return suid.userId; 4096 } 4097 } 4098 4099 @Override 4100 public int getFlagsForUid(int uid) { 4101 synchronized (mPackages) { 4102 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4103 if (obj instanceof SharedUserSetting) { 4104 final SharedUserSetting sus = (SharedUserSetting) obj; 4105 return sus.pkgFlags; 4106 } else if (obj instanceof PackageSetting) { 4107 final PackageSetting ps = (PackageSetting) obj; 4108 return ps.pkgFlags; 4109 } 4110 } 4111 return 0; 4112 } 4113 4114 @Override 4115 public int getPrivateFlagsForUid(int uid) { 4116 synchronized (mPackages) { 4117 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4118 if (obj instanceof SharedUserSetting) { 4119 final SharedUserSetting sus = (SharedUserSetting) obj; 4120 return sus.pkgPrivateFlags; 4121 } else if (obj instanceof PackageSetting) { 4122 final PackageSetting ps = (PackageSetting) obj; 4123 return ps.pkgPrivateFlags; 4124 } 4125 } 4126 return 0; 4127 } 4128 4129 @Override 4130 public boolean isUidPrivileged(int uid) { 4131 uid = UserHandle.getAppId(uid); 4132 // reader 4133 synchronized (mPackages) { 4134 Object obj = mSettings.getUserIdLPr(uid); 4135 if (obj instanceof SharedUserSetting) { 4136 final SharedUserSetting sus = (SharedUserSetting) obj; 4137 final Iterator<PackageSetting> it = sus.packages.iterator(); 4138 while (it.hasNext()) { 4139 if (it.next().isPrivileged()) { 4140 return true; 4141 } 4142 } 4143 } else if (obj instanceof PackageSetting) { 4144 final PackageSetting ps = (PackageSetting) obj; 4145 return ps.isPrivileged(); 4146 } 4147 } 4148 return false; 4149 } 4150 4151 @Override 4152 public String[] getAppOpPermissionPackages(String permissionName) { 4153 synchronized (mPackages) { 4154 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4155 if (pkgs == null) { 4156 return null; 4157 } 4158 return pkgs.toArray(new String[pkgs.size()]); 4159 } 4160 } 4161 4162 @Override 4163 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4164 int flags, int userId) { 4165 if (!sUserManager.exists(userId)) return null; 4166 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4167 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4168 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4169 } 4170 4171 @Override 4172 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4173 IntentFilter filter, int match, ComponentName activity) { 4174 final int userId = UserHandle.getCallingUserId(); 4175 if (DEBUG_PREFERRED) { 4176 Log.v(TAG, "setLastChosenActivity intent=" + intent 4177 + " resolvedType=" + resolvedType 4178 + " flags=" + flags 4179 + " filter=" + filter 4180 + " match=" + match 4181 + " activity=" + activity); 4182 filter.dump(new PrintStreamPrinter(System.out), " "); 4183 } 4184 intent.setComponent(null); 4185 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4186 // Find any earlier preferred or last chosen entries and nuke them 4187 findPreferredActivity(intent, resolvedType, 4188 flags, query, 0, false, true, false, userId); 4189 // Add the new activity as the last chosen for this filter 4190 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4191 "Setting last chosen"); 4192 } 4193 4194 @Override 4195 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4196 final int userId = UserHandle.getCallingUserId(); 4197 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4198 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4199 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4200 false, false, false, userId); 4201 } 4202 4203 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4204 int flags, List<ResolveInfo> query, int userId) { 4205 if (query != null) { 4206 final int N = query.size(); 4207 if (N == 1) { 4208 return query.get(0); 4209 } else if (N > 1) { 4210 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4211 // If there is more than one activity with the same priority, 4212 // then let the user decide between them. 4213 ResolveInfo r0 = query.get(0); 4214 ResolveInfo r1 = query.get(1); 4215 if (DEBUG_INTENT_MATCHING || debug) { 4216 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4217 + r1.activityInfo.name + "=" + r1.priority); 4218 } 4219 // If the first activity has a higher priority, or a different 4220 // default, then it is always desireable to pick it. 4221 if (r0.priority != r1.priority 4222 || r0.preferredOrder != r1.preferredOrder 4223 || r0.isDefault != r1.isDefault) { 4224 return query.get(0); 4225 } 4226 // If we have saved a preference for a preferred activity for 4227 // this Intent, use that. 4228 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4229 flags, query, r0.priority, true, false, debug, userId); 4230 if (ri != null) { 4231 return ri; 4232 } 4233 ri = new ResolveInfo(mResolveInfo); 4234 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4235 ri.activityInfo.applicationInfo = new ApplicationInfo( 4236 ri.activityInfo.applicationInfo); 4237 if (userId != 0) { 4238 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4239 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4240 } 4241 // Make sure that the resolver is displayable in car mode 4242 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4243 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4244 return ri; 4245 } 4246 } 4247 return null; 4248 } 4249 4250 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4251 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4252 final int N = query.size(); 4253 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4254 .get(userId); 4255 // Get the list of persistent preferred activities that handle the intent 4256 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4257 List<PersistentPreferredActivity> pprefs = ppir != null 4258 ? ppir.queryIntent(intent, resolvedType, 4259 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4260 : null; 4261 if (pprefs != null && pprefs.size() > 0) { 4262 final int M = pprefs.size(); 4263 for (int i=0; i<M; i++) { 4264 final PersistentPreferredActivity ppa = pprefs.get(i); 4265 if (DEBUG_PREFERRED || debug) { 4266 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4267 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4268 + "\n component=" + ppa.mComponent); 4269 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4270 } 4271 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4272 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4273 if (DEBUG_PREFERRED || debug) { 4274 Slog.v(TAG, "Found persistent preferred activity:"); 4275 if (ai != null) { 4276 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4277 } else { 4278 Slog.v(TAG, " null"); 4279 } 4280 } 4281 if (ai == null) { 4282 // This previously registered persistent preferred activity 4283 // component is no longer known. Ignore it and do NOT remove it. 4284 continue; 4285 } 4286 for (int j=0; j<N; j++) { 4287 final ResolveInfo ri = query.get(j); 4288 if (!ri.activityInfo.applicationInfo.packageName 4289 .equals(ai.applicationInfo.packageName)) { 4290 continue; 4291 } 4292 if (!ri.activityInfo.name.equals(ai.name)) { 4293 continue; 4294 } 4295 // Found a persistent preference that can handle the intent. 4296 if (DEBUG_PREFERRED || debug) { 4297 Slog.v(TAG, "Returning persistent preferred activity: " + 4298 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4299 } 4300 return ri; 4301 } 4302 } 4303 } 4304 return null; 4305 } 4306 4307 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4308 List<ResolveInfo> query, int priority, boolean always, 4309 boolean removeMatches, boolean debug, int userId) { 4310 if (!sUserManager.exists(userId)) return null; 4311 // writer 4312 synchronized (mPackages) { 4313 if (intent.getSelector() != null) { 4314 intent = intent.getSelector(); 4315 } 4316 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4317 4318 // Try to find a matching persistent preferred activity. 4319 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4320 debug, userId); 4321 4322 // If a persistent preferred activity matched, use it. 4323 if (pri != null) { 4324 return pri; 4325 } 4326 4327 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4328 // Get the list of preferred activities that handle the intent 4329 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4330 List<PreferredActivity> prefs = pir != null 4331 ? pir.queryIntent(intent, resolvedType, 4332 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4333 : null; 4334 if (prefs != null && prefs.size() > 0) { 4335 boolean changed = false; 4336 try { 4337 // First figure out how good the original match set is. 4338 // We will only allow preferred activities that came 4339 // from the same match quality. 4340 int match = 0; 4341 4342 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4343 4344 final int N = query.size(); 4345 for (int j=0; j<N; j++) { 4346 final ResolveInfo ri = query.get(j); 4347 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4348 + ": 0x" + Integer.toHexString(match)); 4349 if (ri.match > match) { 4350 match = ri.match; 4351 } 4352 } 4353 4354 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4355 + Integer.toHexString(match)); 4356 4357 match &= IntentFilter.MATCH_CATEGORY_MASK; 4358 final int M = prefs.size(); 4359 for (int i=0; i<M; i++) { 4360 final PreferredActivity pa = prefs.get(i); 4361 if (DEBUG_PREFERRED || debug) { 4362 Slog.v(TAG, "Checking PreferredActivity ds=" 4363 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4364 + "\n component=" + pa.mPref.mComponent); 4365 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4366 } 4367 if (pa.mPref.mMatch != match) { 4368 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4369 + Integer.toHexString(pa.mPref.mMatch)); 4370 continue; 4371 } 4372 // If it's not an "always" type preferred activity and that's what we're 4373 // looking for, skip it. 4374 if (always && !pa.mPref.mAlways) { 4375 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4376 continue; 4377 } 4378 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4379 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4380 if (DEBUG_PREFERRED || debug) { 4381 Slog.v(TAG, "Found preferred activity:"); 4382 if (ai != null) { 4383 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4384 } else { 4385 Slog.v(TAG, " null"); 4386 } 4387 } 4388 if (ai == null) { 4389 // This previously registered preferred activity 4390 // component is no longer known. Most likely an update 4391 // to the app was installed and in the new version this 4392 // component no longer exists. Clean it up by removing 4393 // it from the preferred activities list, and skip it. 4394 Slog.w(TAG, "Removing dangling preferred activity: " 4395 + pa.mPref.mComponent); 4396 pir.removeFilter(pa); 4397 changed = true; 4398 continue; 4399 } 4400 for (int j=0; j<N; j++) { 4401 final ResolveInfo ri = query.get(j); 4402 if (!ri.activityInfo.applicationInfo.packageName 4403 .equals(ai.applicationInfo.packageName)) { 4404 continue; 4405 } 4406 if (!ri.activityInfo.name.equals(ai.name)) { 4407 continue; 4408 } 4409 4410 if (removeMatches) { 4411 pir.removeFilter(pa); 4412 changed = true; 4413 if (DEBUG_PREFERRED) { 4414 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4415 } 4416 break; 4417 } 4418 4419 // Okay we found a previously set preferred or last chosen app. 4420 // If the result set is different from when this 4421 // was created, we need to clear it and re-ask the 4422 // user their preference, if we're looking for an "always" type entry. 4423 if (always && !pa.mPref.sameSet(query)) { 4424 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4425 + intent + " type " + resolvedType); 4426 if (DEBUG_PREFERRED) { 4427 Slog.v(TAG, "Removing preferred activity since set changed " 4428 + pa.mPref.mComponent); 4429 } 4430 pir.removeFilter(pa); 4431 // Re-add the filter as a "last chosen" entry (!always) 4432 PreferredActivity lastChosen = new PreferredActivity( 4433 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4434 pir.addFilter(lastChosen); 4435 changed = true; 4436 return null; 4437 } 4438 4439 // Yay! Either the set matched or we're looking for the last chosen 4440 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4441 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4442 return ri; 4443 } 4444 } 4445 } finally { 4446 if (changed) { 4447 if (DEBUG_PREFERRED) { 4448 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4449 } 4450 scheduleWritePackageRestrictionsLocked(userId); 4451 } 4452 } 4453 } 4454 } 4455 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4456 return null; 4457 } 4458 4459 /* 4460 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4461 */ 4462 @Override 4463 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4464 int targetUserId) { 4465 mContext.enforceCallingOrSelfPermission( 4466 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4467 List<CrossProfileIntentFilter> matches = 4468 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4469 if (matches != null) { 4470 int size = matches.size(); 4471 for (int i = 0; i < size; i++) { 4472 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4473 } 4474 } 4475 if (hasWebURI(intent)) { 4476 // cross-profile app linking works only towards the parent. 4477 final UserInfo parent = getProfileParent(sourceUserId); 4478 synchronized(mPackages) { 4479 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4480 intent, resolvedType, 0, sourceUserId, parent.id); 4481 return xpDomainInfo != null; 4482 } 4483 } 4484 return false; 4485 } 4486 4487 private UserInfo getProfileParent(int userId) { 4488 final long identity = Binder.clearCallingIdentity(); 4489 try { 4490 return sUserManager.getProfileParent(userId); 4491 } finally { 4492 Binder.restoreCallingIdentity(identity); 4493 } 4494 } 4495 4496 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4497 String resolvedType, int userId) { 4498 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4499 if (resolver != null) { 4500 return resolver.queryIntent(intent, resolvedType, false, userId); 4501 } 4502 return null; 4503 } 4504 4505 @Override 4506 public List<ResolveInfo> queryIntentActivities(Intent intent, 4507 String resolvedType, int flags, int userId) { 4508 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4509 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4510 ComponentName comp = intent.getComponent(); 4511 if (comp == null) { 4512 if (intent.getSelector() != null) { 4513 intent = intent.getSelector(); 4514 comp = intent.getComponent(); 4515 } 4516 } 4517 4518 if (comp != null) { 4519 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4520 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4521 if (ai != null) { 4522 final ResolveInfo ri = new ResolveInfo(); 4523 ri.activityInfo = ai; 4524 list.add(ri); 4525 } 4526 return list; 4527 } 4528 4529 // reader 4530 synchronized (mPackages) { 4531 final String pkgName = intent.getPackage(); 4532 if (pkgName == null) { 4533 List<CrossProfileIntentFilter> matchingFilters = 4534 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4535 // Check for results that need to skip the current profile. 4536 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4537 resolvedType, flags, userId); 4538 if (xpResolveInfo != null) { 4539 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4540 result.add(xpResolveInfo); 4541 return filterIfNotSystemUser(result, userId); 4542 } 4543 4544 // Check for results in the current profile. 4545 List<ResolveInfo> result = mActivities.queryIntent( 4546 intent, resolvedType, flags, userId); 4547 4548 // Check for cross profile results. 4549 xpResolveInfo = queryCrossProfileIntents( 4550 matchingFilters, intent, resolvedType, flags, userId); 4551 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4552 result.add(xpResolveInfo); 4553 Collections.sort(result, mResolvePrioritySorter); 4554 } 4555 result = filterIfNotSystemUser(result, userId); 4556 if (hasWebURI(intent)) { 4557 CrossProfileDomainInfo xpDomainInfo = null; 4558 final UserInfo parent = getProfileParent(userId); 4559 if (parent != null) { 4560 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4561 flags, userId, parent.id); 4562 } 4563 if (xpDomainInfo != null) { 4564 if (xpResolveInfo != null) { 4565 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4566 // in the result. 4567 result.remove(xpResolveInfo); 4568 } 4569 if (result.size() == 0) { 4570 result.add(xpDomainInfo.resolveInfo); 4571 return result; 4572 } 4573 } else if (result.size() <= 1) { 4574 return result; 4575 } 4576 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4577 xpDomainInfo, userId); 4578 Collections.sort(result, mResolvePrioritySorter); 4579 } 4580 return result; 4581 } 4582 final PackageParser.Package pkg = mPackages.get(pkgName); 4583 if (pkg != null) { 4584 return filterIfNotSystemUser( 4585 mActivities.queryIntentForPackage( 4586 intent, resolvedType, flags, pkg.activities, userId), 4587 userId); 4588 } 4589 return new ArrayList<ResolveInfo>(); 4590 } 4591 } 4592 4593 private static class CrossProfileDomainInfo { 4594 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4595 ResolveInfo resolveInfo; 4596 /* Best domain verification status of the activities found in the other profile */ 4597 int bestDomainVerificationStatus; 4598 } 4599 4600 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4601 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4602 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4603 sourceUserId)) { 4604 return null; 4605 } 4606 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4607 resolvedType, flags, parentUserId); 4608 4609 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4610 return null; 4611 } 4612 CrossProfileDomainInfo result = null; 4613 int size = resultTargetUser.size(); 4614 for (int i = 0; i < size; i++) { 4615 ResolveInfo riTargetUser = resultTargetUser.get(i); 4616 // Intent filter verification is only for filters that specify a host. So don't return 4617 // those that handle all web uris. 4618 if (riTargetUser.handleAllWebDataURI) { 4619 continue; 4620 } 4621 String packageName = riTargetUser.activityInfo.packageName; 4622 PackageSetting ps = mSettings.mPackages.get(packageName); 4623 if (ps == null) { 4624 continue; 4625 } 4626 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4627 int status = (int)(verificationState >> 32); 4628 if (result == null) { 4629 result = new CrossProfileDomainInfo(); 4630 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4631 sourceUserId, parentUserId); 4632 result.bestDomainVerificationStatus = status; 4633 } else { 4634 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4635 result.bestDomainVerificationStatus); 4636 } 4637 } 4638 // Don't consider matches with status NEVER across profiles. 4639 if (result != null && result.bestDomainVerificationStatus 4640 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4641 return null; 4642 } 4643 return result; 4644 } 4645 4646 /** 4647 * Verification statuses are ordered from the worse to the best, except for 4648 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4649 */ 4650 private int bestDomainVerificationStatus(int status1, int status2) { 4651 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4652 return status2; 4653 } 4654 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4655 return status1; 4656 } 4657 return (int) MathUtils.max(status1, status2); 4658 } 4659 4660 private boolean isUserEnabled(int userId) { 4661 long callingId = Binder.clearCallingIdentity(); 4662 try { 4663 UserInfo userInfo = sUserManager.getUserInfo(userId); 4664 return userInfo != null && userInfo.isEnabled(); 4665 } finally { 4666 Binder.restoreCallingIdentity(callingId); 4667 } 4668 } 4669 4670 /** 4671 * Filter out activities with systemUserOnly flag set, when current user is not System. 4672 * 4673 * @return filtered list 4674 */ 4675 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4676 if (userId == UserHandle.USER_SYSTEM) { 4677 return resolveInfos; 4678 } 4679 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4680 ResolveInfo info = resolveInfos.get(i); 4681 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4682 resolveInfos.remove(i); 4683 } 4684 } 4685 return resolveInfos; 4686 } 4687 4688 private static boolean hasWebURI(Intent intent) { 4689 if (intent.getData() == null) { 4690 return false; 4691 } 4692 final String scheme = intent.getScheme(); 4693 if (TextUtils.isEmpty(scheme)) { 4694 return false; 4695 } 4696 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4697 } 4698 4699 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4700 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4701 int userId) { 4702 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4703 4704 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4705 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4706 candidates.size()); 4707 } 4708 4709 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4710 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4711 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4712 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4713 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4714 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4715 4716 synchronized (mPackages) { 4717 final int count = candidates.size(); 4718 // First, try to use linked apps. Partition the candidates into four lists: 4719 // one for the final results, one for the "do not use ever", one for "undefined status" 4720 // and finally one for "browser app type". 4721 for (int n=0; n<count; n++) { 4722 ResolveInfo info = candidates.get(n); 4723 String packageName = info.activityInfo.packageName; 4724 PackageSetting ps = mSettings.mPackages.get(packageName); 4725 if (ps != null) { 4726 // Add to the special match all list (Browser use case) 4727 if (info.handleAllWebDataURI) { 4728 matchAllList.add(info); 4729 continue; 4730 } 4731 // Try to get the status from User settings first 4732 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4733 int status = (int)(packedStatus >> 32); 4734 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4735 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4736 if (DEBUG_DOMAIN_VERIFICATION) { 4737 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4738 + " : linkgen=" + linkGeneration); 4739 } 4740 // Use link-enabled generation as preferredOrder, i.e. 4741 // prefer newly-enabled over earlier-enabled. 4742 info.preferredOrder = linkGeneration; 4743 alwaysList.add(info); 4744 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4745 if (DEBUG_DOMAIN_VERIFICATION) { 4746 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4747 } 4748 neverList.add(info); 4749 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4750 if (DEBUG_DOMAIN_VERIFICATION) { 4751 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4752 } 4753 alwaysAskList.add(info); 4754 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4755 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4756 if (DEBUG_DOMAIN_VERIFICATION) { 4757 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4758 } 4759 undefinedList.add(info); 4760 } 4761 } 4762 } 4763 4764 // We'll want to include browser possibilities in a few cases 4765 boolean includeBrowser = false; 4766 4767 // First try to add the "always" resolution(s) for the current user, if any 4768 if (alwaysList.size() > 0) { 4769 result.addAll(alwaysList); 4770 } else { 4771 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4772 result.addAll(undefinedList); 4773 // Maybe add one for the other profile. 4774 if (xpDomainInfo != null && ( 4775 xpDomainInfo.bestDomainVerificationStatus 4776 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4777 result.add(xpDomainInfo.resolveInfo); 4778 } 4779 includeBrowser = true; 4780 } 4781 4782 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4783 // If there were 'always' entries their preferred order has been set, so we also 4784 // back that off to make the alternatives equivalent 4785 if (alwaysAskList.size() > 0) { 4786 for (ResolveInfo i : result) { 4787 i.preferredOrder = 0; 4788 } 4789 result.addAll(alwaysAskList); 4790 includeBrowser = true; 4791 } 4792 4793 if (includeBrowser) { 4794 // Also add browsers (all of them or only the default one) 4795 if (DEBUG_DOMAIN_VERIFICATION) { 4796 Slog.v(TAG, " ...including browsers in candidate set"); 4797 } 4798 if ((matchFlags & MATCH_ALL) != 0) { 4799 result.addAll(matchAllList); 4800 } else { 4801 // Browser/generic handling case. If there's a default browser, go straight 4802 // to that (but only if there is no other higher-priority match). 4803 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4804 int maxMatchPrio = 0; 4805 ResolveInfo defaultBrowserMatch = null; 4806 final int numCandidates = matchAllList.size(); 4807 for (int n = 0; n < numCandidates; n++) { 4808 ResolveInfo info = matchAllList.get(n); 4809 // track the highest overall match priority... 4810 if (info.priority > maxMatchPrio) { 4811 maxMatchPrio = info.priority; 4812 } 4813 // ...and the highest-priority default browser match 4814 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4815 if (defaultBrowserMatch == null 4816 || (defaultBrowserMatch.priority < info.priority)) { 4817 if (debug) { 4818 Slog.v(TAG, "Considering default browser match " + info); 4819 } 4820 defaultBrowserMatch = info; 4821 } 4822 } 4823 } 4824 if (defaultBrowserMatch != null 4825 && defaultBrowserMatch.priority >= maxMatchPrio 4826 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4827 { 4828 if (debug) { 4829 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4830 } 4831 result.add(defaultBrowserMatch); 4832 } else { 4833 result.addAll(matchAllList); 4834 } 4835 } 4836 4837 // If there is nothing selected, add all candidates and remove the ones that the user 4838 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4839 if (result.size() == 0) { 4840 result.addAll(candidates); 4841 result.removeAll(neverList); 4842 } 4843 } 4844 } 4845 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4846 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4847 result.size()); 4848 for (ResolveInfo info : result) { 4849 Slog.v(TAG, " + " + info.activityInfo); 4850 } 4851 } 4852 return result; 4853 } 4854 4855 // Returns a packed value as a long: 4856 // 4857 // high 'int'-sized word: link status: undefined/ask/never/always. 4858 // low 'int'-sized word: relative priority among 'always' results. 4859 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4860 long result = ps.getDomainVerificationStatusForUser(userId); 4861 // if none available, get the master status 4862 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4863 if (ps.getIntentFilterVerificationInfo() != null) { 4864 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4865 } 4866 } 4867 return result; 4868 } 4869 4870 private ResolveInfo querySkipCurrentProfileIntents( 4871 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4872 int flags, int sourceUserId) { 4873 if (matchingFilters != null) { 4874 int size = matchingFilters.size(); 4875 for (int i = 0; i < size; i ++) { 4876 CrossProfileIntentFilter filter = matchingFilters.get(i); 4877 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4878 // Checking if there are activities in the target user that can handle the 4879 // intent. 4880 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4881 resolvedType, flags, sourceUserId); 4882 if (resolveInfo != null) { 4883 return resolveInfo; 4884 } 4885 } 4886 } 4887 } 4888 return null; 4889 } 4890 4891 // Return matching ResolveInfo if any for skip current profile intent filters. 4892 private ResolveInfo queryCrossProfileIntents( 4893 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4894 int flags, int sourceUserId) { 4895 if (matchingFilters != null) { 4896 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4897 // match the same intent. For performance reasons, it is better not to 4898 // run queryIntent twice for the same userId 4899 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4900 int size = matchingFilters.size(); 4901 for (int i = 0; i < size; i++) { 4902 CrossProfileIntentFilter filter = matchingFilters.get(i); 4903 int targetUserId = filter.getTargetUserId(); 4904 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4905 && !alreadyTriedUserIds.get(targetUserId)) { 4906 // Checking if there are activities in the target user that can handle the 4907 // intent. 4908 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4909 resolvedType, flags, sourceUserId); 4910 if (resolveInfo != null) return resolveInfo; 4911 alreadyTriedUserIds.put(targetUserId, true); 4912 } 4913 } 4914 } 4915 return null; 4916 } 4917 4918 /** 4919 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4920 * will forward the intent to the filter's target user. 4921 * Otherwise, returns null. 4922 */ 4923 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4924 String resolvedType, int flags, int sourceUserId) { 4925 int targetUserId = filter.getTargetUserId(); 4926 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4927 resolvedType, flags, targetUserId); 4928 if (resultTargetUser != null && !resultTargetUser.isEmpty() 4929 && isUserEnabled(targetUserId)) { 4930 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 4931 } 4932 return null; 4933 } 4934 4935 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 4936 int sourceUserId, int targetUserId) { 4937 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4938 long ident = Binder.clearCallingIdentity(); 4939 boolean targetIsProfile; 4940 try { 4941 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 4942 } finally { 4943 Binder.restoreCallingIdentity(ident); 4944 } 4945 String className; 4946 if (targetIsProfile) { 4947 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4948 } else { 4949 className = FORWARD_INTENT_TO_PARENT; 4950 } 4951 ComponentName forwardingActivityComponentName = new ComponentName( 4952 mAndroidApplication.packageName, className); 4953 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4954 sourceUserId); 4955 if (!targetIsProfile) { 4956 forwardingActivityInfo.showUserIcon = targetUserId; 4957 forwardingResolveInfo.noResourceId = true; 4958 } 4959 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4960 forwardingResolveInfo.priority = 0; 4961 forwardingResolveInfo.preferredOrder = 0; 4962 forwardingResolveInfo.match = 0; 4963 forwardingResolveInfo.isDefault = true; 4964 forwardingResolveInfo.filter = filter; 4965 forwardingResolveInfo.targetUserId = targetUserId; 4966 return forwardingResolveInfo; 4967 } 4968 4969 @Override 4970 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4971 Intent[] specifics, String[] specificTypes, Intent intent, 4972 String resolvedType, int flags, int userId) { 4973 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4974 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4975 false, "query intent activity options"); 4976 final String resultsAction = intent.getAction(); 4977 4978 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4979 | PackageManager.GET_RESOLVED_FILTER, userId); 4980 4981 if (DEBUG_INTENT_MATCHING) { 4982 Log.v(TAG, "Query " + intent + ": " + results); 4983 } 4984 4985 int specificsPos = 0; 4986 int N; 4987 4988 // todo: note that the algorithm used here is O(N^2). This 4989 // isn't a problem in our current environment, but if we start running 4990 // into situations where we have more than 5 or 10 matches then this 4991 // should probably be changed to something smarter... 4992 4993 // First we go through and resolve each of the specific items 4994 // that were supplied, taking care of removing any corresponding 4995 // duplicate items in the generic resolve list. 4996 if (specifics != null) { 4997 for (int i=0; i<specifics.length; i++) { 4998 final Intent sintent = specifics[i]; 4999 if (sintent == null) { 5000 continue; 5001 } 5002 5003 if (DEBUG_INTENT_MATCHING) { 5004 Log.v(TAG, "Specific #" + i + ": " + sintent); 5005 } 5006 5007 String action = sintent.getAction(); 5008 if (resultsAction != null && resultsAction.equals(action)) { 5009 // If this action was explicitly requested, then don't 5010 // remove things that have it. 5011 action = null; 5012 } 5013 5014 ResolveInfo ri = null; 5015 ActivityInfo ai = null; 5016 5017 ComponentName comp = sintent.getComponent(); 5018 if (comp == null) { 5019 ri = resolveIntent( 5020 sintent, 5021 specificTypes != null ? specificTypes[i] : null, 5022 flags, userId); 5023 if (ri == null) { 5024 continue; 5025 } 5026 if (ri == mResolveInfo) { 5027 // ACK! Must do something better with this. 5028 } 5029 ai = ri.activityInfo; 5030 comp = new ComponentName(ai.applicationInfo.packageName, 5031 ai.name); 5032 } else { 5033 ai = getActivityInfo(comp, flags, userId); 5034 if (ai == null) { 5035 continue; 5036 } 5037 } 5038 5039 // Look for any generic query activities that are duplicates 5040 // of this specific one, and remove them from the results. 5041 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5042 N = results.size(); 5043 int j; 5044 for (j=specificsPos; j<N; j++) { 5045 ResolveInfo sri = results.get(j); 5046 if ((sri.activityInfo.name.equals(comp.getClassName()) 5047 && sri.activityInfo.applicationInfo.packageName.equals( 5048 comp.getPackageName())) 5049 || (action != null && sri.filter.matchAction(action))) { 5050 results.remove(j); 5051 if (DEBUG_INTENT_MATCHING) Log.v( 5052 TAG, "Removing duplicate item from " + j 5053 + " due to specific " + specificsPos); 5054 if (ri == null) { 5055 ri = sri; 5056 } 5057 j--; 5058 N--; 5059 } 5060 } 5061 5062 // Add this specific item to its proper place. 5063 if (ri == null) { 5064 ri = new ResolveInfo(); 5065 ri.activityInfo = ai; 5066 } 5067 results.add(specificsPos, ri); 5068 ri.specificIndex = i; 5069 specificsPos++; 5070 } 5071 } 5072 5073 // Now we go through the remaining generic results and remove any 5074 // duplicate actions that are found here. 5075 N = results.size(); 5076 for (int i=specificsPos; i<N-1; i++) { 5077 final ResolveInfo rii = results.get(i); 5078 if (rii.filter == null) { 5079 continue; 5080 } 5081 5082 // Iterate over all of the actions of this result's intent 5083 // filter... typically this should be just one. 5084 final Iterator<String> it = rii.filter.actionsIterator(); 5085 if (it == null) { 5086 continue; 5087 } 5088 while (it.hasNext()) { 5089 final String action = it.next(); 5090 if (resultsAction != null && resultsAction.equals(action)) { 5091 // If this action was explicitly requested, then don't 5092 // remove things that have it. 5093 continue; 5094 } 5095 for (int j=i+1; j<N; j++) { 5096 final ResolveInfo rij = results.get(j); 5097 if (rij.filter != null && rij.filter.hasAction(action)) { 5098 results.remove(j); 5099 if (DEBUG_INTENT_MATCHING) Log.v( 5100 TAG, "Removing duplicate item from " + j 5101 + " due to action " + action + " at " + i); 5102 j--; 5103 N--; 5104 } 5105 } 5106 } 5107 5108 // If the caller didn't request filter information, drop it now 5109 // so we don't have to marshall/unmarshall it. 5110 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5111 rii.filter = null; 5112 } 5113 } 5114 5115 // Filter out the caller activity if so requested. 5116 if (caller != null) { 5117 N = results.size(); 5118 for (int i=0; i<N; i++) { 5119 ActivityInfo ainfo = results.get(i).activityInfo; 5120 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5121 && caller.getClassName().equals(ainfo.name)) { 5122 results.remove(i); 5123 break; 5124 } 5125 } 5126 } 5127 5128 // If the caller didn't request filter information, 5129 // drop them now so we don't have to 5130 // marshall/unmarshall it. 5131 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5132 N = results.size(); 5133 for (int i=0; i<N; i++) { 5134 results.get(i).filter = null; 5135 } 5136 } 5137 5138 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5139 return results; 5140 } 5141 5142 @Override 5143 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5144 int userId) { 5145 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5146 ComponentName comp = intent.getComponent(); 5147 if (comp == null) { 5148 if (intent.getSelector() != null) { 5149 intent = intent.getSelector(); 5150 comp = intent.getComponent(); 5151 } 5152 } 5153 if (comp != null) { 5154 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5155 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5156 if (ai != null) { 5157 ResolveInfo ri = new ResolveInfo(); 5158 ri.activityInfo = ai; 5159 list.add(ri); 5160 } 5161 return list; 5162 } 5163 5164 // reader 5165 synchronized (mPackages) { 5166 String pkgName = intent.getPackage(); 5167 if (pkgName == null) { 5168 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5169 } 5170 final PackageParser.Package pkg = mPackages.get(pkgName); 5171 if (pkg != null) { 5172 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5173 userId); 5174 } 5175 return null; 5176 } 5177 } 5178 5179 @Override 5180 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5181 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5182 if (!sUserManager.exists(userId)) return null; 5183 if (query != null) { 5184 if (query.size() >= 1) { 5185 // If there is more than one service with the same priority, 5186 // just arbitrarily pick the first one. 5187 return query.get(0); 5188 } 5189 } 5190 return null; 5191 } 5192 5193 @Override 5194 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5195 int userId) { 5196 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5197 ComponentName comp = intent.getComponent(); 5198 if (comp == null) { 5199 if (intent.getSelector() != null) { 5200 intent = intent.getSelector(); 5201 comp = intent.getComponent(); 5202 } 5203 } 5204 if (comp != null) { 5205 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5206 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5207 if (si != null) { 5208 final ResolveInfo ri = new ResolveInfo(); 5209 ri.serviceInfo = si; 5210 list.add(ri); 5211 } 5212 return list; 5213 } 5214 5215 // reader 5216 synchronized (mPackages) { 5217 String pkgName = intent.getPackage(); 5218 if (pkgName == null) { 5219 return mServices.queryIntent(intent, resolvedType, flags, userId); 5220 } 5221 final PackageParser.Package pkg = mPackages.get(pkgName); 5222 if (pkg != null) { 5223 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5224 userId); 5225 } 5226 return null; 5227 } 5228 } 5229 5230 @Override 5231 public List<ResolveInfo> queryIntentContentProviders( 5232 Intent intent, String resolvedType, int flags, int userId) { 5233 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5234 ComponentName comp = intent.getComponent(); 5235 if (comp == null) { 5236 if (intent.getSelector() != null) { 5237 intent = intent.getSelector(); 5238 comp = intent.getComponent(); 5239 } 5240 } 5241 if (comp != null) { 5242 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5243 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5244 if (pi != null) { 5245 final ResolveInfo ri = new ResolveInfo(); 5246 ri.providerInfo = pi; 5247 list.add(ri); 5248 } 5249 return list; 5250 } 5251 5252 // reader 5253 synchronized (mPackages) { 5254 String pkgName = intent.getPackage(); 5255 if (pkgName == null) { 5256 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5257 } 5258 final PackageParser.Package pkg = mPackages.get(pkgName); 5259 if (pkg != null) { 5260 return mProviders.queryIntentForPackage( 5261 intent, resolvedType, flags, pkg.providers, userId); 5262 } 5263 return null; 5264 } 5265 } 5266 5267 @Override 5268 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5269 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5270 5271 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5272 5273 // writer 5274 synchronized (mPackages) { 5275 ArrayList<PackageInfo> list; 5276 if (listUninstalled) { 5277 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5278 for (PackageSetting ps : mSettings.mPackages.values()) { 5279 PackageInfo pi; 5280 if (ps.pkg != null) { 5281 pi = generatePackageInfo(ps.pkg, flags, userId); 5282 } else { 5283 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5284 } 5285 if (pi != null) { 5286 list.add(pi); 5287 } 5288 } 5289 } else { 5290 list = new ArrayList<PackageInfo>(mPackages.size()); 5291 for (PackageParser.Package p : mPackages.values()) { 5292 PackageInfo pi = generatePackageInfo(p, flags, userId); 5293 if (pi != null) { 5294 list.add(pi); 5295 } 5296 } 5297 } 5298 5299 return new ParceledListSlice<PackageInfo>(list); 5300 } 5301 } 5302 5303 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5304 String[] permissions, boolean[] tmp, int flags, int userId) { 5305 int numMatch = 0; 5306 final PermissionsState permissionsState = ps.getPermissionsState(); 5307 for (int i=0; i<permissions.length; i++) { 5308 final String permission = permissions[i]; 5309 if (permissionsState.hasPermission(permission, userId)) { 5310 tmp[i] = true; 5311 numMatch++; 5312 } else { 5313 tmp[i] = false; 5314 } 5315 } 5316 if (numMatch == 0) { 5317 return; 5318 } 5319 PackageInfo pi; 5320 if (ps.pkg != null) { 5321 pi = generatePackageInfo(ps.pkg, flags, userId); 5322 } else { 5323 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5324 } 5325 // The above might return null in cases of uninstalled apps or install-state 5326 // skew across users/profiles. 5327 if (pi != null) { 5328 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5329 if (numMatch == permissions.length) { 5330 pi.requestedPermissions = permissions; 5331 } else { 5332 pi.requestedPermissions = new String[numMatch]; 5333 numMatch = 0; 5334 for (int i=0; i<permissions.length; i++) { 5335 if (tmp[i]) { 5336 pi.requestedPermissions[numMatch] = permissions[i]; 5337 numMatch++; 5338 } 5339 } 5340 } 5341 } 5342 list.add(pi); 5343 } 5344 } 5345 5346 @Override 5347 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5348 String[] permissions, int flags, int userId) { 5349 if (!sUserManager.exists(userId)) return null; 5350 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5351 5352 // writer 5353 synchronized (mPackages) { 5354 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5355 boolean[] tmpBools = new boolean[permissions.length]; 5356 if (listUninstalled) { 5357 for (PackageSetting ps : mSettings.mPackages.values()) { 5358 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5359 } 5360 } else { 5361 for (PackageParser.Package pkg : mPackages.values()) { 5362 PackageSetting ps = (PackageSetting)pkg.mExtras; 5363 if (ps != null) { 5364 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5365 userId); 5366 } 5367 } 5368 } 5369 5370 return new ParceledListSlice<PackageInfo>(list); 5371 } 5372 } 5373 5374 @Override 5375 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5376 if (!sUserManager.exists(userId)) return null; 5377 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5378 5379 // writer 5380 synchronized (mPackages) { 5381 ArrayList<ApplicationInfo> list; 5382 if (listUninstalled) { 5383 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5384 for (PackageSetting ps : mSettings.mPackages.values()) { 5385 ApplicationInfo ai; 5386 if (ps.pkg != null) { 5387 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5388 ps.readUserState(userId), userId); 5389 } else { 5390 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5391 } 5392 if (ai != null) { 5393 list.add(ai); 5394 } 5395 } 5396 } else { 5397 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5398 for (PackageParser.Package p : mPackages.values()) { 5399 if (p.mExtras != null) { 5400 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5401 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5402 if (ai != null) { 5403 list.add(ai); 5404 } 5405 } 5406 } 5407 } 5408 5409 return new ParceledListSlice<ApplicationInfo>(list); 5410 } 5411 } 5412 5413 public List<ApplicationInfo> getPersistentApplications(int flags) { 5414 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5415 5416 // reader 5417 synchronized (mPackages) { 5418 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5419 final int userId = UserHandle.getCallingUserId(); 5420 while (i.hasNext()) { 5421 final PackageParser.Package p = i.next(); 5422 if (p.applicationInfo != null 5423 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5424 && (!mSafeMode || isSystemApp(p))) { 5425 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5426 if (ps != null) { 5427 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5428 ps.readUserState(userId), userId); 5429 if (ai != null) { 5430 finalList.add(ai); 5431 } 5432 } 5433 } 5434 } 5435 } 5436 5437 return finalList; 5438 } 5439 5440 @Override 5441 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5442 if (!sUserManager.exists(userId)) return null; 5443 // reader 5444 synchronized (mPackages) { 5445 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5446 PackageSetting ps = provider != null 5447 ? mSettings.mPackages.get(provider.owner.packageName) 5448 : null; 5449 return ps != null 5450 && mSettings.isEnabledLPr(provider.info, flags, userId) 5451 && (!mSafeMode || (provider.info.applicationInfo.flags 5452 &ApplicationInfo.FLAG_SYSTEM) != 0) 5453 ? PackageParser.generateProviderInfo(provider, flags, 5454 ps.readUserState(userId), userId) 5455 : null; 5456 } 5457 } 5458 5459 /** 5460 * @deprecated 5461 */ 5462 @Deprecated 5463 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5464 // reader 5465 synchronized (mPackages) { 5466 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5467 .entrySet().iterator(); 5468 final int userId = UserHandle.getCallingUserId(); 5469 while (i.hasNext()) { 5470 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5471 PackageParser.Provider p = entry.getValue(); 5472 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5473 5474 if (ps != null && p.syncable 5475 && (!mSafeMode || (p.info.applicationInfo.flags 5476 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5477 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5478 ps.readUserState(userId), userId); 5479 if (info != null) { 5480 outNames.add(entry.getKey()); 5481 outInfo.add(info); 5482 } 5483 } 5484 } 5485 } 5486 } 5487 5488 @Override 5489 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5490 int uid, int flags) { 5491 ArrayList<ProviderInfo> finalList = null; 5492 // reader 5493 synchronized (mPackages) { 5494 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5495 final int userId = processName != null ? 5496 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5497 while (i.hasNext()) { 5498 final PackageParser.Provider p = i.next(); 5499 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5500 if (ps != null && p.info.authority != null 5501 && (processName == null 5502 || (p.info.processName.equals(processName) 5503 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5504 && mSettings.isEnabledLPr(p.info, flags, userId) 5505 && (!mSafeMode 5506 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5507 if (finalList == null) { 5508 finalList = new ArrayList<ProviderInfo>(3); 5509 } 5510 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5511 ps.readUserState(userId), userId); 5512 if (info != null) { 5513 finalList.add(info); 5514 } 5515 } 5516 } 5517 } 5518 5519 if (finalList != null) { 5520 Collections.sort(finalList, mProviderInitOrderSorter); 5521 return new ParceledListSlice<ProviderInfo>(finalList); 5522 } 5523 5524 return null; 5525 } 5526 5527 @Override 5528 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5529 int flags) { 5530 // reader 5531 synchronized (mPackages) { 5532 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5533 return PackageParser.generateInstrumentationInfo(i, flags); 5534 } 5535 } 5536 5537 @Override 5538 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5539 int flags) { 5540 ArrayList<InstrumentationInfo> finalList = 5541 new ArrayList<InstrumentationInfo>(); 5542 5543 // reader 5544 synchronized (mPackages) { 5545 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5546 while (i.hasNext()) { 5547 final PackageParser.Instrumentation p = i.next(); 5548 if (targetPackage == null 5549 || targetPackage.equals(p.info.targetPackage)) { 5550 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5551 flags); 5552 if (ii != null) { 5553 finalList.add(ii); 5554 } 5555 } 5556 } 5557 } 5558 5559 return finalList; 5560 } 5561 5562 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5563 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5564 if (overlays == null) { 5565 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5566 return; 5567 } 5568 for (PackageParser.Package opkg : overlays.values()) { 5569 // Not much to do if idmap fails: we already logged the error 5570 // and we certainly don't want to abort installation of pkg simply 5571 // because an overlay didn't fit properly. For these reasons, 5572 // ignore the return value of createIdmapForPackagePairLI. 5573 createIdmapForPackagePairLI(pkg, opkg); 5574 } 5575 } 5576 5577 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5578 PackageParser.Package opkg) { 5579 if (!opkg.mTrustedOverlay) { 5580 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5581 opkg.baseCodePath + ": overlay not trusted"); 5582 return false; 5583 } 5584 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5585 if (overlaySet == null) { 5586 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5587 opkg.baseCodePath + " but target package has no known overlays"); 5588 return false; 5589 } 5590 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5591 // TODO: generate idmap for split APKs 5592 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5593 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5594 + opkg.baseCodePath); 5595 return false; 5596 } 5597 PackageParser.Package[] overlayArray = 5598 overlaySet.values().toArray(new PackageParser.Package[0]); 5599 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5600 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5601 return p1.mOverlayPriority - p2.mOverlayPriority; 5602 } 5603 }; 5604 Arrays.sort(overlayArray, cmp); 5605 5606 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5607 int i = 0; 5608 for (PackageParser.Package p : overlayArray) { 5609 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5610 } 5611 return true; 5612 } 5613 5614 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5615 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5616 try { 5617 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5618 } finally { 5619 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5620 } 5621 } 5622 5623 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5624 final File[] files = dir.listFiles(); 5625 if (ArrayUtils.isEmpty(files)) { 5626 Log.d(TAG, "No files in app dir " + dir); 5627 return; 5628 } 5629 5630 if (DEBUG_PACKAGE_SCANNING) { 5631 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5632 + " flags=0x" + Integer.toHexString(parseFlags)); 5633 } 5634 5635 for (File file : files) { 5636 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5637 && !PackageInstallerService.isStageName(file.getName()); 5638 if (!isPackage) { 5639 // Ignore entries which are not packages 5640 continue; 5641 } 5642 try { 5643 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5644 scanFlags, currentTime, null); 5645 } catch (PackageManagerException e) { 5646 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5647 5648 // Delete invalid userdata apps 5649 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5650 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5651 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5652 if (file.isDirectory()) { 5653 mInstaller.rmPackageDir(file.getAbsolutePath()); 5654 } else { 5655 file.delete(); 5656 } 5657 } 5658 } 5659 } 5660 } 5661 5662 private static File getSettingsProblemFile() { 5663 File dataDir = Environment.getDataDirectory(); 5664 File systemDir = new File(dataDir, "system"); 5665 File fname = new File(systemDir, "uiderrors.txt"); 5666 return fname; 5667 } 5668 5669 static void reportSettingsProblem(int priority, String msg) { 5670 logCriticalInfo(priority, msg); 5671 } 5672 5673 static void logCriticalInfo(int priority, String msg) { 5674 Slog.println(priority, TAG, msg); 5675 EventLogTags.writePmCriticalInfo(msg); 5676 try { 5677 File fname = getSettingsProblemFile(); 5678 FileOutputStream out = new FileOutputStream(fname, true); 5679 PrintWriter pw = new FastPrintWriter(out); 5680 SimpleDateFormat formatter = new SimpleDateFormat(); 5681 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5682 pw.println(dateString + ": " + msg); 5683 pw.close(); 5684 FileUtils.setPermissions( 5685 fname.toString(), 5686 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5687 -1, -1); 5688 } catch (java.io.IOException e) { 5689 } 5690 } 5691 5692 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5693 PackageParser.Package pkg, File srcFile, int parseFlags) 5694 throws PackageManagerException { 5695 if (ps != null 5696 && ps.codePath.equals(srcFile) 5697 && ps.timeStamp == srcFile.lastModified() 5698 && !isCompatSignatureUpdateNeeded(pkg) 5699 && !isRecoverSignatureUpdateNeeded(pkg)) { 5700 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5701 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5702 ArraySet<PublicKey> signingKs; 5703 synchronized (mPackages) { 5704 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5705 } 5706 if (ps.signatures.mSignatures != null 5707 && ps.signatures.mSignatures.length != 0 5708 && signingKs != null) { 5709 // Optimization: reuse the existing cached certificates 5710 // if the package appears to be unchanged. 5711 pkg.mSignatures = ps.signatures.mSignatures; 5712 pkg.mSigningKeys = signingKs; 5713 return; 5714 } 5715 5716 Slog.w(TAG, "PackageSetting for " + ps.name 5717 + " is missing signatures. Collecting certs again to recover them."); 5718 } else { 5719 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5720 } 5721 5722 try { 5723 pp.collectCertificates(pkg, parseFlags); 5724 pp.collectManifestDigest(pkg); 5725 } catch (PackageParserException e) { 5726 throw PackageManagerException.from(e); 5727 } 5728 } 5729 5730 /** 5731 * Traces a package scan. 5732 * @see #scanPackageLI(File, int, int, long, UserHandle) 5733 */ 5734 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5735 long currentTime, UserHandle user) throws PackageManagerException { 5736 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5737 try { 5738 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5739 } finally { 5740 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5741 } 5742 } 5743 5744 /** 5745 * Scans a package and returns the newly parsed package. 5746 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5747 */ 5748 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5749 long currentTime, UserHandle user) throws PackageManagerException { 5750 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5751 parseFlags |= mDefParseFlags; 5752 PackageParser pp = new PackageParser(); 5753 pp.setSeparateProcesses(mSeparateProcesses); 5754 pp.setOnlyCoreApps(mOnlyCore); 5755 pp.setDisplayMetrics(mMetrics); 5756 5757 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5758 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5759 } 5760 5761 final PackageParser.Package pkg; 5762 try { 5763 pkg = pp.parsePackage(scanFile, parseFlags); 5764 } catch (PackageParserException e) { 5765 throw PackageManagerException.from(e); 5766 } 5767 5768 PackageSetting ps = null; 5769 PackageSetting updatedPkg; 5770 // reader 5771 synchronized (mPackages) { 5772 // Look to see if we already know about this package. 5773 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5774 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5775 // This package has been renamed to its original name. Let's 5776 // use that. 5777 ps = mSettings.peekPackageLPr(oldName); 5778 } 5779 // If there was no original package, see one for the real package name. 5780 if (ps == null) { 5781 ps = mSettings.peekPackageLPr(pkg.packageName); 5782 } 5783 // Check to see if this package could be hiding/updating a system 5784 // package. Must look for it either under the original or real 5785 // package name depending on our state. 5786 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5787 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5788 } 5789 boolean updatedPkgBetter = false; 5790 // First check if this is a system package that may involve an update 5791 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5792 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5793 // it needs to drop FLAG_PRIVILEGED. 5794 if (locationIsPrivileged(scanFile)) { 5795 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5796 } else { 5797 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5798 } 5799 5800 if (ps != null && !ps.codePath.equals(scanFile)) { 5801 // The path has changed from what was last scanned... check the 5802 // version of the new path against what we have stored to determine 5803 // what to do. 5804 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5805 if (pkg.mVersionCode <= ps.versionCode) { 5806 // The system package has been updated and the code path does not match 5807 // Ignore entry. Skip it. 5808 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5809 + " ignored: updated version " + ps.versionCode 5810 + " better than this " + pkg.mVersionCode); 5811 if (!updatedPkg.codePath.equals(scanFile)) { 5812 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5813 + ps.name + " changing from " + updatedPkg.codePathString 5814 + " to " + scanFile); 5815 updatedPkg.codePath = scanFile; 5816 updatedPkg.codePathString = scanFile.toString(); 5817 updatedPkg.resourcePath = scanFile; 5818 updatedPkg.resourcePathString = scanFile.toString(); 5819 } 5820 updatedPkg.pkg = pkg; 5821 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5822 "Package " + ps.name + " at " + scanFile 5823 + " ignored: updated version " + ps.versionCode 5824 + " better than this " + pkg.mVersionCode); 5825 } else { 5826 // The current app on the system partition is better than 5827 // what we have updated to on the data partition; switch 5828 // back to the system partition version. 5829 // At this point, its safely assumed that package installation for 5830 // apps in system partition will go through. If not there won't be a working 5831 // version of the app 5832 // writer 5833 synchronized (mPackages) { 5834 // Just remove the loaded entries from package lists. 5835 mPackages.remove(ps.name); 5836 } 5837 5838 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5839 + " reverting from " + ps.codePathString 5840 + ": new version " + pkg.mVersionCode 5841 + " better than installed " + ps.versionCode); 5842 5843 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5844 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5845 synchronized (mInstallLock) { 5846 args.cleanUpResourcesLI(); 5847 } 5848 synchronized (mPackages) { 5849 mSettings.enableSystemPackageLPw(ps.name); 5850 } 5851 updatedPkgBetter = true; 5852 } 5853 } 5854 } 5855 5856 if (updatedPkg != null) { 5857 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5858 // initially 5859 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5860 5861 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5862 // flag set initially 5863 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5864 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5865 } 5866 } 5867 5868 // Verify certificates against what was last scanned 5869 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5870 5871 /* 5872 * A new system app appeared, but we already had a non-system one of the 5873 * same name installed earlier. 5874 */ 5875 boolean shouldHideSystemApp = false; 5876 if (updatedPkg == null && ps != null 5877 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5878 /* 5879 * Check to make sure the signatures match first. If they don't, 5880 * wipe the installed application and its data. 5881 */ 5882 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5883 != PackageManager.SIGNATURE_MATCH) { 5884 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5885 + " signatures don't match existing userdata copy; removing"); 5886 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5887 ps = null; 5888 } else { 5889 /* 5890 * If the newly-added system app is an older version than the 5891 * already installed version, hide it. It will be scanned later 5892 * and re-added like an update. 5893 */ 5894 if (pkg.mVersionCode <= ps.versionCode) { 5895 shouldHideSystemApp = true; 5896 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5897 + " but new version " + pkg.mVersionCode + " better than installed " 5898 + ps.versionCode + "; hiding system"); 5899 } else { 5900 /* 5901 * The newly found system app is a newer version that the 5902 * one previously installed. Simply remove the 5903 * already-installed application and replace it with our own 5904 * while keeping the application data. 5905 */ 5906 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5907 + " reverting from " + ps.codePathString + ": new version " 5908 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5909 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5910 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5911 synchronized (mInstallLock) { 5912 args.cleanUpResourcesLI(); 5913 } 5914 } 5915 } 5916 } 5917 5918 // The apk is forward locked (not public) if its code and resources 5919 // are kept in different files. (except for app in either system or 5920 // vendor path). 5921 // TODO grab this value from PackageSettings 5922 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5923 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5924 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5925 } 5926 } 5927 5928 // TODO: extend to support forward-locked splits 5929 String resourcePath = null; 5930 String baseResourcePath = null; 5931 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5932 if (ps != null && ps.resourcePathString != null) { 5933 resourcePath = ps.resourcePathString; 5934 baseResourcePath = ps.resourcePathString; 5935 } else { 5936 // Should not happen at all. Just log an error. 5937 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5938 } 5939 } else { 5940 resourcePath = pkg.codePath; 5941 baseResourcePath = pkg.baseCodePath; 5942 } 5943 5944 // Set application objects path explicitly. 5945 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5946 pkg.applicationInfo.setCodePath(pkg.codePath); 5947 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5948 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5949 pkg.applicationInfo.setResourcePath(resourcePath); 5950 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5951 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5952 5953 // Note that we invoke the following method only if we are about to unpack an application 5954 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5955 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5956 5957 /* 5958 * If the system app should be overridden by a previously installed 5959 * data, hide the system app now and let the /data/app scan pick it up 5960 * again. 5961 */ 5962 if (shouldHideSystemApp) { 5963 synchronized (mPackages) { 5964 mSettings.disableSystemPackageLPw(pkg.packageName); 5965 } 5966 } 5967 5968 return scannedPkg; 5969 } 5970 5971 private static String fixProcessName(String defProcessName, 5972 String processName, int uid) { 5973 if (processName == null) { 5974 return defProcessName; 5975 } 5976 return processName; 5977 } 5978 5979 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5980 throws PackageManagerException { 5981 if (pkgSetting.signatures.mSignatures != null) { 5982 // Already existing package. Make sure signatures match 5983 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5984 == PackageManager.SIGNATURE_MATCH; 5985 if (!match) { 5986 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5987 == PackageManager.SIGNATURE_MATCH; 5988 } 5989 if (!match) { 5990 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5991 == PackageManager.SIGNATURE_MATCH; 5992 } 5993 if (!match) { 5994 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5995 + pkg.packageName + " signatures do not match the " 5996 + "previously installed version; ignoring!"); 5997 } 5998 } 5999 6000 // Check for shared user signatures 6001 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6002 // Already existing package. Make sure signatures match 6003 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6004 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6005 if (!match) { 6006 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6007 == PackageManager.SIGNATURE_MATCH; 6008 } 6009 if (!match) { 6010 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6011 == PackageManager.SIGNATURE_MATCH; 6012 } 6013 if (!match) { 6014 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6015 "Package " + pkg.packageName 6016 + " has no signatures that match those in shared user " 6017 + pkgSetting.sharedUser.name + "; ignoring!"); 6018 } 6019 } 6020 } 6021 6022 /** 6023 * Enforces that only the system UID or root's UID can call a method exposed 6024 * via Binder. 6025 * 6026 * @param message used as message if SecurityException is thrown 6027 * @throws SecurityException if the caller is not system or root 6028 */ 6029 private static final void enforceSystemOrRoot(String message) { 6030 final int uid = Binder.getCallingUid(); 6031 if (uid != Process.SYSTEM_UID && uid != 0) { 6032 throw new SecurityException(message); 6033 } 6034 } 6035 6036 @Override 6037 public void performFstrimIfNeeded() { 6038 enforceSystemOrRoot("Only the system can request fstrim"); 6039 6040 // Before everything else, see whether we need to fstrim. 6041 try { 6042 IMountService ms = PackageHelper.getMountService(); 6043 if (ms != null) { 6044 final boolean isUpgrade = isUpgrade(); 6045 boolean doTrim = isUpgrade; 6046 if (doTrim) { 6047 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6048 } else { 6049 final long interval = android.provider.Settings.Global.getLong( 6050 mContext.getContentResolver(), 6051 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6052 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6053 if (interval > 0) { 6054 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6055 if (timeSinceLast > interval) { 6056 doTrim = true; 6057 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6058 + "; running immediately"); 6059 } 6060 } 6061 } 6062 if (doTrim) { 6063 if (!isFirstBoot()) { 6064 try { 6065 ActivityManagerNative.getDefault().showBootMessage( 6066 mContext.getResources().getString( 6067 R.string.android_upgrading_fstrim), true); 6068 } catch (RemoteException e) { 6069 } 6070 } 6071 ms.runMaintenance(); 6072 } 6073 } else { 6074 Slog.e(TAG, "Mount service unavailable!"); 6075 } 6076 } catch (RemoteException e) { 6077 // Can't happen; MountService is local 6078 } 6079 } 6080 6081 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6082 List<ResolveInfo> ris = null; 6083 try { 6084 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6085 intent, null, 0, userId); 6086 } catch (RemoteException e) { 6087 } 6088 ArraySet<String> pkgNames = new ArraySet<String>(); 6089 if (ris != null) { 6090 for (ResolveInfo ri : ris) { 6091 pkgNames.add(ri.activityInfo.packageName); 6092 } 6093 } 6094 return pkgNames; 6095 } 6096 6097 @Override 6098 public void notifyPackageUse(String packageName) { 6099 synchronized (mPackages) { 6100 PackageParser.Package p = mPackages.get(packageName); 6101 if (p == null) { 6102 return; 6103 } 6104 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6105 } 6106 } 6107 6108 @Override 6109 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6110 return performDexOptTraced(packageName, instructionSet); 6111 } 6112 6113 public boolean performDexOpt(String packageName, String instructionSet) { 6114 return performDexOptTraced(packageName, instructionSet); 6115 } 6116 6117 private boolean performDexOptTraced(String packageName, String instructionSet) { 6118 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6119 try { 6120 return performDexOptInternal(packageName, instructionSet); 6121 } finally { 6122 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6123 } 6124 } 6125 6126 private boolean performDexOptInternal(String packageName, String instructionSet) { 6127 PackageParser.Package p; 6128 final String targetInstructionSet; 6129 synchronized (mPackages) { 6130 p = mPackages.get(packageName); 6131 if (p == null) { 6132 return false; 6133 } 6134 mPackageUsage.write(false); 6135 6136 targetInstructionSet = instructionSet != null ? instructionSet : 6137 getPrimaryInstructionSet(p.applicationInfo); 6138 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6139 return false; 6140 } 6141 } 6142 long callingId = Binder.clearCallingIdentity(); 6143 try { 6144 synchronized (mInstallLock) { 6145 final String[] instructionSets = new String[] { targetInstructionSet }; 6146 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6147 true /* inclDependencies */); 6148 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6149 } 6150 } finally { 6151 Binder.restoreCallingIdentity(callingId); 6152 } 6153 } 6154 6155 public ArraySet<String> getPackagesThatNeedDexOpt() { 6156 ArraySet<String> pkgs = null; 6157 synchronized (mPackages) { 6158 for (PackageParser.Package p : mPackages.values()) { 6159 if (DEBUG_DEXOPT) { 6160 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6161 } 6162 if (!p.mDexOptPerformed.isEmpty()) { 6163 continue; 6164 } 6165 if (pkgs == null) { 6166 pkgs = new ArraySet<String>(); 6167 } 6168 pkgs.add(p.packageName); 6169 } 6170 } 6171 return pkgs; 6172 } 6173 6174 public void shutdown() { 6175 mPackageUsage.write(true); 6176 } 6177 6178 @Override 6179 public void forceDexOpt(String packageName) { 6180 enforceSystemOrRoot("forceDexOpt"); 6181 6182 PackageParser.Package pkg; 6183 synchronized (mPackages) { 6184 pkg = mPackages.get(packageName); 6185 if (pkg == null) { 6186 throw new IllegalArgumentException("Missing package: " + packageName); 6187 } 6188 } 6189 6190 synchronized (mInstallLock) { 6191 final String[] instructionSets = new String[] { 6192 getPrimaryInstructionSet(pkg.applicationInfo) }; 6193 6194 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6195 6196 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6197 true /* inclDependencies */); 6198 6199 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6200 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6201 throw new IllegalStateException("Failed to dexopt: " + res); 6202 } 6203 } 6204 } 6205 6206 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6207 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6208 Slog.w(TAG, "Unable to update from " + oldPkg.name 6209 + " to " + newPkg.packageName 6210 + ": old package not in system partition"); 6211 return false; 6212 } else if (mPackages.get(oldPkg.name) != null) { 6213 Slog.w(TAG, "Unable to update from " + oldPkg.name 6214 + " to " + newPkg.packageName 6215 + ": old package still exists"); 6216 return false; 6217 } 6218 return true; 6219 } 6220 6221 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6222 int[] users = sUserManager.getUserIds(); 6223 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6224 if (res < 0) { 6225 return res; 6226 } 6227 for (int user : users) { 6228 if (user != 0) { 6229 res = mInstaller.createUserData(volumeUuid, packageName, 6230 UserHandle.getUid(user, uid), user, seinfo); 6231 if (res < 0) { 6232 return res; 6233 } 6234 } 6235 } 6236 return res; 6237 } 6238 6239 private int removeDataDirsLI(String volumeUuid, String packageName) { 6240 int[] users = sUserManager.getUserIds(); 6241 int res = 0; 6242 for (int user : users) { 6243 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6244 if (resInner < 0) { 6245 res = resInner; 6246 } 6247 } 6248 6249 return res; 6250 } 6251 6252 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6253 int[] users = sUserManager.getUserIds(); 6254 int res = 0; 6255 for (int user : users) { 6256 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6257 if (resInner < 0) { 6258 res = resInner; 6259 } 6260 } 6261 return res; 6262 } 6263 6264 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6265 PackageParser.Package changingLib) { 6266 if (file.path != null) { 6267 usesLibraryFiles.add(file.path); 6268 return; 6269 } 6270 PackageParser.Package p = mPackages.get(file.apk); 6271 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6272 // If we are doing this while in the middle of updating a library apk, 6273 // then we need to make sure to use that new apk for determining the 6274 // dependencies here. (We haven't yet finished committing the new apk 6275 // to the package manager state.) 6276 if (p == null || p.packageName.equals(changingLib.packageName)) { 6277 p = changingLib; 6278 } 6279 } 6280 if (p != null) { 6281 usesLibraryFiles.addAll(p.getAllCodePaths()); 6282 } 6283 } 6284 6285 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6286 PackageParser.Package changingLib) throws PackageManagerException { 6287 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6288 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6289 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6290 for (int i=0; i<N; i++) { 6291 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6292 if (file == null) { 6293 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6294 "Package " + pkg.packageName + " requires unavailable shared library " 6295 + pkg.usesLibraries.get(i) + "; failing!"); 6296 } 6297 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6298 } 6299 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6300 for (int i=0; i<N; i++) { 6301 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6302 if (file == null) { 6303 Slog.w(TAG, "Package " + pkg.packageName 6304 + " desires unavailable shared library " 6305 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6306 } else { 6307 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6308 } 6309 } 6310 N = usesLibraryFiles.size(); 6311 if (N > 0) { 6312 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6313 } else { 6314 pkg.usesLibraryFiles = null; 6315 } 6316 } 6317 } 6318 6319 private static boolean hasString(List<String> list, List<String> which) { 6320 if (list == null) { 6321 return false; 6322 } 6323 for (int i=list.size()-1; i>=0; i--) { 6324 for (int j=which.size()-1; j>=0; j--) { 6325 if (which.get(j).equals(list.get(i))) { 6326 return true; 6327 } 6328 } 6329 } 6330 return false; 6331 } 6332 6333 private void updateAllSharedLibrariesLPw() { 6334 for (PackageParser.Package pkg : mPackages.values()) { 6335 try { 6336 updateSharedLibrariesLPw(pkg, null); 6337 } catch (PackageManagerException e) { 6338 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6339 } 6340 } 6341 } 6342 6343 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6344 PackageParser.Package changingPkg) { 6345 ArrayList<PackageParser.Package> res = null; 6346 for (PackageParser.Package pkg : mPackages.values()) { 6347 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6348 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6349 if (res == null) { 6350 res = new ArrayList<PackageParser.Package>(); 6351 } 6352 res.add(pkg); 6353 try { 6354 updateSharedLibrariesLPw(pkg, changingPkg); 6355 } catch (PackageManagerException e) { 6356 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6357 } 6358 } 6359 } 6360 return res; 6361 } 6362 6363 /** 6364 * Derive the value of the {@code cpuAbiOverride} based on the provided 6365 * value and an optional stored value from the package settings. 6366 */ 6367 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6368 String cpuAbiOverride = null; 6369 6370 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6371 cpuAbiOverride = null; 6372 } else if (abiOverride != null) { 6373 cpuAbiOverride = abiOverride; 6374 } else if (settings != null) { 6375 cpuAbiOverride = settings.cpuAbiOverrideString; 6376 } 6377 6378 return cpuAbiOverride; 6379 } 6380 6381 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6382 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6384 try { 6385 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6386 } finally { 6387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6388 } 6389 } 6390 6391 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6392 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6393 boolean success = false; 6394 try { 6395 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6396 currentTime, user); 6397 success = true; 6398 return res; 6399 } finally { 6400 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6401 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6402 } 6403 } 6404 } 6405 6406 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6407 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6408 final File scanFile = new File(pkg.codePath); 6409 if (pkg.applicationInfo.getCodePath() == null || 6410 pkg.applicationInfo.getResourcePath() == null) { 6411 // Bail out. The resource and code paths haven't been set. 6412 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6413 "Code and resource paths haven't been set correctly"); 6414 } 6415 6416 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6417 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6418 } else { 6419 // Only allow system apps to be flagged as core apps. 6420 pkg.coreApp = false; 6421 } 6422 6423 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6424 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6425 } 6426 6427 if (mCustomResolverComponentName != null && 6428 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6429 setUpCustomResolverActivity(pkg); 6430 } 6431 6432 if (pkg.packageName.equals("android")) { 6433 synchronized (mPackages) { 6434 if (mAndroidApplication != null) { 6435 Slog.w(TAG, "*************************************************"); 6436 Slog.w(TAG, "Core android package being redefined. Skipping."); 6437 Slog.w(TAG, " file=" + scanFile); 6438 Slog.w(TAG, "*************************************************"); 6439 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6440 "Core android package being redefined. Skipping."); 6441 } 6442 6443 // Set up information for our fall-back user intent resolution activity. 6444 mPlatformPackage = pkg; 6445 pkg.mVersionCode = mSdkVersion; 6446 mAndroidApplication = pkg.applicationInfo; 6447 6448 if (!mResolverReplaced) { 6449 mResolveActivity.applicationInfo = mAndroidApplication; 6450 mResolveActivity.name = ResolverActivity.class.getName(); 6451 mResolveActivity.packageName = mAndroidApplication.packageName; 6452 mResolveActivity.processName = "system:ui"; 6453 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6454 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6455 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6456 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6457 mResolveActivity.exported = true; 6458 mResolveActivity.enabled = true; 6459 mResolveInfo.activityInfo = mResolveActivity; 6460 mResolveInfo.priority = 0; 6461 mResolveInfo.preferredOrder = 0; 6462 mResolveInfo.match = 0; 6463 mResolveComponentName = new ComponentName( 6464 mAndroidApplication.packageName, mResolveActivity.name); 6465 } 6466 } 6467 } 6468 6469 if (DEBUG_PACKAGE_SCANNING) { 6470 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6471 Log.d(TAG, "Scanning package " + pkg.packageName); 6472 } 6473 6474 if (mPackages.containsKey(pkg.packageName) 6475 || mSharedLibraries.containsKey(pkg.packageName)) { 6476 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6477 "Application package " + pkg.packageName 6478 + " already installed. Skipping duplicate."); 6479 } 6480 6481 // If we're only installing presumed-existing packages, require that the 6482 // scanned APK is both already known and at the path previously established 6483 // for it. Previously unknown packages we pick up normally, but if we have an 6484 // a priori expectation about this package's install presence, enforce it. 6485 // With a singular exception for new system packages. When an OTA contains 6486 // a new system package, we allow the codepath to change from a system location 6487 // to the user-installed location. If we don't allow this change, any newer, 6488 // user-installed version of the application will be ignored. 6489 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6490 if (mExpectingBetter.containsKey(pkg.packageName)) { 6491 logCriticalInfo(Log.WARN, 6492 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6493 } else { 6494 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6495 if (known != null) { 6496 if (DEBUG_PACKAGE_SCANNING) { 6497 Log.d(TAG, "Examining " + pkg.codePath 6498 + " and requiring known paths " + known.codePathString 6499 + " & " + known.resourcePathString); 6500 } 6501 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6502 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6503 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6504 "Application package " + pkg.packageName 6505 + " found at " + pkg.applicationInfo.getCodePath() 6506 + " but expected at " + known.codePathString + "; ignoring."); 6507 } 6508 } 6509 } 6510 } 6511 6512 // Initialize package source and resource directories 6513 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6514 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6515 6516 SharedUserSetting suid = null; 6517 PackageSetting pkgSetting = null; 6518 6519 if (!isSystemApp(pkg)) { 6520 // Only system apps can use these features. 6521 pkg.mOriginalPackages = null; 6522 pkg.mRealPackage = null; 6523 pkg.mAdoptPermissions = null; 6524 } 6525 6526 // writer 6527 synchronized (mPackages) { 6528 if (pkg.mSharedUserId != null) { 6529 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6530 if (suid == null) { 6531 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6532 "Creating application package " + pkg.packageName 6533 + " for shared user failed"); 6534 } 6535 if (DEBUG_PACKAGE_SCANNING) { 6536 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6537 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6538 + "): packages=" + suid.packages); 6539 } 6540 } 6541 6542 // Check if we are renaming from an original package name. 6543 PackageSetting origPackage = null; 6544 String realName = null; 6545 if (pkg.mOriginalPackages != null) { 6546 // This package may need to be renamed to a previously 6547 // installed name. Let's check on that... 6548 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6549 if (pkg.mOriginalPackages.contains(renamed)) { 6550 // This package had originally been installed as the 6551 // original name, and we have already taken care of 6552 // transitioning to the new one. Just update the new 6553 // one to continue using the old name. 6554 realName = pkg.mRealPackage; 6555 if (!pkg.packageName.equals(renamed)) { 6556 // Callers into this function may have already taken 6557 // care of renaming the package; only do it here if 6558 // it is not already done. 6559 pkg.setPackageName(renamed); 6560 } 6561 6562 } else { 6563 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6564 if ((origPackage = mSettings.peekPackageLPr( 6565 pkg.mOriginalPackages.get(i))) != null) { 6566 // We do have the package already installed under its 6567 // original name... should we use it? 6568 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6569 // New package is not compatible with original. 6570 origPackage = null; 6571 continue; 6572 } else if (origPackage.sharedUser != null) { 6573 // Make sure uid is compatible between packages. 6574 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6575 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6576 + " to " + pkg.packageName + ": old uid " 6577 + origPackage.sharedUser.name 6578 + " differs from " + pkg.mSharedUserId); 6579 origPackage = null; 6580 continue; 6581 } 6582 } else { 6583 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6584 + pkg.packageName + " to old name " + origPackage.name); 6585 } 6586 break; 6587 } 6588 } 6589 } 6590 } 6591 6592 if (mTransferedPackages.contains(pkg.packageName)) { 6593 Slog.w(TAG, "Package " + pkg.packageName 6594 + " was transferred to another, but its .apk remains"); 6595 } 6596 6597 // Just create the setting, don't add it yet. For already existing packages 6598 // the PkgSetting exists already and doesn't have to be created. 6599 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6600 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6601 pkg.applicationInfo.primaryCpuAbi, 6602 pkg.applicationInfo.secondaryCpuAbi, 6603 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6604 user, false); 6605 if (pkgSetting == null) { 6606 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6607 "Creating application package " + pkg.packageName + " failed"); 6608 } 6609 6610 if (pkgSetting.origPackage != null) { 6611 // If we are first transitioning from an original package, 6612 // fix up the new package's name now. We need to do this after 6613 // looking up the package under its new name, so getPackageLP 6614 // can take care of fiddling things correctly. 6615 pkg.setPackageName(origPackage.name); 6616 6617 // File a report about this. 6618 String msg = "New package " + pkgSetting.realName 6619 + " renamed to replace old package " + pkgSetting.name; 6620 reportSettingsProblem(Log.WARN, msg); 6621 6622 // Make a note of it. 6623 mTransferedPackages.add(origPackage.name); 6624 6625 // No longer need to retain this. 6626 pkgSetting.origPackage = null; 6627 } 6628 6629 if (realName != null) { 6630 // Make a note of it. 6631 mTransferedPackages.add(pkg.packageName); 6632 } 6633 6634 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6635 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6636 } 6637 6638 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6639 // Check all shared libraries and map to their actual file path. 6640 // We only do this here for apps not on a system dir, because those 6641 // are the only ones that can fail an install due to this. We 6642 // will take care of the system apps by updating all of their 6643 // library paths after the scan is done. 6644 updateSharedLibrariesLPw(pkg, null); 6645 } 6646 6647 if (mFoundPolicyFile) { 6648 SELinuxMMAC.assignSeinfoValue(pkg); 6649 } 6650 6651 pkg.applicationInfo.uid = pkgSetting.appId; 6652 pkg.mExtras = pkgSetting; 6653 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6654 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6655 // We just determined the app is signed correctly, so bring 6656 // over the latest parsed certs. 6657 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6658 } else { 6659 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6660 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6661 "Package " + pkg.packageName + " upgrade keys do not match the " 6662 + "previously installed version"); 6663 } else { 6664 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6665 String msg = "System package " + pkg.packageName 6666 + " signature changed; retaining data."; 6667 reportSettingsProblem(Log.WARN, msg); 6668 } 6669 } 6670 } else { 6671 try { 6672 verifySignaturesLP(pkgSetting, pkg); 6673 // We just determined the app is signed correctly, so bring 6674 // over the latest parsed certs. 6675 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6676 } catch (PackageManagerException e) { 6677 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6678 throw e; 6679 } 6680 // The signature has changed, but this package is in the system 6681 // image... let's recover! 6682 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6683 // However... if this package is part of a shared user, but it 6684 // doesn't match the signature of the shared user, let's fail. 6685 // What this means is that you can't change the signatures 6686 // associated with an overall shared user, which doesn't seem all 6687 // that unreasonable. 6688 if (pkgSetting.sharedUser != null) { 6689 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6690 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6691 throw new PackageManagerException( 6692 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6693 "Signature mismatch for shared user : " 6694 + pkgSetting.sharedUser); 6695 } 6696 } 6697 // File a report about this. 6698 String msg = "System package " + pkg.packageName 6699 + " signature changed; retaining data."; 6700 reportSettingsProblem(Log.WARN, msg); 6701 } 6702 } 6703 // Verify that this new package doesn't have any content providers 6704 // that conflict with existing packages. Only do this if the 6705 // package isn't already installed, since we don't want to break 6706 // things that are installed. 6707 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6708 final int N = pkg.providers.size(); 6709 int i; 6710 for (i=0; i<N; i++) { 6711 PackageParser.Provider p = pkg.providers.get(i); 6712 if (p.info.authority != null) { 6713 String names[] = p.info.authority.split(";"); 6714 for (int j = 0; j < names.length; j++) { 6715 if (mProvidersByAuthority.containsKey(names[j])) { 6716 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6717 final String otherPackageName = 6718 ((other != null && other.getComponentName() != null) ? 6719 other.getComponentName().getPackageName() : "?"); 6720 throw new PackageManagerException( 6721 INSTALL_FAILED_CONFLICTING_PROVIDER, 6722 "Can't install because provider name " + names[j] 6723 + " (in package " + pkg.applicationInfo.packageName 6724 + ") is already used by " + otherPackageName); 6725 } 6726 } 6727 } 6728 } 6729 } 6730 6731 if (pkg.mAdoptPermissions != null) { 6732 // This package wants to adopt ownership of permissions from 6733 // another package. 6734 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6735 final String origName = pkg.mAdoptPermissions.get(i); 6736 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6737 if (orig != null) { 6738 if (verifyPackageUpdateLPr(orig, pkg)) { 6739 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6740 + pkg.packageName); 6741 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6742 } 6743 } 6744 } 6745 } 6746 } 6747 6748 final String pkgName = pkg.packageName; 6749 6750 final long scanFileTime = scanFile.lastModified(); 6751 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6752 pkg.applicationInfo.processName = fixProcessName( 6753 pkg.applicationInfo.packageName, 6754 pkg.applicationInfo.processName, 6755 pkg.applicationInfo.uid); 6756 6757 File dataPath; 6758 if (mPlatformPackage == pkg) { 6759 // The system package is special. 6760 dataPath = new File(Environment.getDataDirectory(), "system"); 6761 6762 pkg.applicationInfo.dataDir = dataPath.getPath(); 6763 6764 } else { 6765 // This is a normal package, need to make its data directory. 6766 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6767 UserHandle.USER_SYSTEM, pkg.packageName); 6768 6769 boolean uidError = false; 6770 if (dataPath.exists()) { 6771 int currentUid = 0; 6772 try { 6773 StructStat stat = Os.stat(dataPath.getPath()); 6774 currentUid = stat.st_uid; 6775 } catch (ErrnoException e) { 6776 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6777 } 6778 6779 // If we have mismatched owners for the data path, we have a problem. 6780 if (currentUid != pkg.applicationInfo.uid) { 6781 boolean recovered = false; 6782 if (currentUid == 0) { 6783 // The directory somehow became owned by root. Wow. 6784 // This is probably because the system was stopped while 6785 // installd was in the middle of messing with its libs 6786 // directory. Ask installd to fix that. 6787 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6788 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6789 if (ret >= 0) { 6790 recovered = true; 6791 String msg = "Package " + pkg.packageName 6792 + " unexpectedly changed to uid 0; recovered to " + 6793 + pkg.applicationInfo.uid; 6794 reportSettingsProblem(Log.WARN, msg); 6795 } 6796 } 6797 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6798 || (scanFlags&SCAN_BOOTING) != 0)) { 6799 // If this is a system app, we can at least delete its 6800 // current data so the application will still work. 6801 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6802 if (ret >= 0) { 6803 // TODO: Kill the processes first 6804 // Old data gone! 6805 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6806 ? "System package " : "Third party package "; 6807 String msg = prefix + pkg.packageName 6808 + " has changed from uid: " 6809 + currentUid + " to " 6810 + pkg.applicationInfo.uid + "; old data erased"; 6811 reportSettingsProblem(Log.WARN, msg); 6812 recovered = true; 6813 6814 // And now re-install the app. 6815 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6816 pkg.applicationInfo.seinfo); 6817 if (ret == -1) { 6818 // Ack should not happen! 6819 msg = prefix + pkg.packageName 6820 + " could not have data directory re-created after delete."; 6821 reportSettingsProblem(Log.WARN, msg); 6822 throw new PackageManagerException( 6823 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6824 } 6825 } 6826 if (!recovered) { 6827 mHasSystemUidErrors = true; 6828 } 6829 } else if (!recovered) { 6830 // If we allow this install to proceed, we will be broken. 6831 // Abort, abort! 6832 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6833 "scanPackageLI"); 6834 } 6835 if (!recovered) { 6836 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6837 + pkg.applicationInfo.uid + "/fs_" 6838 + currentUid; 6839 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6840 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6841 String msg = "Package " + pkg.packageName 6842 + " has mismatched uid: " 6843 + currentUid + " on disk, " 6844 + pkg.applicationInfo.uid + " in settings"; 6845 // writer 6846 synchronized (mPackages) { 6847 mSettings.mReadMessages.append(msg); 6848 mSettings.mReadMessages.append('\n'); 6849 uidError = true; 6850 if (!pkgSetting.uidError) { 6851 reportSettingsProblem(Log.ERROR, msg); 6852 } 6853 } 6854 } 6855 } 6856 pkg.applicationInfo.dataDir = dataPath.getPath(); 6857 if (mShouldRestoreconData) { 6858 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6859 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6860 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6861 } 6862 } else { 6863 if (DEBUG_PACKAGE_SCANNING) { 6864 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6865 Log.v(TAG, "Want this data dir: " + dataPath); 6866 } 6867 //invoke installer to do the actual installation 6868 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6869 pkg.applicationInfo.seinfo); 6870 if (ret < 0) { 6871 // Error from installer 6872 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6873 "Unable to create data dirs [errorCode=" + ret + "]"); 6874 } 6875 6876 if (dataPath.exists()) { 6877 pkg.applicationInfo.dataDir = dataPath.getPath(); 6878 } else { 6879 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6880 pkg.applicationInfo.dataDir = null; 6881 } 6882 } 6883 6884 pkgSetting.uidError = uidError; 6885 } 6886 6887 final String path = scanFile.getPath(); 6888 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6889 6890 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6891 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6892 6893 // Some system apps still use directory structure for native libraries 6894 // in which case we might end up not detecting abi solely based on apk 6895 // structure. Try to detect abi based on directory structure. 6896 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6897 pkg.applicationInfo.primaryCpuAbi == null) { 6898 setBundledAppAbisAndRoots(pkg, pkgSetting); 6899 setNativeLibraryPaths(pkg); 6900 } 6901 6902 } else { 6903 if ((scanFlags & SCAN_MOVE) != 0) { 6904 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6905 // but we already have this packages package info in the PackageSetting. We just 6906 // use that and derive the native library path based on the new codepath. 6907 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6908 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6909 } 6910 6911 // Set native library paths again. For moves, the path will be updated based on the 6912 // ABIs we've determined above. For non-moves, the path will be updated based on the 6913 // ABIs we determined during compilation, but the path will depend on the final 6914 // package path (after the rename away from the stage path). 6915 setNativeLibraryPaths(pkg); 6916 } 6917 6918 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6919 final int[] userIds = sUserManager.getUserIds(); 6920 synchronized (mInstallLock) { 6921 // Make sure all user data directories are ready to roll; we're okay 6922 // if they already exist 6923 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6924 for (int userId : userIds) { 6925 if (userId != UserHandle.USER_SYSTEM) { 6926 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6927 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6928 pkg.applicationInfo.seinfo); 6929 } 6930 } 6931 } 6932 6933 // Create a native library symlink only if we have native libraries 6934 // and if the native libraries are 32 bit libraries. We do not provide 6935 // this symlink for 64 bit libraries. 6936 if (pkg.applicationInfo.primaryCpuAbi != null && 6937 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6938 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 6939 try { 6940 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6941 for (int userId : userIds) { 6942 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6943 nativeLibPath, userId) < 0) { 6944 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6945 "Failed linking native library dir (user=" + userId + ")"); 6946 } 6947 } 6948 } finally { 6949 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6950 } 6951 } 6952 } 6953 6954 // This is a special case for the "system" package, where the ABI is 6955 // dictated by the zygote configuration (and init.rc). We should keep track 6956 // of this ABI so that we can deal with "normal" applications that run under 6957 // the same UID correctly. 6958 if (mPlatformPackage == pkg) { 6959 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6960 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6961 } 6962 6963 // If there's a mismatch between the abi-override in the package setting 6964 // and the abiOverride specified for the install. Warn about this because we 6965 // would've already compiled the app without taking the package setting into 6966 // account. 6967 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6968 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6969 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6970 " for package: " + pkg.packageName); 6971 } 6972 } 6973 6974 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6975 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6976 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6977 6978 // Copy the derived override back to the parsed package, so that we can 6979 // update the package settings accordingly. 6980 pkg.cpuAbiOverride = cpuAbiOverride; 6981 6982 if (DEBUG_ABI_SELECTION) { 6983 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6984 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6985 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6986 } 6987 6988 // Push the derived path down into PackageSettings so we know what to 6989 // clean up at uninstall time. 6990 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6991 6992 if (DEBUG_ABI_SELECTION) { 6993 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6994 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6995 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6996 } 6997 6998 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6999 // We don't do this here during boot because we can do it all 7000 // at once after scanning all existing packages. 7001 // 7002 // We also do this *before* we perform dexopt on this package, so that 7003 // we can avoid redundant dexopts, and also to make sure we've got the 7004 // code and package path correct. 7005 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7006 pkg, true /* boot complete */); 7007 } 7008 7009 if (mFactoryTest && pkg.requestedPermissions.contains( 7010 android.Manifest.permission.FACTORY_TEST)) { 7011 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7012 } 7013 7014 ArrayList<PackageParser.Package> clientLibPkgs = null; 7015 7016 // writer 7017 synchronized (mPackages) { 7018 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7019 // Only system apps can add new shared libraries. 7020 if (pkg.libraryNames != null) { 7021 for (int i=0; i<pkg.libraryNames.size(); i++) { 7022 String name = pkg.libraryNames.get(i); 7023 boolean allowed = false; 7024 if (pkg.isUpdatedSystemApp()) { 7025 // New library entries can only be added through the 7026 // system image. This is important to get rid of a lot 7027 // of nasty edge cases: for example if we allowed a non- 7028 // system update of the app to add a library, then uninstalling 7029 // the update would make the library go away, and assumptions 7030 // we made such as through app install filtering would now 7031 // have allowed apps on the device which aren't compatible 7032 // with it. Better to just have the restriction here, be 7033 // conservative, and create many fewer cases that can negatively 7034 // impact the user experience. 7035 final PackageSetting sysPs = mSettings 7036 .getDisabledSystemPkgLPr(pkg.packageName); 7037 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7038 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7039 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7040 allowed = true; 7041 break; 7042 } 7043 } 7044 } 7045 } else { 7046 allowed = true; 7047 } 7048 if (allowed) { 7049 if (!mSharedLibraries.containsKey(name)) { 7050 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7051 } else if (!name.equals(pkg.packageName)) { 7052 Slog.w(TAG, "Package " + pkg.packageName + " library " 7053 + name + " already exists; skipping"); 7054 } 7055 } else { 7056 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7057 + name + " that is not declared on system image; skipping"); 7058 } 7059 } 7060 if ((scanFlags & SCAN_BOOTING) == 0) { 7061 // If we are not booting, we need to update any applications 7062 // that are clients of our shared library. If we are booting, 7063 // this will all be done once the scan is complete. 7064 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7065 } 7066 } 7067 } 7068 } 7069 7070 // Request the ActivityManager to kill the process(only for existing packages) 7071 // so that we do not end up in a confused state while the user is still using the older 7072 // version of the application while the new one gets installed. 7073 if ((scanFlags & SCAN_REPLACING) != 0) { 7074 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7075 7076 killApplication(pkg.applicationInfo.packageName, 7077 pkg.applicationInfo.uid, "replace pkg"); 7078 7079 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7080 } 7081 7082 // Also need to kill any apps that are dependent on the library. 7083 if (clientLibPkgs != null) { 7084 for (int i=0; i<clientLibPkgs.size(); i++) { 7085 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7086 killApplication(clientPkg.applicationInfo.packageName, 7087 clientPkg.applicationInfo.uid, "update lib"); 7088 } 7089 } 7090 7091 // Make sure we're not adding any bogus keyset info 7092 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7093 ksms.assertScannedPackageValid(pkg); 7094 7095 // writer 7096 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7097 7098 boolean createIdmapFailed = false; 7099 synchronized (mPackages) { 7100 // We don't expect installation to fail beyond this point 7101 7102 // Add the new setting to mSettings 7103 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7104 // Add the new setting to mPackages 7105 mPackages.put(pkg.applicationInfo.packageName, pkg); 7106 // Make sure we don't accidentally delete its data. 7107 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7108 while (iter.hasNext()) { 7109 PackageCleanItem item = iter.next(); 7110 if (pkgName.equals(item.packageName)) { 7111 iter.remove(); 7112 } 7113 } 7114 7115 // Take care of first install / last update times. 7116 if (currentTime != 0) { 7117 if (pkgSetting.firstInstallTime == 0) { 7118 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7119 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7120 pkgSetting.lastUpdateTime = currentTime; 7121 } 7122 } else if (pkgSetting.firstInstallTime == 0) { 7123 // We need *something*. Take time time stamp of the file. 7124 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7125 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7126 if (scanFileTime != pkgSetting.timeStamp) { 7127 // A package on the system image has changed; consider this 7128 // to be an update. 7129 pkgSetting.lastUpdateTime = scanFileTime; 7130 } 7131 } 7132 7133 // Add the package's KeySets to the global KeySetManagerService 7134 ksms.addScannedPackageLPw(pkg); 7135 7136 int N = pkg.providers.size(); 7137 StringBuilder r = null; 7138 int i; 7139 for (i=0; i<N; i++) { 7140 PackageParser.Provider p = pkg.providers.get(i); 7141 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7142 p.info.processName, pkg.applicationInfo.uid); 7143 mProviders.addProvider(p); 7144 p.syncable = p.info.isSyncable; 7145 if (p.info.authority != null) { 7146 String names[] = p.info.authority.split(";"); 7147 p.info.authority = null; 7148 for (int j = 0; j < names.length; j++) { 7149 if (j == 1 && p.syncable) { 7150 // We only want the first authority for a provider to possibly be 7151 // syncable, so if we already added this provider using a different 7152 // authority clear the syncable flag. We copy the provider before 7153 // changing it because the mProviders object contains a reference 7154 // to a provider that we don't want to change. 7155 // Only do this for the second authority since the resulting provider 7156 // object can be the same for all future authorities for this provider. 7157 p = new PackageParser.Provider(p); 7158 p.syncable = false; 7159 } 7160 if (!mProvidersByAuthority.containsKey(names[j])) { 7161 mProvidersByAuthority.put(names[j], p); 7162 if (p.info.authority == null) { 7163 p.info.authority = names[j]; 7164 } else { 7165 p.info.authority = p.info.authority + ";" + names[j]; 7166 } 7167 if (DEBUG_PACKAGE_SCANNING) { 7168 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7169 Log.d(TAG, "Registered content provider: " + names[j] 7170 + ", className = " + p.info.name + ", isSyncable = " 7171 + p.info.isSyncable); 7172 } 7173 } else { 7174 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7175 Slog.w(TAG, "Skipping provider name " + names[j] + 7176 " (in package " + pkg.applicationInfo.packageName + 7177 "): name already used by " 7178 + ((other != null && other.getComponentName() != null) 7179 ? other.getComponentName().getPackageName() : "?")); 7180 } 7181 } 7182 } 7183 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7184 if (r == null) { 7185 r = new StringBuilder(256); 7186 } else { 7187 r.append(' '); 7188 } 7189 r.append(p.info.name); 7190 } 7191 } 7192 if (r != null) { 7193 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7194 } 7195 7196 N = pkg.services.size(); 7197 r = null; 7198 for (i=0; i<N; i++) { 7199 PackageParser.Service s = pkg.services.get(i); 7200 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7201 s.info.processName, pkg.applicationInfo.uid); 7202 mServices.addService(s); 7203 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7204 if (r == null) { 7205 r = new StringBuilder(256); 7206 } else { 7207 r.append(' '); 7208 } 7209 r.append(s.info.name); 7210 } 7211 } 7212 if (r != null) { 7213 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7214 } 7215 7216 N = pkg.receivers.size(); 7217 r = null; 7218 for (i=0; i<N; i++) { 7219 PackageParser.Activity a = pkg.receivers.get(i); 7220 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7221 a.info.processName, pkg.applicationInfo.uid); 7222 mReceivers.addActivity(a, "receiver"); 7223 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7224 if (r == null) { 7225 r = new StringBuilder(256); 7226 } else { 7227 r.append(' '); 7228 } 7229 r.append(a.info.name); 7230 } 7231 } 7232 if (r != null) { 7233 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7234 } 7235 7236 N = pkg.activities.size(); 7237 r = null; 7238 for (i=0; i<N; i++) { 7239 PackageParser.Activity a = pkg.activities.get(i); 7240 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7241 a.info.processName, pkg.applicationInfo.uid); 7242 mActivities.addActivity(a, "activity"); 7243 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7244 if (r == null) { 7245 r = new StringBuilder(256); 7246 } else { 7247 r.append(' '); 7248 } 7249 r.append(a.info.name); 7250 } 7251 } 7252 if (r != null) { 7253 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7254 } 7255 7256 N = pkg.permissionGroups.size(); 7257 r = null; 7258 for (i=0; i<N; i++) { 7259 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7260 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7261 if (cur == null) { 7262 mPermissionGroups.put(pg.info.name, pg); 7263 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7264 if (r == null) { 7265 r = new StringBuilder(256); 7266 } else { 7267 r.append(' '); 7268 } 7269 r.append(pg.info.name); 7270 } 7271 } else { 7272 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7273 + pg.info.packageName + " ignored: original from " 7274 + cur.info.packageName); 7275 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7276 if (r == null) { 7277 r = new StringBuilder(256); 7278 } else { 7279 r.append(' '); 7280 } 7281 r.append("DUP:"); 7282 r.append(pg.info.name); 7283 } 7284 } 7285 } 7286 if (r != null) { 7287 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7288 } 7289 7290 N = pkg.permissions.size(); 7291 r = null; 7292 for (i=0; i<N; i++) { 7293 PackageParser.Permission p = pkg.permissions.get(i); 7294 7295 // Assume by default that we did not install this permission into the system. 7296 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7297 7298 // Now that permission groups have a special meaning, we ignore permission 7299 // groups for legacy apps to prevent unexpected behavior. In particular, 7300 // permissions for one app being granted to someone just becuase they happen 7301 // to be in a group defined by another app (before this had no implications). 7302 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7303 p.group = mPermissionGroups.get(p.info.group); 7304 // Warn for a permission in an unknown group. 7305 if (p.info.group != null && p.group == null) { 7306 Slog.w(TAG, "Permission " + p.info.name + " from package " 7307 + p.info.packageName + " in an unknown group " + p.info.group); 7308 } 7309 } 7310 7311 ArrayMap<String, BasePermission> permissionMap = 7312 p.tree ? mSettings.mPermissionTrees 7313 : mSettings.mPermissions; 7314 BasePermission bp = permissionMap.get(p.info.name); 7315 7316 // Allow system apps to redefine non-system permissions 7317 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7318 final boolean currentOwnerIsSystem = (bp.perm != null 7319 && isSystemApp(bp.perm.owner)); 7320 if (isSystemApp(p.owner)) { 7321 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7322 // It's a built-in permission and no owner, take ownership now 7323 bp.packageSetting = pkgSetting; 7324 bp.perm = p; 7325 bp.uid = pkg.applicationInfo.uid; 7326 bp.sourcePackage = p.info.packageName; 7327 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7328 } else if (!currentOwnerIsSystem) { 7329 String msg = "New decl " + p.owner + " of permission " 7330 + p.info.name + " is system; overriding " + bp.sourcePackage; 7331 reportSettingsProblem(Log.WARN, msg); 7332 bp = null; 7333 } 7334 } 7335 } 7336 7337 if (bp == null) { 7338 bp = new BasePermission(p.info.name, p.info.packageName, 7339 BasePermission.TYPE_NORMAL); 7340 permissionMap.put(p.info.name, bp); 7341 } 7342 7343 if (bp.perm == null) { 7344 if (bp.sourcePackage == null 7345 || bp.sourcePackage.equals(p.info.packageName)) { 7346 BasePermission tree = findPermissionTreeLP(p.info.name); 7347 if (tree == null 7348 || tree.sourcePackage.equals(p.info.packageName)) { 7349 bp.packageSetting = pkgSetting; 7350 bp.perm = p; 7351 bp.uid = pkg.applicationInfo.uid; 7352 bp.sourcePackage = p.info.packageName; 7353 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7354 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7355 if (r == null) { 7356 r = new StringBuilder(256); 7357 } else { 7358 r.append(' '); 7359 } 7360 r.append(p.info.name); 7361 } 7362 } else { 7363 Slog.w(TAG, "Permission " + p.info.name + " from package " 7364 + p.info.packageName + " ignored: base tree " 7365 + tree.name + " is from package " 7366 + tree.sourcePackage); 7367 } 7368 } else { 7369 Slog.w(TAG, "Permission " + p.info.name + " from package " 7370 + p.info.packageName + " ignored: original from " 7371 + bp.sourcePackage); 7372 } 7373 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7374 if (r == null) { 7375 r = new StringBuilder(256); 7376 } else { 7377 r.append(' '); 7378 } 7379 r.append("DUP:"); 7380 r.append(p.info.name); 7381 } 7382 if (bp.perm == p) { 7383 bp.protectionLevel = p.info.protectionLevel; 7384 } 7385 } 7386 7387 if (r != null) { 7388 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7389 } 7390 7391 N = pkg.instrumentation.size(); 7392 r = null; 7393 for (i=0; i<N; i++) { 7394 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7395 a.info.packageName = pkg.applicationInfo.packageName; 7396 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7397 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7398 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7399 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7400 a.info.dataDir = pkg.applicationInfo.dataDir; 7401 7402 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7403 // need other information about the application, like the ABI and what not ? 7404 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7405 mInstrumentation.put(a.getComponentName(), a); 7406 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7407 if (r == null) { 7408 r = new StringBuilder(256); 7409 } else { 7410 r.append(' '); 7411 } 7412 r.append(a.info.name); 7413 } 7414 } 7415 if (r != null) { 7416 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7417 } 7418 7419 if (pkg.protectedBroadcasts != null) { 7420 N = pkg.protectedBroadcasts.size(); 7421 for (i=0; i<N; i++) { 7422 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7423 } 7424 } 7425 7426 pkgSetting.setTimeStamp(scanFileTime); 7427 7428 // Create idmap files for pairs of (packages, overlay packages). 7429 // Note: "android", ie framework-res.apk, is handled by native layers. 7430 if (pkg.mOverlayTarget != null) { 7431 // This is an overlay package. 7432 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7433 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7434 mOverlays.put(pkg.mOverlayTarget, 7435 new ArrayMap<String, PackageParser.Package>()); 7436 } 7437 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7438 map.put(pkg.packageName, pkg); 7439 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7440 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7441 createIdmapFailed = true; 7442 } 7443 } 7444 } else if (mOverlays.containsKey(pkg.packageName) && 7445 !pkg.packageName.equals("android")) { 7446 // This is a regular package, with one or more known overlay packages. 7447 createIdmapsForPackageLI(pkg); 7448 } 7449 } 7450 7451 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7452 7453 if (createIdmapFailed) { 7454 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7455 "scanPackageLI failed to createIdmap"); 7456 } 7457 return pkg; 7458 } 7459 7460 /** 7461 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7462 * is derived purely on the basis of the contents of {@code scanFile} and 7463 * {@code cpuAbiOverride}. 7464 * 7465 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7466 */ 7467 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7468 String cpuAbiOverride, boolean extractLibs) 7469 throws PackageManagerException { 7470 // TODO: We can probably be smarter about this stuff. For installed apps, 7471 // we can calculate this information at install time once and for all. For 7472 // system apps, we can probably assume that this information doesn't change 7473 // after the first boot scan. As things stand, we do lots of unnecessary work. 7474 7475 // Give ourselves some initial paths; we'll come back for another 7476 // pass once we've determined ABI below. 7477 setNativeLibraryPaths(pkg); 7478 7479 // We would never need to extract libs for forward-locked and external packages, 7480 // since the container service will do it for us. We shouldn't attempt to 7481 // extract libs from system app when it was not updated. 7482 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7483 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7484 extractLibs = false; 7485 } 7486 7487 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7488 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7489 7490 NativeLibraryHelper.Handle handle = null; 7491 try { 7492 handle = NativeLibraryHelper.Handle.create(pkg); 7493 // TODO(multiArch): This can be null for apps that didn't go through the 7494 // usual installation process. We can calculate it again, like we 7495 // do during install time. 7496 // 7497 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7498 // unnecessary. 7499 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7500 7501 // Null out the abis so that they can be recalculated. 7502 pkg.applicationInfo.primaryCpuAbi = null; 7503 pkg.applicationInfo.secondaryCpuAbi = null; 7504 if (isMultiArch(pkg.applicationInfo)) { 7505 // Warn if we've set an abiOverride for multi-lib packages.. 7506 // By definition, we need to copy both 32 and 64 bit libraries for 7507 // such packages. 7508 if (pkg.cpuAbiOverride != null 7509 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7510 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7511 } 7512 7513 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7514 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7515 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7516 if (extractLibs) { 7517 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7518 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7519 useIsaSpecificSubdirs); 7520 } else { 7521 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7522 } 7523 } 7524 7525 maybeThrowExceptionForMultiArchCopy( 7526 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7527 7528 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7529 if (extractLibs) { 7530 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7531 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7532 useIsaSpecificSubdirs); 7533 } else { 7534 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7535 } 7536 } 7537 7538 maybeThrowExceptionForMultiArchCopy( 7539 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7540 7541 if (abi64 >= 0) { 7542 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7543 } 7544 7545 if (abi32 >= 0) { 7546 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7547 if (abi64 >= 0) { 7548 pkg.applicationInfo.secondaryCpuAbi = abi; 7549 } else { 7550 pkg.applicationInfo.primaryCpuAbi = abi; 7551 } 7552 } 7553 } else { 7554 String[] abiList = (cpuAbiOverride != null) ? 7555 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7556 7557 // Enable gross and lame hacks for apps that are built with old 7558 // SDK tools. We must scan their APKs for renderscript bitcode and 7559 // not launch them if it's present. Don't bother checking on devices 7560 // that don't have 64 bit support. 7561 boolean needsRenderScriptOverride = false; 7562 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7563 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7564 abiList = Build.SUPPORTED_32_BIT_ABIS; 7565 needsRenderScriptOverride = true; 7566 } 7567 7568 final int copyRet; 7569 if (extractLibs) { 7570 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7571 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7572 } else { 7573 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7574 } 7575 7576 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7577 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7578 "Error unpackaging native libs for app, errorCode=" + copyRet); 7579 } 7580 7581 if (copyRet >= 0) { 7582 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7583 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7584 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7585 } else if (needsRenderScriptOverride) { 7586 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7587 } 7588 } 7589 } catch (IOException ioe) { 7590 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7591 } finally { 7592 IoUtils.closeQuietly(handle); 7593 } 7594 7595 // Now that we've calculated the ABIs and determined if it's an internal app, 7596 // we will go ahead and populate the nativeLibraryPath. 7597 setNativeLibraryPaths(pkg); 7598 } 7599 7600 /** 7601 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7602 * i.e, so that all packages can be run inside a single process if required. 7603 * 7604 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7605 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7606 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7607 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7608 * updating a package that belongs to a shared user. 7609 * 7610 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7611 * adds unnecessary complexity. 7612 */ 7613 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7614 PackageParser.Package scannedPackage, boolean bootComplete) { 7615 String requiredInstructionSet = null; 7616 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7617 requiredInstructionSet = VMRuntime.getInstructionSet( 7618 scannedPackage.applicationInfo.primaryCpuAbi); 7619 } 7620 7621 PackageSetting requirer = null; 7622 for (PackageSetting ps : packagesForUser) { 7623 // If packagesForUser contains scannedPackage, we skip it. This will happen 7624 // when scannedPackage is an update of an existing package. Without this check, 7625 // we will never be able to change the ABI of any package belonging to a shared 7626 // user, even if it's compatible with other packages. 7627 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7628 if (ps.primaryCpuAbiString == null) { 7629 continue; 7630 } 7631 7632 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7633 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7634 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7635 // this but there's not much we can do. 7636 String errorMessage = "Instruction set mismatch, " 7637 + ((requirer == null) ? "[caller]" : requirer) 7638 + " requires " + requiredInstructionSet + " whereas " + ps 7639 + " requires " + instructionSet; 7640 Slog.w(TAG, errorMessage); 7641 } 7642 7643 if (requiredInstructionSet == null) { 7644 requiredInstructionSet = instructionSet; 7645 requirer = ps; 7646 } 7647 } 7648 } 7649 7650 if (requiredInstructionSet != null) { 7651 String adjustedAbi; 7652 if (requirer != null) { 7653 // requirer != null implies that either scannedPackage was null or that scannedPackage 7654 // did not require an ABI, in which case we have to adjust scannedPackage to match 7655 // the ABI of the set (which is the same as requirer's ABI) 7656 adjustedAbi = requirer.primaryCpuAbiString; 7657 if (scannedPackage != null) { 7658 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7659 } 7660 } else { 7661 // requirer == null implies that we're updating all ABIs in the set to 7662 // match scannedPackage. 7663 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7664 } 7665 7666 for (PackageSetting ps : packagesForUser) { 7667 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7668 if (ps.primaryCpuAbiString != null) { 7669 continue; 7670 } 7671 7672 ps.primaryCpuAbiString = adjustedAbi; 7673 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7674 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7675 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7676 mInstaller.rmdex(ps.codePathString, 7677 getDexCodeInstructionSet(getPreferredInstructionSet())); 7678 } 7679 } 7680 } 7681 } 7682 } 7683 7684 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7685 synchronized (mPackages) { 7686 mResolverReplaced = true; 7687 // Set up information for custom user intent resolution activity. 7688 mResolveActivity.applicationInfo = pkg.applicationInfo; 7689 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7690 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7691 mResolveActivity.processName = pkg.applicationInfo.packageName; 7692 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7693 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7694 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7695 mResolveActivity.theme = 0; 7696 mResolveActivity.exported = true; 7697 mResolveActivity.enabled = true; 7698 mResolveInfo.activityInfo = mResolveActivity; 7699 mResolveInfo.priority = 0; 7700 mResolveInfo.preferredOrder = 0; 7701 mResolveInfo.match = 0; 7702 mResolveComponentName = mCustomResolverComponentName; 7703 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7704 mResolveComponentName); 7705 } 7706 } 7707 7708 private static String calculateBundledApkRoot(final String codePathString) { 7709 final File codePath = new File(codePathString); 7710 final File codeRoot; 7711 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7712 codeRoot = Environment.getRootDirectory(); 7713 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7714 codeRoot = Environment.getOemDirectory(); 7715 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7716 codeRoot = Environment.getVendorDirectory(); 7717 } else { 7718 // Unrecognized code path; take its top real segment as the apk root: 7719 // e.g. /something/app/blah.apk => /something 7720 try { 7721 File f = codePath.getCanonicalFile(); 7722 File parent = f.getParentFile(); // non-null because codePath is a file 7723 File tmp; 7724 while ((tmp = parent.getParentFile()) != null) { 7725 f = parent; 7726 parent = tmp; 7727 } 7728 codeRoot = f; 7729 Slog.w(TAG, "Unrecognized code path " 7730 + codePath + " - using " + codeRoot); 7731 } catch (IOException e) { 7732 // Can't canonicalize the code path -- shenanigans? 7733 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7734 return Environment.getRootDirectory().getPath(); 7735 } 7736 } 7737 return codeRoot.getPath(); 7738 } 7739 7740 /** 7741 * Derive and set the location of native libraries for the given package, 7742 * which varies depending on where and how the package was installed. 7743 */ 7744 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7745 final ApplicationInfo info = pkg.applicationInfo; 7746 final String codePath = pkg.codePath; 7747 final File codeFile = new File(codePath); 7748 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7749 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7750 7751 info.nativeLibraryRootDir = null; 7752 info.nativeLibraryRootRequiresIsa = false; 7753 info.nativeLibraryDir = null; 7754 info.secondaryNativeLibraryDir = null; 7755 7756 if (isApkFile(codeFile)) { 7757 // Monolithic install 7758 if (bundledApp) { 7759 // If "/system/lib64/apkname" exists, assume that is the per-package 7760 // native library directory to use; otherwise use "/system/lib/apkname". 7761 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7762 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7763 getPrimaryInstructionSet(info)); 7764 7765 // This is a bundled system app so choose the path based on the ABI. 7766 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7767 // is just the default path. 7768 final String apkName = deriveCodePathName(codePath); 7769 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7770 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7771 apkName).getAbsolutePath(); 7772 7773 if (info.secondaryCpuAbi != null) { 7774 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7775 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7776 secondaryLibDir, apkName).getAbsolutePath(); 7777 } 7778 } else if (asecApp) { 7779 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7780 .getAbsolutePath(); 7781 } else { 7782 final String apkName = deriveCodePathName(codePath); 7783 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7784 .getAbsolutePath(); 7785 } 7786 7787 info.nativeLibraryRootRequiresIsa = false; 7788 info.nativeLibraryDir = info.nativeLibraryRootDir; 7789 } else { 7790 // Cluster install 7791 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7792 info.nativeLibraryRootRequiresIsa = true; 7793 7794 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7795 getPrimaryInstructionSet(info)).getAbsolutePath(); 7796 7797 if (info.secondaryCpuAbi != null) { 7798 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7799 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7800 } 7801 } 7802 } 7803 7804 /** 7805 * Calculate the abis and roots for a bundled app. These can uniquely 7806 * be determined from the contents of the system partition, i.e whether 7807 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7808 * of this information, and instead assume that the system was built 7809 * sensibly. 7810 */ 7811 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7812 PackageSetting pkgSetting) { 7813 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7814 7815 // If "/system/lib64/apkname" exists, assume that is the per-package 7816 // native library directory to use; otherwise use "/system/lib/apkname". 7817 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7818 setBundledAppAbi(pkg, apkRoot, apkName); 7819 // pkgSetting might be null during rescan following uninstall of updates 7820 // to a bundled app, so accommodate that possibility. The settings in 7821 // that case will be established later from the parsed package. 7822 // 7823 // If the settings aren't null, sync them up with what we've just derived. 7824 // note that apkRoot isn't stored in the package settings. 7825 if (pkgSetting != null) { 7826 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7827 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7828 } 7829 } 7830 7831 /** 7832 * Deduces the ABI of a bundled app and sets the relevant fields on the 7833 * parsed pkg object. 7834 * 7835 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7836 * under which system libraries are installed. 7837 * @param apkName the name of the installed package. 7838 */ 7839 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7840 final File codeFile = new File(pkg.codePath); 7841 7842 final boolean has64BitLibs; 7843 final boolean has32BitLibs; 7844 if (isApkFile(codeFile)) { 7845 // Monolithic install 7846 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7847 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7848 } else { 7849 // Cluster install 7850 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7851 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7852 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7853 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7854 has64BitLibs = (new File(rootDir, isa)).exists(); 7855 } else { 7856 has64BitLibs = false; 7857 } 7858 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7859 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7860 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7861 has32BitLibs = (new File(rootDir, isa)).exists(); 7862 } else { 7863 has32BitLibs = false; 7864 } 7865 } 7866 7867 if (has64BitLibs && !has32BitLibs) { 7868 // The package has 64 bit libs, but not 32 bit libs. Its primary 7869 // ABI should be 64 bit. We can safely assume here that the bundled 7870 // native libraries correspond to the most preferred ABI in the list. 7871 7872 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7873 pkg.applicationInfo.secondaryCpuAbi = null; 7874 } else if (has32BitLibs && !has64BitLibs) { 7875 // The package has 32 bit libs but not 64 bit libs. Its primary 7876 // ABI should be 32 bit. 7877 7878 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7879 pkg.applicationInfo.secondaryCpuAbi = null; 7880 } else if (has32BitLibs && has64BitLibs) { 7881 // The application has both 64 and 32 bit bundled libraries. We check 7882 // here that the app declares multiArch support, and warn if it doesn't. 7883 // 7884 // We will be lenient here and record both ABIs. The primary will be the 7885 // ABI that's higher on the list, i.e, a device that's configured to prefer 7886 // 64 bit apps will see a 64 bit primary ABI, 7887 7888 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7889 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7890 } 7891 7892 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7893 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7894 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7895 } else { 7896 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7897 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7898 } 7899 } else { 7900 pkg.applicationInfo.primaryCpuAbi = null; 7901 pkg.applicationInfo.secondaryCpuAbi = null; 7902 } 7903 } 7904 7905 private void killApplication(String pkgName, int appId, String reason) { 7906 // Request the ActivityManager to kill the process(only for existing packages) 7907 // so that we do not end up in a confused state while the user is still using the older 7908 // version of the application while the new one gets installed. 7909 IActivityManager am = ActivityManagerNative.getDefault(); 7910 if (am != null) { 7911 try { 7912 am.killApplicationWithAppId(pkgName, appId, reason); 7913 } catch (RemoteException e) { 7914 } 7915 } 7916 } 7917 7918 void removePackageLI(PackageSetting ps, boolean chatty) { 7919 if (DEBUG_INSTALL) { 7920 if (chatty) 7921 Log.d(TAG, "Removing package " + ps.name); 7922 } 7923 7924 // writer 7925 synchronized (mPackages) { 7926 mPackages.remove(ps.name); 7927 final PackageParser.Package pkg = ps.pkg; 7928 if (pkg != null) { 7929 cleanPackageDataStructuresLILPw(pkg, chatty); 7930 } 7931 } 7932 } 7933 7934 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7935 if (DEBUG_INSTALL) { 7936 if (chatty) 7937 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7938 } 7939 7940 // writer 7941 synchronized (mPackages) { 7942 mPackages.remove(pkg.applicationInfo.packageName); 7943 cleanPackageDataStructuresLILPw(pkg, chatty); 7944 } 7945 } 7946 7947 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7948 int N = pkg.providers.size(); 7949 StringBuilder r = null; 7950 int i; 7951 for (i=0; i<N; i++) { 7952 PackageParser.Provider p = pkg.providers.get(i); 7953 mProviders.removeProvider(p); 7954 if (p.info.authority == null) { 7955 7956 /* There was another ContentProvider with this authority when 7957 * this app was installed so this authority is null, 7958 * Ignore it as we don't have to unregister the provider. 7959 */ 7960 continue; 7961 } 7962 String names[] = p.info.authority.split(";"); 7963 for (int j = 0; j < names.length; j++) { 7964 if (mProvidersByAuthority.get(names[j]) == p) { 7965 mProvidersByAuthority.remove(names[j]); 7966 if (DEBUG_REMOVE) { 7967 if (chatty) 7968 Log.d(TAG, "Unregistered content provider: " + names[j] 7969 + ", className = " + p.info.name + ", isSyncable = " 7970 + p.info.isSyncable); 7971 } 7972 } 7973 } 7974 if (DEBUG_REMOVE && chatty) { 7975 if (r == null) { 7976 r = new StringBuilder(256); 7977 } else { 7978 r.append(' '); 7979 } 7980 r.append(p.info.name); 7981 } 7982 } 7983 if (r != null) { 7984 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7985 } 7986 7987 N = pkg.services.size(); 7988 r = null; 7989 for (i=0; i<N; i++) { 7990 PackageParser.Service s = pkg.services.get(i); 7991 mServices.removeService(s); 7992 if (chatty) { 7993 if (r == null) { 7994 r = new StringBuilder(256); 7995 } else { 7996 r.append(' '); 7997 } 7998 r.append(s.info.name); 7999 } 8000 } 8001 if (r != null) { 8002 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8003 } 8004 8005 N = pkg.receivers.size(); 8006 r = null; 8007 for (i=0; i<N; i++) { 8008 PackageParser.Activity a = pkg.receivers.get(i); 8009 mReceivers.removeActivity(a, "receiver"); 8010 if (DEBUG_REMOVE && chatty) { 8011 if (r == null) { 8012 r = new StringBuilder(256); 8013 } else { 8014 r.append(' '); 8015 } 8016 r.append(a.info.name); 8017 } 8018 } 8019 if (r != null) { 8020 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8021 } 8022 8023 N = pkg.activities.size(); 8024 r = null; 8025 for (i=0; i<N; i++) { 8026 PackageParser.Activity a = pkg.activities.get(i); 8027 mActivities.removeActivity(a, "activity"); 8028 if (DEBUG_REMOVE && chatty) { 8029 if (r == null) { 8030 r = new StringBuilder(256); 8031 } else { 8032 r.append(' '); 8033 } 8034 r.append(a.info.name); 8035 } 8036 } 8037 if (r != null) { 8038 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8039 } 8040 8041 N = pkg.permissions.size(); 8042 r = null; 8043 for (i=0; i<N; i++) { 8044 PackageParser.Permission p = pkg.permissions.get(i); 8045 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8046 if (bp == null) { 8047 bp = mSettings.mPermissionTrees.get(p.info.name); 8048 } 8049 if (bp != null && bp.perm == p) { 8050 bp.perm = null; 8051 if (DEBUG_REMOVE && chatty) { 8052 if (r == null) { 8053 r = new StringBuilder(256); 8054 } else { 8055 r.append(' '); 8056 } 8057 r.append(p.info.name); 8058 } 8059 } 8060 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8061 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8062 if (appOpPerms != null) { 8063 appOpPerms.remove(pkg.packageName); 8064 } 8065 } 8066 } 8067 if (r != null) { 8068 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8069 } 8070 8071 N = pkg.requestedPermissions.size(); 8072 r = null; 8073 for (i=0; i<N; i++) { 8074 String perm = pkg.requestedPermissions.get(i); 8075 BasePermission bp = mSettings.mPermissions.get(perm); 8076 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8077 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8078 if (appOpPerms != null) { 8079 appOpPerms.remove(pkg.packageName); 8080 if (appOpPerms.isEmpty()) { 8081 mAppOpPermissionPackages.remove(perm); 8082 } 8083 } 8084 } 8085 } 8086 if (r != null) { 8087 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8088 } 8089 8090 N = pkg.instrumentation.size(); 8091 r = null; 8092 for (i=0; i<N; i++) { 8093 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8094 mInstrumentation.remove(a.getComponentName()); 8095 if (DEBUG_REMOVE && chatty) { 8096 if (r == null) { 8097 r = new StringBuilder(256); 8098 } else { 8099 r.append(' '); 8100 } 8101 r.append(a.info.name); 8102 } 8103 } 8104 if (r != null) { 8105 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8106 } 8107 8108 r = null; 8109 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8110 // Only system apps can hold shared libraries. 8111 if (pkg.libraryNames != null) { 8112 for (i=0; i<pkg.libraryNames.size(); i++) { 8113 String name = pkg.libraryNames.get(i); 8114 SharedLibraryEntry cur = mSharedLibraries.get(name); 8115 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8116 mSharedLibraries.remove(name); 8117 if (DEBUG_REMOVE && chatty) { 8118 if (r == null) { 8119 r = new StringBuilder(256); 8120 } else { 8121 r.append(' '); 8122 } 8123 r.append(name); 8124 } 8125 } 8126 } 8127 } 8128 } 8129 if (r != null) { 8130 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8131 } 8132 } 8133 8134 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8135 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8136 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8137 return true; 8138 } 8139 } 8140 return false; 8141 } 8142 8143 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8144 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8145 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8146 8147 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8148 int flags) { 8149 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8150 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8151 } 8152 8153 private void updatePermissionsLPw(String changingPkg, 8154 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8155 // Make sure there are no dangling permission trees. 8156 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8157 while (it.hasNext()) { 8158 final BasePermission bp = it.next(); 8159 if (bp.packageSetting == null) { 8160 // We may not yet have parsed the package, so just see if 8161 // we still know about its settings. 8162 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8163 } 8164 if (bp.packageSetting == null) { 8165 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8166 + " from package " + bp.sourcePackage); 8167 it.remove(); 8168 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8169 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8170 Slog.i(TAG, "Removing old permission tree: " + bp.name 8171 + " from package " + bp.sourcePackage); 8172 flags |= UPDATE_PERMISSIONS_ALL; 8173 it.remove(); 8174 } 8175 } 8176 } 8177 8178 // Make sure all dynamic permissions have been assigned to a package, 8179 // and make sure there are no dangling permissions. 8180 it = mSettings.mPermissions.values().iterator(); 8181 while (it.hasNext()) { 8182 final BasePermission bp = it.next(); 8183 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8184 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8185 + bp.name + " pkg=" + bp.sourcePackage 8186 + " info=" + bp.pendingInfo); 8187 if (bp.packageSetting == null && bp.pendingInfo != null) { 8188 final BasePermission tree = findPermissionTreeLP(bp.name); 8189 if (tree != null && tree.perm != null) { 8190 bp.packageSetting = tree.packageSetting; 8191 bp.perm = new PackageParser.Permission(tree.perm.owner, 8192 new PermissionInfo(bp.pendingInfo)); 8193 bp.perm.info.packageName = tree.perm.info.packageName; 8194 bp.perm.info.name = bp.name; 8195 bp.uid = tree.uid; 8196 } 8197 } 8198 } 8199 if (bp.packageSetting == null) { 8200 // We may not yet have parsed the package, so just see if 8201 // we still know about its settings. 8202 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8203 } 8204 if (bp.packageSetting == null) { 8205 Slog.w(TAG, "Removing dangling permission: " + bp.name 8206 + " from package " + bp.sourcePackage); 8207 it.remove(); 8208 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8209 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8210 Slog.i(TAG, "Removing old permission: " + bp.name 8211 + " from package " + bp.sourcePackage); 8212 flags |= UPDATE_PERMISSIONS_ALL; 8213 it.remove(); 8214 } 8215 } 8216 } 8217 8218 // Now update the permissions for all packages, in particular 8219 // replace the granted permissions of the system packages. 8220 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8221 for (PackageParser.Package pkg : mPackages.values()) { 8222 if (pkg != pkgInfo) { 8223 // Only replace for packages on requested volume 8224 final String volumeUuid = getVolumeUuidForPackage(pkg); 8225 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8226 && Objects.equals(replaceVolumeUuid, volumeUuid); 8227 grantPermissionsLPw(pkg, replace, changingPkg); 8228 } 8229 } 8230 } 8231 8232 if (pkgInfo != null) { 8233 // Only replace for packages on requested volume 8234 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8235 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8236 && Objects.equals(replaceVolumeUuid, volumeUuid); 8237 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8238 } 8239 } 8240 8241 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8242 String packageOfInterest) { 8243 // IMPORTANT: There are two types of permissions: install and runtime. 8244 // Install time permissions are granted when the app is installed to 8245 // all device users and users added in the future. Runtime permissions 8246 // are granted at runtime explicitly to specific users. Normal and signature 8247 // protected permissions are install time permissions. Dangerous permissions 8248 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8249 // otherwise they are runtime permissions. This function does not manage 8250 // runtime permissions except for the case an app targeting Lollipop MR1 8251 // being upgraded to target a newer SDK, in which case dangerous permissions 8252 // are transformed from install time to runtime ones. 8253 8254 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8255 if (ps == null) { 8256 return; 8257 } 8258 8259 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8260 8261 PermissionsState permissionsState = ps.getPermissionsState(); 8262 PermissionsState origPermissions = permissionsState; 8263 8264 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8265 8266 boolean runtimePermissionsRevoked = false; 8267 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8268 8269 boolean changedInstallPermission = false; 8270 8271 if (replace) { 8272 ps.installPermissionsFixed = false; 8273 if (!ps.isSharedUser()) { 8274 origPermissions = new PermissionsState(permissionsState); 8275 permissionsState.reset(); 8276 } else { 8277 // We need to know only about runtime permission changes since the 8278 // calling code always writes the install permissions state but 8279 // the runtime ones are written only if changed. The only cases of 8280 // changed runtime permissions here are promotion of an install to 8281 // runtime and revocation of a runtime from a shared user. 8282 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8283 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8284 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8285 runtimePermissionsRevoked = true; 8286 } 8287 } 8288 } 8289 8290 permissionsState.setGlobalGids(mGlobalGids); 8291 8292 final int N = pkg.requestedPermissions.size(); 8293 for (int i=0; i<N; i++) { 8294 final String name = pkg.requestedPermissions.get(i); 8295 final BasePermission bp = mSettings.mPermissions.get(name); 8296 8297 if (DEBUG_INSTALL) { 8298 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8299 } 8300 8301 if (bp == null || bp.packageSetting == null) { 8302 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8303 Slog.w(TAG, "Unknown permission " + name 8304 + " in package " + pkg.packageName); 8305 } 8306 continue; 8307 } 8308 8309 final String perm = bp.name; 8310 boolean allowedSig = false; 8311 int grant = GRANT_DENIED; 8312 8313 // Keep track of app op permissions. 8314 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8315 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8316 if (pkgs == null) { 8317 pkgs = new ArraySet<>(); 8318 mAppOpPermissionPackages.put(bp.name, pkgs); 8319 } 8320 pkgs.add(pkg.packageName); 8321 } 8322 8323 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8324 switch (level) { 8325 case PermissionInfo.PROTECTION_NORMAL: { 8326 // For all apps normal permissions are install time ones. 8327 grant = GRANT_INSTALL; 8328 } break; 8329 8330 case PermissionInfo.PROTECTION_DANGEROUS: { 8331 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8332 // For legacy apps dangerous permissions are install time ones. 8333 grant = GRANT_INSTALL_LEGACY; 8334 } else if (origPermissions.hasInstallPermission(bp.name)) { 8335 // For legacy apps that became modern, install becomes runtime. 8336 grant = GRANT_UPGRADE; 8337 } else if (mPromoteSystemApps 8338 && isSystemApp(ps) 8339 && mExistingSystemPackages.contains(ps.name)) { 8340 // For legacy system apps, install becomes runtime. 8341 // We cannot check hasInstallPermission() for system apps since those 8342 // permissions were granted implicitly and not persisted pre-M. 8343 grant = GRANT_UPGRADE; 8344 } else { 8345 // For modern apps keep runtime permissions unchanged. 8346 grant = GRANT_RUNTIME; 8347 } 8348 } break; 8349 8350 case PermissionInfo.PROTECTION_SIGNATURE: { 8351 // For all apps signature permissions are install time ones. 8352 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8353 if (allowedSig) { 8354 grant = GRANT_INSTALL; 8355 } 8356 } break; 8357 } 8358 8359 if (DEBUG_INSTALL) { 8360 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8361 } 8362 8363 if (grant != GRANT_DENIED) { 8364 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8365 // If this is an existing, non-system package, then 8366 // we can't add any new permissions to it. 8367 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8368 // Except... if this is a permission that was added 8369 // to the platform (note: need to only do this when 8370 // updating the platform). 8371 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8372 grant = GRANT_DENIED; 8373 } 8374 } 8375 } 8376 8377 switch (grant) { 8378 case GRANT_INSTALL: { 8379 // Revoke this as runtime permission to handle the case of 8380 // a runtime permission being downgraded to an install one. 8381 for (int userId : UserManagerService.getInstance().getUserIds()) { 8382 if (origPermissions.getRuntimePermissionState( 8383 bp.name, userId) != null) { 8384 // Revoke the runtime permission and clear the flags. 8385 origPermissions.revokeRuntimePermission(bp, userId); 8386 origPermissions.updatePermissionFlags(bp, userId, 8387 PackageManager.MASK_PERMISSION_FLAGS, 0); 8388 // If we revoked a permission permission, we have to write. 8389 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8390 changedRuntimePermissionUserIds, userId); 8391 } 8392 } 8393 // Grant an install permission. 8394 if (permissionsState.grantInstallPermission(bp) != 8395 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8396 changedInstallPermission = true; 8397 } 8398 } break; 8399 8400 case GRANT_INSTALL_LEGACY: { 8401 // Grant an install permission. 8402 if (permissionsState.grantInstallPermission(bp) != 8403 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8404 changedInstallPermission = true; 8405 } 8406 } break; 8407 8408 case GRANT_RUNTIME: { 8409 // Grant previously granted runtime permissions. 8410 for (int userId : UserManagerService.getInstance().getUserIds()) { 8411 PermissionState permissionState = origPermissions 8412 .getRuntimePermissionState(bp.name, userId); 8413 final int flags = permissionState != null 8414 ? permissionState.getFlags() : 0; 8415 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8416 if (permissionsState.grantRuntimePermission(bp, userId) == 8417 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8418 // If we cannot put the permission as it was, we have to write. 8419 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8420 changedRuntimePermissionUserIds, userId); 8421 } 8422 } 8423 // Propagate the permission flags. 8424 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8425 } 8426 } break; 8427 8428 case GRANT_UPGRADE: { 8429 // Grant runtime permissions for a previously held install permission. 8430 PermissionState permissionState = origPermissions 8431 .getInstallPermissionState(bp.name); 8432 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8433 8434 if (origPermissions.revokeInstallPermission(bp) 8435 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8436 // We will be transferring the permission flags, so clear them. 8437 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8438 PackageManager.MASK_PERMISSION_FLAGS, 0); 8439 changedInstallPermission = true; 8440 } 8441 8442 // If the permission is not to be promoted to runtime we ignore it and 8443 // also its other flags as they are not applicable to install permissions. 8444 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8445 for (int userId : currentUserIds) { 8446 if (permissionsState.grantRuntimePermission(bp, userId) != 8447 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8448 // Transfer the permission flags. 8449 permissionsState.updatePermissionFlags(bp, userId, 8450 flags, flags); 8451 // If we granted the permission, we have to write. 8452 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8453 changedRuntimePermissionUserIds, userId); 8454 } 8455 } 8456 } 8457 } break; 8458 8459 default: { 8460 if (packageOfInterest == null 8461 || packageOfInterest.equals(pkg.packageName)) { 8462 Slog.w(TAG, "Not granting permission " + perm 8463 + " to package " + pkg.packageName 8464 + " because it was previously installed without"); 8465 } 8466 } break; 8467 } 8468 } else { 8469 if (permissionsState.revokeInstallPermission(bp) != 8470 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8471 // Also drop the permission flags. 8472 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8473 PackageManager.MASK_PERMISSION_FLAGS, 0); 8474 changedInstallPermission = true; 8475 Slog.i(TAG, "Un-granting permission " + perm 8476 + " from package " + pkg.packageName 8477 + " (protectionLevel=" + bp.protectionLevel 8478 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8479 + ")"); 8480 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8481 // Don't print warning for app op permissions, since it is fine for them 8482 // not to be granted, there is a UI for the user to decide. 8483 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8484 Slog.w(TAG, "Not granting permission " + perm 8485 + " to package " + pkg.packageName 8486 + " (protectionLevel=" + bp.protectionLevel 8487 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8488 + ")"); 8489 } 8490 } 8491 } 8492 } 8493 8494 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8495 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8496 // This is the first that we have heard about this package, so the 8497 // permissions we have now selected are fixed until explicitly 8498 // changed. 8499 ps.installPermissionsFixed = true; 8500 } 8501 8502 // Persist the runtime permissions state for users with changes. If permissions 8503 // were revoked because no app in the shared user declares them we have to 8504 // write synchronously to avoid losing runtime permissions state. 8505 for (int userId : changedRuntimePermissionUserIds) { 8506 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8507 } 8508 8509 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8510 } 8511 8512 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8513 boolean allowed = false; 8514 final int NP = PackageParser.NEW_PERMISSIONS.length; 8515 for (int ip=0; ip<NP; ip++) { 8516 final PackageParser.NewPermissionInfo npi 8517 = PackageParser.NEW_PERMISSIONS[ip]; 8518 if (npi.name.equals(perm) 8519 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8520 allowed = true; 8521 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8522 + pkg.packageName); 8523 break; 8524 } 8525 } 8526 return allowed; 8527 } 8528 8529 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8530 BasePermission bp, PermissionsState origPermissions) { 8531 boolean allowed; 8532 allowed = (compareSignatures( 8533 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8534 == PackageManager.SIGNATURE_MATCH) 8535 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8536 == PackageManager.SIGNATURE_MATCH); 8537 if (!allowed && (bp.protectionLevel 8538 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8539 if (isSystemApp(pkg)) { 8540 // For updated system applications, a system permission 8541 // is granted only if it had been defined by the original application. 8542 if (pkg.isUpdatedSystemApp()) { 8543 final PackageSetting sysPs = mSettings 8544 .getDisabledSystemPkgLPr(pkg.packageName); 8545 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8546 // If the original was granted this permission, we take 8547 // that grant decision as read and propagate it to the 8548 // update. 8549 if (sysPs.isPrivileged()) { 8550 allowed = true; 8551 } 8552 } else { 8553 // The system apk may have been updated with an older 8554 // version of the one on the data partition, but which 8555 // granted a new system permission that it didn't have 8556 // before. In this case we do want to allow the app to 8557 // now get the new permission if the ancestral apk is 8558 // privileged to get it. 8559 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8560 for (int j=0; 8561 j<sysPs.pkg.requestedPermissions.size(); j++) { 8562 if (perm.equals( 8563 sysPs.pkg.requestedPermissions.get(j))) { 8564 allowed = true; 8565 break; 8566 } 8567 } 8568 } 8569 } 8570 } else { 8571 allowed = isPrivilegedApp(pkg); 8572 } 8573 } 8574 } 8575 if (!allowed) { 8576 if (!allowed && (bp.protectionLevel 8577 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8578 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8579 // If this was a previously normal/dangerous permission that got moved 8580 // to a system permission as part of the runtime permission redesign, then 8581 // we still want to blindly grant it to old apps. 8582 allowed = true; 8583 } 8584 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8585 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8586 // If this permission is to be granted to the system installer and 8587 // this app is an installer, then it gets the permission. 8588 allowed = true; 8589 } 8590 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8591 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8592 // If this permission is to be granted to the system verifier and 8593 // this app is a verifier, then it gets the permission. 8594 allowed = true; 8595 } 8596 if (!allowed && (bp.protectionLevel 8597 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8598 && isSystemApp(pkg)) { 8599 // Any pre-installed system app is allowed to get this permission. 8600 allowed = true; 8601 } 8602 if (!allowed && (bp.protectionLevel 8603 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8604 // For development permissions, a development permission 8605 // is granted only if it was already granted. 8606 allowed = origPermissions.hasInstallPermission(perm); 8607 } 8608 } 8609 return allowed; 8610 } 8611 8612 final class ActivityIntentResolver 8613 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8614 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8615 boolean defaultOnly, int userId) { 8616 if (!sUserManager.exists(userId)) return null; 8617 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8618 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8619 } 8620 8621 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8622 int userId) { 8623 if (!sUserManager.exists(userId)) return null; 8624 mFlags = flags; 8625 return super.queryIntent(intent, resolvedType, 8626 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8627 } 8628 8629 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8630 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8631 if (!sUserManager.exists(userId)) return null; 8632 if (packageActivities == null) { 8633 return null; 8634 } 8635 mFlags = flags; 8636 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8637 final int N = packageActivities.size(); 8638 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8639 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8640 8641 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8642 for (int i = 0; i < N; ++i) { 8643 intentFilters = packageActivities.get(i).intents; 8644 if (intentFilters != null && intentFilters.size() > 0) { 8645 PackageParser.ActivityIntentInfo[] array = 8646 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8647 intentFilters.toArray(array); 8648 listCut.add(array); 8649 } 8650 } 8651 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8652 } 8653 8654 public final void addActivity(PackageParser.Activity a, String type) { 8655 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8656 mActivities.put(a.getComponentName(), a); 8657 if (DEBUG_SHOW_INFO) 8658 Log.v( 8659 TAG, " " + type + " " + 8660 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8661 if (DEBUG_SHOW_INFO) 8662 Log.v(TAG, " Class=" + a.info.name); 8663 final int NI = a.intents.size(); 8664 for (int j=0; j<NI; j++) { 8665 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8666 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8667 intent.setPriority(0); 8668 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8669 + a.className + " with priority > 0, forcing to 0"); 8670 } 8671 if (DEBUG_SHOW_INFO) { 8672 Log.v(TAG, " IntentFilter:"); 8673 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8674 } 8675 if (!intent.debugCheck()) { 8676 Log.w(TAG, "==> For Activity " + a.info.name); 8677 } 8678 addFilter(intent); 8679 } 8680 } 8681 8682 public final void removeActivity(PackageParser.Activity a, String type) { 8683 mActivities.remove(a.getComponentName()); 8684 if (DEBUG_SHOW_INFO) { 8685 Log.v(TAG, " " + type + " " 8686 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8687 : a.info.name) + ":"); 8688 Log.v(TAG, " Class=" + a.info.name); 8689 } 8690 final int NI = a.intents.size(); 8691 for (int j=0; j<NI; j++) { 8692 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8693 if (DEBUG_SHOW_INFO) { 8694 Log.v(TAG, " IntentFilter:"); 8695 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8696 } 8697 removeFilter(intent); 8698 } 8699 } 8700 8701 @Override 8702 protected boolean allowFilterResult( 8703 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8704 ActivityInfo filterAi = filter.activity.info; 8705 for (int i=dest.size()-1; i>=0; i--) { 8706 ActivityInfo destAi = dest.get(i).activityInfo; 8707 if (destAi.name == filterAi.name 8708 && destAi.packageName == filterAi.packageName) { 8709 return false; 8710 } 8711 } 8712 return true; 8713 } 8714 8715 @Override 8716 protected ActivityIntentInfo[] newArray(int size) { 8717 return new ActivityIntentInfo[size]; 8718 } 8719 8720 @Override 8721 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8722 if (!sUserManager.exists(userId)) return true; 8723 PackageParser.Package p = filter.activity.owner; 8724 if (p != null) { 8725 PackageSetting ps = (PackageSetting)p.mExtras; 8726 if (ps != null) { 8727 // System apps are never considered stopped for purposes of 8728 // filtering, because there may be no way for the user to 8729 // actually re-launch them. 8730 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8731 && ps.getStopped(userId); 8732 } 8733 } 8734 return false; 8735 } 8736 8737 @Override 8738 protected boolean isPackageForFilter(String packageName, 8739 PackageParser.ActivityIntentInfo info) { 8740 return packageName.equals(info.activity.owner.packageName); 8741 } 8742 8743 @Override 8744 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8745 int match, int userId) { 8746 if (!sUserManager.exists(userId)) return null; 8747 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8748 return null; 8749 } 8750 final PackageParser.Activity activity = info.activity; 8751 if (mSafeMode && (activity.info.applicationInfo.flags 8752 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8753 return null; 8754 } 8755 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8756 if (ps == null) { 8757 return null; 8758 } 8759 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8760 ps.readUserState(userId), userId); 8761 if (ai == null) { 8762 return null; 8763 } 8764 final ResolveInfo res = new ResolveInfo(); 8765 res.activityInfo = ai; 8766 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8767 res.filter = info; 8768 } 8769 if (info != null) { 8770 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8771 } 8772 res.priority = info.getPriority(); 8773 res.preferredOrder = activity.owner.mPreferredOrder; 8774 //System.out.println("Result: " + res.activityInfo.className + 8775 // " = " + res.priority); 8776 res.match = match; 8777 res.isDefault = info.hasDefault; 8778 res.labelRes = info.labelRes; 8779 res.nonLocalizedLabel = info.nonLocalizedLabel; 8780 if (userNeedsBadging(userId)) { 8781 res.noResourceId = true; 8782 } else { 8783 res.icon = info.icon; 8784 } 8785 res.iconResourceId = info.icon; 8786 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8787 return res; 8788 } 8789 8790 @Override 8791 protected void sortResults(List<ResolveInfo> results) { 8792 Collections.sort(results, mResolvePrioritySorter); 8793 } 8794 8795 @Override 8796 protected void dumpFilter(PrintWriter out, String prefix, 8797 PackageParser.ActivityIntentInfo filter) { 8798 out.print(prefix); out.print( 8799 Integer.toHexString(System.identityHashCode(filter.activity))); 8800 out.print(' '); 8801 filter.activity.printComponentShortName(out); 8802 out.print(" filter "); 8803 out.println(Integer.toHexString(System.identityHashCode(filter))); 8804 } 8805 8806 @Override 8807 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8808 return filter.activity; 8809 } 8810 8811 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8812 PackageParser.Activity activity = (PackageParser.Activity)label; 8813 out.print(prefix); out.print( 8814 Integer.toHexString(System.identityHashCode(activity))); 8815 out.print(' '); 8816 activity.printComponentShortName(out); 8817 if (count > 1) { 8818 out.print(" ("); out.print(count); out.print(" filters)"); 8819 } 8820 out.println(); 8821 } 8822 8823// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8824// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8825// final List<ResolveInfo> retList = Lists.newArrayList(); 8826// while (i.hasNext()) { 8827// final ResolveInfo resolveInfo = i.next(); 8828// if (isEnabledLP(resolveInfo.activityInfo)) { 8829// retList.add(resolveInfo); 8830// } 8831// } 8832// return retList; 8833// } 8834 8835 // Keys are String (activity class name), values are Activity. 8836 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8837 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8838 private int mFlags; 8839 } 8840 8841 private final class ServiceIntentResolver 8842 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8843 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8844 boolean defaultOnly, int userId) { 8845 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8846 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8847 } 8848 8849 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8850 int userId) { 8851 if (!sUserManager.exists(userId)) return null; 8852 mFlags = flags; 8853 return super.queryIntent(intent, resolvedType, 8854 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8855 } 8856 8857 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8858 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8859 if (!sUserManager.exists(userId)) return null; 8860 if (packageServices == null) { 8861 return null; 8862 } 8863 mFlags = flags; 8864 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8865 final int N = packageServices.size(); 8866 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8867 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8868 8869 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8870 for (int i = 0; i < N; ++i) { 8871 intentFilters = packageServices.get(i).intents; 8872 if (intentFilters != null && intentFilters.size() > 0) { 8873 PackageParser.ServiceIntentInfo[] array = 8874 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8875 intentFilters.toArray(array); 8876 listCut.add(array); 8877 } 8878 } 8879 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8880 } 8881 8882 public final void addService(PackageParser.Service s) { 8883 mServices.put(s.getComponentName(), s); 8884 if (DEBUG_SHOW_INFO) { 8885 Log.v(TAG, " " 8886 + (s.info.nonLocalizedLabel != null 8887 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8888 Log.v(TAG, " Class=" + s.info.name); 8889 } 8890 final int NI = s.intents.size(); 8891 int j; 8892 for (j=0; j<NI; j++) { 8893 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8894 if (DEBUG_SHOW_INFO) { 8895 Log.v(TAG, " IntentFilter:"); 8896 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8897 } 8898 if (!intent.debugCheck()) { 8899 Log.w(TAG, "==> For Service " + s.info.name); 8900 } 8901 addFilter(intent); 8902 } 8903 } 8904 8905 public final void removeService(PackageParser.Service s) { 8906 mServices.remove(s.getComponentName()); 8907 if (DEBUG_SHOW_INFO) { 8908 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8909 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8910 Log.v(TAG, " Class=" + s.info.name); 8911 } 8912 final int NI = s.intents.size(); 8913 int j; 8914 for (j=0; j<NI; j++) { 8915 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8916 if (DEBUG_SHOW_INFO) { 8917 Log.v(TAG, " IntentFilter:"); 8918 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8919 } 8920 removeFilter(intent); 8921 } 8922 } 8923 8924 @Override 8925 protected boolean allowFilterResult( 8926 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8927 ServiceInfo filterSi = filter.service.info; 8928 for (int i=dest.size()-1; i>=0; i--) { 8929 ServiceInfo destAi = dest.get(i).serviceInfo; 8930 if (destAi.name == filterSi.name 8931 && destAi.packageName == filterSi.packageName) { 8932 return false; 8933 } 8934 } 8935 return true; 8936 } 8937 8938 @Override 8939 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8940 return new PackageParser.ServiceIntentInfo[size]; 8941 } 8942 8943 @Override 8944 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8945 if (!sUserManager.exists(userId)) return true; 8946 PackageParser.Package p = filter.service.owner; 8947 if (p != null) { 8948 PackageSetting ps = (PackageSetting)p.mExtras; 8949 if (ps != null) { 8950 // System apps are never considered stopped for purposes of 8951 // filtering, because there may be no way for the user to 8952 // actually re-launch them. 8953 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8954 && ps.getStopped(userId); 8955 } 8956 } 8957 return false; 8958 } 8959 8960 @Override 8961 protected boolean isPackageForFilter(String packageName, 8962 PackageParser.ServiceIntentInfo info) { 8963 return packageName.equals(info.service.owner.packageName); 8964 } 8965 8966 @Override 8967 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8968 int match, int userId) { 8969 if (!sUserManager.exists(userId)) return null; 8970 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8971 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8972 return null; 8973 } 8974 final PackageParser.Service service = info.service; 8975 if (mSafeMode && (service.info.applicationInfo.flags 8976 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8977 return null; 8978 } 8979 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8980 if (ps == null) { 8981 return null; 8982 } 8983 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8984 ps.readUserState(userId), userId); 8985 if (si == null) { 8986 return null; 8987 } 8988 final ResolveInfo res = new ResolveInfo(); 8989 res.serviceInfo = si; 8990 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8991 res.filter = filter; 8992 } 8993 res.priority = info.getPriority(); 8994 res.preferredOrder = service.owner.mPreferredOrder; 8995 res.match = match; 8996 res.isDefault = info.hasDefault; 8997 res.labelRes = info.labelRes; 8998 res.nonLocalizedLabel = info.nonLocalizedLabel; 8999 res.icon = info.icon; 9000 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9001 return res; 9002 } 9003 9004 @Override 9005 protected void sortResults(List<ResolveInfo> results) { 9006 Collections.sort(results, mResolvePrioritySorter); 9007 } 9008 9009 @Override 9010 protected void dumpFilter(PrintWriter out, String prefix, 9011 PackageParser.ServiceIntentInfo filter) { 9012 out.print(prefix); out.print( 9013 Integer.toHexString(System.identityHashCode(filter.service))); 9014 out.print(' '); 9015 filter.service.printComponentShortName(out); 9016 out.print(" filter "); 9017 out.println(Integer.toHexString(System.identityHashCode(filter))); 9018 } 9019 9020 @Override 9021 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9022 return filter.service; 9023 } 9024 9025 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9026 PackageParser.Service service = (PackageParser.Service)label; 9027 out.print(prefix); out.print( 9028 Integer.toHexString(System.identityHashCode(service))); 9029 out.print(' '); 9030 service.printComponentShortName(out); 9031 if (count > 1) { 9032 out.print(" ("); out.print(count); out.print(" filters)"); 9033 } 9034 out.println(); 9035 } 9036 9037// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9038// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9039// final List<ResolveInfo> retList = Lists.newArrayList(); 9040// while (i.hasNext()) { 9041// final ResolveInfo resolveInfo = (ResolveInfo) i; 9042// if (isEnabledLP(resolveInfo.serviceInfo)) { 9043// retList.add(resolveInfo); 9044// } 9045// } 9046// return retList; 9047// } 9048 9049 // Keys are String (activity class name), values are Activity. 9050 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9051 = new ArrayMap<ComponentName, PackageParser.Service>(); 9052 private int mFlags; 9053 }; 9054 9055 private final class ProviderIntentResolver 9056 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9057 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9058 boolean defaultOnly, int userId) { 9059 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9060 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9061 } 9062 9063 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9064 int userId) { 9065 if (!sUserManager.exists(userId)) 9066 return null; 9067 mFlags = flags; 9068 return super.queryIntent(intent, resolvedType, 9069 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9070 } 9071 9072 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9073 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9074 if (!sUserManager.exists(userId)) 9075 return null; 9076 if (packageProviders == null) { 9077 return null; 9078 } 9079 mFlags = flags; 9080 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9081 final int N = packageProviders.size(); 9082 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9083 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9084 9085 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9086 for (int i = 0; i < N; ++i) { 9087 intentFilters = packageProviders.get(i).intents; 9088 if (intentFilters != null && intentFilters.size() > 0) { 9089 PackageParser.ProviderIntentInfo[] array = 9090 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9091 intentFilters.toArray(array); 9092 listCut.add(array); 9093 } 9094 } 9095 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9096 } 9097 9098 public final void addProvider(PackageParser.Provider p) { 9099 if (mProviders.containsKey(p.getComponentName())) { 9100 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9101 return; 9102 } 9103 9104 mProviders.put(p.getComponentName(), p); 9105 if (DEBUG_SHOW_INFO) { 9106 Log.v(TAG, " " 9107 + (p.info.nonLocalizedLabel != null 9108 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9109 Log.v(TAG, " Class=" + p.info.name); 9110 } 9111 final int NI = p.intents.size(); 9112 int j; 9113 for (j = 0; j < NI; j++) { 9114 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9115 if (DEBUG_SHOW_INFO) { 9116 Log.v(TAG, " IntentFilter:"); 9117 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9118 } 9119 if (!intent.debugCheck()) { 9120 Log.w(TAG, "==> For Provider " + p.info.name); 9121 } 9122 addFilter(intent); 9123 } 9124 } 9125 9126 public final void removeProvider(PackageParser.Provider p) { 9127 mProviders.remove(p.getComponentName()); 9128 if (DEBUG_SHOW_INFO) { 9129 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9130 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9131 Log.v(TAG, " Class=" + p.info.name); 9132 } 9133 final int NI = p.intents.size(); 9134 int j; 9135 for (j = 0; j < NI; j++) { 9136 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9137 if (DEBUG_SHOW_INFO) { 9138 Log.v(TAG, " IntentFilter:"); 9139 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9140 } 9141 removeFilter(intent); 9142 } 9143 } 9144 9145 @Override 9146 protected boolean allowFilterResult( 9147 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9148 ProviderInfo filterPi = filter.provider.info; 9149 for (int i = dest.size() - 1; i >= 0; i--) { 9150 ProviderInfo destPi = dest.get(i).providerInfo; 9151 if (destPi.name == filterPi.name 9152 && destPi.packageName == filterPi.packageName) { 9153 return false; 9154 } 9155 } 9156 return true; 9157 } 9158 9159 @Override 9160 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9161 return new PackageParser.ProviderIntentInfo[size]; 9162 } 9163 9164 @Override 9165 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9166 if (!sUserManager.exists(userId)) 9167 return true; 9168 PackageParser.Package p = filter.provider.owner; 9169 if (p != null) { 9170 PackageSetting ps = (PackageSetting) p.mExtras; 9171 if (ps != null) { 9172 // System apps are never considered stopped for purposes of 9173 // filtering, because there may be no way for the user to 9174 // actually re-launch them. 9175 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9176 && ps.getStopped(userId); 9177 } 9178 } 9179 return false; 9180 } 9181 9182 @Override 9183 protected boolean isPackageForFilter(String packageName, 9184 PackageParser.ProviderIntentInfo info) { 9185 return packageName.equals(info.provider.owner.packageName); 9186 } 9187 9188 @Override 9189 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9190 int match, int userId) { 9191 if (!sUserManager.exists(userId)) 9192 return null; 9193 final PackageParser.ProviderIntentInfo info = filter; 9194 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9195 return null; 9196 } 9197 final PackageParser.Provider provider = info.provider; 9198 if (mSafeMode && (provider.info.applicationInfo.flags 9199 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9200 return null; 9201 } 9202 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9203 if (ps == null) { 9204 return null; 9205 } 9206 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9207 ps.readUserState(userId), userId); 9208 if (pi == null) { 9209 return null; 9210 } 9211 final ResolveInfo res = new ResolveInfo(); 9212 res.providerInfo = pi; 9213 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9214 res.filter = filter; 9215 } 9216 res.priority = info.getPriority(); 9217 res.preferredOrder = provider.owner.mPreferredOrder; 9218 res.match = match; 9219 res.isDefault = info.hasDefault; 9220 res.labelRes = info.labelRes; 9221 res.nonLocalizedLabel = info.nonLocalizedLabel; 9222 res.icon = info.icon; 9223 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9224 return res; 9225 } 9226 9227 @Override 9228 protected void sortResults(List<ResolveInfo> results) { 9229 Collections.sort(results, mResolvePrioritySorter); 9230 } 9231 9232 @Override 9233 protected void dumpFilter(PrintWriter out, String prefix, 9234 PackageParser.ProviderIntentInfo filter) { 9235 out.print(prefix); 9236 out.print( 9237 Integer.toHexString(System.identityHashCode(filter.provider))); 9238 out.print(' '); 9239 filter.provider.printComponentShortName(out); 9240 out.print(" filter "); 9241 out.println(Integer.toHexString(System.identityHashCode(filter))); 9242 } 9243 9244 @Override 9245 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9246 return filter.provider; 9247 } 9248 9249 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9250 PackageParser.Provider provider = (PackageParser.Provider)label; 9251 out.print(prefix); out.print( 9252 Integer.toHexString(System.identityHashCode(provider))); 9253 out.print(' '); 9254 provider.printComponentShortName(out); 9255 if (count > 1) { 9256 out.print(" ("); out.print(count); out.print(" filters)"); 9257 } 9258 out.println(); 9259 } 9260 9261 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9262 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9263 private int mFlags; 9264 }; 9265 9266 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9267 new Comparator<ResolveInfo>() { 9268 public int compare(ResolveInfo r1, ResolveInfo r2) { 9269 int v1 = r1.priority; 9270 int v2 = r2.priority; 9271 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9272 if (v1 != v2) { 9273 return (v1 > v2) ? -1 : 1; 9274 } 9275 v1 = r1.preferredOrder; 9276 v2 = r2.preferredOrder; 9277 if (v1 != v2) { 9278 return (v1 > v2) ? -1 : 1; 9279 } 9280 if (r1.isDefault != r2.isDefault) { 9281 return r1.isDefault ? -1 : 1; 9282 } 9283 v1 = r1.match; 9284 v2 = r2.match; 9285 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9286 if (v1 != v2) { 9287 return (v1 > v2) ? -1 : 1; 9288 } 9289 if (r1.system != r2.system) { 9290 return r1.system ? -1 : 1; 9291 } 9292 return 0; 9293 } 9294 }; 9295 9296 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9297 new Comparator<ProviderInfo>() { 9298 public int compare(ProviderInfo p1, ProviderInfo p2) { 9299 final int v1 = p1.initOrder; 9300 final int v2 = p2.initOrder; 9301 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9302 } 9303 }; 9304 9305 final void sendPackageBroadcast(final String action, final String pkg, 9306 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9307 final int[] userIds) { 9308 mHandler.post(new Runnable() { 9309 @Override 9310 public void run() { 9311 try { 9312 final IActivityManager am = ActivityManagerNative.getDefault(); 9313 if (am == null) return; 9314 final int[] resolvedUserIds; 9315 if (userIds == null) { 9316 resolvedUserIds = am.getRunningUserIds(); 9317 } else { 9318 resolvedUserIds = userIds; 9319 } 9320 for (int id : resolvedUserIds) { 9321 final Intent intent = new Intent(action, 9322 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9323 if (extras != null) { 9324 intent.putExtras(extras); 9325 } 9326 if (targetPkg != null) { 9327 intent.setPackage(targetPkg); 9328 } 9329 // Modify the UID when posting to other users 9330 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9331 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9332 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9333 intent.putExtra(Intent.EXTRA_UID, uid); 9334 } 9335 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9336 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9337 if (DEBUG_BROADCASTS) { 9338 RuntimeException here = new RuntimeException("here"); 9339 here.fillInStackTrace(); 9340 Slog.d(TAG, "Sending to user " + id + ": " 9341 + intent.toShortString(false, true, false, false) 9342 + " " + intent.getExtras(), here); 9343 } 9344 am.broadcastIntent(null, intent, null, finishedReceiver, 9345 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9346 null, finishedReceiver != null, false, id); 9347 } 9348 } catch (RemoteException ex) { 9349 } 9350 } 9351 }); 9352 } 9353 9354 /** 9355 * Check if the external storage media is available. This is true if there 9356 * is a mounted external storage medium or if the external storage is 9357 * emulated. 9358 */ 9359 private boolean isExternalMediaAvailable() { 9360 return mMediaMounted || Environment.isExternalStorageEmulated(); 9361 } 9362 9363 @Override 9364 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9365 // writer 9366 synchronized (mPackages) { 9367 if (!isExternalMediaAvailable()) { 9368 // If the external storage is no longer mounted at this point, 9369 // the caller may not have been able to delete all of this 9370 // packages files and can not delete any more. Bail. 9371 return null; 9372 } 9373 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9374 if (lastPackage != null) { 9375 pkgs.remove(lastPackage); 9376 } 9377 if (pkgs.size() > 0) { 9378 return pkgs.get(0); 9379 } 9380 } 9381 return null; 9382 } 9383 9384 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9385 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9386 userId, andCode ? 1 : 0, packageName); 9387 if (mSystemReady) { 9388 msg.sendToTarget(); 9389 } else { 9390 if (mPostSystemReadyMessages == null) { 9391 mPostSystemReadyMessages = new ArrayList<>(); 9392 } 9393 mPostSystemReadyMessages.add(msg); 9394 } 9395 } 9396 9397 void startCleaningPackages() { 9398 // reader 9399 synchronized (mPackages) { 9400 if (!isExternalMediaAvailable()) { 9401 return; 9402 } 9403 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9404 return; 9405 } 9406 } 9407 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9408 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9409 IActivityManager am = ActivityManagerNative.getDefault(); 9410 if (am != null) { 9411 try { 9412 am.startService(null, intent, null, mContext.getOpPackageName(), 9413 UserHandle.USER_SYSTEM); 9414 } catch (RemoteException e) { 9415 } 9416 } 9417 } 9418 9419 @Override 9420 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9421 int installFlags, String installerPackageName, VerificationParams verificationParams, 9422 String packageAbiOverride) { 9423 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9424 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9425 } 9426 9427 @Override 9428 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9429 int installFlags, String installerPackageName, VerificationParams verificationParams, 9430 String packageAbiOverride, int userId) { 9431 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9432 9433 final int callingUid = Binder.getCallingUid(); 9434 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9435 9436 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9437 try { 9438 if (observer != null) { 9439 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9440 } 9441 } catch (RemoteException re) { 9442 } 9443 return; 9444 } 9445 9446 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9447 installFlags |= PackageManager.INSTALL_FROM_ADB; 9448 9449 } else { 9450 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9451 // about installerPackageName. 9452 9453 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9454 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9455 } 9456 9457 UserHandle user; 9458 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9459 user = UserHandle.ALL; 9460 } else { 9461 user = new UserHandle(userId); 9462 } 9463 9464 // Only system components can circumvent runtime permissions when installing. 9465 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9466 && mContext.checkCallingOrSelfPermission(Manifest.permission 9467 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9468 throw new SecurityException("You need the " 9469 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9470 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9471 } 9472 9473 verificationParams.setInstallerUid(callingUid); 9474 9475 final File originFile = new File(originPath); 9476 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9477 9478 final Message msg = mHandler.obtainMessage(INIT_COPY); 9479 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9480 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9481 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9482 msg.obj = params; 9483 9484 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9485 System.identityHashCode(msg.obj)); 9486 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9487 System.identityHashCode(msg.obj)); 9488 9489 mHandler.sendMessage(msg); 9490 } 9491 9492 void installStage(String packageName, File stagedDir, String stagedCid, 9493 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9494 String installerPackageName, int installerUid, UserHandle user) { 9495 final VerificationParams verifParams = new VerificationParams( 9496 null, sessionParams.originatingUri, sessionParams.referrerUri, 9497 sessionParams.originatingUid, null); 9498 verifParams.setInstallerUid(installerUid); 9499 9500 final OriginInfo origin; 9501 if (stagedDir != null) { 9502 origin = OriginInfo.fromStagedFile(stagedDir); 9503 } else { 9504 origin = OriginInfo.fromStagedContainer(stagedCid); 9505 } 9506 9507 final Message msg = mHandler.obtainMessage(INIT_COPY); 9508 final InstallParams params = new InstallParams(origin, null, observer, 9509 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9510 verifParams, user, sessionParams.abiOverride, 9511 sessionParams.grantedRuntimePermissions); 9512 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9513 msg.obj = params; 9514 9515 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9516 System.identityHashCode(msg.obj)); 9517 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9518 System.identityHashCode(msg.obj)); 9519 9520 mHandler.sendMessage(msg); 9521 } 9522 9523 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9524 Bundle extras = new Bundle(1); 9525 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9526 9527 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9528 packageName, extras, null, null, new int[] {userId}); 9529 try { 9530 IActivityManager am = ActivityManagerNative.getDefault(); 9531 final boolean isSystem = 9532 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9533 if (isSystem && am.isUserRunning(userId, false)) { 9534 // The just-installed/enabled app is bundled on the system, so presumed 9535 // to be able to run automatically without needing an explicit launch. 9536 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9537 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9538 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9539 .setPackage(packageName); 9540 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9541 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9542 } 9543 } catch (RemoteException e) { 9544 // shouldn't happen 9545 Slog.w(TAG, "Unable to bootstrap installed package", e); 9546 } 9547 } 9548 9549 @Override 9550 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9551 int userId) { 9552 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9553 PackageSetting pkgSetting; 9554 final int uid = Binder.getCallingUid(); 9555 enforceCrossUserPermission(uid, userId, true, true, 9556 "setApplicationHiddenSetting for user " + userId); 9557 9558 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9559 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9560 return false; 9561 } 9562 9563 long callingId = Binder.clearCallingIdentity(); 9564 try { 9565 boolean sendAdded = false; 9566 boolean sendRemoved = false; 9567 // writer 9568 synchronized (mPackages) { 9569 pkgSetting = mSettings.mPackages.get(packageName); 9570 if (pkgSetting == null) { 9571 return false; 9572 } 9573 if (pkgSetting.getHidden(userId) != hidden) { 9574 pkgSetting.setHidden(hidden, userId); 9575 mSettings.writePackageRestrictionsLPr(userId); 9576 if (hidden) { 9577 sendRemoved = true; 9578 } else { 9579 sendAdded = true; 9580 } 9581 } 9582 } 9583 if (sendAdded) { 9584 sendPackageAddedForUser(packageName, pkgSetting, userId); 9585 return true; 9586 } 9587 if (sendRemoved) { 9588 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9589 "hiding pkg"); 9590 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9591 return true; 9592 } 9593 } finally { 9594 Binder.restoreCallingIdentity(callingId); 9595 } 9596 return false; 9597 } 9598 9599 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9600 int userId) { 9601 final PackageRemovedInfo info = new PackageRemovedInfo(); 9602 info.removedPackage = packageName; 9603 info.removedUsers = new int[] {userId}; 9604 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9605 info.sendBroadcast(false, false, false); 9606 } 9607 9608 /** 9609 * Returns true if application is not found or there was an error. Otherwise it returns 9610 * the hidden state of the package for the given user. 9611 */ 9612 @Override 9613 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9614 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9615 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9616 false, "getApplicationHidden for user " + userId); 9617 PackageSetting pkgSetting; 9618 long callingId = Binder.clearCallingIdentity(); 9619 try { 9620 // writer 9621 synchronized (mPackages) { 9622 pkgSetting = mSettings.mPackages.get(packageName); 9623 if (pkgSetting == null) { 9624 return true; 9625 } 9626 return pkgSetting.getHidden(userId); 9627 } 9628 } finally { 9629 Binder.restoreCallingIdentity(callingId); 9630 } 9631 } 9632 9633 /** 9634 * @hide 9635 */ 9636 @Override 9637 public int installExistingPackageAsUser(String packageName, int userId) { 9638 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9639 null); 9640 PackageSetting pkgSetting; 9641 final int uid = Binder.getCallingUid(); 9642 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9643 + userId); 9644 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9645 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9646 } 9647 9648 long callingId = Binder.clearCallingIdentity(); 9649 try { 9650 boolean sendAdded = false; 9651 9652 // writer 9653 synchronized (mPackages) { 9654 pkgSetting = mSettings.mPackages.get(packageName); 9655 if (pkgSetting == null) { 9656 return PackageManager.INSTALL_FAILED_INVALID_URI; 9657 } 9658 if (!pkgSetting.getInstalled(userId)) { 9659 pkgSetting.setInstalled(true, userId); 9660 pkgSetting.setHidden(false, userId); 9661 mSettings.writePackageRestrictionsLPr(userId); 9662 sendAdded = true; 9663 } 9664 } 9665 9666 if (sendAdded) { 9667 sendPackageAddedForUser(packageName, pkgSetting, userId); 9668 } 9669 } finally { 9670 Binder.restoreCallingIdentity(callingId); 9671 } 9672 9673 return PackageManager.INSTALL_SUCCEEDED; 9674 } 9675 9676 boolean isUserRestricted(int userId, String restrictionKey) { 9677 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9678 if (restrictions.getBoolean(restrictionKey, false)) { 9679 Log.w(TAG, "User is restricted: " + restrictionKey); 9680 return true; 9681 } 9682 return false; 9683 } 9684 9685 @Override 9686 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9687 mContext.enforceCallingOrSelfPermission( 9688 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9689 "Only package verification agents can verify applications"); 9690 9691 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9692 final PackageVerificationResponse response = new PackageVerificationResponse( 9693 verificationCode, Binder.getCallingUid()); 9694 msg.arg1 = id; 9695 msg.obj = response; 9696 mHandler.sendMessage(msg); 9697 } 9698 9699 @Override 9700 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9701 long millisecondsToDelay) { 9702 mContext.enforceCallingOrSelfPermission( 9703 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9704 "Only package verification agents can extend verification timeouts"); 9705 9706 final PackageVerificationState state = mPendingVerification.get(id); 9707 final PackageVerificationResponse response = new PackageVerificationResponse( 9708 verificationCodeAtTimeout, Binder.getCallingUid()); 9709 9710 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9711 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9712 } 9713 if (millisecondsToDelay < 0) { 9714 millisecondsToDelay = 0; 9715 } 9716 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9717 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9718 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9719 } 9720 9721 if ((state != null) && !state.timeoutExtended()) { 9722 state.extendTimeout(); 9723 9724 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9725 msg.arg1 = id; 9726 msg.obj = response; 9727 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9728 } 9729 } 9730 9731 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9732 int verificationCode, UserHandle user) { 9733 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9734 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9735 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9736 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9737 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9738 9739 mContext.sendBroadcastAsUser(intent, user, 9740 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9741 } 9742 9743 private ComponentName matchComponentForVerifier(String packageName, 9744 List<ResolveInfo> receivers) { 9745 ActivityInfo targetReceiver = null; 9746 9747 final int NR = receivers.size(); 9748 for (int i = 0; i < NR; i++) { 9749 final ResolveInfo info = receivers.get(i); 9750 if (info.activityInfo == null) { 9751 continue; 9752 } 9753 9754 if (packageName.equals(info.activityInfo.packageName)) { 9755 targetReceiver = info.activityInfo; 9756 break; 9757 } 9758 } 9759 9760 if (targetReceiver == null) { 9761 return null; 9762 } 9763 9764 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9765 } 9766 9767 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9768 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9769 if (pkgInfo.verifiers.length == 0) { 9770 return null; 9771 } 9772 9773 final int N = pkgInfo.verifiers.length; 9774 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9775 for (int i = 0; i < N; i++) { 9776 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9777 9778 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9779 receivers); 9780 if (comp == null) { 9781 continue; 9782 } 9783 9784 final int verifierUid = getUidForVerifier(verifierInfo); 9785 if (verifierUid == -1) { 9786 continue; 9787 } 9788 9789 if (DEBUG_VERIFY) { 9790 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9791 + " with the correct signature"); 9792 } 9793 sufficientVerifiers.add(comp); 9794 verificationState.addSufficientVerifier(verifierUid); 9795 } 9796 9797 return sufficientVerifiers; 9798 } 9799 9800 private int getUidForVerifier(VerifierInfo verifierInfo) { 9801 synchronized (mPackages) { 9802 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9803 if (pkg == null) { 9804 return -1; 9805 } else if (pkg.mSignatures.length != 1) { 9806 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9807 + " has more than one signature; ignoring"); 9808 return -1; 9809 } 9810 9811 /* 9812 * If the public key of the package's signature does not match 9813 * our expected public key, then this is a different package and 9814 * we should skip. 9815 */ 9816 9817 final byte[] expectedPublicKey; 9818 try { 9819 final Signature verifierSig = pkg.mSignatures[0]; 9820 final PublicKey publicKey = verifierSig.getPublicKey(); 9821 expectedPublicKey = publicKey.getEncoded(); 9822 } catch (CertificateException e) { 9823 return -1; 9824 } 9825 9826 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9827 9828 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9829 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9830 + " does not have the expected public key; ignoring"); 9831 return -1; 9832 } 9833 9834 return pkg.applicationInfo.uid; 9835 } 9836 } 9837 9838 @Override 9839 public void finishPackageInstall(int token) { 9840 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9841 9842 if (DEBUG_INSTALL) { 9843 Slog.v(TAG, "BM finishing package install for " + token); 9844 } 9845 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 9846 9847 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9848 mHandler.sendMessage(msg); 9849 } 9850 9851 /** 9852 * Get the verification agent timeout. 9853 * 9854 * @return verification timeout in milliseconds 9855 */ 9856 private long getVerificationTimeout() { 9857 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9858 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9859 DEFAULT_VERIFICATION_TIMEOUT); 9860 } 9861 9862 /** 9863 * Get the default verification agent response code. 9864 * 9865 * @return default verification response code 9866 */ 9867 private int getDefaultVerificationResponse() { 9868 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9869 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9870 DEFAULT_VERIFICATION_RESPONSE); 9871 } 9872 9873 /** 9874 * Check whether or not package verification has been enabled. 9875 * 9876 * @return true if verification should be performed 9877 */ 9878 private boolean isVerificationEnabled(int userId, int installFlags) { 9879 if (!DEFAULT_VERIFY_ENABLE) { 9880 return false; 9881 } 9882 // TODO: fix b/25118622; don't bypass verification 9883 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 9884 return false; 9885 } 9886 9887 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9888 9889 // Check if installing from ADB 9890 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9891 // Do not run verification in a test harness environment 9892 if (ActivityManager.isRunningInTestHarness()) { 9893 return false; 9894 } 9895 if (ensureVerifyAppsEnabled) { 9896 return true; 9897 } 9898 // Check if the developer does not want package verification for ADB installs 9899 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9900 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9901 return false; 9902 } 9903 } 9904 9905 if (ensureVerifyAppsEnabled) { 9906 return true; 9907 } 9908 9909 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9910 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9911 } 9912 9913 @Override 9914 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9915 throws RemoteException { 9916 mContext.enforceCallingOrSelfPermission( 9917 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9918 "Only intentfilter verification agents can verify applications"); 9919 9920 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9921 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9922 Binder.getCallingUid(), verificationCode, failedDomains); 9923 msg.arg1 = id; 9924 msg.obj = response; 9925 mHandler.sendMessage(msg); 9926 } 9927 9928 @Override 9929 public int getIntentVerificationStatus(String packageName, int userId) { 9930 synchronized (mPackages) { 9931 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9932 } 9933 } 9934 9935 @Override 9936 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9937 mContext.enforceCallingOrSelfPermission( 9938 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9939 9940 boolean result = false; 9941 synchronized (mPackages) { 9942 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9943 } 9944 if (result) { 9945 scheduleWritePackageRestrictionsLocked(userId); 9946 } 9947 return result; 9948 } 9949 9950 @Override 9951 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9952 synchronized (mPackages) { 9953 return mSettings.getIntentFilterVerificationsLPr(packageName); 9954 } 9955 } 9956 9957 @Override 9958 public List<IntentFilter> getAllIntentFilters(String packageName) { 9959 if (TextUtils.isEmpty(packageName)) { 9960 return Collections.<IntentFilter>emptyList(); 9961 } 9962 synchronized (mPackages) { 9963 PackageParser.Package pkg = mPackages.get(packageName); 9964 if (pkg == null || pkg.activities == null) { 9965 return Collections.<IntentFilter>emptyList(); 9966 } 9967 final int count = pkg.activities.size(); 9968 ArrayList<IntentFilter> result = new ArrayList<>(); 9969 for (int n=0; n<count; n++) { 9970 PackageParser.Activity activity = pkg.activities.get(n); 9971 if (activity.intents != null || activity.intents.size() > 0) { 9972 result.addAll(activity.intents); 9973 } 9974 } 9975 return result; 9976 } 9977 } 9978 9979 @Override 9980 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9981 mContext.enforceCallingOrSelfPermission( 9982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9983 9984 synchronized (mPackages) { 9985 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9986 if (packageName != null) { 9987 result |= updateIntentVerificationStatus(packageName, 9988 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9989 userId); 9990 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9991 packageName, userId); 9992 } 9993 return result; 9994 } 9995 } 9996 9997 @Override 9998 public String getDefaultBrowserPackageName(int userId) { 9999 synchronized (mPackages) { 10000 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10001 } 10002 } 10003 10004 /** 10005 * Get the "allow unknown sources" setting. 10006 * 10007 * @return the current "allow unknown sources" setting 10008 */ 10009 private int getUnknownSourcesSettings() { 10010 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10011 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10012 -1); 10013 } 10014 10015 @Override 10016 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10017 final int uid = Binder.getCallingUid(); 10018 // writer 10019 synchronized (mPackages) { 10020 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10021 if (targetPackageSetting == null) { 10022 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10023 } 10024 10025 PackageSetting installerPackageSetting; 10026 if (installerPackageName != null) { 10027 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10028 if (installerPackageSetting == null) { 10029 throw new IllegalArgumentException("Unknown installer package: " 10030 + installerPackageName); 10031 } 10032 } else { 10033 installerPackageSetting = null; 10034 } 10035 10036 Signature[] callerSignature; 10037 Object obj = mSettings.getUserIdLPr(uid); 10038 if (obj != null) { 10039 if (obj instanceof SharedUserSetting) { 10040 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10041 } else if (obj instanceof PackageSetting) { 10042 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10043 } else { 10044 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10045 } 10046 } else { 10047 throw new SecurityException("Unknown calling uid " + uid); 10048 } 10049 10050 // Verify: can't set installerPackageName to a package that is 10051 // not signed with the same cert as the caller. 10052 if (installerPackageSetting != null) { 10053 if (compareSignatures(callerSignature, 10054 installerPackageSetting.signatures.mSignatures) 10055 != PackageManager.SIGNATURE_MATCH) { 10056 throw new SecurityException( 10057 "Caller does not have same cert as new installer package " 10058 + installerPackageName); 10059 } 10060 } 10061 10062 // Verify: if target already has an installer package, it must 10063 // be signed with the same cert as the caller. 10064 if (targetPackageSetting.installerPackageName != null) { 10065 PackageSetting setting = mSettings.mPackages.get( 10066 targetPackageSetting.installerPackageName); 10067 // If the currently set package isn't valid, then it's always 10068 // okay to change it. 10069 if (setting != null) { 10070 if (compareSignatures(callerSignature, 10071 setting.signatures.mSignatures) 10072 != PackageManager.SIGNATURE_MATCH) { 10073 throw new SecurityException( 10074 "Caller does not have same cert as old installer package " 10075 + targetPackageSetting.installerPackageName); 10076 } 10077 } 10078 } 10079 10080 // Okay! 10081 targetPackageSetting.installerPackageName = installerPackageName; 10082 scheduleWriteSettingsLocked(); 10083 } 10084 } 10085 10086 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10087 // Queue up an async operation since the package installation may take a little while. 10088 mHandler.post(new Runnable() { 10089 public void run() { 10090 mHandler.removeCallbacks(this); 10091 // Result object to be returned 10092 PackageInstalledInfo res = new PackageInstalledInfo(); 10093 res.returnCode = currentStatus; 10094 res.uid = -1; 10095 res.pkg = null; 10096 res.removedInfo = new PackageRemovedInfo(); 10097 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10098 args.doPreInstall(res.returnCode); 10099 synchronized (mInstallLock) { 10100 installPackageTracedLI(args, res); 10101 } 10102 args.doPostInstall(res.returnCode, res.uid); 10103 } 10104 10105 // A restore should be performed at this point if (a) the install 10106 // succeeded, (b) the operation is not an update, and (c) the new 10107 // package has not opted out of backup participation. 10108 final boolean update = res.removedInfo.removedPackage != null; 10109 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10110 boolean doRestore = !update 10111 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10112 10113 // Set up the post-install work request bookkeeping. This will be used 10114 // and cleaned up by the post-install event handling regardless of whether 10115 // there's a restore pass performed. Token values are >= 1. 10116 int token; 10117 if (mNextInstallToken < 0) mNextInstallToken = 1; 10118 token = mNextInstallToken++; 10119 10120 PostInstallData data = new PostInstallData(args, res); 10121 mRunningInstalls.put(token, data); 10122 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10123 10124 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10125 // Pass responsibility to the Backup Manager. It will perform a 10126 // restore if appropriate, then pass responsibility back to the 10127 // Package Manager to run the post-install observer callbacks 10128 // and broadcasts. 10129 IBackupManager bm = IBackupManager.Stub.asInterface( 10130 ServiceManager.getService(Context.BACKUP_SERVICE)); 10131 if (bm != null) { 10132 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10133 + " to BM for possible restore"); 10134 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10135 try { 10136 // TODO: http://b/22388012 10137 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10138 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10139 } else { 10140 doRestore = false; 10141 } 10142 } catch (RemoteException e) { 10143 // can't happen; the backup manager is local 10144 } catch (Exception e) { 10145 Slog.e(TAG, "Exception trying to enqueue restore", e); 10146 doRestore = false; 10147 } 10148 } else { 10149 Slog.e(TAG, "Backup Manager not found!"); 10150 doRestore = false; 10151 } 10152 } 10153 10154 if (!doRestore) { 10155 // No restore possible, or the Backup Manager was mysteriously not 10156 // available -- just fire the post-install work request directly. 10157 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10158 10159 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10160 10161 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10162 mHandler.sendMessage(msg); 10163 } 10164 } 10165 }); 10166 } 10167 10168 private abstract class HandlerParams { 10169 private static final int MAX_RETRIES = 4; 10170 10171 /** 10172 * Number of times startCopy() has been attempted and had a non-fatal 10173 * error. 10174 */ 10175 private int mRetries = 0; 10176 10177 /** User handle for the user requesting the information or installation. */ 10178 private final UserHandle mUser; 10179 String traceMethod; 10180 int traceCookie; 10181 10182 HandlerParams(UserHandle user) { 10183 mUser = user; 10184 } 10185 10186 UserHandle getUser() { 10187 return mUser; 10188 } 10189 10190 HandlerParams setTraceMethod(String traceMethod) { 10191 this.traceMethod = traceMethod; 10192 return this; 10193 } 10194 10195 HandlerParams setTraceCookie(int traceCookie) { 10196 this.traceCookie = traceCookie; 10197 return this; 10198 } 10199 10200 final boolean startCopy() { 10201 boolean res; 10202 try { 10203 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10204 10205 if (++mRetries > MAX_RETRIES) { 10206 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10207 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10208 handleServiceError(); 10209 return false; 10210 } else { 10211 handleStartCopy(); 10212 res = true; 10213 } 10214 } catch (RemoteException e) { 10215 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10216 mHandler.sendEmptyMessage(MCS_RECONNECT); 10217 res = false; 10218 } 10219 handleReturnCode(); 10220 return res; 10221 } 10222 10223 final void serviceError() { 10224 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10225 handleServiceError(); 10226 handleReturnCode(); 10227 } 10228 10229 abstract void handleStartCopy() throws RemoteException; 10230 abstract void handleServiceError(); 10231 abstract void handleReturnCode(); 10232 } 10233 10234 class MeasureParams extends HandlerParams { 10235 private final PackageStats mStats; 10236 private boolean mSuccess; 10237 10238 private final IPackageStatsObserver mObserver; 10239 10240 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10241 super(new UserHandle(stats.userHandle)); 10242 mObserver = observer; 10243 mStats = stats; 10244 } 10245 10246 @Override 10247 public String toString() { 10248 return "MeasureParams{" 10249 + Integer.toHexString(System.identityHashCode(this)) 10250 + " " + mStats.packageName + "}"; 10251 } 10252 10253 @Override 10254 void handleStartCopy() throws RemoteException { 10255 synchronized (mInstallLock) { 10256 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10257 } 10258 10259 if (mSuccess) { 10260 final boolean mounted; 10261 if (Environment.isExternalStorageEmulated()) { 10262 mounted = true; 10263 } else { 10264 final String status = Environment.getExternalStorageState(); 10265 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10266 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10267 } 10268 10269 if (mounted) { 10270 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10271 10272 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10273 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10274 10275 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10276 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10277 10278 // Always subtract cache size, since it's a subdirectory 10279 mStats.externalDataSize -= mStats.externalCacheSize; 10280 10281 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10282 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10283 10284 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10285 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10286 } 10287 } 10288 } 10289 10290 @Override 10291 void handleReturnCode() { 10292 if (mObserver != null) { 10293 try { 10294 mObserver.onGetStatsCompleted(mStats, mSuccess); 10295 } catch (RemoteException e) { 10296 Slog.i(TAG, "Observer no longer exists."); 10297 } 10298 } 10299 } 10300 10301 @Override 10302 void handleServiceError() { 10303 Slog.e(TAG, "Could not measure application " + mStats.packageName 10304 + " external storage"); 10305 } 10306 } 10307 10308 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10309 throws RemoteException { 10310 long result = 0; 10311 for (File path : paths) { 10312 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10313 } 10314 return result; 10315 } 10316 10317 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10318 for (File path : paths) { 10319 try { 10320 mcs.clearDirectory(path.getAbsolutePath()); 10321 } catch (RemoteException e) { 10322 } 10323 } 10324 } 10325 10326 static class OriginInfo { 10327 /** 10328 * Location where install is coming from, before it has been 10329 * copied/renamed into place. This could be a single monolithic APK 10330 * file, or a cluster directory. This location may be untrusted. 10331 */ 10332 final File file; 10333 final String cid; 10334 10335 /** 10336 * Flag indicating that {@link #file} or {@link #cid} has already been 10337 * staged, meaning downstream users don't need to defensively copy the 10338 * contents. 10339 */ 10340 final boolean staged; 10341 10342 /** 10343 * Flag indicating that {@link #file} or {@link #cid} is an already 10344 * installed app that is being moved. 10345 */ 10346 final boolean existing; 10347 10348 final String resolvedPath; 10349 final File resolvedFile; 10350 10351 static OriginInfo fromNothing() { 10352 return new OriginInfo(null, null, false, false); 10353 } 10354 10355 static OriginInfo fromUntrustedFile(File file) { 10356 return new OriginInfo(file, null, false, false); 10357 } 10358 10359 static OriginInfo fromExistingFile(File file) { 10360 return new OriginInfo(file, null, false, true); 10361 } 10362 10363 static OriginInfo fromStagedFile(File file) { 10364 return new OriginInfo(file, null, true, false); 10365 } 10366 10367 static OriginInfo fromStagedContainer(String cid) { 10368 return new OriginInfo(null, cid, true, false); 10369 } 10370 10371 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10372 this.file = file; 10373 this.cid = cid; 10374 this.staged = staged; 10375 this.existing = existing; 10376 10377 if (cid != null) { 10378 resolvedPath = PackageHelper.getSdDir(cid); 10379 resolvedFile = new File(resolvedPath); 10380 } else if (file != null) { 10381 resolvedPath = file.getAbsolutePath(); 10382 resolvedFile = file; 10383 } else { 10384 resolvedPath = null; 10385 resolvedFile = null; 10386 } 10387 } 10388 } 10389 10390 class MoveInfo { 10391 final int moveId; 10392 final String fromUuid; 10393 final String toUuid; 10394 final String packageName; 10395 final String dataAppName; 10396 final int appId; 10397 final String seinfo; 10398 10399 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10400 String dataAppName, int appId, String seinfo) { 10401 this.moveId = moveId; 10402 this.fromUuid = fromUuid; 10403 this.toUuid = toUuid; 10404 this.packageName = packageName; 10405 this.dataAppName = dataAppName; 10406 this.appId = appId; 10407 this.seinfo = seinfo; 10408 } 10409 } 10410 10411 class InstallParams extends HandlerParams { 10412 final OriginInfo origin; 10413 final MoveInfo move; 10414 final IPackageInstallObserver2 observer; 10415 int installFlags; 10416 final String installerPackageName; 10417 final String volumeUuid; 10418 final VerificationParams verificationParams; 10419 private InstallArgs mArgs; 10420 private int mRet; 10421 final String packageAbiOverride; 10422 final String[] grantedRuntimePermissions; 10423 10424 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10425 int installFlags, String installerPackageName, String volumeUuid, 10426 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10427 String[] grantedPermissions) { 10428 super(user); 10429 this.origin = origin; 10430 this.move = move; 10431 this.observer = observer; 10432 this.installFlags = installFlags; 10433 this.installerPackageName = installerPackageName; 10434 this.volumeUuid = volumeUuid; 10435 this.verificationParams = verificationParams; 10436 this.packageAbiOverride = packageAbiOverride; 10437 this.grantedRuntimePermissions = grantedPermissions; 10438 } 10439 10440 @Override 10441 public String toString() { 10442 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10443 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10444 } 10445 10446 public ManifestDigest getManifestDigest() { 10447 if (verificationParams == null) { 10448 return null; 10449 } 10450 return verificationParams.getManifestDigest(); 10451 } 10452 10453 private int installLocationPolicy(PackageInfoLite pkgLite) { 10454 String packageName = pkgLite.packageName; 10455 int installLocation = pkgLite.installLocation; 10456 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10457 // reader 10458 synchronized (mPackages) { 10459 PackageParser.Package pkg = mPackages.get(packageName); 10460 if (pkg != null) { 10461 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10462 // Check for downgrading. 10463 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10464 try { 10465 checkDowngrade(pkg, pkgLite); 10466 } catch (PackageManagerException e) { 10467 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10468 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10469 } 10470 } 10471 // Check for updated system application. 10472 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10473 if (onSd) { 10474 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10475 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10476 } 10477 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10478 } else { 10479 if (onSd) { 10480 // Install flag overrides everything. 10481 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10482 } 10483 // If current upgrade specifies particular preference 10484 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10485 // Application explicitly specified internal. 10486 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10487 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10488 // App explictly prefers external. Let policy decide 10489 } else { 10490 // Prefer previous location 10491 if (isExternal(pkg)) { 10492 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10493 } 10494 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10495 } 10496 } 10497 } else { 10498 // Invalid install. Return error code 10499 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10500 } 10501 } 10502 } 10503 // All the special cases have been taken care of. 10504 // Return result based on recommended install location. 10505 if (onSd) { 10506 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10507 } 10508 return pkgLite.recommendedInstallLocation; 10509 } 10510 10511 /* 10512 * Invoke remote method to get package information and install 10513 * location values. Override install location based on default 10514 * policy if needed and then create install arguments based 10515 * on the install location. 10516 */ 10517 public void handleStartCopy() throws RemoteException { 10518 int ret = PackageManager.INSTALL_SUCCEEDED; 10519 10520 // If we're already staged, we've firmly committed to an install location 10521 if (origin.staged) { 10522 if (origin.file != null) { 10523 installFlags |= PackageManager.INSTALL_INTERNAL; 10524 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10525 } else if (origin.cid != null) { 10526 installFlags |= PackageManager.INSTALL_EXTERNAL; 10527 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10528 } else { 10529 throw new IllegalStateException("Invalid stage location"); 10530 } 10531 } 10532 10533 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10534 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10535 PackageInfoLite pkgLite = null; 10536 10537 if (onInt && onSd) { 10538 // Check if both bits are set. 10539 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10540 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10541 } else { 10542 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10543 packageAbiOverride); 10544 10545 /* 10546 * If we have too little free space, try to free cache 10547 * before giving up. 10548 */ 10549 if (!origin.staged && pkgLite.recommendedInstallLocation 10550 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10551 // TODO: focus freeing disk space on the target device 10552 final StorageManager storage = StorageManager.from(mContext); 10553 final long lowThreshold = storage.getStorageLowBytes( 10554 Environment.getDataDirectory()); 10555 10556 final long sizeBytes = mContainerService.calculateInstalledSize( 10557 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10558 10559 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10560 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10561 installFlags, packageAbiOverride); 10562 } 10563 10564 /* 10565 * The cache free must have deleted the file we 10566 * downloaded to install. 10567 * 10568 * TODO: fix the "freeCache" call to not delete 10569 * the file we care about. 10570 */ 10571 if (pkgLite.recommendedInstallLocation 10572 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10573 pkgLite.recommendedInstallLocation 10574 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10575 } 10576 } 10577 } 10578 10579 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10580 int loc = pkgLite.recommendedInstallLocation; 10581 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10582 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10583 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10584 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10585 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10586 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10587 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10588 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10589 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10590 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10591 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10592 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10593 } else { 10594 // Override with defaults if needed. 10595 loc = installLocationPolicy(pkgLite); 10596 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10597 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10598 } else if (!onSd && !onInt) { 10599 // Override install location with flags 10600 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10601 // Set the flag to install on external media. 10602 installFlags |= PackageManager.INSTALL_EXTERNAL; 10603 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10604 } else { 10605 // Make sure the flag for installing on external 10606 // media is unset 10607 installFlags |= PackageManager.INSTALL_INTERNAL; 10608 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10609 } 10610 } 10611 } 10612 } 10613 10614 final InstallArgs args = createInstallArgs(this); 10615 mArgs = args; 10616 10617 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10618 // TODO: http://b/22976637 10619 // Apps installed for "all" users use the device owner to verify the app 10620 UserHandle verifierUser = getUser(); 10621 if (verifierUser == UserHandle.ALL) { 10622 verifierUser = UserHandle.SYSTEM; 10623 } 10624 10625 /* 10626 * Determine if we have any installed package verifiers. If we 10627 * do, then we'll defer to them to verify the packages. 10628 */ 10629 final int requiredUid = mRequiredVerifierPackage == null ? -1 10630 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10631 if (!origin.existing && requiredUid != -1 10632 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10633 final Intent verification = new Intent( 10634 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10635 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10636 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10637 PACKAGE_MIME_TYPE); 10638 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10639 10640 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10641 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10642 verifierUser.getIdentifier()); 10643 10644 if (DEBUG_VERIFY) { 10645 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10646 + verification.toString() + " with " + pkgLite.verifiers.length 10647 + " optional verifiers"); 10648 } 10649 10650 final int verificationId = mPendingVerificationToken++; 10651 10652 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10653 10654 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10655 installerPackageName); 10656 10657 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10658 installFlags); 10659 10660 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10661 pkgLite.packageName); 10662 10663 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10664 pkgLite.versionCode); 10665 10666 if (verificationParams != null) { 10667 if (verificationParams.getVerificationURI() != null) { 10668 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10669 verificationParams.getVerificationURI()); 10670 } 10671 if (verificationParams.getOriginatingURI() != null) { 10672 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10673 verificationParams.getOriginatingURI()); 10674 } 10675 if (verificationParams.getReferrer() != null) { 10676 verification.putExtra(Intent.EXTRA_REFERRER, 10677 verificationParams.getReferrer()); 10678 } 10679 if (verificationParams.getOriginatingUid() >= 0) { 10680 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10681 verificationParams.getOriginatingUid()); 10682 } 10683 if (verificationParams.getInstallerUid() >= 0) { 10684 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10685 verificationParams.getInstallerUid()); 10686 } 10687 } 10688 10689 final PackageVerificationState verificationState = new PackageVerificationState( 10690 requiredUid, args); 10691 10692 mPendingVerification.append(verificationId, verificationState); 10693 10694 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10695 receivers, verificationState); 10696 10697 /* 10698 * If any sufficient verifiers were listed in the package 10699 * manifest, attempt to ask them. 10700 */ 10701 if (sufficientVerifiers != null) { 10702 final int N = sufficientVerifiers.size(); 10703 if (N == 0) { 10704 Slog.i(TAG, "Additional verifiers required, but none installed."); 10705 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10706 } else { 10707 for (int i = 0; i < N; i++) { 10708 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10709 10710 final Intent sufficientIntent = new Intent(verification); 10711 sufficientIntent.setComponent(verifierComponent); 10712 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10713 } 10714 } 10715 } 10716 10717 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10718 mRequiredVerifierPackage, receivers); 10719 if (ret == PackageManager.INSTALL_SUCCEEDED 10720 && mRequiredVerifierPackage != null) { 10721 Trace.asyncTraceBegin( 10722 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10723 /* 10724 * Send the intent to the required verification agent, 10725 * but only start the verification timeout after the 10726 * target BroadcastReceivers have run. 10727 */ 10728 verification.setComponent(requiredVerifierComponent); 10729 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10730 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10731 new BroadcastReceiver() { 10732 @Override 10733 public void onReceive(Context context, Intent intent) { 10734 final Message msg = mHandler 10735 .obtainMessage(CHECK_PENDING_VERIFICATION); 10736 msg.arg1 = verificationId; 10737 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10738 } 10739 }, null, 0, null, null); 10740 10741 /* 10742 * We don't want the copy to proceed until verification 10743 * succeeds, so null out this field. 10744 */ 10745 mArgs = null; 10746 } 10747 } else { 10748 /* 10749 * No package verification is enabled, so immediately start 10750 * the remote call to initiate copy using temporary file. 10751 */ 10752 ret = args.copyApk(mContainerService, true); 10753 } 10754 } 10755 10756 mRet = ret; 10757 } 10758 10759 @Override 10760 void handleReturnCode() { 10761 // If mArgs is null, then MCS couldn't be reached. When it 10762 // reconnects, it will try again to install. At that point, this 10763 // will succeed. 10764 if (mArgs != null) { 10765 processPendingInstall(mArgs, mRet); 10766 } 10767 } 10768 10769 @Override 10770 void handleServiceError() { 10771 mArgs = createInstallArgs(this); 10772 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10773 } 10774 10775 public boolean isForwardLocked() { 10776 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10777 } 10778 } 10779 10780 /** 10781 * Used during creation of InstallArgs 10782 * 10783 * @param installFlags package installation flags 10784 * @return true if should be installed on external storage 10785 */ 10786 private static boolean installOnExternalAsec(int installFlags) { 10787 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10788 return false; 10789 } 10790 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10791 return true; 10792 } 10793 return false; 10794 } 10795 10796 /** 10797 * Used during creation of InstallArgs 10798 * 10799 * @param installFlags package installation flags 10800 * @return true if should be installed as forward locked 10801 */ 10802 private static boolean installForwardLocked(int installFlags) { 10803 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10804 } 10805 10806 private InstallArgs createInstallArgs(InstallParams params) { 10807 if (params.move != null) { 10808 return new MoveInstallArgs(params); 10809 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10810 return new AsecInstallArgs(params); 10811 } else { 10812 return new FileInstallArgs(params); 10813 } 10814 } 10815 10816 /** 10817 * Create args that describe an existing installed package. Typically used 10818 * when cleaning up old installs, or used as a move source. 10819 */ 10820 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10821 String resourcePath, String[] instructionSets) { 10822 final boolean isInAsec; 10823 if (installOnExternalAsec(installFlags)) { 10824 /* Apps on SD card are always in ASEC containers. */ 10825 isInAsec = true; 10826 } else if (installForwardLocked(installFlags) 10827 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10828 /* 10829 * Forward-locked apps are only in ASEC containers if they're the 10830 * new style 10831 */ 10832 isInAsec = true; 10833 } else { 10834 isInAsec = false; 10835 } 10836 10837 if (isInAsec) { 10838 return new AsecInstallArgs(codePath, instructionSets, 10839 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10840 } else { 10841 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10842 } 10843 } 10844 10845 static abstract class InstallArgs { 10846 /** @see InstallParams#origin */ 10847 final OriginInfo origin; 10848 /** @see InstallParams#move */ 10849 final MoveInfo move; 10850 10851 final IPackageInstallObserver2 observer; 10852 // Always refers to PackageManager flags only 10853 final int installFlags; 10854 final String installerPackageName; 10855 final String volumeUuid; 10856 final ManifestDigest manifestDigest; 10857 final UserHandle user; 10858 final String abiOverride; 10859 final String[] installGrantPermissions; 10860 /** If non-null, drop an async trace when the install completes */ 10861 final String traceMethod; 10862 final int traceCookie; 10863 10864 // The list of instruction sets supported by this app. This is currently 10865 // only used during the rmdex() phase to clean up resources. We can get rid of this 10866 // if we move dex files under the common app path. 10867 /* nullable */ String[] instructionSets; 10868 10869 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10870 int installFlags, String installerPackageName, String volumeUuid, 10871 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10872 String abiOverride, String[] installGrantPermissions, 10873 String traceMethod, int traceCookie) { 10874 this.origin = origin; 10875 this.move = move; 10876 this.installFlags = installFlags; 10877 this.observer = observer; 10878 this.installerPackageName = installerPackageName; 10879 this.volumeUuid = volumeUuid; 10880 this.manifestDigest = manifestDigest; 10881 this.user = user; 10882 this.instructionSets = instructionSets; 10883 this.abiOverride = abiOverride; 10884 this.installGrantPermissions = installGrantPermissions; 10885 this.traceMethod = traceMethod; 10886 this.traceCookie = traceCookie; 10887 } 10888 10889 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10890 abstract int doPreInstall(int status); 10891 10892 /** 10893 * Rename package into final resting place. All paths on the given 10894 * scanned package should be updated to reflect the rename. 10895 */ 10896 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10897 abstract int doPostInstall(int status, int uid); 10898 10899 /** @see PackageSettingBase#codePathString */ 10900 abstract String getCodePath(); 10901 /** @see PackageSettingBase#resourcePathString */ 10902 abstract String getResourcePath(); 10903 10904 // Need installer lock especially for dex file removal. 10905 abstract void cleanUpResourcesLI(); 10906 abstract boolean doPostDeleteLI(boolean delete); 10907 10908 /** 10909 * Called before the source arguments are copied. This is used mostly 10910 * for MoveParams when it needs to read the source file to put it in the 10911 * destination. 10912 */ 10913 int doPreCopy() { 10914 return PackageManager.INSTALL_SUCCEEDED; 10915 } 10916 10917 /** 10918 * Called after the source arguments are copied. This is used mostly for 10919 * MoveParams when it needs to read the source file to put it in the 10920 * destination. 10921 * 10922 * @return 10923 */ 10924 int doPostCopy(int uid) { 10925 return PackageManager.INSTALL_SUCCEEDED; 10926 } 10927 10928 protected boolean isFwdLocked() { 10929 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10930 } 10931 10932 protected boolean isExternalAsec() { 10933 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10934 } 10935 10936 UserHandle getUser() { 10937 return user; 10938 } 10939 } 10940 10941 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10942 if (!allCodePaths.isEmpty()) { 10943 if (instructionSets == null) { 10944 throw new IllegalStateException("instructionSet == null"); 10945 } 10946 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10947 for (String codePath : allCodePaths) { 10948 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10949 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10950 if (retCode < 0) { 10951 Slog.w(TAG, "Couldn't remove dex file for package: " 10952 + " at location " + codePath + ", retcode=" + retCode); 10953 // we don't consider this to be a failure of the core package deletion 10954 } 10955 } 10956 } 10957 } 10958 } 10959 10960 /** 10961 * Logic to handle installation of non-ASEC applications, including copying 10962 * and renaming logic. 10963 */ 10964 class FileInstallArgs extends InstallArgs { 10965 private File codeFile; 10966 private File resourceFile; 10967 10968 // Example topology: 10969 // /data/app/com.example/base.apk 10970 // /data/app/com.example/split_foo.apk 10971 // /data/app/com.example/lib/arm/libfoo.so 10972 // /data/app/com.example/lib/arm64/libfoo.so 10973 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10974 10975 /** New install */ 10976 FileInstallArgs(InstallParams params) { 10977 super(params.origin, params.move, params.observer, params.installFlags, 10978 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10979 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 10980 params.grantedRuntimePermissions, 10981 params.traceMethod, params.traceCookie); 10982 if (isFwdLocked()) { 10983 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10984 } 10985 } 10986 10987 /** Existing install */ 10988 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10989 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10990 null, null, null, 0); 10991 this.codeFile = (codePath != null) ? new File(codePath) : null; 10992 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10993 } 10994 10995 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10996 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 10997 try { 10998 return doCopyApk(imcs, temp); 10999 } finally { 11000 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11001 } 11002 } 11003 11004 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11005 if (origin.staged) { 11006 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11007 codeFile = origin.file; 11008 resourceFile = origin.file; 11009 return PackageManager.INSTALL_SUCCEEDED; 11010 } 11011 11012 try { 11013 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11014 codeFile = tempDir; 11015 resourceFile = tempDir; 11016 } catch (IOException e) { 11017 Slog.w(TAG, "Failed to create copy file: " + e); 11018 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11019 } 11020 11021 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11022 @Override 11023 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11024 if (!FileUtils.isValidExtFilename(name)) { 11025 throw new IllegalArgumentException("Invalid filename: " + name); 11026 } 11027 try { 11028 final File file = new File(codeFile, name); 11029 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11030 O_RDWR | O_CREAT, 0644); 11031 Os.chmod(file.getAbsolutePath(), 0644); 11032 return new ParcelFileDescriptor(fd); 11033 } catch (ErrnoException e) { 11034 throw new RemoteException("Failed to open: " + e.getMessage()); 11035 } 11036 } 11037 }; 11038 11039 int ret = PackageManager.INSTALL_SUCCEEDED; 11040 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11041 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11042 Slog.e(TAG, "Failed to copy package"); 11043 return ret; 11044 } 11045 11046 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11047 NativeLibraryHelper.Handle handle = null; 11048 try { 11049 handle = NativeLibraryHelper.Handle.create(codeFile); 11050 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11051 abiOverride); 11052 } catch (IOException e) { 11053 Slog.e(TAG, "Copying native libraries failed", e); 11054 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11055 } finally { 11056 IoUtils.closeQuietly(handle); 11057 } 11058 11059 return ret; 11060 } 11061 11062 int doPreInstall(int status) { 11063 if (status != PackageManager.INSTALL_SUCCEEDED) { 11064 cleanUp(); 11065 } 11066 return status; 11067 } 11068 11069 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11070 if (status != PackageManager.INSTALL_SUCCEEDED) { 11071 cleanUp(); 11072 return false; 11073 } 11074 11075 final File targetDir = codeFile.getParentFile(); 11076 final File beforeCodeFile = codeFile; 11077 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11078 11079 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11080 try { 11081 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11082 } catch (ErrnoException e) { 11083 Slog.w(TAG, "Failed to rename", e); 11084 return false; 11085 } 11086 11087 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11088 Slog.w(TAG, "Failed to restorecon"); 11089 return false; 11090 } 11091 11092 // Reflect the rename internally 11093 codeFile = afterCodeFile; 11094 resourceFile = afterCodeFile; 11095 11096 // Reflect the rename in scanned details 11097 pkg.codePath = afterCodeFile.getAbsolutePath(); 11098 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11099 pkg.baseCodePath); 11100 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11101 pkg.splitCodePaths); 11102 11103 // Reflect the rename in app info 11104 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11105 pkg.applicationInfo.setCodePath(pkg.codePath); 11106 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11107 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11108 pkg.applicationInfo.setResourcePath(pkg.codePath); 11109 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11110 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11111 11112 return true; 11113 } 11114 11115 int doPostInstall(int status, int uid) { 11116 if (status != PackageManager.INSTALL_SUCCEEDED) { 11117 cleanUp(); 11118 } 11119 return status; 11120 } 11121 11122 @Override 11123 String getCodePath() { 11124 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11125 } 11126 11127 @Override 11128 String getResourcePath() { 11129 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11130 } 11131 11132 private boolean cleanUp() { 11133 if (codeFile == null || !codeFile.exists()) { 11134 return false; 11135 } 11136 11137 if (codeFile.isDirectory()) { 11138 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11139 } else { 11140 codeFile.delete(); 11141 } 11142 11143 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11144 resourceFile.delete(); 11145 } 11146 11147 return true; 11148 } 11149 11150 void cleanUpResourcesLI() { 11151 // Try enumerating all code paths before deleting 11152 List<String> allCodePaths = Collections.EMPTY_LIST; 11153 if (codeFile != null && codeFile.exists()) { 11154 try { 11155 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11156 allCodePaths = pkg.getAllCodePaths(); 11157 } catch (PackageParserException e) { 11158 // Ignored; we tried our best 11159 } 11160 } 11161 11162 cleanUp(); 11163 removeDexFiles(allCodePaths, instructionSets); 11164 } 11165 11166 boolean doPostDeleteLI(boolean delete) { 11167 // XXX err, shouldn't we respect the delete flag? 11168 cleanUpResourcesLI(); 11169 return true; 11170 } 11171 } 11172 11173 private boolean isAsecExternal(String cid) { 11174 final String asecPath = PackageHelper.getSdFilesystem(cid); 11175 return !asecPath.startsWith(mAsecInternalPath); 11176 } 11177 11178 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11179 PackageManagerException { 11180 if (copyRet < 0) { 11181 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11182 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11183 throw new PackageManagerException(copyRet, message); 11184 } 11185 } 11186 } 11187 11188 /** 11189 * Extract the MountService "container ID" from the full code path of an 11190 * .apk. 11191 */ 11192 static String cidFromCodePath(String fullCodePath) { 11193 int eidx = fullCodePath.lastIndexOf("/"); 11194 String subStr1 = fullCodePath.substring(0, eidx); 11195 int sidx = subStr1.lastIndexOf("/"); 11196 return subStr1.substring(sidx+1, eidx); 11197 } 11198 11199 /** 11200 * Logic to handle installation of ASEC applications, including copying and 11201 * renaming logic. 11202 */ 11203 class AsecInstallArgs extends InstallArgs { 11204 static final String RES_FILE_NAME = "pkg.apk"; 11205 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11206 11207 String cid; 11208 String packagePath; 11209 String resourcePath; 11210 11211 /** New install */ 11212 AsecInstallArgs(InstallParams params) { 11213 super(params.origin, params.move, params.observer, params.installFlags, 11214 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11215 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11216 params.grantedRuntimePermissions, 11217 params.traceMethod, params.traceCookie); 11218 } 11219 11220 /** Existing install */ 11221 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11222 boolean isExternal, boolean isForwardLocked) { 11223 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11224 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11225 instructionSets, null, null, null, 0); 11226 // Hackily pretend we're still looking at a full code path 11227 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11228 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11229 } 11230 11231 // Extract cid from fullCodePath 11232 int eidx = fullCodePath.lastIndexOf("/"); 11233 String subStr1 = fullCodePath.substring(0, eidx); 11234 int sidx = subStr1.lastIndexOf("/"); 11235 cid = subStr1.substring(sidx+1, eidx); 11236 setMountPath(subStr1); 11237 } 11238 11239 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11240 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11241 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11242 instructionSets, null, null, null, 0); 11243 this.cid = cid; 11244 setMountPath(PackageHelper.getSdDir(cid)); 11245 } 11246 11247 void createCopyFile() { 11248 cid = mInstallerService.allocateExternalStageCidLegacy(); 11249 } 11250 11251 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11252 if (origin.staged) { 11253 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11254 cid = origin.cid; 11255 setMountPath(PackageHelper.getSdDir(cid)); 11256 return PackageManager.INSTALL_SUCCEEDED; 11257 } 11258 11259 if (temp) { 11260 createCopyFile(); 11261 } else { 11262 /* 11263 * Pre-emptively destroy the container since it's destroyed if 11264 * copying fails due to it existing anyway. 11265 */ 11266 PackageHelper.destroySdDir(cid); 11267 } 11268 11269 final String newMountPath = imcs.copyPackageToContainer( 11270 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11271 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11272 11273 if (newMountPath != null) { 11274 setMountPath(newMountPath); 11275 return PackageManager.INSTALL_SUCCEEDED; 11276 } else { 11277 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11278 } 11279 } 11280 11281 @Override 11282 String getCodePath() { 11283 return packagePath; 11284 } 11285 11286 @Override 11287 String getResourcePath() { 11288 return resourcePath; 11289 } 11290 11291 int doPreInstall(int status) { 11292 if (status != PackageManager.INSTALL_SUCCEEDED) { 11293 // Destroy container 11294 PackageHelper.destroySdDir(cid); 11295 } else { 11296 boolean mounted = PackageHelper.isContainerMounted(cid); 11297 if (!mounted) { 11298 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11299 Process.SYSTEM_UID); 11300 if (newMountPath != null) { 11301 setMountPath(newMountPath); 11302 } else { 11303 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11304 } 11305 } 11306 } 11307 return status; 11308 } 11309 11310 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11311 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11312 String newMountPath = null; 11313 if (PackageHelper.isContainerMounted(cid)) { 11314 // Unmount the container 11315 if (!PackageHelper.unMountSdDir(cid)) { 11316 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11317 return false; 11318 } 11319 } 11320 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11321 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11322 " which might be stale. Will try to clean up."); 11323 // Clean up the stale container and proceed to recreate. 11324 if (!PackageHelper.destroySdDir(newCacheId)) { 11325 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11326 return false; 11327 } 11328 // Successfully cleaned up stale container. Try to rename again. 11329 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11330 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11331 + " inspite of cleaning it up."); 11332 return false; 11333 } 11334 } 11335 if (!PackageHelper.isContainerMounted(newCacheId)) { 11336 Slog.w(TAG, "Mounting container " + newCacheId); 11337 newMountPath = PackageHelper.mountSdDir(newCacheId, 11338 getEncryptKey(), Process.SYSTEM_UID); 11339 } else { 11340 newMountPath = PackageHelper.getSdDir(newCacheId); 11341 } 11342 if (newMountPath == null) { 11343 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11344 return false; 11345 } 11346 Log.i(TAG, "Succesfully renamed " + cid + 11347 " to " + newCacheId + 11348 " at new path: " + newMountPath); 11349 cid = newCacheId; 11350 11351 final File beforeCodeFile = new File(packagePath); 11352 setMountPath(newMountPath); 11353 final File afterCodeFile = new File(packagePath); 11354 11355 // Reflect the rename in scanned details 11356 pkg.codePath = afterCodeFile.getAbsolutePath(); 11357 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11358 pkg.baseCodePath); 11359 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11360 pkg.splitCodePaths); 11361 11362 // Reflect the rename in app info 11363 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11364 pkg.applicationInfo.setCodePath(pkg.codePath); 11365 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11366 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11367 pkg.applicationInfo.setResourcePath(pkg.codePath); 11368 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11369 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11370 11371 return true; 11372 } 11373 11374 private void setMountPath(String mountPath) { 11375 final File mountFile = new File(mountPath); 11376 11377 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11378 if (monolithicFile.exists()) { 11379 packagePath = monolithicFile.getAbsolutePath(); 11380 if (isFwdLocked()) { 11381 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11382 } else { 11383 resourcePath = packagePath; 11384 } 11385 } else { 11386 packagePath = mountFile.getAbsolutePath(); 11387 resourcePath = packagePath; 11388 } 11389 } 11390 11391 int doPostInstall(int status, int uid) { 11392 if (status != PackageManager.INSTALL_SUCCEEDED) { 11393 cleanUp(); 11394 } else { 11395 final int groupOwner; 11396 final String protectedFile; 11397 if (isFwdLocked()) { 11398 groupOwner = UserHandle.getSharedAppGid(uid); 11399 protectedFile = RES_FILE_NAME; 11400 } else { 11401 groupOwner = -1; 11402 protectedFile = null; 11403 } 11404 11405 if (uid < Process.FIRST_APPLICATION_UID 11406 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11407 Slog.e(TAG, "Failed to finalize " + cid); 11408 PackageHelper.destroySdDir(cid); 11409 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11410 } 11411 11412 boolean mounted = PackageHelper.isContainerMounted(cid); 11413 if (!mounted) { 11414 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11415 } 11416 } 11417 return status; 11418 } 11419 11420 private void cleanUp() { 11421 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11422 11423 // Destroy secure container 11424 PackageHelper.destroySdDir(cid); 11425 } 11426 11427 private List<String> getAllCodePaths() { 11428 final File codeFile = new File(getCodePath()); 11429 if (codeFile != null && codeFile.exists()) { 11430 try { 11431 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11432 return pkg.getAllCodePaths(); 11433 } catch (PackageParserException e) { 11434 // Ignored; we tried our best 11435 } 11436 } 11437 return Collections.EMPTY_LIST; 11438 } 11439 11440 void cleanUpResourcesLI() { 11441 // Enumerate all code paths before deleting 11442 cleanUpResourcesLI(getAllCodePaths()); 11443 } 11444 11445 private void cleanUpResourcesLI(List<String> allCodePaths) { 11446 cleanUp(); 11447 removeDexFiles(allCodePaths, instructionSets); 11448 } 11449 11450 String getPackageName() { 11451 return getAsecPackageName(cid); 11452 } 11453 11454 boolean doPostDeleteLI(boolean delete) { 11455 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11456 final List<String> allCodePaths = getAllCodePaths(); 11457 boolean mounted = PackageHelper.isContainerMounted(cid); 11458 if (mounted) { 11459 // Unmount first 11460 if (PackageHelper.unMountSdDir(cid)) { 11461 mounted = false; 11462 } 11463 } 11464 if (!mounted && delete) { 11465 cleanUpResourcesLI(allCodePaths); 11466 } 11467 return !mounted; 11468 } 11469 11470 @Override 11471 int doPreCopy() { 11472 if (isFwdLocked()) { 11473 if (!PackageHelper.fixSdPermissions(cid, 11474 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11475 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11476 } 11477 } 11478 11479 return PackageManager.INSTALL_SUCCEEDED; 11480 } 11481 11482 @Override 11483 int doPostCopy(int uid) { 11484 if (isFwdLocked()) { 11485 if (uid < Process.FIRST_APPLICATION_UID 11486 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11487 RES_FILE_NAME)) { 11488 Slog.e(TAG, "Failed to finalize " + cid); 11489 PackageHelper.destroySdDir(cid); 11490 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11491 } 11492 } 11493 11494 return PackageManager.INSTALL_SUCCEEDED; 11495 } 11496 } 11497 11498 /** 11499 * Logic to handle movement of existing installed applications. 11500 */ 11501 class MoveInstallArgs extends InstallArgs { 11502 private File codeFile; 11503 private File resourceFile; 11504 11505 /** New install */ 11506 MoveInstallArgs(InstallParams params) { 11507 super(params.origin, params.move, params.observer, params.installFlags, 11508 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11509 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11510 params.grantedRuntimePermissions, 11511 params.traceMethod, params.traceCookie); 11512 } 11513 11514 int copyApk(IMediaContainerService imcs, boolean temp) { 11515 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11516 + move.fromUuid + " to " + move.toUuid); 11517 synchronized (mInstaller) { 11518 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11519 move.dataAppName, move.appId, move.seinfo) != 0) { 11520 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11521 } 11522 } 11523 11524 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11525 resourceFile = codeFile; 11526 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11527 11528 return PackageManager.INSTALL_SUCCEEDED; 11529 } 11530 11531 int doPreInstall(int status) { 11532 if (status != PackageManager.INSTALL_SUCCEEDED) { 11533 cleanUp(move.toUuid); 11534 } 11535 return status; 11536 } 11537 11538 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11539 if (status != PackageManager.INSTALL_SUCCEEDED) { 11540 cleanUp(move.toUuid); 11541 return false; 11542 } 11543 11544 // Reflect the move in app info 11545 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11546 pkg.applicationInfo.setCodePath(pkg.codePath); 11547 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11548 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11549 pkg.applicationInfo.setResourcePath(pkg.codePath); 11550 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11551 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11552 11553 return true; 11554 } 11555 11556 int doPostInstall(int status, int uid) { 11557 if (status == PackageManager.INSTALL_SUCCEEDED) { 11558 cleanUp(move.fromUuid); 11559 } else { 11560 cleanUp(move.toUuid); 11561 } 11562 return status; 11563 } 11564 11565 @Override 11566 String getCodePath() { 11567 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11568 } 11569 11570 @Override 11571 String getResourcePath() { 11572 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11573 } 11574 11575 private boolean cleanUp(String volumeUuid) { 11576 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11577 move.dataAppName); 11578 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11579 synchronized (mInstallLock) { 11580 // Clean up both app data and code 11581 removeDataDirsLI(volumeUuid, move.packageName); 11582 if (codeFile.isDirectory()) { 11583 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11584 } else { 11585 codeFile.delete(); 11586 } 11587 } 11588 return true; 11589 } 11590 11591 void cleanUpResourcesLI() { 11592 throw new UnsupportedOperationException(); 11593 } 11594 11595 boolean doPostDeleteLI(boolean delete) { 11596 throw new UnsupportedOperationException(); 11597 } 11598 } 11599 11600 static String getAsecPackageName(String packageCid) { 11601 int idx = packageCid.lastIndexOf("-"); 11602 if (idx == -1) { 11603 return packageCid; 11604 } 11605 return packageCid.substring(0, idx); 11606 } 11607 11608 // Utility method used to create code paths based on package name and available index. 11609 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11610 String idxStr = ""; 11611 int idx = 1; 11612 // Fall back to default value of idx=1 if prefix is not 11613 // part of oldCodePath 11614 if (oldCodePath != null) { 11615 String subStr = oldCodePath; 11616 // Drop the suffix right away 11617 if (suffix != null && subStr.endsWith(suffix)) { 11618 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11619 } 11620 // If oldCodePath already contains prefix find out the 11621 // ending index to either increment or decrement. 11622 int sidx = subStr.lastIndexOf(prefix); 11623 if (sidx != -1) { 11624 subStr = subStr.substring(sidx + prefix.length()); 11625 if (subStr != null) { 11626 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11627 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11628 } 11629 try { 11630 idx = Integer.parseInt(subStr); 11631 if (idx <= 1) { 11632 idx++; 11633 } else { 11634 idx--; 11635 } 11636 } catch(NumberFormatException e) { 11637 } 11638 } 11639 } 11640 } 11641 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11642 return prefix + idxStr; 11643 } 11644 11645 private File getNextCodePath(File targetDir, String packageName) { 11646 int suffix = 1; 11647 File result; 11648 do { 11649 result = new File(targetDir, packageName + "-" + suffix); 11650 suffix++; 11651 } while (result.exists()); 11652 return result; 11653 } 11654 11655 // Utility method that returns the relative package path with respect 11656 // to the installation directory. Like say for /data/data/com.test-1.apk 11657 // string com.test-1 is returned. 11658 static String deriveCodePathName(String codePath) { 11659 if (codePath == null) { 11660 return null; 11661 } 11662 final File codeFile = new File(codePath); 11663 final String name = codeFile.getName(); 11664 if (codeFile.isDirectory()) { 11665 return name; 11666 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11667 final int lastDot = name.lastIndexOf('.'); 11668 return name.substring(0, lastDot); 11669 } else { 11670 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11671 return null; 11672 } 11673 } 11674 11675 class PackageInstalledInfo { 11676 String name; 11677 int uid; 11678 // The set of users that originally had this package installed. 11679 int[] origUsers; 11680 // The set of users that now have this package installed. 11681 int[] newUsers; 11682 PackageParser.Package pkg; 11683 int returnCode; 11684 String returnMsg; 11685 PackageRemovedInfo removedInfo; 11686 11687 public void setError(int code, String msg) { 11688 returnCode = code; 11689 returnMsg = msg; 11690 Slog.w(TAG, msg); 11691 } 11692 11693 public void setError(String msg, PackageParserException e) { 11694 returnCode = e.error; 11695 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11696 Slog.w(TAG, msg, e); 11697 } 11698 11699 public void setError(String msg, PackageManagerException e) { 11700 returnCode = e.error; 11701 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11702 Slog.w(TAG, msg, e); 11703 } 11704 11705 // In some error cases we want to convey more info back to the observer 11706 String origPackage; 11707 String origPermission; 11708 } 11709 11710 /* 11711 * Install a non-existing package. 11712 */ 11713 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11714 UserHandle user, String installerPackageName, String volumeUuid, 11715 PackageInstalledInfo res) { 11716 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11717 11718 // Remember this for later, in case we need to rollback this install 11719 String pkgName = pkg.packageName; 11720 11721 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11722 // TODO: b/23350563 11723 final boolean dataDirExists = Environment 11724 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11725 11726 synchronized(mPackages) { 11727 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11728 // A package with the same name is already installed, though 11729 // it has been renamed to an older name. The package we 11730 // are trying to install should be installed as an update to 11731 // the existing one, but that has not been requested, so bail. 11732 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11733 + " without first uninstalling package running as " 11734 + mSettings.mRenamedPackages.get(pkgName)); 11735 return; 11736 } 11737 if (mPackages.containsKey(pkgName)) { 11738 // Don't allow installation over an existing package with the same name. 11739 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11740 + " without first uninstalling."); 11741 return; 11742 } 11743 } 11744 11745 try { 11746 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11747 System.currentTimeMillis(), user); 11748 11749 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11750 // delete the partially installed application. the data directory will have to be 11751 // restored if it was already existing 11752 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11753 // remove package from internal structures. Note that we want deletePackageX to 11754 // delete the package data and cache directories that it created in 11755 // scanPackageLocked, unless those directories existed before we even tried to 11756 // install. 11757 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11758 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11759 res.removedInfo, true); 11760 } 11761 11762 } catch (PackageManagerException e) { 11763 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11764 } 11765 11766 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11767 } 11768 11769 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11770 // Can't rotate keys during boot or if sharedUser. 11771 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11772 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11773 return false; 11774 } 11775 // app is using upgradeKeySets; make sure all are valid 11776 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11777 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11778 for (int i = 0; i < upgradeKeySets.length; i++) { 11779 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11780 Slog.wtf(TAG, "Package " 11781 + (oldPs.name != null ? oldPs.name : "<null>") 11782 + " contains upgrade-key-set reference to unknown key-set: " 11783 + upgradeKeySets[i] 11784 + " reverting to signatures check."); 11785 return false; 11786 } 11787 } 11788 return true; 11789 } 11790 11791 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11792 // Upgrade keysets are being used. Determine if new package has a superset of the 11793 // required keys. 11794 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11795 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11796 for (int i = 0; i < upgradeKeySets.length; i++) { 11797 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11798 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11799 return true; 11800 } 11801 } 11802 return false; 11803 } 11804 11805 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11806 UserHandle user, String installerPackageName, String volumeUuid, 11807 PackageInstalledInfo res) { 11808 final PackageParser.Package oldPackage; 11809 final String pkgName = pkg.packageName; 11810 final int[] allUsers; 11811 final boolean[] perUserInstalled; 11812 11813 // First find the old package info and check signatures 11814 synchronized(mPackages) { 11815 oldPackage = mPackages.get(pkgName); 11816 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11817 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11818 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11819 if(!checkUpgradeKeySetLP(ps, pkg)) { 11820 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11821 "New package not signed by keys specified by upgrade-keysets: " 11822 + pkgName); 11823 return; 11824 } 11825 } else { 11826 // default to original signature matching 11827 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11828 != PackageManager.SIGNATURE_MATCH) { 11829 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11830 "New package has a different signature: " + pkgName); 11831 return; 11832 } 11833 } 11834 11835 // In case of rollback, remember per-user/profile install state 11836 allUsers = sUserManager.getUserIds(); 11837 perUserInstalled = new boolean[allUsers.length]; 11838 for (int i = 0; i < allUsers.length; i++) { 11839 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11840 } 11841 } 11842 11843 boolean sysPkg = (isSystemApp(oldPackage)); 11844 if (sysPkg) { 11845 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11846 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11847 } else { 11848 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11849 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11850 } 11851 } 11852 11853 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11854 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11855 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11856 String volumeUuid, PackageInstalledInfo res) { 11857 String pkgName = deletedPackage.packageName; 11858 boolean deletedPkg = true; 11859 boolean updatedSettings = false; 11860 11861 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11862 + deletedPackage); 11863 long origUpdateTime; 11864 if (pkg.mExtras != null) { 11865 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11866 } else { 11867 origUpdateTime = 0; 11868 } 11869 11870 // First delete the existing package while retaining the data directory 11871 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11872 res.removedInfo, true)) { 11873 // If the existing package wasn't successfully deleted 11874 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11875 deletedPkg = false; 11876 } else { 11877 // Successfully deleted the old package; proceed with replace. 11878 11879 // If deleted package lived in a container, give users a chance to 11880 // relinquish resources before killing. 11881 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11882 if (DEBUG_INSTALL) { 11883 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11884 } 11885 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11886 final ArrayList<String> pkgList = new ArrayList<String>(1); 11887 pkgList.add(deletedPackage.applicationInfo.packageName); 11888 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11889 } 11890 11891 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11892 try { 11893 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 11894 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11895 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11896 perUserInstalled, res, user); 11897 updatedSettings = true; 11898 } catch (PackageManagerException e) { 11899 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11900 } 11901 } 11902 11903 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11904 // remove package from internal structures. Note that we want deletePackageX to 11905 // delete the package data and cache directories that it created in 11906 // scanPackageLocked, unless those directories existed before we even tried to 11907 // install. 11908 if(updatedSettings) { 11909 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11910 deletePackageLI( 11911 pkgName, null, true, allUsers, perUserInstalled, 11912 PackageManager.DELETE_KEEP_DATA, 11913 res.removedInfo, true); 11914 } 11915 // Since we failed to install the new package we need to restore the old 11916 // package that we deleted. 11917 if (deletedPkg) { 11918 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11919 File restoreFile = new File(deletedPackage.codePath); 11920 // Parse old package 11921 boolean oldExternal = isExternal(deletedPackage); 11922 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11923 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11924 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11925 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11926 try { 11927 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 11928 null); 11929 } catch (PackageManagerException e) { 11930 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11931 + e.getMessage()); 11932 return; 11933 } 11934 // Restore of old package succeeded. Update permissions. 11935 // writer 11936 synchronized (mPackages) { 11937 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11938 UPDATE_PERMISSIONS_ALL); 11939 // can downgrade to reader 11940 mSettings.writeLPr(); 11941 } 11942 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11943 } 11944 } 11945 } 11946 11947 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11948 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11949 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11950 String volumeUuid, PackageInstalledInfo res) { 11951 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11952 + ", old=" + deletedPackage); 11953 boolean disabledSystem = false; 11954 boolean updatedSettings = false; 11955 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11956 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11957 != 0) { 11958 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11959 } 11960 String packageName = deletedPackage.packageName; 11961 if (packageName == null) { 11962 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11963 "Attempt to delete null packageName."); 11964 return; 11965 } 11966 PackageParser.Package oldPkg; 11967 PackageSetting oldPkgSetting; 11968 // reader 11969 synchronized (mPackages) { 11970 oldPkg = mPackages.get(packageName); 11971 oldPkgSetting = mSettings.mPackages.get(packageName); 11972 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11973 (oldPkgSetting == null)) { 11974 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11975 "Couldn't find package:" + packageName + " information"); 11976 return; 11977 } 11978 } 11979 11980 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 11981 11982 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11983 res.removedInfo.removedPackage = packageName; 11984 // Remove existing system package 11985 removePackageLI(oldPkgSetting, true); 11986 // writer 11987 synchronized (mPackages) { 11988 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11989 if (!disabledSystem && deletedPackage != null) { 11990 // We didn't need to disable the .apk as a current system package, 11991 // which means we are replacing another update that is already 11992 // installed. We need to make sure to delete the older one's .apk. 11993 res.removedInfo.args = createInstallArgsForExisting(0, 11994 deletedPackage.applicationInfo.getCodePath(), 11995 deletedPackage.applicationInfo.getResourcePath(), 11996 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11997 } else { 11998 res.removedInfo.args = null; 11999 } 12000 } 12001 12002 // Successfully disabled the old package. Now proceed with re-installation 12003 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12004 12005 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12006 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12007 12008 PackageParser.Package newPackage = null; 12009 try { 12010 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12011 if (newPackage.mExtras != null) { 12012 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12013 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12014 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12015 12016 // is the update attempting to change shared user? that isn't going to work... 12017 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12018 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12019 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12020 + " to " + newPkgSetting.sharedUser); 12021 updatedSettings = true; 12022 } 12023 } 12024 12025 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12026 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12027 perUserInstalled, res, user); 12028 updatedSettings = true; 12029 } 12030 12031 } catch (PackageManagerException e) { 12032 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12033 } 12034 12035 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12036 // Re installation failed. Restore old information 12037 // Remove new pkg information 12038 if (newPackage != null) { 12039 removeInstalledPackageLI(newPackage, true); 12040 } 12041 // Add back the old system package 12042 try { 12043 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12044 } catch (PackageManagerException e) { 12045 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12046 } 12047 // Restore the old system information in Settings 12048 synchronized (mPackages) { 12049 if (disabledSystem) { 12050 mSettings.enableSystemPackageLPw(packageName); 12051 } 12052 if (updatedSettings) { 12053 mSettings.setInstallerPackageName(packageName, 12054 oldPkgSetting.installerPackageName); 12055 } 12056 mSettings.writeLPr(); 12057 } 12058 } 12059 } 12060 12061 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12062 // Collect all used permissions in the UID 12063 ArraySet<String> usedPermissions = new ArraySet<>(); 12064 final int packageCount = su.packages.size(); 12065 for (int i = 0; i < packageCount; i++) { 12066 PackageSetting ps = su.packages.valueAt(i); 12067 if (ps.pkg == null) { 12068 continue; 12069 } 12070 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12071 for (int j = 0; j < requestedPermCount; j++) { 12072 String permission = ps.pkg.requestedPermissions.get(j); 12073 BasePermission bp = mSettings.mPermissions.get(permission); 12074 if (bp != null) { 12075 usedPermissions.add(permission); 12076 } 12077 } 12078 } 12079 12080 PermissionsState permissionsState = su.getPermissionsState(); 12081 // Prune install permissions 12082 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12083 final int installPermCount = installPermStates.size(); 12084 for (int i = installPermCount - 1; i >= 0; i--) { 12085 PermissionState permissionState = installPermStates.get(i); 12086 if (!usedPermissions.contains(permissionState.getName())) { 12087 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12088 if (bp != null) { 12089 permissionsState.revokeInstallPermission(bp); 12090 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12091 PackageManager.MASK_PERMISSION_FLAGS, 0); 12092 } 12093 } 12094 } 12095 12096 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12097 12098 // Prune runtime permissions 12099 for (int userId : allUserIds) { 12100 List<PermissionState> runtimePermStates = permissionsState 12101 .getRuntimePermissionStates(userId); 12102 final int runtimePermCount = runtimePermStates.size(); 12103 for (int i = runtimePermCount - 1; i >= 0; i--) { 12104 PermissionState permissionState = runtimePermStates.get(i); 12105 if (!usedPermissions.contains(permissionState.getName())) { 12106 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12107 if (bp != null) { 12108 permissionsState.revokeRuntimePermission(bp, userId); 12109 permissionsState.updatePermissionFlags(bp, userId, 12110 PackageManager.MASK_PERMISSION_FLAGS, 0); 12111 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12112 runtimePermissionChangedUserIds, userId); 12113 } 12114 } 12115 } 12116 } 12117 12118 return runtimePermissionChangedUserIds; 12119 } 12120 12121 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12122 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12123 UserHandle user) { 12124 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12125 12126 String pkgName = newPackage.packageName; 12127 synchronized (mPackages) { 12128 //write settings. the installStatus will be incomplete at this stage. 12129 //note that the new package setting would have already been 12130 //added to mPackages. It hasn't been persisted yet. 12131 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12132 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12133 mSettings.writeLPr(); 12134 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12135 } 12136 12137 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12138 synchronized (mPackages) { 12139 updatePermissionsLPw(newPackage.packageName, newPackage, 12140 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12141 ? UPDATE_PERMISSIONS_ALL : 0)); 12142 // For system-bundled packages, we assume that installing an upgraded version 12143 // of the package implies that the user actually wants to run that new code, 12144 // so we enable the package. 12145 PackageSetting ps = mSettings.mPackages.get(pkgName); 12146 if (ps != null) { 12147 if (isSystemApp(newPackage)) { 12148 // NB: implicit assumption that system package upgrades apply to all users 12149 if (DEBUG_INSTALL) { 12150 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12151 } 12152 if (res.origUsers != null) { 12153 for (int userHandle : res.origUsers) { 12154 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12155 userHandle, installerPackageName); 12156 } 12157 } 12158 // Also convey the prior install/uninstall state 12159 if (allUsers != null && perUserInstalled != null) { 12160 for (int i = 0; i < allUsers.length; i++) { 12161 if (DEBUG_INSTALL) { 12162 Slog.d(TAG, " user " + allUsers[i] 12163 + " => " + perUserInstalled[i]); 12164 } 12165 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12166 } 12167 // these install state changes will be persisted in the 12168 // upcoming call to mSettings.writeLPr(). 12169 } 12170 } 12171 // It's implied that when a user requests installation, they want the app to be 12172 // installed and enabled. 12173 int userId = user.getIdentifier(); 12174 if (userId != UserHandle.USER_ALL) { 12175 ps.setInstalled(true, userId); 12176 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12177 } 12178 } 12179 res.name = pkgName; 12180 res.uid = newPackage.applicationInfo.uid; 12181 res.pkg = newPackage; 12182 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12183 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12184 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12185 //to update install status 12186 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12187 mSettings.writeLPr(); 12188 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12189 } 12190 12191 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12192 } 12193 12194 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12195 try { 12196 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12197 installPackageLI(args, res); 12198 } finally { 12199 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12200 } 12201 } 12202 12203 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12204 final int installFlags = args.installFlags; 12205 final String installerPackageName = args.installerPackageName; 12206 final String volumeUuid = args.volumeUuid; 12207 final File tmpPackageFile = new File(args.getCodePath()); 12208 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12209 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12210 || (args.volumeUuid != null)); 12211 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12212 boolean replace = false; 12213 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12214 if (args.move != null) { 12215 // moving a complete application; perfom an initial scan on the new install location 12216 scanFlags |= SCAN_INITIAL; 12217 } 12218 // Result object to be returned 12219 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12220 12221 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12222 12223 // Retrieve PackageSettings and parse package 12224 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12225 | PackageParser.PARSE_ENFORCE_CODE 12226 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12227 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12228 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12229 PackageParser pp = new PackageParser(); 12230 pp.setSeparateProcesses(mSeparateProcesses); 12231 pp.setDisplayMetrics(mMetrics); 12232 12233 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12234 final PackageParser.Package pkg; 12235 try { 12236 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12237 } catch (PackageParserException e) { 12238 res.setError("Failed parse during installPackageLI", e); 12239 return; 12240 } finally { 12241 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12242 } 12243 12244 // Mark that we have an install time CPU ABI override. 12245 pkg.cpuAbiOverride = args.abiOverride; 12246 12247 String pkgName = res.name = pkg.packageName; 12248 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12249 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12250 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12251 return; 12252 } 12253 } 12254 12255 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12256 try { 12257 pp.collectCertificates(pkg, parseFlags); 12258 } catch (PackageParserException e) { 12259 res.setError("Failed collect during installPackageLI", e); 12260 return; 12261 } finally { 12262 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12263 } 12264 12265 /* If the installer passed in a manifest digest, compare it now. */ 12266 if (args.manifestDigest != null) { 12267 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12268 try { 12269 pp.collectManifestDigest(pkg); 12270 } catch (PackageParserException e) { 12271 res.setError("Failed collect during installPackageLI", e); 12272 return; 12273 } finally { 12274 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12275 } 12276 12277 if (DEBUG_INSTALL) { 12278 final String parsedManifest = pkg.manifestDigest == null ? "null" 12279 : pkg.manifestDigest.toString(); 12280 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12281 + parsedManifest); 12282 } 12283 12284 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12285 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12286 return; 12287 } 12288 } else if (DEBUG_INSTALL) { 12289 final String parsedManifest = pkg.manifestDigest == null 12290 ? "null" : pkg.manifestDigest.toString(); 12291 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12292 } 12293 12294 // Get rid of all references to package scan path via parser. 12295 pp = null; 12296 String oldCodePath = null; 12297 boolean systemApp = false; 12298 synchronized (mPackages) { 12299 // Check if installing already existing package 12300 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12301 String oldName = mSettings.mRenamedPackages.get(pkgName); 12302 if (pkg.mOriginalPackages != null 12303 && pkg.mOriginalPackages.contains(oldName) 12304 && mPackages.containsKey(oldName)) { 12305 // This package is derived from an original package, 12306 // and this device has been updating from that original 12307 // name. We must continue using the original name, so 12308 // rename the new package here. 12309 pkg.setPackageName(oldName); 12310 pkgName = pkg.packageName; 12311 replace = true; 12312 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12313 + oldName + " pkgName=" + pkgName); 12314 } else if (mPackages.containsKey(pkgName)) { 12315 // This package, under its official name, already exists 12316 // on the device; we should replace it. 12317 replace = true; 12318 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12319 } 12320 12321 // Prevent apps opting out from runtime permissions 12322 if (replace) { 12323 PackageParser.Package oldPackage = mPackages.get(pkgName); 12324 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12325 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12326 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12327 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12328 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12329 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12330 + " doesn't support runtime permissions but the old" 12331 + " target SDK " + oldTargetSdk + " does."); 12332 return; 12333 } 12334 } 12335 } 12336 12337 PackageSetting ps = mSettings.mPackages.get(pkgName); 12338 if (ps != null) { 12339 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12340 12341 // Quick sanity check that we're signed correctly if updating; 12342 // we'll check this again later when scanning, but we want to 12343 // bail early here before tripping over redefined permissions. 12344 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12345 if (!checkUpgradeKeySetLP(ps, pkg)) { 12346 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12347 + pkg.packageName + " upgrade keys do not match the " 12348 + "previously installed version"); 12349 return; 12350 } 12351 } else { 12352 try { 12353 verifySignaturesLP(ps, pkg); 12354 } catch (PackageManagerException e) { 12355 res.setError(e.error, e.getMessage()); 12356 return; 12357 } 12358 } 12359 12360 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12361 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12362 systemApp = (ps.pkg.applicationInfo.flags & 12363 ApplicationInfo.FLAG_SYSTEM) != 0; 12364 } 12365 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12366 } 12367 12368 // Check whether the newly-scanned package wants to define an already-defined perm 12369 int N = pkg.permissions.size(); 12370 for (int i = N-1; i >= 0; i--) { 12371 PackageParser.Permission perm = pkg.permissions.get(i); 12372 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12373 if (bp != null) { 12374 // If the defining package is signed with our cert, it's okay. This 12375 // also includes the "updating the same package" case, of course. 12376 // "updating same package" could also involve key-rotation. 12377 final boolean sigsOk; 12378 if (bp.sourcePackage.equals(pkg.packageName) 12379 && (bp.packageSetting instanceof PackageSetting) 12380 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12381 scanFlags))) { 12382 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12383 } else { 12384 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12385 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12386 } 12387 if (!sigsOk) { 12388 // If the owning package is the system itself, we log but allow 12389 // install to proceed; we fail the install on all other permission 12390 // redefinitions. 12391 if (!bp.sourcePackage.equals("android")) { 12392 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12393 + pkg.packageName + " attempting to redeclare permission " 12394 + perm.info.name + " already owned by " + bp.sourcePackage); 12395 res.origPermission = perm.info.name; 12396 res.origPackage = bp.sourcePackage; 12397 return; 12398 } else { 12399 Slog.w(TAG, "Package " + pkg.packageName 12400 + " attempting to redeclare system permission " 12401 + perm.info.name + "; ignoring new declaration"); 12402 pkg.permissions.remove(i); 12403 } 12404 } 12405 } 12406 } 12407 12408 } 12409 12410 if (systemApp && onExternal) { 12411 // Disable updates to system apps on sdcard 12412 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12413 "Cannot install updates to system apps on sdcard"); 12414 return; 12415 } 12416 12417 if (args.move != null) { 12418 // We did an in-place move, so dex is ready to roll 12419 scanFlags |= SCAN_NO_DEX; 12420 scanFlags |= SCAN_MOVE; 12421 12422 synchronized (mPackages) { 12423 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12424 if (ps == null) { 12425 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12426 "Missing settings for moved package " + pkgName); 12427 } 12428 12429 // We moved the entire application as-is, so bring over the 12430 // previously derived ABI information. 12431 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12432 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12433 } 12434 12435 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12436 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12437 scanFlags |= SCAN_NO_DEX; 12438 12439 try { 12440 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12441 true /* extract libs */); 12442 } catch (PackageManagerException pme) { 12443 Slog.e(TAG, "Error deriving application ABI", pme); 12444 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12445 return; 12446 } 12447 } 12448 12449 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12450 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12451 return; 12452 } 12453 12454 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12455 12456 if (replace) { 12457 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12458 installerPackageName, volumeUuid, res); 12459 } else { 12460 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12461 args.user, installerPackageName, volumeUuid, res); 12462 } 12463 synchronized (mPackages) { 12464 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12465 if (ps != null) { 12466 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12467 } 12468 } 12469 } 12470 12471 private void startIntentFilterVerifications(int userId, boolean replacing, 12472 PackageParser.Package pkg) { 12473 if (mIntentFilterVerifierComponent == null) { 12474 Slog.w(TAG, "No IntentFilter verification will not be done as " 12475 + "there is no IntentFilterVerifier available!"); 12476 return; 12477 } 12478 12479 final int verifierUid = getPackageUid( 12480 mIntentFilterVerifierComponent.getPackageName(), 12481 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12482 12483 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12484 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12485 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12486 mHandler.sendMessage(msg); 12487 } 12488 12489 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12490 PackageParser.Package pkg) { 12491 int size = pkg.activities.size(); 12492 if (size == 0) { 12493 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12494 "No activity, so no need to verify any IntentFilter!"); 12495 return; 12496 } 12497 12498 final boolean hasDomainURLs = hasDomainURLs(pkg); 12499 if (!hasDomainURLs) { 12500 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12501 "No domain URLs, so no need to verify any IntentFilter!"); 12502 return; 12503 } 12504 12505 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12506 + " if any IntentFilter from the " + size 12507 + " Activities needs verification ..."); 12508 12509 int count = 0; 12510 final String packageName = pkg.packageName; 12511 12512 synchronized (mPackages) { 12513 // If this is a new install and we see that we've already run verification for this 12514 // package, we have nothing to do: it means the state was restored from backup. 12515 if (!replacing) { 12516 IntentFilterVerificationInfo ivi = 12517 mSettings.getIntentFilterVerificationLPr(packageName); 12518 if (ivi != null) { 12519 if (DEBUG_DOMAIN_VERIFICATION) { 12520 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12521 + ivi.getStatusString()); 12522 } 12523 return; 12524 } 12525 } 12526 12527 // If any filters need to be verified, then all need to be. 12528 boolean needToVerify = false; 12529 for (PackageParser.Activity a : pkg.activities) { 12530 for (ActivityIntentInfo filter : a.intents) { 12531 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12532 if (DEBUG_DOMAIN_VERIFICATION) { 12533 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12534 } 12535 needToVerify = true; 12536 break; 12537 } 12538 } 12539 } 12540 12541 if (needToVerify) { 12542 final int verificationId = mIntentFilterVerificationToken++; 12543 for (PackageParser.Activity a : pkg.activities) { 12544 for (ActivityIntentInfo filter : a.intents) { 12545 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12546 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12547 "Verification needed for IntentFilter:" + filter.toString()); 12548 mIntentFilterVerifier.addOneIntentFilterVerification( 12549 verifierUid, userId, verificationId, filter, packageName); 12550 count++; 12551 } 12552 } 12553 } 12554 } 12555 } 12556 12557 if (count > 0) { 12558 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12559 + " IntentFilter verification" + (count > 1 ? "s" : "") 12560 + " for userId:" + userId); 12561 mIntentFilterVerifier.startVerifications(userId); 12562 } else { 12563 if (DEBUG_DOMAIN_VERIFICATION) { 12564 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12565 } 12566 } 12567 } 12568 12569 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12570 final ComponentName cn = filter.activity.getComponentName(); 12571 final String packageName = cn.getPackageName(); 12572 12573 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12574 packageName); 12575 if (ivi == null) { 12576 return true; 12577 } 12578 int status = ivi.getStatus(); 12579 switch (status) { 12580 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12581 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12582 return true; 12583 12584 default: 12585 // Nothing to do 12586 return false; 12587 } 12588 } 12589 12590 private static boolean isMultiArch(PackageSetting ps) { 12591 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12592 } 12593 12594 private static boolean isMultiArch(ApplicationInfo info) { 12595 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12596 } 12597 12598 private static boolean isExternal(PackageParser.Package pkg) { 12599 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12600 } 12601 12602 private static boolean isExternal(PackageSetting ps) { 12603 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12604 } 12605 12606 private static boolean isExternal(ApplicationInfo info) { 12607 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12608 } 12609 12610 private static boolean isSystemApp(PackageParser.Package pkg) { 12611 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12612 } 12613 12614 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12615 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12616 } 12617 12618 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12619 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12620 } 12621 12622 private static boolean isSystemApp(PackageSetting ps) { 12623 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12624 } 12625 12626 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12627 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12628 } 12629 12630 private int packageFlagsToInstallFlags(PackageSetting ps) { 12631 int installFlags = 0; 12632 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12633 // This existing package was an external ASEC install when we have 12634 // the external flag without a UUID 12635 installFlags |= PackageManager.INSTALL_EXTERNAL; 12636 } 12637 if (ps.isForwardLocked()) { 12638 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12639 } 12640 return installFlags; 12641 } 12642 12643 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12644 if (isExternal(pkg)) { 12645 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12646 return StorageManager.UUID_PRIMARY_PHYSICAL; 12647 } else { 12648 return pkg.volumeUuid; 12649 } 12650 } else { 12651 return StorageManager.UUID_PRIVATE_INTERNAL; 12652 } 12653 } 12654 12655 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12656 if (isExternal(pkg)) { 12657 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12658 return mSettings.getExternalVersion(); 12659 } else { 12660 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12661 } 12662 } else { 12663 return mSettings.getInternalVersion(); 12664 } 12665 } 12666 12667 private void deleteTempPackageFiles() { 12668 final FilenameFilter filter = new FilenameFilter() { 12669 public boolean accept(File dir, String name) { 12670 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12671 } 12672 }; 12673 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12674 file.delete(); 12675 } 12676 } 12677 12678 @Override 12679 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12680 int flags) { 12681 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12682 flags); 12683 } 12684 12685 @Override 12686 public void deletePackage(final String packageName, 12687 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12688 mContext.enforceCallingOrSelfPermission( 12689 android.Manifest.permission.DELETE_PACKAGES, null); 12690 Preconditions.checkNotNull(packageName); 12691 Preconditions.checkNotNull(observer); 12692 final int uid = Binder.getCallingUid(); 12693 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12694 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12695 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12696 mContext.enforceCallingPermission( 12697 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12698 "deletePackage for user " + userId); 12699 } 12700 12701 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12702 try { 12703 observer.onPackageDeleted(packageName, 12704 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12705 } catch (RemoteException re) { 12706 } 12707 return; 12708 } 12709 12710 for (int currentUserId : users) { 12711 if (getBlockUninstallForUser(packageName, currentUserId)) { 12712 try { 12713 observer.onPackageDeleted(packageName, 12714 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12715 } catch (RemoteException re) { 12716 } 12717 return; 12718 } 12719 } 12720 12721 if (DEBUG_REMOVE) { 12722 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12723 } 12724 // Queue up an async operation since the package deletion may take a little while. 12725 mHandler.post(new Runnable() { 12726 public void run() { 12727 mHandler.removeCallbacks(this); 12728 final int returnCode = deletePackageX(packageName, userId, flags); 12729 try { 12730 observer.onPackageDeleted(packageName, returnCode, null); 12731 } catch (RemoteException e) { 12732 Log.i(TAG, "Observer no longer exists."); 12733 } //end catch 12734 } //end run 12735 }); 12736 } 12737 12738 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12739 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12740 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12741 try { 12742 if (dpm != null) { 12743 // Does the package contains the device owner? 12744 if (dpm.isDeviceOwnerPackage(packageName)) { 12745 return true; 12746 } 12747 // Does it contain a device admin for any user? 12748 int[] users; 12749 if (userId == UserHandle.USER_ALL) { 12750 users = sUserManager.getUserIds(); 12751 } else { 12752 users = new int[]{userId}; 12753 } 12754 for (int i = 0; i < users.length; ++i) { 12755 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12756 return true; 12757 } 12758 } 12759 } 12760 } catch (RemoteException e) { 12761 } 12762 return false; 12763 } 12764 12765 /** 12766 * This method is an internal method that could be get invoked either 12767 * to delete an installed package or to clean up a failed installation. 12768 * After deleting an installed package, a broadcast is sent to notify any 12769 * listeners that the package has been installed. For cleaning up a failed 12770 * installation, the broadcast is not necessary since the package's 12771 * installation wouldn't have sent the initial broadcast either 12772 * The key steps in deleting a package are 12773 * deleting the package information in internal structures like mPackages, 12774 * deleting the packages base directories through installd 12775 * updating mSettings to reflect current status 12776 * persisting settings for later use 12777 * sending a broadcast if necessary 12778 */ 12779 private int deletePackageX(String packageName, int userId, int flags) { 12780 final PackageRemovedInfo info = new PackageRemovedInfo(); 12781 final boolean res; 12782 12783 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12784 ? UserHandle.ALL : new UserHandle(userId); 12785 12786 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12787 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12788 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12789 } 12790 12791 boolean removedForAllUsers = false; 12792 boolean systemUpdate = false; 12793 12794 // for the uninstall-updates case and restricted profiles, remember the per- 12795 // userhandle installed state 12796 int[] allUsers; 12797 boolean[] perUserInstalled; 12798 synchronized (mPackages) { 12799 PackageSetting ps = mSettings.mPackages.get(packageName); 12800 allUsers = sUserManager.getUserIds(); 12801 perUserInstalled = new boolean[allUsers.length]; 12802 for (int i = 0; i < allUsers.length; i++) { 12803 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12804 } 12805 } 12806 12807 synchronized (mInstallLock) { 12808 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12809 res = deletePackageLI(packageName, removeForUser, 12810 true, allUsers, perUserInstalled, 12811 flags | REMOVE_CHATTY, info, true); 12812 systemUpdate = info.isRemovedPackageSystemUpdate; 12813 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12814 removedForAllUsers = true; 12815 } 12816 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12817 + " removedForAllUsers=" + removedForAllUsers); 12818 } 12819 12820 if (res) { 12821 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12822 12823 // If the removed package was a system update, the old system package 12824 // was re-enabled; we need to broadcast this information 12825 if (systemUpdate) { 12826 Bundle extras = new Bundle(1); 12827 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12828 ? info.removedAppId : info.uid); 12829 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12830 12831 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12832 extras, null, null, null); 12833 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12834 extras, null, null, null); 12835 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12836 null, packageName, null, null); 12837 } 12838 } 12839 // Force a gc here. 12840 Runtime.getRuntime().gc(); 12841 // Delete the resources here after sending the broadcast to let 12842 // other processes clean up before deleting resources. 12843 if (info.args != null) { 12844 synchronized (mInstallLock) { 12845 info.args.doPostDeleteLI(true); 12846 } 12847 } 12848 12849 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12850 } 12851 12852 class PackageRemovedInfo { 12853 String removedPackage; 12854 int uid = -1; 12855 int removedAppId = -1; 12856 int[] removedUsers = null; 12857 boolean isRemovedPackageSystemUpdate = false; 12858 // Clean up resources deleted packages. 12859 InstallArgs args = null; 12860 12861 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12862 Bundle extras = new Bundle(1); 12863 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12864 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12865 if (replacing) { 12866 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12867 } 12868 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12869 if (removedPackage != null) { 12870 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12871 extras, null, null, removedUsers); 12872 if (fullRemove && !replacing) { 12873 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12874 extras, null, null, removedUsers); 12875 } 12876 } 12877 if (removedAppId >= 0) { 12878 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12879 removedUsers); 12880 } 12881 } 12882 } 12883 12884 /* 12885 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12886 * flag is not set, the data directory is removed as well. 12887 * make sure this flag is set for partially installed apps. If not its meaningless to 12888 * delete a partially installed application. 12889 */ 12890 private void removePackageDataLI(PackageSetting ps, 12891 int[] allUserHandles, boolean[] perUserInstalled, 12892 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12893 String packageName = ps.name; 12894 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12895 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12896 // Retrieve object to delete permissions for shared user later on 12897 final PackageSetting deletedPs; 12898 // reader 12899 synchronized (mPackages) { 12900 deletedPs = mSettings.mPackages.get(packageName); 12901 if (outInfo != null) { 12902 outInfo.removedPackage = packageName; 12903 outInfo.removedUsers = deletedPs != null 12904 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12905 : null; 12906 } 12907 } 12908 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12909 removeDataDirsLI(ps.volumeUuid, packageName); 12910 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12911 } 12912 // writer 12913 synchronized (mPackages) { 12914 if (deletedPs != null) { 12915 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12916 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12917 clearDefaultBrowserIfNeeded(packageName); 12918 if (outInfo != null) { 12919 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12920 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12921 } 12922 updatePermissionsLPw(deletedPs.name, null, 0); 12923 if (deletedPs.sharedUser != null) { 12924 // Remove permissions associated with package. Since runtime 12925 // permissions are per user we have to kill the removed package 12926 // or packages running under the shared user of the removed 12927 // package if revoking the permissions requested only by the removed 12928 // package is successful and this causes a change in gids. 12929 for (int userId : UserManagerService.getInstance().getUserIds()) { 12930 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12931 userId); 12932 if (userIdToKill == UserHandle.USER_ALL 12933 || userIdToKill >= UserHandle.USER_SYSTEM) { 12934 // If gids changed for this user, kill all affected packages. 12935 mHandler.post(new Runnable() { 12936 @Override 12937 public void run() { 12938 // This has to happen with no lock held. 12939 killApplication(deletedPs.name, deletedPs.appId, 12940 KILL_APP_REASON_GIDS_CHANGED); 12941 } 12942 }); 12943 break; 12944 } 12945 } 12946 } 12947 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12948 } 12949 // make sure to preserve per-user disabled state if this removal was just 12950 // a downgrade of a system app to the factory package 12951 if (allUserHandles != null && perUserInstalled != null) { 12952 if (DEBUG_REMOVE) { 12953 Slog.d(TAG, "Propagating install state across downgrade"); 12954 } 12955 for (int i = 0; i < allUserHandles.length; i++) { 12956 if (DEBUG_REMOVE) { 12957 Slog.d(TAG, " user " + allUserHandles[i] 12958 + " => " + perUserInstalled[i]); 12959 } 12960 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12961 } 12962 } 12963 } 12964 // can downgrade to reader 12965 if (writeSettings) { 12966 // Save settings now 12967 mSettings.writeLPr(); 12968 } 12969 } 12970 if (outInfo != null) { 12971 // A user ID was deleted here. Go through all users and remove it 12972 // from KeyStore. 12973 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12974 } 12975 } 12976 12977 static boolean locationIsPrivileged(File path) { 12978 try { 12979 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12980 .getCanonicalPath(); 12981 return path.getCanonicalPath().startsWith(privilegedAppDir); 12982 } catch (IOException e) { 12983 Slog.e(TAG, "Unable to access code path " + path); 12984 } 12985 return false; 12986 } 12987 12988 /* 12989 * Tries to delete system package. 12990 */ 12991 private boolean deleteSystemPackageLI(PackageSetting newPs, 12992 int[] allUserHandles, boolean[] perUserInstalled, 12993 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12994 final boolean applyUserRestrictions 12995 = (allUserHandles != null) && (perUserInstalled != null); 12996 PackageSetting disabledPs = null; 12997 // Confirm if the system package has been updated 12998 // An updated system app can be deleted. This will also have to restore 12999 // the system pkg from system partition 13000 // reader 13001 synchronized (mPackages) { 13002 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13003 } 13004 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13005 + " disabledPs=" + disabledPs); 13006 if (disabledPs == null) { 13007 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13008 return false; 13009 } else if (DEBUG_REMOVE) { 13010 Slog.d(TAG, "Deleting system pkg from data partition"); 13011 } 13012 if (DEBUG_REMOVE) { 13013 if (applyUserRestrictions) { 13014 Slog.d(TAG, "Remembering install states:"); 13015 for (int i = 0; i < allUserHandles.length; i++) { 13016 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13017 } 13018 } 13019 } 13020 // Delete the updated package 13021 outInfo.isRemovedPackageSystemUpdate = true; 13022 if (disabledPs.versionCode < newPs.versionCode) { 13023 // Delete data for downgrades 13024 flags &= ~PackageManager.DELETE_KEEP_DATA; 13025 } else { 13026 // Preserve data by setting flag 13027 flags |= PackageManager.DELETE_KEEP_DATA; 13028 } 13029 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13030 allUserHandles, perUserInstalled, outInfo, writeSettings); 13031 if (!ret) { 13032 return false; 13033 } 13034 // writer 13035 synchronized (mPackages) { 13036 // Reinstate the old system package 13037 mSettings.enableSystemPackageLPw(newPs.name); 13038 // Remove any native libraries from the upgraded package. 13039 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13040 } 13041 // Install the system package 13042 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13043 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13044 if (locationIsPrivileged(disabledPs.codePath)) { 13045 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13046 } 13047 13048 final PackageParser.Package newPkg; 13049 try { 13050 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13051 } catch (PackageManagerException e) { 13052 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13053 return false; 13054 } 13055 13056 // writer 13057 synchronized (mPackages) { 13058 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13059 13060 // Propagate the permissions state as we do not want to drop on the floor 13061 // runtime permissions. The update permissions method below will take 13062 // care of removing obsolete permissions and grant install permissions. 13063 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13064 updatePermissionsLPw(newPkg.packageName, newPkg, 13065 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13066 13067 if (applyUserRestrictions) { 13068 if (DEBUG_REMOVE) { 13069 Slog.d(TAG, "Propagating install state across reinstall"); 13070 } 13071 for (int i = 0; i < allUserHandles.length; i++) { 13072 if (DEBUG_REMOVE) { 13073 Slog.d(TAG, " user " + allUserHandles[i] 13074 + " => " + perUserInstalled[i]); 13075 } 13076 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13077 13078 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13079 } 13080 // Regardless of writeSettings we need to ensure that this restriction 13081 // state propagation is persisted 13082 mSettings.writeAllUsersPackageRestrictionsLPr(); 13083 } 13084 // can downgrade to reader here 13085 if (writeSettings) { 13086 mSettings.writeLPr(); 13087 } 13088 } 13089 return true; 13090 } 13091 13092 private boolean deleteInstalledPackageLI(PackageSetting ps, 13093 boolean deleteCodeAndResources, int flags, 13094 int[] allUserHandles, boolean[] perUserInstalled, 13095 PackageRemovedInfo outInfo, boolean writeSettings) { 13096 if (outInfo != null) { 13097 outInfo.uid = ps.appId; 13098 } 13099 13100 // Delete package data from internal structures and also remove data if flag is set 13101 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13102 13103 // Delete application code and resources 13104 if (deleteCodeAndResources && (outInfo != null)) { 13105 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13106 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13107 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13108 } 13109 return true; 13110 } 13111 13112 @Override 13113 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13114 int userId) { 13115 mContext.enforceCallingOrSelfPermission( 13116 android.Manifest.permission.DELETE_PACKAGES, null); 13117 synchronized (mPackages) { 13118 PackageSetting ps = mSettings.mPackages.get(packageName); 13119 if (ps == null) { 13120 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13121 return false; 13122 } 13123 if (!ps.getInstalled(userId)) { 13124 // Can't block uninstall for an app that is not installed or enabled. 13125 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13126 return false; 13127 } 13128 ps.setBlockUninstall(blockUninstall, userId); 13129 mSettings.writePackageRestrictionsLPr(userId); 13130 } 13131 return true; 13132 } 13133 13134 @Override 13135 public boolean getBlockUninstallForUser(String packageName, int userId) { 13136 synchronized (mPackages) { 13137 PackageSetting ps = mSettings.mPackages.get(packageName); 13138 if (ps == null) { 13139 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13140 return false; 13141 } 13142 return ps.getBlockUninstall(userId); 13143 } 13144 } 13145 13146 /* 13147 * This method handles package deletion in general 13148 */ 13149 private boolean deletePackageLI(String packageName, UserHandle user, 13150 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13151 int flags, PackageRemovedInfo outInfo, 13152 boolean writeSettings) { 13153 if (packageName == null) { 13154 Slog.w(TAG, "Attempt to delete null packageName."); 13155 return false; 13156 } 13157 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13158 PackageSetting ps; 13159 boolean dataOnly = false; 13160 int removeUser = -1; 13161 int appId = -1; 13162 synchronized (mPackages) { 13163 ps = mSettings.mPackages.get(packageName); 13164 if (ps == null) { 13165 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13166 return false; 13167 } 13168 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13169 && user.getIdentifier() != UserHandle.USER_ALL) { 13170 // The caller is asking that the package only be deleted for a single 13171 // user. To do this, we just mark its uninstalled state and delete 13172 // its data. If this is a system app, we only allow this to happen if 13173 // they have set the special DELETE_SYSTEM_APP which requests different 13174 // semantics than normal for uninstalling system apps. 13175 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13176 final int userId = user.getIdentifier(); 13177 ps.setUserState(userId, 13178 COMPONENT_ENABLED_STATE_DEFAULT, 13179 false, //installed 13180 true, //stopped 13181 true, //notLaunched 13182 false, //hidden 13183 null, null, null, 13184 false, // blockUninstall 13185 ps.readUserState(userId).domainVerificationStatus, 0); 13186 if (!isSystemApp(ps)) { 13187 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13188 // Other user still have this package installed, so all 13189 // we need to do is clear this user's data and save that 13190 // it is uninstalled. 13191 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13192 removeUser = user.getIdentifier(); 13193 appId = ps.appId; 13194 scheduleWritePackageRestrictionsLocked(removeUser); 13195 } else { 13196 // We need to set it back to 'installed' so the uninstall 13197 // broadcasts will be sent correctly. 13198 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13199 ps.setInstalled(true, user.getIdentifier()); 13200 } 13201 } else { 13202 // This is a system app, so we assume that the 13203 // other users still have this package installed, so all 13204 // we need to do is clear this user's data and save that 13205 // it is uninstalled. 13206 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13207 removeUser = user.getIdentifier(); 13208 appId = ps.appId; 13209 scheduleWritePackageRestrictionsLocked(removeUser); 13210 } 13211 } 13212 } 13213 13214 if (removeUser >= 0) { 13215 // From above, we determined that we are deleting this only 13216 // for a single user. Continue the work here. 13217 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13218 if (outInfo != null) { 13219 outInfo.removedPackage = packageName; 13220 outInfo.removedAppId = appId; 13221 outInfo.removedUsers = new int[] {removeUser}; 13222 } 13223 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13224 removeKeystoreDataIfNeeded(removeUser, appId); 13225 schedulePackageCleaning(packageName, removeUser, false); 13226 synchronized (mPackages) { 13227 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13228 scheduleWritePackageRestrictionsLocked(removeUser); 13229 } 13230 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13231 } 13232 return true; 13233 } 13234 13235 if (dataOnly) { 13236 // Delete application data first 13237 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13238 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13239 return true; 13240 } 13241 13242 boolean ret = false; 13243 if (isSystemApp(ps)) { 13244 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13245 // When an updated system application is deleted we delete the existing resources as well and 13246 // fall back to existing code in system partition 13247 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13248 flags, outInfo, writeSettings); 13249 } else { 13250 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13251 // Kill application pre-emptively especially for apps on sd. 13252 killApplication(packageName, ps.appId, "uninstall pkg"); 13253 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13254 allUserHandles, perUserInstalled, 13255 outInfo, writeSettings); 13256 } 13257 13258 return ret; 13259 } 13260 13261 private final class ClearStorageConnection implements ServiceConnection { 13262 IMediaContainerService mContainerService; 13263 13264 @Override 13265 public void onServiceConnected(ComponentName name, IBinder service) { 13266 synchronized (this) { 13267 mContainerService = IMediaContainerService.Stub.asInterface(service); 13268 notifyAll(); 13269 } 13270 } 13271 13272 @Override 13273 public void onServiceDisconnected(ComponentName name) { 13274 } 13275 } 13276 13277 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13278 final boolean mounted; 13279 if (Environment.isExternalStorageEmulated()) { 13280 mounted = true; 13281 } else { 13282 final String status = Environment.getExternalStorageState(); 13283 13284 mounted = status.equals(Environment.MEDIA_MOUNTED) 13285 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13286 } 13287 13288 if (!mounted) { 13289 return; 13290 } 13291 13292 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13293 int[] users; 13294 if (userId == UserHandle.USER_ALL) { 13295 users = sUserManager.getUserIds(); 13296 } else { 13297 users = new int[] { userId }; 13298 } 13299 final ClearStorageConnection conn = new ClearStorageConnection(); 13300 if (mContext.bindServiceAsUser( 13301 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13302 try { 13303 for (int curUser : users) { 13304 long timeout = SystemClock.uptimeMillis() + 5000; 13305 synchronized (conn) { 13306 long now = SystemClock.uptimeMillis(); 13307 while (conn.mContainerService == null && now < timeout) { 13308 try { 13309 conn.wait(timeout - now); 13310 } catch (InterruptedException e) { 13311 } 13312 } 13313 } 13314 if (conn.mContainerService == null) { 13315 return; 13316 } 13317 13318 final UserEnvironment userEnv = new UserEnvironment(curUser); 13319 clearDirectory(conn.mContainerService, 13320 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13321 if (allData) { 13322 clearDirectory(conn.mContainerService, 13323 userEnv.buildExternalStorageAppDataDirs(packageName)); 13324 clearDirectory(conn.mContainerService, 13325 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13326 } 13327 } 13328 } finally { 13329 mContext.unbindService(conn); 13330 } 13331 } 13332 } 13333 13334 @Override 13335 public void clearApplicationUserData(final String packageName, 13336 final IPackageDataObserver observer, final int userId) { 13337 mContext.enforceCallingOrSelfPermission( 13338 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13339 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13340 // Queue up an async operation since the package deletion may take a little while. 13341 mHandler.post(new Runnable() { 13342 public void run() { 13343 mHandler.removeCallbacks(this); 13344 final boolean succeeded; 13345 synchronized (mInstallLock) { 13346 succeeded = clearApplicationUserDataLI(packageName, userId); 13347 } 13348 clearExternalStorageDataSync(packageName, userId, true); 13349 if (succeeded) { 13350 // invoke DeviceStorageMonitor's update method to clear any notifications 13351 DeviceStorageMonitorInternal 13352 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13353 if (dsm != null) { 13354 dsm.checkMemory(); 13355 } 13356 } 13357 if(observer != null) { 13358 try { 13359 observer.onRemoveCompleted(packageName, succeeded); 13360 } catch (RemoteException e) { 13361 Log.i(TAG, "Observer no longer exists."); 13362 } 13363 } //end if observer 13364 } //end run 13365 }); 13366 } 13367 13368 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13369 if (packageName == null) { 13370 Slog.w(TAG, "Attempt to delete null packageName."); 13371 return false; 13372 } 13373 13374 // Try finding details about the requested package 13375 PackageParser.Package pkg; 13376 synchronized (mPackages) { 13377 pkg = mPackages.get(packageName); 13378 if (pkg == null) { 13379 final PackageSetting ps = mSettings.mPackages.get(packageName); 13380 if (ps != null) { 13381 pkg = ps.pkg; 13382 } 13383 } 13384 13385 if (pkg == null) { 13386 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13387 return false; 13388 } 13389 13390 PackageSetting ps = (PackageSetting) pkg.mExtras; 13391 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13392 } 13393 13394 // Always delete data directories for package, even if we found no other 13395 // record of app. This helps users recover from UID mismatches without 13396 // resorting to a full data wipe. 13397 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13398 if (retCode < 0) { 13399 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13400 return false; 13401 } 13402 13403 final int appId = pkg.applicationInfo.uid; 13404 removeKeystoreDataIfNeeded(userId, appId); 13405 13406 // Create a native library symlink only if we have native libraries 13407 // and if the native libraries are 32 bit libraries. We do not provide 13408 // this symlink for 64 bit libraries. 13409 if (pkg.applicationInfo.primaryCpuAbi != null && 13410 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13411 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13412 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13413 nativeLibPath, userId) < 0) { 13414 Slog.w(TAG, "Failed linking native library dir"); 13415 return false; 13416 } 13417 } 13418 13419 return true; 13420 } 13421 13422 /** 13423 * Reverts user permission state changes (permissions and flags) in 13424 * all packages for a given user. 13425 * 13426 * @param userId The device user for which to do a reset. 13427 */ 13428 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13429 final int packageCount = mPackages.size(); 13430 for (int i = 0; i < packageCount; i++) { 13431 PackageParser.Package pkg = mPackages.valueAt(i); 13432 PackageSetting ps = (PackageSetting) pkg.mExtras; 13433 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13434 } 13435 } 13436 13437 /** 13438 * Reverts user permission state changes (permissions and flags). 13439 * 13440 * @param ps The package for which to reset. 13441 * @param userId The device user for which to do a reset. 13442 */ 13443 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13444 final PackageSetting ps, final int userId) { 13445 if (ps.pkg == null) { 13446 return; 13447 } 13448 13449 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13450 | FLAG_PERMISSION_USER_FIXED 13451 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13452 13453 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13454 | FLAG_PERMISSION_POLICY_FIXED; 13455 13456 boolean writeInstallPermissions = false; 13457 boolean writeRuntimePermissions = false; 13458 13459 final int permissionCount = ps.pkg.requestedPermissions.size(); 13460 for (int i = 0; i < permissionCount; i++) { 13461 String permission = ps.pkg.requestedPermissions.get(i); 13462 13463 BasePermission bp = mSettings.mPermissions.get(permission); 13464 if (bp == null) { 13465 continue; 13466 } 13467 13468 // If shared user we just reset the state to which only this app contributed. 13469 if (ps.sharedUser != null) { 13470 boolean used = false; 13471 final int packageCount = ps.sharedUser.packages.size(); 13472 for (int j = 0; j < packageCount; j++) { 13473 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13474 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13475 && pkg.pkg.requestedPermissions.contains(permission)) { 13476 used = true; 13477 break; 13478 } 13479 } 13480 if (used) { 13481 continue; 13482 } 13483 } 13484 13485 PermissionsState permissionsState = ps.getPermissionsState(); 13486 13487 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13488 13489 // Always clear the user settable flags. 13490 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13491 bp.name) != null; 13492 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13493 if (hasInstallState) { 13494 writeInstallPermissions = true; 13495 } else { 13496 writeRuntimePermissions = true; 13497 } 13498 } 13499 13500 // Below is only runtime permission handling. 13501 if (!bp.isRuntime()) { 13502 continue; 13503 } 13504 13505 // Never clobber system or policy. 13506 if ((oldFlags & policyOrSystemFlags) != 0) { 13507 continue; 13508 } 13509 13510 // If this permission was granted by default, make sure it is. 13511 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13512 if (permissionsState.grantRuntimePermission(bp, userId) 13513 != PERMISSION_OPERATION_FAILURE) { 13514 writeRuntimePermissions = true; 13515 } 13516 } else { 13517 // Otherwise, reset the permission. 13518 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13519 switch (revokeResult) { 13520 case PERMISSION_OPERATION_SUCCESS: { 13521 writeRuntimePermissions = true; 13522 } break; 13523 13524 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13525 writeRuntimePermissions = true; 13526 final int appId = ps.appId; 13527 mHandler.post(new Runnable() { 13528 @Override 13529 public void run() { 13530 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13531 } 13532 }); 13533 } break; 13534 } 13535 } 13536 } 13537 13538 // Synchronously write as we are taking permissions away. 13539 if (writeRuntimePermissions) { 13540 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13541 } 13542 13543 // Synchronously write as we are taking permissions away. 13544 if (writeInstallPermissions) { 13545 mSettings.writeLPr(); 13546 } 13547 } 13548 13549 /** 13550 * Remove entries from the keystore daemon. Will only remove it if the 13551 * {@code appId} is valid. 13552 */ 13553 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13554 if (appId < 0) { 13555 return; 13556 } 13557 13558 final KeyStore keyStore = KeyStore.getInstance(); 13559 if (keyStore != null) { 13560 if (userId == UserHandle.USER_ALL) { 13561 for (final int individual : sUserManager.getUserIds()) { 13562 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13563 } 13564 } else { 13565 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13566 } 13567 } else { 13568 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13569 } 13570 } 13571 13572 @Override 13573 public void deleteApplicationCacheFiles(final String packageName, 13574 final IPackageDataObserver observer) { 13575 mContext.enforceCallingOrSelfPermission( 13576 android.Manifest.permission.DELETE_CACHE_FILES, null); 13577 // Queue up an async operation since the package deletion may take a little while. 13578 final int userId = UserHandle.getCallingUserId(); 13579 mHandler.post(new Runnable() { 13580 public void run() { 13581 mHandler.removeCallbacks(this); 13582 final boolean succeded; 13583 synchronized (mInstallLock) { 13584 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13585 } 13586 clearExternalStorageDataSync(packageName, userId, false); 13587 if (observer != null) { 13588 try { 13589 observer.onRemoveCompleted(packageName, succeded); 13590 } catch (RemoteException e) { 13591 Log.i(TAG, "Observer no longer exists."); 13592 } 13593 } //end if observer 13594 } //end run 13595 }); 13596 } 13597 13598 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13599 if (packageName == null) { 13600 Slog.w(TAG, "Attempt to delete null packageName."); 13601 return false; 13602 } 13603 PackageParser.Package p; 13604 synchronized (mPackages) { 13605 p = mPackages.get(packageName); 13606 } 13607 if (p == null) { 13608 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13609 return false; 13610 } 13611 final ApplicationInfo applicationInfo = p.applicationInfo; 13612 if (applicationInfo == null) { 13613 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13614 return false; 13615 } 13616 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13617 if (retCode < 0) { 13618 Slog.w(TAG, "Couldn't remove cache files for package: " 13619 + packageName + " u" + userId); 13620 return false; 13621 } 13622 return true; 13623 } 13624 13625 @Override 13626 public void getPackageSizeInfo(final String packageName, int userHandle, 13627 final IPackageStatsObserver observer) { 13628 mContext.enforceCallingOrSelfPermission( 13629 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13630 if (packageName == null) { 13631 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13632 } 13633 13634 PackageStats stats = new PackageStats(packageName, userHandle); 13635 13636 /* 13637 * Queue up an async operation since the package measurement may take a 13638 * little while. 13639 */ 13640 Message msg = mHandler.obtainMessage(INIT_COPY); 13641 msg.obj = new MeasureParams(stats, observer); 13642 mHandler.sendMessage(msg); 13643 } 13644 13645 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13646 PackageStats pStats) { 13647 if (packageName == null) { 13648 Slog.w(TAG, "Attempt to get size of null packageName."); 13649 return false; 13650 } 13651 PackageParser.Package p; 13652 boolean dataOnly = false; 13653 String libDirRoot = null; 13654 String asecPath = null; 13655 PackageSetting ps = null; 13656 synchronized (mPackages) { 13657 p = mPackages.get(packageName); 13658 ps = mSettings.mPackages.get(packageName); 13659 if(p == null) { 13660 dataOnly = true; 13661 if((ps == null) || (ps.pkg == null)) { 13662 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13663 return false; 13664 } 13665 p = ps.pkg; 13666 } 13667 if (ps != null) { 13668 libDirRoot = ps.legacyNativeLibraryPathString; 13669 } 13670 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13671 final long token = Binder.clearCallingIdentity(); 13672 try { 13673 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13674 if (secureContainerId != null) { 13675 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13676 } 13677 } finally { 13678 Binder.restoreCallingIdentity(token); 13679 } 13680 } 13681 } 13682 String publicSrcDir = null; 13683 if(!dataOnly) { 13684 final ApplicationInfo applicationInfo = p.applicationInfo; 13685 if (applicationInfo == null) { 13686 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13687 return false; 13688 } 13689 if (p.isForwardLocked()) { 13690 publicSrcDir = applicationInfo.getBaseResourcePath(); 13691 } 13692 } 13693 // TODO: extend to measure size of split APKs 13694 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13695 // not just the first level. 13696 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13697 // just the primary. 13698 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13699 13700 String apkPath; 13701 File packageDir = new File(p.codePath); 13702 13703 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13704 apkPath = packageDir.getAbsolutePath(); 13705 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13706 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13707 libDirRoot = null; 13708 } 13709 } else { 13710 apkPath = p.baseCodePath; 13711 } 13712 13713 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13714 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13715 if (res < 0) { 13716 return false; 13717 } 13718 13719 // Fix-up for forward-locked applications in ASEC containers. 13720 if (!isExternal(p)) { 13721 pStats.codeSize += pStats.externalCodeSize; 13722 pStats.externalCodeSize = 0L; 13723 } 13724 13725 return true; 13726 } 13727 13728 13729 @Override 13730 public void addPackageToPreferred(String packageName) { 13731 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13732 } 13733 13734 @Override 13735 public void removePackageFromPreferred(String packageName) { 13736 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13737 } 13738 13739 @Override 13740 public List<PackageInfo> getPreferredPackages(int flags) { 13741 return new ArrayList<PackageInfo>(); 13742 } 13743 13744 private int getUidTargetSdkVersionLockedLPr(int uid) { 13745 Object obj = mSettings.getUserIdLPr(uid); 13746 if (obj instanceof SharedUserSetting) { 13747 final SharedUserSetting sus = (SharedUserSetting) obj; 13748 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13749 final Iterator<PackageSetting> it = sus.packages.iterator(); 13750 while (it.hasNext()) { 13751 final PackageSetting ps = it.next(); 13752 if (ps.pkg != null) { 13753 int v = ps.pkg.applicationInfo.targetSdkVersion; 13754 if (v < vers) vers = v; 13755 } 13756 } 13757 return vers; 13758 } else if (obj instanceof PackageSetting) { 13759 final PackageSetting ps = (PackageSetting) obj; 13760 if (ps.pkg != null) { 13761 return ps.pkg.applicationInfo.targetSdkVersion; 13762 } 13763 } 13764 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13765 } 13766 13767 @Override 13768 public void addPreferredActivity(IntentFilter filter, int match, 13769 ComponentName[] set, ComponentName activity, int userId) { 13770 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13771 "Adding preferred"); 13772 } 13773 13774 private void addPreferredActivityInternal(IntentFilter filter, int match, 13775 ComponentName[] set, ComponentName activity, boolean always, int userId, 13776 String opname) { 13777 // writer 13778 int callingUid = Binder.getCallingUid(); 13779 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13780 if (filter.countActions() == 0) { 13781 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13782 return; 13783 } 13784 synchronized (mPackages) { 13785 if (mContext.checkCallingOrSelfPermission( 13786 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13787 != PackageManager.PERMISSION_GRANTED) { 13788 if (getUidTargetSdkVersionLockedLPr(callingUid) 13789 < Build.VERSION_CODES.FROYO) { 13790 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13791 + callingUid); 13792 return; 13793 } 13794 mContext.enforceCallingOrSelfPermission( 13795 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13796 } 13797 13798 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13799 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13800 + userId + ":"); 13801 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13802 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13803 scheduleWritePackageRestrictionsLocked(userId); 13804 } 13805 } 13806 13807 @Override 13808 public void replacePreferredActivity(IntentFilter filter, int match, 13809 ComponentName[] set, ComponentName activity, int userId) { 13810 if (filter.countActions() != 1) { 13811 throw new IllegalArgumentException( 13812 "replacePreferredActivity expects filter to have only 1 action."); 13813 } 13814 if (filter.countDataAuthorities() != 0 13815 || filter.countDataPaths() != 0 13816 || filter.countDataSchemes() > 1 13817 || filter.countDataTypes() != 0) { 13818 throw new IllegalArgumentException( 13819 "replacePreferredActivity expects filter to have no data authorities, " + 13820 "paths, or types; and at most one scheme."); 13821 } 13822 13823 final int callingUid = Binder.getCallingUid(); 13824 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13825 synchronized (mPackages) { 13826 if (mContext.checkCallingOrSelfPermission( 13827 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13828 != PackageManager.PERMISSION_GRANTED) { 13829 if (getUidTargetSdkVersionLockedLPr(callingUid) 13830 < Build.VERSION_CODES.FROYO) { 13831 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13832 + Binder.getCallingUid()); 13833 return; 13834 } 13835 mContext.enforceCallingOrSelfPermission( 13836 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13837 } 13838 13839 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13840 if (pir != null) { 13841 // Get all of the existing entries that exactly match this filter. 13842 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13843 if (existing != null && existing.size() == 1) { 13844 PreferredActivity cur = existing.get(0); 13845 if (DEBUG_PREFERRED) { 13846 Slog.i(TAG, "Checking replace of preferred:"); 13847 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13848 if (!cur.mPref.mAlways) { 13849 Slog.i(TAG, " -- CUR; not mAlways!"); 13850 } else { 13851 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13852 Slog.i(TAG, " -- CUR: mSet=" 13853 + Arrays.toString(cur.mPref.mSetComponents)); 13854 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13855 Slog.i(TAG, " -- NEW: mMatch=" 13856 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13857 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13858 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13859 } 13860 } 13861 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13862 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13863 && cur.mPref.sameSet(set)) { 13864 // Setting the preferred activity to what it happens to be already 13865 if (DEBUG_PREFERRED) { 13866 Slog.i(TAG, "Replacing with same preferred activity " 13867 + cur.mPref.mShortComponent + " for user " 13868 + userId + ":"); 13869 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13870 } 13871 return; 13872 } 13873 } 13874 13875 if (existing != null) { 13876 if (DEBUG_PREFERRED) { 13877 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13878 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13879 } 13880 for (int i = 0; i < existing.size(); i++) { 13881 PreferredActivity pa = existing.get(i); 13882 if (DEBUG_PREFERRED) { 13883 Slog.i(TAG, "Removing existing preferred activity " 13884 + pa.mPref.mComponent + ":"); 13885 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13886 } 13887 pir.removeFilter(pa); 13888 } 13889 } 13890 } 13891 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13892 "Replacing preferred"); 13893 } 13894 } 13895 13896 @Override 13897 public void clearPackagePreferredActivities(String packageName) { 13898 final int uid = Binder.getCallingUid(); 13899 // writer 13900 synchronized (mPackages) { 13901 PackageParser.Package pkg = mPackages.get(packageName); 13902 if (pkg == null || pkg.applicationInfo.uid != uid) { 13903 if (mContext.checkCallingOrSelfPermission( 13904 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13905 != PackageManager.PERMISSION_GRANTED) { 13906 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13907 < Build.VERSION_CODES.FROYO) { 13908 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13909 + Binder.getCallingUid()); 13910 return; 13911 } 13912 mContext.enforceCallingOrSelfPermission( 13913 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13914 } 13915 } 13916 13917 int user = UserHandle.getCallingUserId(); 13918 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13919 scheduleWritePackageRestrictionsLocked(user); 13920 } 13921 } 13922 } 13923 13924 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13925 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13926 ArrayList<PreferredActivity> removed = null; 13927 boolean changed = false; 13928 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13929 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13930 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13931 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13932 continue; 13933 } 13934 Iterator<PreferredActivity> it = pir.filterIterator(); 13935 while (it.hasNext()) { 13936 PreferredActivity pa = it.next(); 13937 // Mark entry for removal only if it matches the package name 13938 // and the entry is of type "always". 13939 if (packageName == null || 13940 (pa.mPref.mComponent.getPackageName().equals(packageName) 13941 && pa.mPref.mAlways)) { 13942 if (removed == null) { 13943 removed = new ArrayList<PreferredActivity>(); 13944 } 13945 removed.add(pa); 13946 } 13947 } 13948 if (removed != null) { 13949 for (int j=0; j<removed.size(); j++) { 13950 PreferredActivity pa = removed.get(j); 13951 pir.removeFilter(pa); 13952 } 13953 changed = true; 13954 } 13955 } 13956 return changed; 13957 } 13958 13959 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13960 private void clearIntentFilterVerificationsLPw(int userId) { 13961 final int packageCount = mPackages.size(); 13962 for (int i = 0; i < packageCount; i++) { 13963 PackageParser.Package pkg = mPackages.valueAt(i); 13964 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13965 } 13966 } 13967 13968 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13969 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13970 if (userId == UserHandle.USER_ALL) { 13971 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13972 sUserManager.getUserIds())) { 13973 for (int oneUserId : sUserManager.getUserIds()) { 13974 scheduleWritePackageRestrictionsLocked(oneUserId); 13975 } 13976 } 13977 } else { 13978 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13979 scheduleWritePackageRestrictionsLocked(userId); 13980 } 13981 } 13982 } 13983 13984 void clearDefaultBrowserIfNeeded(String packageName) { 13985 for (int oneUserId : sUserManager.getUserIds()) { 13986 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13987 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13988 if (packageName.equals(defaultBrowserPackageName)) { 13989 setDefaultBrowserPackageName(null, oneUserId); 13990 } 13991 } 13992 } 13993 13994 @Override 13995 public void resetApplicationPreferences(int userId) { 13996 mContext.enforceCallingOrSelfPermission( 13997 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13998 // writer 13999 synchronized (mPackages) { 14000 final long identity = Binder.clearCallingIdentity(); 14001 try { 14002 clearPackagePreferredActivitiesLPw(null, userId); 14003 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14004 // TODO: We have to reset the default SMS and Phone. This requires 14005 // significant refactoring to keep all default apps in the package 14006 // manager (cleaner but more work) or have the services provide 14007 // callbacks to the package manager to request a default app reset. 14008 applyFactoryDefaultBrowserLPw(userId); 14009 clearIntentFilterVerificationsLPw(userId); 14010 primeDomainVerificationsLPw(userId); 14011 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14012 scheduleWritePackageRestrictionsLocked(userId); 14013 } finally { 14014 Binder.restoreCallingIdentity(identity); 14015 } 14016 } 14017 } 14018 14019 @Override 14020 public int getPreferredActivities(List<IntentFilter> outFilters, 14021 List<ComponentName> outActivities, String packageName) { 14022 14023 int num = 0; 14024 final int userId = UserHandle.getCallingUserId(); 14025 // reader 14026 synchronized (mPackages) { 14027 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14028 if (pir != null) { 14029 final Iterator<PreferredActivity> it = pir.filterIterator(); 14030 while (it.hasNext()) { 14031 final PreferredActivity pa = it.next(); 14032 if (packageName == null 14033 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14034 && pa.mPref.mAlways)) { 14035 if (outFilters != null) { 14036 outFilters.add(new IntentFilter(pa)); 14037 } 14038 if (outActivities != null) { 14039 outActivities.add(pa.mPref.mComponent); 14040 } 14041 } 14042 } 14043 } 14044 } 14045 14046 return num; 14047 } 14048 14049 @Override 14050 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14051 int userId) { 14052 int callingUid = Binder.getCallingUid(); 14053 if (callingUid != Process.SYSTEM_UID) { 14054 throw new SecurityException( 14055 "addPersistentPreferredActivity can only be run by the system"); 14056 } 14057 if (filter.countActions() == 0) { 14058 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14059 return; 14060 } 14061 synchronized (mPackages) { 14062 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14063 " :"); 14064 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14065 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14066 new PersistentPreferredActivity(filter, activity)); 14067 scheduleWritePackageRestrictionsLocked(userId); 14068 } 14069 } 14070 14071 @Override 14072 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14073 int callingUid = Binder.getCallingUid(); 14074 if (callingUid != Process.SYSTEM_UID) { 14075 throw new SecurityException( 14076 "clearPackagePersistentPreferredActivities can only be run by the system"); 14077 } 14078 ArrayList<PersistentPreferredActivity> removed = null; 14079 boolean changed = false; 14080 synchronized (mPackages) { 14081 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14082 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14083 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14084 .valueAt(i); 14085 if (userId != thisUserId) { 14086 continue; 14087 } 14088 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14089 while (it.hasNext()) { 14090 PersistentPreferredActivity ppa = it.next(); 14091 // Mark entry for removal only if it matches the package name. 14092 if (ppa.mComponent.getPackageName().equals(packageName)) { 14093 if (removed == null) { 14094 removed = new ArrayList<PersistentPreferredActivity>(); 14095 } 14096 removed.add(ppa); 14097 } 14098 } 14099 if (removed != null) { 14100 for (int j=0; j<removed.size(); j++) { 14101 PersistentPreferredActivity ppa = removed.get(j); 14102 ppir.removeFilter(ppa); 14103 } 14104 changed = true; 14105 } 14106 } 14107 14108 if (changed) { 14109 scheduleWritePackageRestrictionsLocked(userId); 14110 } 14111 } 14112 } 14113 14114 /** 14115 * Common machinery for picking apart a restored XML blob and passing 14116 * it to a caller-supplied functor to be applied to the running system. 14117 */ 14118 private void restoreFromXml(XmlPullParser parser, int userId, 14119 String expectedStartTag, BlobXmlRestorer functor) 14120 throws IOException, XmlPullParserException { 14121 int type; 14122 while ((type = parser.next()) != XmlPullParser.START_TAG 14123 && type != XmlPullParser.END_DOCUMENT) { 14124 } 14125 if (type != XmlPullParser.START_TAG) { 14126 // oops didn't find a start tag?! 14127 if (DEBUG_BACKUP) { 14128 Slog.e(TAG, "Didn't find start tag during restore"); 14129 } 14130 return; 14131 } 14132 14133 // this is supposed to be TAG_PREFERRED_BACKUP 14134 if (!expectedStartTag.equals(parser.getName())) { 14135 if (DEBUG_BACKUP) { 14136 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14137 } 14138 return; 14139 } 14140 14141 // skip interfering stuff, then we're aligned with the backing implementation 14142 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14143 functor.apply(parser, userId); 14144 } 14145 14146 private interface BlobXmlRestorer { 14147 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14148 } 14149 14150 /** 14151 * Non-Binder method, support for the backup/restore mechanism: write the 14152 * full set of preferred activities in its canonical XML format. Returns the 14153 * XML output as a byte array, or null if there is none. 14154 */ 14155 @Override 14156 public byte[] getPreferredActivityBackup(int userId) { 14157 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14158 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14159 } 14160 14161 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14162 try { 14163 final XmlSerializer serializer = new FastXmlSerializer(); 14164 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14165 serializer.startDocument(null, true); 14166 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14167 14168 synchronized (mPackages) { 14169 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14170 } 14171 14172 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14173 serializer.endDocument(); 14174 serializer.flush(); 14175 } catch (Exception e) { 14176 if (DEBUG_BACKUP) { 14177 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14178 } 14179 return null; 14180 } 14181 14182 return dataStream.toByteArray(); 14183 } 14184 14185 @Override 14186 public void restorePreferredActivities(byte[] backup, int userId) { 14187 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14188 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14189 } 14190 14191 try { 14192 final XmlPullParser parser = Xml.newPullParser(); 14193 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14194 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14195 new BlobXmlRestorer() { 14196 @Override 14197 public void apply(XmlPullParser parser, int userId) 14198 throws XmlPullParserException, IOException { 14199 synchronized (mPackages) { 14200 mSettings.readPreferredActivitiesLPw(parser, userId); 14201 } 14202 } 14203 } ); 14204 } catch (Exception e) { 14205 if (DEBUG_BACKUP) { 14206 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14207 } 14208 } 14209 } 14210 14211 /** 14212 * Non-Binder method, support for the backup/restore mechanism: write the 14213 * default browser (etc) settings in its canonical XML format. Returns the default 14214 * browser XML representation as a byte array, or null if there is none. 14215 */ 14216 @Override 14217 public byte[] getDefaultAppsBackup(int userId) { 14218 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14219 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14220 } 14221 14222 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14223 try { 14224 final XmlSerializer serializer = new FastXmlSerializer(); 14225 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14226 serializer.startDocument(null, true); 14227 serializer.startTag(null, TAG_DEFAULT_APPS); 14228 14229 synchronized (mPackages) { 14230 mSettings.writeDefaultAppsLPr(serializer, userId); 14231 } 14232 14233 serializer.endTag(null, TAG_DEFAULT_APPS); 14234 serializer.endDocument(); 14235 serializer.flush(); 14236 } catch (Exception e) { 14237 if (DEBUG_BACKUP) { 14238 Slog.e(TAG, "Unable to write default apps for backup", e); 14239 } 14240 return null; 14241 } 14242 14243 return dataStream.toByteArray(); 14244 } 14245 14246 @Override 14247 public void restoreDefaultApps(byte[] backup, int userId) { 14248 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14249 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14250 } 14251 14252 try { 14253 final XmlPullParser parser = Xml.newPullParser(); 14254 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14255 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14256 new BlobXmlRestorer() { 14257 @Override 14258 public void apply(XmlPullParser parser, int userId) 14259 throws XmlPullParserException, IOException { 14260 synchronized (mPackages) { 14261 mSettings.readDefaultAppsLPw(parser, userId); 14262 } 14263 } 14264 } ); 14265 } catch (Exception e) { 14266 if (DEBUG_BACKUP) { 14267 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14268 } 14269 } 14270 } 14271 14272 @Override 14273 public byte[] getIntentFilterVerificationBackup(int userId) { 14274 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14275 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14276 } 14277 14278 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14279 try { 14280 final XmlSerializer serializer = new FastXmlSerializer(); 14281 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14282 serializer.startDocument(null, true); 14283 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14284 14285 synchronized (mPackages) { 14286 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14287 } 14288 14289 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14290 serializer.endDocument(); 14291 serializer.flush(); 14292 } catch (Exception e) { 14293 if (DEBUG_BACKUP) { 14294 Slog.e(TAG, "Unable to write default apps for backup", e); 14295 } 14296 return null; 14297 } 14298 14299 return dataStream.toByteArray(); 14300 } 14301 14302 @Override 14303 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14304 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14305 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14306 } 14307 14308 try { 14309 final XmlPullParser parser = Xml.newPullParser(); 14310 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14311 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14312 new BlobXmlRestorer() { 14313 @Override 14314 public void apply(XmlPullParser parser, int userId) 14315 throws XmlPullParserException, IOException { 14316 synchronized (mPackages) { 14317 mSettings.readAllDomainVerificationsLPr(parser, userId); 14318 mSettings.writeLPr(); 14319 } 14320 } 14321 } ); 14322 } catch (Exception e) { 14323 if (DEBUG_BACKUP) { 14324 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14325 } 14326 } 14327 } 14328 14329 @Override 14330 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14331 int sourceUserId, int targetUserId, int flags) { 14332 mContext.enforceCallingOrSelfPermission( 14333 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14334 int callingUid = Binder.getCallingUid(); 14335 enforceOwnerRights(ownerPackage, callingUid); 14336 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14337 if (intentFilter.countActions() == 0) { 14338 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14339 return; 14340 } 14341 synchronized (mPackages) { 14342 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14343 ownerPackage, targetUserId, flags); 14344 CrossProfileIntentResolver resolver = 14345 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14346 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14347 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14348 if (existing != null) { 14349 int size = existing.size(); 14350 for (int i = 0; i < size; i++) { 14351 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14352 return; 14353 } 14354 } 14355 } 14356 resolver.addFilter(newFilter); 14357 scheduleWritePackageRestrictionsLocked(sourceUserId); 14358 } 14359 } 14360 14361 @Override 14362 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14363 mContext.enforceCallingOrSelfPermission( 14364 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14365 int callingUid = Binder.getCallingUid(); 14366 enforceOwnerRights(ownerPackage, callingUid); 14367 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14368 synchronized (mPackages) { 14369 CrossProfileIntentResolver resolver = 14370 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14371 ArraySet<CrossProfileIntentFilter> set = 14372 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14373 for (CrossProfileIntentFilter filter : set) { 14374 if (filter.getOwnerPackage().equals(ownerPackage)) { 14375 resolver.removeFilter(filter); 14376 } 14377 } 14378 scheduleWritePackageRestrictionsLocked(sourceUserId); 14379 } 14380 } 14381 14382 // Enforcing that callingUid is owning pkg on userId 14383 private void enforceOwnerRights(String pkg, int callingUid) { 14384 // The system owns everything. 14385 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14386 return; 14387 } 14388 int callingUserId = UserHandle.getUserId(callingUid); 14389 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14390 if (pi == null) { 14391 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14392 + callingUserId); 14393 } 14394 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14395 throw new SecurityException("Calling uid " + callingUid 14396 + " does not own package " + pkg); 14397 } 14398 } 14399 14400 @Override 14401 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14402 Intent intent = new Intent(Intent.ACTION_MAIN); 14403 intent.addCategory(Intent.CATEGORY_HOME); 14404 14405 final int callingUserId = UserHandle.getCallingUserId(); 14406 List<ResolveInfo> list = queryIntentActivities(intent, null, 14407 PackageManager.GET_META_DATA, callingUserId); 14408 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14409 true, false, false, callingUserId); 14410 14411 allHomeCandidates.clear(); 14412 if (list != null) { 14413 for (ResolveInfo ri : list) { 14414 allHomeCandidates.add(ri); 14415 } 14416 } 14417 return (preferred == null || preferred.activityInfo == null) 14418 ? null 14419 : new ComponentName(preferred.activityInfo.packageName, 14420 preferred.activityInfo.name); 14421 } 14422 14423 @Override 14424 public void setApplicationEnabledSetting(String appPackageName, 14425 int newState, int flags, int userId, String callingPackage) { 14426 if (!sUserManager.exists(userId)) return; 14427 if (callingPackage == null) { 14428 callingPackage = Integer.toString(Binder.getCallingUid()); 14429 } 14430 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14431 } 14432 14433 @Override 14434 public void setComponentEnabledSetting(ComponentName componentName, 14435 int newState, int flags, int userId) { 14436 if (!sUserManager.exists(userId)) return; 14437 setEnabledSetting(componentName.getPackageName(), 14438 componentName.getClassName(), newState, flags, userId, null); 14439 } 14440 14441 private void setEnabledSetting(final String packageName, String className, int newState, 14442 final int flags, int userId, String callingPackage) { 14443 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14444 || newState == COMPONENT_ENABLED_STATE_ENABLED 14445 || newState == COMPONENT_ENABLED_STATE_DISABLED 14446 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14447 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14448 throw new IllegalArgumentException("Invalid new component state: " 14449 + newState); 14450 } 14451 PackageSetting pkgSetting; 14452 final int uid = Binder.getCallingUid(); 14453 final int permission = mContext.checkCallingOrSelfPermission( 14454 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14455 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14456 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14457 boolean sendNow = false; 14458 boolean isApp = (className == null); 14459 String componentName = isApp ? packageName : className; 14460 int packageUid = -1; 14461 ArrayList<String> components; 14462 14463 // writer 14464 synchronized (mPackages) { 14465 pkgSetting = mSettings.mPackages.get(packageName); 14466 if (pkgSetting == null) { 14467 if (className == null) { 14468 throw new IllegalArgumentException( 14469 "Unknown package: " + packageName); 14470 } 14471 throw new IllegalArgumentException( 14472 "Unknown component: " + packageName 14473 + "/" + className); 14474 } 14475 // Allow root and verify that userId is not being specified by a different user 14476 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14477 throw new SecurityException( 14478 "Permission Denial: attempt to change component state from pid=" 14479 + Binder.getCallingPid() 14480 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14481 } 14482 if (className == null) { 14483 // We're dealing with an application/package level state change 14484 if (pkgSetting.getEnabled(userId) == newState) { 14485 // Nothing to do 14486 return; 14487 } 14488 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14489 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14490 // Don't care about who enables an app. 14491 callingPackage = null; 14492 } 14493 pkgSetting.setEnabled(newState, userId, callingPackage); 14494 // pkgSetting.pkg.mSetEnabled = newState; 14495 } else { 14496 // We're dealing with a component level state change 14497 // First, verify that this is a valid class name. 14498 PackageParser.Package pkg = pkgSetting.pkg; 14499 if (pkg == null || !pkg.hasComponentClassName(className)) { 14500 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14501 throw new IllegalArgumentException("Component class " + className 14502 + " does not exist in " + packageName); 14503 } else { 14504 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14505 + className + " does not exist in " + packageName); 14506 } 14507 } 14508 switch (newState) { 14509 case COMPONENT_ENABLED_STATE_ENABLED: 14510 if (!pkgSetting.enableComponentLPw(className, userId)) { 14511 return; 14512 } 14513 break; 14514 case COMPONENT_ENABLED_STATE_DISABLED: 14515 if (!pkgSetting.disableComponentLPw(className, userId)) { 14516 return; 14517 } 14518 break; 14519 case COMPONENT_ENABLED_STATE_DEFAULT: 14520 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14521 return; 14522 } 14523 break; 14524 default: 14525 Slog.e(TAG, "Invalid new component state: " + newState); 14526 return; 14527 } 14528 } 14529 scheduleWritePackageRestrictionsLocked(userId); 14530 components = mPendingBroadcasts.get(userId, packageName); 14531 final boolean newPackage = components == null; 14532 if (newPackage) { 14533 components = new ArrayList<String>(); 14534 } 14535 if (!components.contains(componentName)) { 14536 components.add(componentName); 14537 } 14538 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14539 sendNow = true; 14540 // Purge entry from pending broadcast list if another one exists already 14541 // since we are sending one right away. 14542 mPendingBroadcasts.remove(userId, packageName); 14543 } else { 14544 if (newPackage) { 14545 mPendingBroadcasts.put(userId, packageName, components); 14546 } 14547 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14548 // Schedule a message 14549 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14550 } 14551 } 14552 } 14553 14554 long callingId = Binder.clearCallingIdentity(); 14555 try { 14556 if (sendNow) { 14557 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14558 sendPackageChangedBroadcast(packageName, 14559 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14560 } 14561 } finally { 14562 Binder.restoreCallingIdentity(callingId); 14563 } 14564 } 14565 14566 private void sendPackageChangedBroadcast(String packageName, 14567 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14568 if (DEBUG_INSTALL) 14569 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14570 + componentNames); 14571 Bundle extras = new Bundle(4); 14572 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14573 String nameList[] = new String[componentNames.size()]; 14574 componentNames.toArray(nameList); 14575 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14576 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14577 extras.putInt(Intent.EXTRA_UID, packageUid); 14578 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14579 new int[] {UserHandle.getUserId(packageUid)}); 14580 } 14581 14582 @Override 14583 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14584 if (!sUserManager.exists(userId)) return; 14585 final int uid = Binder.getCallingUid(); 14586 final int permission = mContext.checkCallingOrSelfPermission( 14587 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14588 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14589 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14590 // writer 14591 synchronized (mPackages) { 14592 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14593 allowedByPermission, uid, userId)) { 14594 scheduleWritePackageRestrictionsLocked(userId); 14595 } 14596 } 14597 } 14598 14599 @Override 14600 public String getInstallerPackageName(String packageName) { 14601 // reader 14602 synchronized (mPackages) { 14603 return mSettings.getInstallerPackageNameLPr(packageName); 14604 } 14605 } 14606 14607 @Override 14608 public int getApplicationEnabledSetting(String packageName, int userId) { 14609 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14610 int uid = Binder.getCallingUid(); 14611 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14612 // reader 14613 synchronized (mPackages) { 14614 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14615 } 14616 } 14617 14618 @Override 14619 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14620 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14621 int uid = Binder.getCallingUid(); 14622 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14623 // reader 14624 synchronized (mPackages) { 14625 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14626 } 14627 } 14628 14629 @Override 14630 public void enterSafeMode() { 14631 enforceSystemOrRoot("Only the system can request entering safe mode"); 14632 14633 if (!mSystemReady) { 14634 mSafeMode = true; 14635 } 14636 } 14637 14638 @Override 14639 public void systemReady() { 14640 mSystemReady = true; 14641 14642 // Read the compatibilty setting when the system is ready. 14643 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14644 mContext.getContentResolver(), 14645 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14646 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14647 if (DEBUG_SETTINGS) { 14648 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14649 } 14650 14651 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14652 14653 synchronized (mPackages) { 14654 // Verify that all of the preferred activity components actually 14655 // exist. It is possible for applications to be updated and at 14656 // that point remove a previously declared activity component that 14657 // had been set as a preferred activity. We try to clean this up 14658 // the next time we encounter that preferred activity, but it is 14659 // possible for the user flow to never be able to return to that 14660 // situation so here we do a sanity check to make sure we haven't 14661 // left any junk around. 14662 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14663 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14664 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14665 removed.clear(); 14666 for (PreferredActivity pa : pir.filterSet()) { 14667 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14668 removed.add(pa); 14669 } 14670 } 14671 if (removed.size() > 0) { 14672 for (int r=0; r<removed.size(); r++) { 14673 PreferredActivity pa = removed.get(r); 14674 Slog.w(TAG, "Removing dangling preferred activity: " 14675 + pa.mPref.mComponent); 14676 pir.removeFilter(pa); 14677 } 14678 mSettings.writePackageRestrictionsLPr( 14679 mSettings.mPreferredActivities.keyAt(i)); 14680 } 14681 } 14682 14683 for (int userId : UserManagerService.getInstance().getUserIds()) { 14684 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14685 grantPermissionsUserIds = ArrayUtils.appendInt( 14686 grantPermissionsUserIds, userId); 14687 } 14688 } 14689 } 14690 sUserManager.systemReady(); 14691 14692 // If we upgraded grant all default permissions before kicking off. 14693 for (int userId : grantPermissionsUserIds) { 14694 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14695 } 14696 14697 // Kick off any messages waiting for system ready 14698 if (mPostSystemReadyMessages != null) { 14699 for (Message msg : mPostSystemReadyMessages) { 14700 msg.sendToTarget(); 14701 } 14702 mPostSystemReadyMessages = null; 14703 } 14704 14705 // Watch for external volumes that come and go over time 14706 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14707 storage.registerListener(mStorageListener); 14708 14709 mInstallerService.systemReady(); 14710 mPackageDexOptimizer.systemReady(); 14711 14712 MountServiceInternal mountServiceInternal = LocalServices.getService( 14713 MountServiceInternal.class); 14714 mountServiceInternal.addExternalStoragePolicy( 14715 new MountServiceInternal.ExternalStorageMountPolicy() { 14716 @Override 14717 public int getMountMode(int uid, String packageName) { 14718 if (Process.isIsolated(uid)) { 14719 return Zygote.MOUNT_EXTERNAL_NONE; 14720 } 14721 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14722 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14723 } 14724 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14725 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14726 } 14727 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14728 return Zygote.MOUNT_EXTERNAL_READ; 14729 } 14730 return Zygote.MOUNT_EXTERNAL_WRITE; 14731 } 14732 14733 @Override 14734 public boolean hasExternalStorage(int uid, String packageName) { 14735 return true; 14736 } 14737 }); 14738 } 14739 14740 @Override 14741 public boolean isSafeMode() { 14742 return mSafeMode; 14743 } 14744 14745 @Override 14746 public boolean hasSystemUidErrors() { 14747 return mHasSystemUidErrors; 14748 } 14749 14750 static String arrayToString(int[] array) { 14751 StringBuffer buf = new StringBuffer(128); 14752 buf.append('['); 14753 if (array != null) { 14754 for (int i=0; i<array.length; i++) { 14755 if (i > 0) buf.append(", "); 14756 buf.append(array[i]); 14757 } 14758 } 14759 buf.append(']'); 14760 return buf.toString(); 14761 } 14762 14763 static class DumpState { 14764 public static final int DUMP_LIBS = 1 << 0; 14765 public static final int DUMP_FEATURES = 1 << 1; 14766 public static final int DUMP_RESOLVERS = 1 << 2; 14767 public static final int DUMP_PERMISSIONS = 1 << 3; 14768 public static final int DUMP_PACKAGES = 1 << 4; 14769 public static final int DUMP_SHARED_USERS = 1 << 5; 14770 public static final int DUMP_MESSAGES = 1 << 6; 14771 public static final int DUMP_PROVIDERS = 1 << 7; 14772 public static final int DUMP_VERIFIERS = 1 << 8; 14773 public static final int DUMP_PREFERRED = 1 << 9; 14774 public static final int DUMP_PREFERRED_XML = 1 << 10; 14775 public static final int DUMP_KEYSETS = 1 << 11; 14776 public static final int DUMP_VERSION = 1 << 12; 14777 public static final int DUMP_INSTALLS = 1 << 13; 14778 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14779 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14780 14781 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14782 14783 private int mTypes; 14784 14785 private int mOptions; 14786 14787 private boolean mTitlePrinted; 14788 14789 private SharedUserSetting mSharedUser; 14790 14791 public boolean isDumping(int type) { 14792 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14793 return true; 14794 } 14795 14796 return (mTypes & type) != 0; 14797 } 14798 14799 public void setDump(int type) { 14800 mTypes |= type; 14801 } 14802 14803 public boolean isOptionEnabled(int option) { 14804 return (mOptions & option) != 0; 14805 } 14806 14807 public void setOptionEnabled(int option) { 14808 mOptions |= option; 14809 } 14810 14811 public boolean onTitlePrinted() { 14812 final boolean printed = mTitlePrinted; 14813 mTitlePrinted = true; 14814 return printed; 14815 } 14816 14817 public boolean getTitlePrinted() { 14818 return mTitlePrinted; 14819 } 14820 14821 public void setTitlePrinted(boolean enabled) { 14822 mTitlePrinted = enabled; 14823 } 14824 14825 public SharedUserSetting getSharedUser() { 14826 return mSharedUser; 14827 } 14828 14829 public void setSharedUser(SharedUserSetting user) { 14830 mSharedUser = user; 14831 } 14832 } 14833 14834 @Override 14835 public void onShellCommand(FileDescriptor in, FileDescriptor out, 14836 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 14837 (new PackageManagerShellCommand(this)).exec( 14838 this, in, out, err, args, resultReceiver); 14839 } 14840 14841 @Override 14842 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14843 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14844 != PackageManager.PERMISSION_GRANTED) { 14845 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14846 + Binder.getCallingPid() 14847 + ", uid=" + Binder.getCallingUid() 14848 + " without permission " 14849 + android.Manifest.permission.DUMP); 14850 return; 14851 } 14852 14853 DumpState dumpState = new DumpState(); 14854 boolean fullPreferred = false; 14855 boolean checkin = false; 14856 14857 String packageName = null; 14858 ArraySet<String> permissionNames = null; 14859 14860 int opti = 0; 14861 while (opti < args.length) { 14862 String opt = args[opti]; 14863 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14864 break; 14865 } 14866 opti++; 14867 14868 if ("-a".equals(opt)) { 14869 // Right now we only know how to print all. 14870 } else if ("-h".equals(opt)) { 14871 pw.println("Package manager dump options:"); 14872 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14873 pw.println(" --checkin: dump for a checkin"); 14874 pw.println(" -f: print details of intent filters"); 14875 pw.println(" -h: print this help"); 14876 pw.println(" cmd may be one of:"); 14877 pw.println(" l[ibraries]: list known shared libraries"); 14878 pw.println(" f[ibraries]: list device features"); 14879 pw.println(" k[eysets]: print known keysets"); 14880 pw.println(" r[esolvers]: dump intent resolvers"); 14881 pw.println(" perm[issions]: dump permissions"); 14882 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14883 pw.println(" pref[erred]: print preferred package settings"); 14884 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14885 pw.println(" prov[iders]: dump content providers"); 14886 pw.println(" p[ackages]: dump installed packages"); 14887 pw.println(" s[hared-users]: dump shared user IDs"); 14888 pw.println(" m[essages]: print collected runtime messages"); 14889 pw.println(" v[erifiers]: print package verifier info"); 14890 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14891 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14892 pw.println(" version: print database version info"); 14893 pw.println(" write: write current settings now"); 14894 pw.println(" installs: details about install sessions"); 14895 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 14896 pw.println(" <package.name>: info about given package"); 14897 return; 14898 } else if ("--checkin".equals(opt)) { 14899 checkin = true; 14900 } else if ("-f".equals(opt)) { 14901 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14902 } else { 14903 pw.println("Unknown argument: " + opt + "; use -h for help"); 14904 } 14905 } 14906 14907 // Is the caller requesting to dump a particular piece of data? 14908 if (opti < args.length) { 14909 String cmd = args[opti]; 14910 opti++; 14911 // Is this a package name? 14912 if ("android".equals(cmd) || cmd.contains(".")) { 14913 packageName = cmd; 14914 // When dumping a single package, we always dump all of its 14915 // filter information since the amount of data will be reasonable. 14916 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14917 } else if ("check-permission".equals(cmd)) { 14918 if (opti >= args.length) { 14919 pw.println("Error: check-permission missing permission argument"); 14920 return; 14921 } 14922 String perm = args[opti]; 14923 opti++; 14924 if (opti >= args.length) { 14925 pw.println("Error: check-permission missing package argument"); 14926 return; 14927 } 14928 String pkg = args[opti]; 14929 opti++; 14930 int user = UserHandle.getUserId(Binder.getCallingUid()); 14931 if (opti < args.length) { 14932 try { 14933 user = Integer.parseInt(args[opti]); 14934 } catch (NumberFormatException e) { 14935 pw.println("Error: check-permission user argument is not a number: " 14936 + args[opti]); 14937 return; 14938 } 14939 } 14940 pw.println(checkPermission(perm, pkg, user)); 14941 return; 14942 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14943 dumpState.setDump(DumpState.DUMP_LIBS); 14944 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14945 dumpState.setDump(DumpState.DUMP_FEATURES); 14946 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14947 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14948 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14949 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14950 } else if ("permission".equals(cmd)) { 14951 if (opti >= args.length) { 14952 pw.println("Error: permission requires permission name"); 14953 return; 14954 } 14955 permissionNames = new ArraySet<>(); 14956 while (opti < args.length) { 14957 permissionNames.add(args[opti]); 14958 opti++; 14959 } 14960 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14961 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14962 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14963 dumpState.setDump(DumpState.DUMP_PREFERRED); 14964 } else if ("preferred-xml".equals(cmd)) { 14965 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14966 if (opti < args.length && "--full".equals(args[opti])) { 14967 fullPreferred = true; 14968 opti++; 14969 } 14970 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14971 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14972 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14973 dumpState.setDump(DumpState.DUMP_PACKAGES); 14974 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14975 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14976 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14977 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14978 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14979 dumpState.setDump(DumpState.DUMP_MESSAGES); 14980 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14981 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14982 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14983 || "intent-filter-verifiers".equals(cmd)) { 14984 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14985 } else if ("version".equals(cmd)) { 14986 dumpState.setDump(DumpState.DUMP_VERSION); 14987 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14988 dumpState.setDump(DumpState.DUMP_KEYSETS); 14989 } else if ("installs".equals(cmd)) { 14990 dumpState.setDump(DumpState.DUMP_INSTALLS); 14991 } else if ("write".equals(cmd)) { 14992 synchronized (mPackages) { 14993 mSettings.writeLPr(); 14994 pw.println("Settings written."); 14995 return; 14996 } 14997 } 14998 } 14999 15000 if (checkin) { 15001 pw.println("vers,1"); 15002 } 15003 15004 // reader 15005 synchronized (mPackages) { 15006 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15007 if (!checkin) { 15008 if (dumpState.onTitlePrinted()) 15009 pw.println(); 15010 pw.println("Database versions:"); 15011 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15012 } 15013 } 15014 15015 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15016 if (!checkin) { 15017 if (dumpState.onTitlePrinted()) 15018 pw.println(); 15019 pw.println("Verifiers:"); 15020 pw.print(" Required: "); 15021 pw.print(mRequiredVerifierPackage); 15022 pw.print(" (uid="); 15023 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15024 pw.println(")"); 15025 } else if (mRequiredVerifierPackage != null) { 15026 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15027 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15028 } 15029 } 15030 15031 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15032 packageName == null) { 15033 if (mIntentFilterVerifierComponent != null) { 15034 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15035 if (!checkin) { 15036 if (dumpState.onTitlePrinted()) 15037 pw.println(); 15038 pw.println("Intent Filter Verifier:"); 15039 pw.print(" Using: "); 15040 pw.print(verifierPackageName); 15041 pw.print(" (uid="); 15042 pw.print(getPackageUid(verifierPackageName, 0)); 15043 pw.println(")"); 15044 } else if (verifierPackageName != null) { 15045 pw.print("ifv,"); pw.print(verifierPackageName); 15046 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15047 } 15048 } else { 15049 pw.println(); 15050 pw.println("No Intent Filter Verifier available!"); 15051 } 15052 } 15053 15054 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15055 boolean printedHeader = false; 15056 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15057 while (it.hasNext()) { 15058 String name = it.next(); 15059 SharedLibraryEntry ent = mSharedLibraries.get(name); 15060 if (!checkin) { 15061 if (!printedHeader) { 15062 if (dumpState.onTitlePrinted()) 15063 pw.println(); 15064 pw.println("Libraries:"); 15065 printedHeader = true; 15066 } 15067 pw.print(" "); 15068 } else { 15069 pw.print("lib,"); 15070 } 15071 pw.print(name); 15072 if (!checkin) { 15073 pw.print(" -> "); 15074 } 15075 if (ent.path != null) { 15076 if (!checkin) { 15077 pw.print("(jar) "); 15078 pw.print(ent.path); 15079 } else { 15080 pw.print(",jar,"); 15081 pw.print(ent.path); 15082 } 15083 } else { 15084 if (!checkin) { 15085 pw.print("(apk) "); 15086 pw.print(ent.apk); 15087 } else { 15088 pw.print(",apk,"); 15089 pw.print(ent.apk); 15090 } 15091 } 15092 pw.println(); 15093 } 15094 } 15095 15096 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15097 if (dumpState.onTitlePrinted()) 15098 pw.println(); 15099 if (!checkin) { 15100 pw.println("Features:"); 15101 } 15102 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15103 while (it.hasNext()) { 15104 String name = it.next(); 15105 if (!checkin) { 15106 pw.print(" "); 15107 } else { 15108 pw.print("feat,"); 15109 } 15110 pw.println(name); 15111 } 15112 } 15113 15114 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15115 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15116 : "Activity Resolver Table:", " ", packageName, 15117 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15118 dumpState.setTitlePrinted(true); 15119 } 15120 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15121 : "Receiver Resolver Table:", " ", packageName, 15122 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15123 dumpState.setTitlePrinted(true); 15124 } 15125 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15126 : "Service Resolver Table:", " ", packageName, 15127 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15128 dumpState.setTitlePrinted(true); 15129 } 15130 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15131 : "Provider Resolver Table:", " ", packageName, 15132 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15133 dumpState.setTitlePrinted(true); 15134 } 15135 } 15136 15137 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15138 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15139 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15140 int user = mSettings.mPreferredActivities.keyAt(i); 15141 if (pir.dump(pw, 15142 dumpState.getTitlePrinted() 15143 ? "\nPreferred Activities User " + user + ":" 15144 : "Preferred Activities User " + user + ":", " ", 15145 packageName, true, false)) { 15146 dumpState.setTitlePrinted(true); 15147 } 15148 } 15149 } 15150 15151 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15152 pw.flush(); 15153 FileOutputStream fout = new FileOutputStream(fd); 15154 BufferedOutputStream str = new BufferedOutputStream(fout); 15155 XmlSerializer serializer = new FastXmlSerializer(); 15156 try { 15157 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15158 serializer.startDocument(null, true); 15159 serializer.setFeature( 15160 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15161 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15162 serializer.endDocument(); 15163 serializer.flush(); 15164 } catch (IllegalArgumentException e) { 15165 pw.println("Failed writing: " + e); 15166 } catch (IllegalStateException e) { 15167 pw.println("Failed writing: " + e); 15168 } catch (IOException e) { 15169 pw.println("Failed writing: " + e); 15170 } 15171 } 15172 15173 if (!checkin 15174 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15175 && packageName == null) { 15176 pw.println(); 15177 int count = mSettings.mPackages.size(); 15178 if (count == 0) { 15179 pw.println("No applications!"); 15180 pw.println(); 15181 } else { 15182 final String prefix = " "; 15183 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15184 if (allPackageSettings.size() == 0) { 15185 pw.println("No domain preferred apps!"); 15186 pw.println(); 15187 } else { 15188 pw.println("App verification status:"); 15189 pw.println(); 15190 count = 0; 15191 for (PackageSetting ps : allPackageSettings) { 15192 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15193 if (ivi == null || ivi.getPackageName() == null) continue; 15194 pw.println(prefix + "Package: " + ivi.getPackageName()); 15195 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15196 pw.println(prefix + "Status: " + ivi.getStatusString()); 15197 pw.println(); 15198 count++; 15199 } 15200 if (count == 0) { 15201 pw.println(prefix + "No app verification established."); 15202 pw.println(); 15203 } 15204 for (int userId : sUserManager.getUserIds()) { 15205 pw.println("App linkages for user " + userId + ":"); 15206 pw.println(); 15207 count = 0; 15208 for (PackageSetting ps : allPackageSettings) { 15209 final long status = ps.getDomainVerificationStatusForUser(userId); 15210 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15211 continue; 15212 } 15213 pw.println(prefix + "Package: " + ps.name); 15214 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15215 String statusStr = IntentFilterVerificationInfo. 15216 getStatusStringFromValue(status); 15217 pw.println(prefix + "Status: " + statusStr); 15218 pw.println(); 15219 count++; 15220 } 15221 if (count == 0) { 15222 pw.println(prefix + "No configured app linkages."); 15223 pw.println(); 15224 } 15225 } 15226 } 15227 } 15228 } 15229 15230 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15231 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15232 if (packageName == null && permissionNames == null) { 15233 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15234 if (iperm == 0) { 15235 if (dumpState.onTitlePrinted()) 15236 pw.println(); 15237 pw.println("AppOp Permissions:"); 15238 } 15239 pw.print(" AppOp Permission "); 15240 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15241 pw.println(":"); 15242 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15243 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15244 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15245 } 15246 } 15247 } 15248 } 15249 15250 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15251 boolean printedSomething = false; 15252 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15253 if (packageName != null && !packageName.equals(p.info.packageName)) { 15254 continue; 15255 } 15256 if (!printedSomething) { 15257 if (dumpState.onTitlePrinted()) 15258 pw.println(); 15259 pw.println("Registered ContentProviders:"); 15260 printedSomething = true; 15261 } 15262 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15263 pw.print(" "); pw.println(p.toString()); 15264 } 15265 printedSomething = false; 15266 for (Map.Entry<String, PackageParser.Provider> entry : 15267 mProvidersByAuthority.entrySet()) { 15268 PackageParser.Provider p = entry.getValue(); 15269 if (packageName != null && !packageName.equals(p.info.packageName)) { 15270 continue; 15271 } 15272 if (!printedSomething) { 15273 if (dumpState.onTitlePrinted()) 15274 pw.println(); 15275 pw.println("ContentProvider Authorities:"); 15276 printedSomething = true; 15277 } 15278 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15279 pw.print(" "); pw.println(p.toString()); 15280 if (p.info != null && p.info.applicationInfo != null) { 15281 final String appInfo = p.info.applicationInfo.toString(); 15282 pw.print(" applicationInfo="); pw.println(appInfo); 15283 } 15284 } 15285 } 15286 15287 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15288 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15289 } 15290 15291 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15292 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15293 } 15294 15295 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15296 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15297 } 15298 15299 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15300 // XXX should handle packageName != null by dumping only install data that 15301 // the given package is involved with. 15302 if (dumpState.onTitlePrinted()) pw.println(); 15303 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15304 } 15305 15306 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15307 if (dumpState.onTitlePrinted()) pw.println(); 15308 mSettings.dumpReadMessagesLPr(pw, dumpState); 15309 15310 pw.println(); 15311 pw.println("Package warning messages:"); 15312 BufferedReader in = null; 15313 String line = null; 15314 try { 15315 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15316 while ((line = in.readLine()) != null) { 15317 if (line.contains("ignored: updated version")) continue; 15318 pw.println(line); 15319 } 15320 } catch (IOException ignored) { 15321 } finally { 15322 IoUtils.closeQuietly(in); 15323 } 15324 } 15325 15326 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15327 BufferedReader in = null; 15328 String line = null; 15329 try { 15330 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15331 while ((line = in.readLine()) != null) { 15332 if (line.contains("ignored: updated version")) continue; 15333 pw.print("msg,"); 15334 pw.println(line); 15335 } 15336 } catch (IOException ignored) { 15337 } finally { 15338 IoUtils.closeQuietly(in); 15339 } 15340 } 15341 } 15342 } 15343 15344 private String dumpDomainString(String packageName) { 15345 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15346 List<IntentFilter> filters = getAllIntentFilters(packageName); 15347 15348 ArraySet<String> result = new ArraySet<>(); 15349 if (iviList.size() > 0) { 15350 for (IntentFilterVerificationInfo ivi : iviList) { 15351 for (String host : ivi.getDomains()) { 15352 result.add(host); 15353 } 15354 } 15355 } 15356 if (filters != null && filters.size() > 0) { 15357 for (IntentFilter filter : filters) { 15358 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15359 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15360 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15361 result.addAll(filter.getHostsList()); 15362 } 15363 } 15364 } 15365 15366 StringBuilder sb = new StringBuilder(result.size() * 16); 15367 for (String domain : result) { 15368 if (sb.length() > 0) sb.append(" "); 15369 sb.append(domain); 15370 } 15371 return sb.toString(); 15372 } 15373 15374 // ------- apps on sdcard specific code ------- 15375 static final boolean DEBUG_SD_INSTALL = false; 15376 15377 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15378 15379 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15380 15381 private boolean mMediaMounted = false; 15382 15383 static String getEncryptKey() { 15384 try { 15385 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15386 SD_ENCRYPTION_KEYSTORE_NAME); 15387 if (sdEncKey == null) { 15388 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15389 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15390 if (sdEncKey == null) { 15391 Slog.e(TAG, "Failed to create encryption keys"); 15392 return null; 15393 } 15394 } 15395 return sdEncKey; 15396 } catch (NoSuchAlgorithmException nsae) { 15397 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15398 return null; 15399 } catch (IOException ioe) { 15400 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15401 return null; 15402 } 15403 } 15404 15405 /* 15406 * Update media status on PackageManager. 15407 */ 15408 @Override 15409 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15410 int callingUid = Binder.getCallingUid(); 15411 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15412 throw new SecurityException("Media status can only be updated by the system"); 15413 } 15414 // reader; this apparently protects mMediaMounted, but should probably 15415 // be a different lock in that case. 15416 synchronized (mPackages) { 15417 Log.i(TAG, "Updating external media status from " 15418 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15419 + (mediaStatus ? "mounted" : "unmounted")); 15420 if (DEBUG_SD_INSTALL) 15421 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15422 + ", mMediaMounted=" + mMediaMounted); 15423 if (mediaStatus == mMediaMounted) { 15424 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15425 : 0, -1); 15426 mHandler.sendMessage(msg); 15427 return; 15428 } 15429 mMediaMounted = mediaStatus; 15430 } 15431 // Queue up an async operation since the package installation may take a 15432 // little while. 15433 mHandler.post(new Runnable() { 15434 public void run() { 15435 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15436 } 15437 }); 15438 } 15439 15440 /** 15441 * Called by MountService when the initial ASECs to scan are available. 15442 * Should block until all the ASEC containers are finished being scanned. 15443 */ 15444 public void scanAvailableAsecs() { 15445 updateExternalMediaStatusInner(true, false, false); 15446 if (mShouldRestoreconData) { 15447 SELinuxMMAC.setRestoreconDone(); 15448 mShouldRestoreconData = false; 15449 } 15450 } 15451 15452 /* 15453 * Collect information of applications on external media, map them against 15454 * existing containers and update information based on current mount status. 15455 * Please note that we always have to report status if reportStatus has been 15456 * set to true especially when unloading packages. 15457 */ 15458 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15459 boolean externalStorage) { 15460 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15461 int[] uidArr = EmptyArray.INT; 15462 15463 final String[] list = PackageHelper.getSecureContainerList(); 15464 if (ArrayUtils.isEmpty(list)) { 15465 Log.i(TAG, "No secure containers found"); 15466 } else { 15467 // Process list of secure containers and categorize them 15468 // as active or stale based on their package internal state. 15469 15470 // reader 15471 synchronized (mPackages) { 15472 for (String cid : list) { 15473 // Leave stages untouched for now; installer service owns them 15474 if (PackageInstallerService.isStageName(cid)) continue; 15475 15476 if (DEBUG_SD_INSTALL) 15477 Log.i(TAG, "Processing container " + cid); 15478 String pkgName = getAsecPackageName(cid); 15479 if (pkgName == null) { 15480 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15481 continue; 15482 } 15483 if (DEBUG_SD_INSTALL) 15484 Log.i(TAG, "Looking for pkg : " + pkgName); 15485 15486 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15487 if (ps == null) { 15488 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15489 continue; 15490 } 15491 15492 /* 15493 * Skip packages that are not external if we're unmounting 15494 * external storage. 15495 */ 15496 if (externalStorage && !isMounted && !isExternal(ps)) { 15497 continue; 15498 } 15499 15500 final AsecInstallArgs args = new AsecInstallArgs(cid, 15501 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15502 // The package status is changed only if the code path 15503 // matches between settings and the container id. 15504 if (ps.codePathString != null 15505 && ps.codePathString.startsWith(args.getCodePath())) { 15506 if (DEBUG_SD_INSTALL) { 15507 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15508 + " at code path: " + ps.codePathString); 15509 } 15510 15511 // We do have a valid package installed on sdcard 15512 processCids.put(args, ps.codePathString); 15513 final int uid = ps.appId; 15514 if (uid != -1) { 15515 uidArr = ArrayUtils.appendInt(uidArr, uid); 15516 } 15517 } else { 15518 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15519 + ps.codePathString); 15520 } 15521 } 15522 } 15523 15524 Arrays.sort(uidArr); 15525 } 15526 15527 // Process packages with valid entries. 15528 if (isMounted) { 15529 if (DEBUG_SD_INSTALL) 15530 Log.i(TAG, "Loading packages"); 15531 loadMediaPackages(processCids, uidArr, externalStorage); 15532 startCleaningPackages(); 15533 mInstallerService.onSecureContainersAvailable(); 15534 } else { 15535 if (DEBUG_SD_INSTALL) 15536 Log.i(TAG, "Unloading packages"); 15537 unloadMediaPackages(processCids, uidArr, reportStatus); 15538 } 15539 } 15540 15541 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15542 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15543 final int size = infos.size(); 15544 final String[] packageNames = new String[size]; 15545 final int[] packageUids = new int[size]; 15546 for (int i = 0; i < size; i++) { 15547 final ApplicationInfo info = infos.get(i); 15548 packageNames[i] = info.packageName; 15549 packageUids[i] = info.uid; 15550 } 15551 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15552 finishedReceiver); 15553 } 15554 15555 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15556 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15557 sendResourcesChangedBroadcast(mediaStatus, replacing, 15558 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15559 } 15560 15561 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15562 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15563 int size = pkgList.length; 15564 if (size > 0) { 15565 // Send broadcasts here 15566 Bundle extras = new Bundle(); 15567 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15568 if (uidArr != null) { 15569 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15570 } 15571 if (replacing) { 15572 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15573 } 15574 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15575 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15576 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15577 } 15578 } 15579 15580 /* 15581 * Look at potentially valid container ids from processCids If package 15582 * information doesn't match the one on record or package scanning fails, 15583 * the cid is added to list of removeCids. We currently don't delete stale 15584 * containers. 15585 */ 15586 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15587 boolean externalStorage) { 15588 ArrayList<String> pkgList = new ArrayList<String>(); 15589 Set<AsecInstallArgs> keys = processCids.keySet(); 15590 15591 for (AsecInstallArgs args : keys) { 15592 String codePath = processCids.get(args); 15593 if (DEBUG_SD_INSTALL) 15594 Log.i(TAG, "Loading container : " + args.cid); 15595 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15596 try { 15597 // Make sure there are no container errors first. 15598 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15599 Slog.e(TAG, "Failed to mount cid : " + args.cid 15600 + " when installing from sdcard"); 15601 continue; 15602 } 15603 // Check code path here. 15604 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15605 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15606 + " does not match one in settings " + codePath); 15607 continue; 15608 } 15609 // Parse package 15610 int parseFlags = mDefParseFlags; 15611 if (args.isExternalAsec()) { 15612 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15613 } 15614 if (args.isFwdLocked()) { 15615 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15616 } 15617 15618 synchronized (mInstallLock) { 15619 PackageParser.Package pkg = null; 15620 try { 15621 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15622 } catch (PackageManagerException e) { 15623 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15624 } 15625 // Scan the package 15626 if (pkg != null) { 15627 /* 15628 * TODO why is the lock being held? doPostInstall is 15629 * called in other places without the lock. This needs 15630 * to be straightened out. 15631 */ 15632 // writer 15633 synchronized (mPackages) { 15634 retCode = PackageManager.INSTALL_SUCCEEDED; 15635 pkgList.add(pkg.packageName); 15636 // Post process args 15637 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15638 pkg.applicationInfo.uid); 15639 } 15640 } else { 15641 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15642 } 15643 } 15644 15645 } finally { 15646 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15647 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15648 } 15649 } 15650 } 15651 // writer 15652 synchronized (mPackages) { 15653 // If the platform SDK has changed since the last time we booted, 15654 // we need to re-grant app permission to catch any new ones that 15655 // appear. This is really a hack, and means that apps can in some 15656 // cases get permissions that the user didn't initially explicitly 15657 // allow... it would be nice to have some better way to handle 15658 // this situation. 15659 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15660 : mSettings.getInternalVersion(); 15661 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15662 : StorageManager.UUID_PRIVATE_INTERNAL; 15663 15664 int updateFlags = UPDATE_PERMISSIONS_ALL; 15665 if (ver.sdkVersion != mSdkVersion) { 15666 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15667 + mSdkVersion + "; regranting permissions for external"); 15668 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15669 } 15670 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15671 15672 // Yay, everything is now upgraded 15673 ver.forceCurrent(); 15674 15675 // can downgrade to reader 15676 // Persist settings 15677 mSettings.writeLPr(); 15678 } 15679 // Send a broadcast to let everyone know we are done processing 15680 if (pkgList.size() > 0) { 15681 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15682 } 15683 } 15684 15685 /* 15686 * Utility method to unload a list of specified containers 15687 */ 15688 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15689 // Just unmount all valid containers. 15690 for (AsecInstallArgs arg : cidArgs) { 15691 synchronized (mInstallLock) { 15692 arg.doPostDeleteLI(false); 15693 } 15694 } 15695 } 15696 15697 /* 15698 * Unload packages mounted on external media. This involves deleting package 15699 * data from internal structures, sending broadcasts about diabled packages, 15700 * gc'ing to free up references, unmounting all secure containers 15701 * corresponding to packages on external media, and posting a 15702 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15703 * that we always have to post this message if status has been requested no 15704 * matter what. 15705 */ 15706 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15707 final boolean reportStatus) { 15708 if (DEBUG_SD_INSTALL) 15709 Log.i(TAG, "unloading media packages"); 15710 ArrayList<String> pkgList = new ArrayList<String>(); 15711 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15712 final Set<AsecInstallArgs> keys = processCids.keySet(); 15713 for (AsecInstallArgs args : keys) { 15714 String pkgName = args.getPackageName(); 15715 if (DEBUG_SD_INSTALL) 15716 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15717 // Delete package internally 15718 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15719 synchronized (mInstallLock) { 15720 boolean res = deletePackageLI(pkgName, null, false, null, null, 15721 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15722 if (res) { 15723 pkgList.add(pkgName); 15724 } else { 15725 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15726 failedList.add(args); 15727 } 15728 } 15729 } 15730 15731 // reader 15732 synchronized (mPackages) { 15733 // We didn't update the settings after removing each package; 15734 // write them now for all packages. 15735 mSettings.writeLPr(); 15736 } 15737 15738 // We have to absolutely send UPDATED_MEDIA_STATUS only 15739 // after confirming that all the receivers processed the ordered 15740 // broadcast when packages get disabled, force a gc to clean things up. 15741 // and unload all the containers. 15742 if (pkgList.size() > 0) { 15743 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15744 new IIntentReceiver.Stub() { 15745 public void performReceive(Intent intent, int resultCode, String data, 15746 Bundle extras, boolean ordered, boolean sticky, 15747 int sendingUser) throws RemoteException { 15748 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15749 reportStatus ? 1 : 0, 1, keys); 15750 mHandler.sendMessage(msg); 15751 } 15752 }); 15753 } else { 15754 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15755 keys); 15756 mHandler.sendMessage(msg); 15757 } 15758 } 15759 15760 private void loadPrivatePackages(final VolumeInfo vol) { 15761 mHandler.post(new Runnable() { 15762 @Override 15763 public void run() { 15764 loadPrivatePackagesInner(vol); 15765 } 15766 }); 15767 } 15768 15769 private void loadPrivatePackagesInner(VolumeInfo vol) { 15770 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15771 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15772 15773 final VersionInfo ver; 15774 final List<PackageSetting> packages; 15775 synchronized (mPackages) { 15776 ver = mSettings.findOrCreateVersion(vol.fsUuid); 15777 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15778 } 15779 15780 for (PackageSetting ps : packages) { 15781 synchronized (mInstallLock) { 15782 final PackageParser.Package pkg; 15783 try { 15784 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 15785 loaded.add(pkg.applicationInfo); 15786 } catch (PackageManagerException e) { 15787 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15788 } 15789 15790 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15791 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15792 } 15793 } 15794 } 15795 15796 synchronized (mPackages) { 15797 int updateFlags = UPDATE_PERMISSIONS_ALL; 15798 if (ver.sdkVersion != mSdkVersion) { 15799 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15800 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15801 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15802 } 15803 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 15804 15805 // Yay, everything is now upgraded 15806 ver.forceCurrent(); 15807 15808 mSettings.writeLPr(); 15809 } 15810 15811 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15812 sendResourcesChangedBroadcast(true, false, loaded, null); 15813 } 15814 15815 private void unloadPrivatePackages(final VolumeInfo vol) { 15816 mHandler.post(new Runnable() { 15817 @Override 15818 public void run() { 15819 unloadPrivatePackagesInner(vol); 15820 } 15821 }); 15822 } 15823 15824 private void unloadPrivatePackagesInner(VolumeInfo vol) { 15825 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15826 synchronized (mInstallLock) { 15827 synchronized (mPackages) { 15828 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15829 for (PackageSetting ps : packages) { 15830 if (ps.pkg == null) continue; 15831 15832 final ApplicationInfo info = ps.pkg.applicationInfo; 15833 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15834 if (deletePackageLI(ps.name, null, false, null, null, 15835 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15836 unloaded.add(info); 15837 } else { 15838 Slog.w(TAG, "Failed to unload " + ps.codePath); 15839 } 15840 } 15841 15842 mSettings.writeLPr(); 15843 } 15844 } 15845 15846 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15847 sendResourcesChangedBroadcast(false, false, unloaded, null); 15848 } 15849 15850 /** 15851 * Examine all users present on given mounted volume, and destroy data 15852 * belonging to users that are no longer valid, or whose user ID has been 15853 * recycled. 15854 */ 15855 private void reconcileUsers(String volumeUuid) { 15856 final File[] files = FileUtils 15857 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15858 for (File file : files) { 15859 if (!file.isDirectory()) continue; 15860 15861 final int userId; 15862 final UserInfo info; 15863 try { 15864 userId = Integer.parseInt(file.getName()); 15865 info = sUserManager.getUserInfo(userId); 15866 } catch (NumberFormatException e) { 15867 Slog.w(TAG, "Invalid user directory " + file); 15868 continue; 15869 } 15870 15871 boolean destroyUser = false; 15872 if (info == null) { 15873 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15874 + " because no matching user was found"); 15875 destroyUser = true; 15876 } else { 15877 try { 15878 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15879 } catch (IOException e) { 15880 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15881 + " because we failed to enforce serial number: " + e); 15882 destroyUser = true; 15883 } 15884 } 15885 15886 if (destroyUser) { 15887 synchronized (mInstallLock) { 15888 mInstaller.removeUserDataDirs(volumeUuid, userId); 15889 } 15890 } 15891 } 15892 15893 final UserManager um = mContext.getSystemService(UserManager.class); 15894 for (UserInfo user : um.getUsers()) { 15895 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15896 if (userDir.exists()) continue; 15897 15898 try { 15899 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15900 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15901 } catch (IOException e) { 15902 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15903 } 15904 } 15905 } 15906 15907 /** 15908 * Examine all apps present on given mounted volume, and destroy apps that 15909 * aren't expected, either due to uninstallation or reinstallation on 15910 * another volume. 15911 */ 15912 private void reconcileApps(String volumeUuid) { 15913 final File[] files = FileUtils 15914 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15915 for (File file : files) { 15916 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15917 && !PackageInstallerService.isStageName(file.getName()); 15918 if (!isPackage) { 15919 // Ignore entries which are not packages 15920 continue; 15921 } 15922 15923 boolean destroyApp = false; 15924 String packageName = null; 15925 try { 15926 final PackageLite pkg = PackageParser.parsePackageLite(file, 15927 PackageParser.PARSE_MUST_BE_APK); 15928 packageName = pkg.packageName; 15929 15930 synchronized (mPackages) { 15931 final PackageSetting ps = mSettings.mPackages.get(packageName); 15932 if (ps == null) { 15933 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15934 + volumeUuid + " because we found no install record"); 15935 destroyApp = true; 15936 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15937 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15938 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15939 destroyApp = true; 15940 } 15941 } 15942 15943 } catch (PackageParserException e) { 15944 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15945 destroyApp = true; 15946 } 15947 15948 if (destroyApp) { 15949 synchronized (mInstallLock) { 15950 if (packageName != null) { 15951 removeDataDirsLI(volumeUuid, packageName); 15952 } 15953 if (file.isDirectory()) { 15954 mInstaller.rmPackageDir(file.getAbsolutePath()); 15955 } else { 15956 file.delete(); 15957 } 15958 } 15959 } 15960 } 15961 } 15962 15963 private void unfreezePackage(String packageName) { 15964 synchronized (mPackages) { 15965 final PackageSetting ps = mSettings.mPackages.get(packageName); 15966 if (ps != null) { 15967 ps.frozen = false; 15968 } 15969 } 15970 } 15971 15972 @Override 15973 public int movePackage(final String packageName, final String volumeUuid) { 15974 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15975 15976 final int moveId = mNextMoveId.getAndIncrement(); 15977 try { 15978 movePackageInternal(packageName, volumeUuid, moveId); 15979 } catch (PackageManagerException e) { 15980 Slog.w(TAG, "Failed to move " + packageName, e); 15981 mMoveCallbacks.notifyStatusChanged(moveId, 15982 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15983 } 15984 return moveId; 15985 } 15986 15987 private void movePackageInternal(final String packageName, final String volumeUuid, 15988 final int moveId) throws PackageManagerException { 15989 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15990 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15991 final PackageManager pm = mContext.getPackageManager(); 15992 15993 final boolean currentAsec; 15994 final String currentVolumeUuid; 15995 final File codeFile; 15996 final String installerPackageName; 15997 final String packageAbiOverride; 15998 final int appId; 15999 final String seinfo; 16000 final String label; 16001 16002 // reader 16003 synchronized (mPackages) { 16004 final PackageParser.Package pkg = mPackages.get(packageName); 16005 final PackageSetting ps = mSettings.mPackages.get(packageName); 16006 if (pkg == null || ps == null) { 16007 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16008 } 16009 16010 if (pkg.applicationInfo.isSystemApp()) { 16011 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16012 "Cannot move system application"); 16013 } 16014 16015 if (pkg.applicationInfo.isExternalAsec()) { 16016 currentAsec = true; 16017 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16018 } else if (pkg.applicationInfo.isForwardLocked()) { 16019 currentAsec = true; 16020 currentVolumeUuid = "forward_locked"; 16021 } else { 16022 currentAsec = false; 16023 currentVolumeUuid = ps.volumeUuid; 16024 16025 final File probe = new File(pkg.codePath); 16026 final File probeOat = new File(probe, "oat"); 16027 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16028 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16029 "Move only supported for modern cluster style installs"); 16030 } 16031 } 16032 16033 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16034 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16035 "Package already moved to " + volumeUuid); 16036 } 16037 16038 if (ps.frozen) { 16039 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16040 "Failed to move already frozen package"); 16041 } 16042 ps.frozen = true; 16043 16044 codeFile = new File(pkg.codePath); 16045 installerPackageName = ps.installerPackageName; 16046 packageAbiOverride = ps.cpuAbiOverrideString; 16047 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16048 seinfo = pkg.applicationInfo.seinfo; 16049 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16050 } 16051 16052 // Now that we're guarded by frozen state, kill app during move 16053 final long token = Binder.clearCallingIdentity(); 16054 try { 16055 killApplication(packageName, appId, "move pkg"); 16056 } finally { 16057 Binder.restoreCallingIdentity(token); 16058 } 16059 16060 final Bundle extras = new Bundle(); 16061 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16062 extras.putString(Intent.EXTRA_TITLE, label); 16063 mMoveCallbacks.notifyCreated(moveId, extras); 16064 16065 int installFlags; 16066 final boolean moveCompleteApp; 16067 final File measurePath; 16068 16069 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16070 installFlags = INSTALL_INTERNAL; 16071 moveCompleteApp = !currentAsec; 16072 measurePath = Environment.getDataAppDirectory(volumeUuid); 16073 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16074 installFlags = INSTALL_EXTERNAL; 16075 moveCompleteApp = false; 16076 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16077 } else { 16078 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16079 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16080 || !volume.isMountedWritable()) { 16081 unfreezePackage(packageName); 16082 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16083 "Move location not mounted private volume"); 16084 } 16085 16086 Preconditions.checkState(!currentAsec); 16087 16088 installFlags = INSTALL_INTERNAL; 16089 moveCompleteApp = true; 16090 measurePath = Environment.getDataAppDirectory(volumeUuid); 16091 } 16092 16093 final PackageStats stats = new PackageStats(null, -1); 16094 synchronized (mInstaller) { 16095 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16096 unfreezePackage(packageName); 16097 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16098 "Failed to measure package size"); 16099 } 16100 } 16101 16102 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16103 + stats.dataSize); 16104 16105 final long startFreeBytes = measurePath.getFreeSpace(); 16106 final long sizeBytes; 16107 if (moveCompleteApp) { 16108 sizeBytes = stats.codeSize + stats.dataSize; 16109 } else { 16110 sizeBytes = stats.codeSize; 16111 } 16112 16113 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16114 unfreezePackage(packageName); 16115 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16116 "Not enough free space to move"); 16117 } 16118 16119 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16120 16121 final CountDownLatch installedLatch = new CountDownLatch(1); 16122 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16123 @Override 16124 public void onUserActionRequired(Intent intent) throws RemoteException { 16125 throw new IllegalStateException(); 16126 } 16127 16128 @Override 16129 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16130 Bundle extras) throws RemoteException { 16131 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16132 + PackageManager.installStatusToString(returnCode, msg)); 16133 16134 installedLatch.countDown(); 16135 16136 // Regardless of success or failure of the move operation, 16137 // always unfreeze the package 16138 unfreezePackage(packageName); 16139 16140 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16141 switch (status) { 16142 case PackageInstaller.STATUS_SUCCESS: 16143 mMoveCallbacks.notifyStatusChanged(moveId, 16144 PackageManager.MOVE_SUCCEEDED); 16145 break; 16146 case PackageInstaller.STATUS_FAILURE_STORAGE: 16147 mMoveCallbacks.notifyStatusChanged(moveId, 16148 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16149 break; 16150 default: 16151 mMoveCallbacks.notifyStatusChanged(moveId, 16152 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16153 break; 16154 } 16155 } 16156 }; 16157 16158 final MoveInfo move; 16159 if (moveCompleteApp) { 16160 // Kick off a thread to report progress estimates 16161 new Thread() { 16162 @Override 16163 public void run() { 16164 while (true) { 16165 try { 16166 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16167 break; 16168 } 16169 } catch (InterruptedException ignored) { 16170 } 16171 16172 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16173 final int progress = 10 + (int) MathUtils.constrain( 16174 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16175 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16176 } 16177 } 16178 }.start(); 16179 16180 final String dataAppName = codeFile.getName(); 16181 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16182 dataAppName, appId, seinfo); 16183 } else { 16184 move = null; 16185 } 16186 16187 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16188 16189 final Message msg = mHandler.obtainMessage(INIT_COPY); 16190 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16191 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16192 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16193 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16194 msg.obj = params; 16195 16196 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16197 System.identityHashCode(msg.obj)); 16198 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16199 System.identityHashCode(msg.obj)); 16200 16201 mHandler.sendMessage(msg); 16202 } 16203 16204 @Override 16205 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16207 16208 final int realMoveId = mNextMoveId.getAndIncrement(); 16209 final Bundle extras = new Bundle(); 16210 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16211 mMoveCallbacks.notifyCreated(realMoveId, extras); 16212 16213 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16214 @Override 16215 public void onCreated(int moveId, Bundle extras) { 16216 // Ignored 16217 } 16218 16219 @Override 16220 public void onStatusChanged(int moveId, int status, long estMillis) { 16221 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16222 } 16223 }; 16224 16225 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16226 storage.setPrimaryStorageUuid(volumeUuid, callback); 16227 return realMoveId; 16228 } 16229 16230 @Override 16231 public int getMoveStatus(int moveId) { 16232 mContext.enforceCallingOrSelfPermission( 16233 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16234 return mMoveCallbacks.mLastStatus.get(moveId); 16235 } 16236 16237 @Override 16238 public void registerMoveCallback(IPackageMoveObserver callback) { 16239 mContext.enforceCallingOrSelfPermission( 16240 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16241 mMoveCallbacks.register(callback); 16242 } 16243 16244 @Override 16245 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16246 mContext.enforceCallingOrSelfPermission( 16247 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16248 mMoveCallbacks.unregister(callback); 16249 } 16250 16251 @Override 16252 public boolean setInstallLocation(int loc) { 16253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16254 null); 16255 if (getInstallLocation() == loc) { 16256 return true; 16257 } 16258 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16259 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16260 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16261 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16262 return true; 16263 } 16264 return false; 16265 } 16266 16267 @Override 16268 public int getInstallLocation() { 16269 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16270 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16271 PackageHelper.APP_INSTALL_AUTO); 16272 } 16273 16274 /** Called by UserManagerService */ 16275 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16276 mDirtyUsers.remove(userHandle); 16277 mSettings.removeUserLPw(userHandle); 16278 mPendingBroadcasts.remove(userHandle); 16279 if (mInstaller != null) { 16280 // Technically, we shouldn't be doing this with the package lock 16281 // held. However, this is very rare, and there is already so much 16282 // other disk I/O going on, that we'll let it slide for now. 16283 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16284 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16285 final String volumeUuid = vol.getFsUuid(); 16286 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16287 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16288 } 16289 } 16290 mUserNeedsBadging.delete(userHandle); 16291 removeUnusedPackagesLILPw(userManager, userHandle); 16292 } 16293 16294 /** 16295 * We're removing userHandle and would like to remove any downloaded packages 16296 * that are no longer in use by any other user. 16297 * @param userHandle the user being removed 16298 */ 16299 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16300 final boolean DEBUG_CLEAN_APKS = false; 16301 int [] users = userManager.getUserIds(); 16302 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16303 while (psit.hasNext()) { 16304 PackageSetting ps = psit.next(); 16305 if (ps.pkg == null) { 16306 continue; 16307 } 16308 final String packageName = ps.pkg.packageName; 16309 // Skip over if system app 16310 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16311 continue; 16312 } 16313 if (DEBUG_CLEAN_APKS) { 16314 Slog.i(TAG, "Checking package " + packageName); 16315 } 16316 boolean keep = false; 16317 for (int i = 0; i < users.length; i++) { 16318 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16319 keep = true; 16320 if (DEBUG_CLEAN_APKS) { 16321 Slog.i(TAG, " Keeping package " + packageName + " for user " 16322 + users[i]); 16323 } 16324 break; 16325 } 16326 } 16327 if (!keep) { 16328 if (DEBUG_CLEAN_APKS) { 16329 Slog.i(TAG, " Removing package " + packageName); 16330 } 16331 mHandler.post(new Runnable() { 16332 public void run() { 16333 deletePackageX(packageName, userHandle, 0); 16334 } //end run 16335 }); 16336 } 16337 } 16338 } 16339 16340 /** Called by UserManagerService */ 16341 void createNewUserLILPw(int userHandle) { 16342 if (mInstaller != null) { 16343 mInstaller.createUserConfig(userHandle); 16344 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16345 applyFactoryDefaultBrowserLPw(userHandle); 16346 primeDomainVerificationsLPw(userHandle); 16347 } 16348 } 16349 16350 void newUserCreated(final int userHandle) { 16351 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16352 } 16353 16354 @Override 16355 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16356 mContext.enforceCallingOrSelfPermission( 16357 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16358 "Only package verification agents can read the verifier device identity"); 16359 16360 synchronized (mPackages) { 16361 return mSettings.getVerifierDeviceIdentityLPw(); 16362 } 16363 } 16364 16365 @Override 16366 public void setPermissionEnforced(String permission, boolean enforced) { 16367 // TODO: Now that we no longer change GID for storage, this should to away. 16368 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16369 "setPermissionEnforced"); 16370 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16371 synchronized (mPackages) { 16372 if (mSettings.mReadExternalStorageEnforced == null 16373 || mSettings.mReadExternalStorageEnforced != enforced) { 16374 mSettings.mReadExternalStorageEnforced = enforced; 16375 mSettings.writeLPr(); 16376 } 16377 } 16378 // kill any non-foreground processes so we restart them and 16379 // grant/revoke the GID. 16380 final IActivityManager am = ActivityManagerNative.getDefault(); 16381 if (am != null) { 16382 final long token = Binder.clearCallingIdentity(); 16383 try { 16384 am.killProcessesBelowForeground("setPermissionEnforcement"); 16385 } catch (RemoteException e) { 16386 } finally { 16387 Binder.restoreCallingIdentity(token); 16388 } 16389 } 16390 } else { 16391 throw new IllegalArgumentException("No selective enforcement for " + permission); 16392 } 16393 } 16394 16395 @Override 16396 @Deprecated 16397 public boolean isPermissionEnforced(String permission) { 16398 return true; 16399 } 16400 16401 @Override 16402 public boolean isStorageLow() { 16403 final long token = Binder.clearCallingIdentity(); 16404 try { 16405 final DeviceStorageMonitorInternal 16406 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16407 if (dsm != null) { 16408 return dsm.isMemoryLow(); 16409 } else { 16410 return false; 16411 } 16412 } finally { 16413 Binder.restoreCallingIdentity(token); 16414 } 16415 } 16416 16417 @Override 16418 public IPackageInstaller getPackageInstaller() { 16419 return mInstallerService; 16420 } 16421 16422 private boolean userNeedsBadging(int userId) { 16423 int index = mUserNeedsBadging.indexOfKey(userId); 16424 if (index < 0) { 16425 final UserInfo userInfo; 16426 final long token = Binder.clearCallingIdentity(); 16427 try { 16428 userInfo = sUserManager.getUserInfo(userId); 16429 } finally { 16430 Binder.restoreCallingIdentity(token); 16431 } 16432 final boolean b; 16433 if (userInfo != null && userInfo.isManagedProfile()) { 16434 b = true; 16435 } else { 16436 b = false; 16437 } 16438 mUserNeedsBadging.put(userId, b); 16439 return b; 16440 } 16441 return mUserNeedsBadging.valueAt(index); 16442 } 16443 16444 @Override 16445 public KeySet getKeySetByAlias(String packageName, String alias) { 16446 if (packageName == null || alias == null) { 16447 return null; 16448 } 16449 synchronized(mPackages) { 16450 final PackageParser.Package pkg = mPackages.get(packageName); 16451 if (pkg == null) { 16452 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16453 throw new IllegalArgumentException("Unknown package: " + packageName); 16454 } 16455 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16456 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16457 } 16458 } 16459 16460 @Override 16461 public KeySet getSigningKeySet(String packageName) { 16462 if (packageName == null) { 16463 return null; 16464 } 16465 synchronized(mPackages) { 16466 final PackageParser.Package pkg = mPackages.get(packageName); 16467 if (pkg == null) { 16468 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16469 throw new IllegalArgumentException("Unknown package: " + packageName); 16470 } 16471 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16472 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16473 throw new SecurityException("May not access signing KeySet of other apps."); 16474 } 16475 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16476 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16477 } 16478 } 16479 16480 @Override 16481 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16482 if (packageName == null || ks == null) { 16483 return false; 16484 } 16485 synchronized(mPackages) { 16486 final PackageParser.Package pkg = mPackages.get(packageName); 16487 if (pkg == null) { 16488 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16489 throw new IllegalArgumentException("Unknown package: " + packageName); 16490 } 16491 IBinder ksh = ks.getToken(); 16492 if (ksh instanceof KeySetHandle) { 16493 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16494 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16495 } 16496 return false; 16497 } 16498 } 16499 16500 @Override 16501 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16502 if (packageName == null || ks == null) { 16503 return false; 16504 } 16505 synchronized(mPackages) { 16506 final PackageParser.Package pkg = mPackages.get(packageName); 16507 if (pkg == null) { 16508 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16509 throw new IllegalArgumentException("Unknown package: " + packageName); 16510 } 16511 IBinder ksh = ks.getToken(); 16512 if (ksh instanceof KeySetHandle) { 16513 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16514 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16515 } 16516 return false; 16517 } 16518 } 16519 16520 /** 16521 * Check and throw if the given before/after packages would be considered a 16522 * downgrade. 16523 */ 16524 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16525 throws PackageManagerException { 16526 if (after.versionCode < before.mVersionCode) { 16527 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16528 "Update version code " + after.versionCode + " is older than current " 16529 + before.mVersionCode); 16530 } else if (after.versionCode == before.mVersionCode) { 16531 if (after.baseRevisionCode < before.baseRevisionCode) { 16532 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16533 "Update base revision code " + after.baseRevisionCode 16534 + " is older than current " + before.baseRevisionCode); 16535 } 16536 16537 if (!ArrayUtils.isEmpty(after.splitNames)) { 16538 for (int i = 0; i < after.splitNames.length; i++) { 16539 final String splitName = after.splitNames[i]; 16540 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16541 if (j != -1) { 16542 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16543 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16544 "Update split " + splitName + " revision code " 16545 + after.splitRevisionCodes[i] + " is older than current " 16546 + before.splitRevisionCodes[j]); 16547 } 16548 } 16549 } 16550 } 16551 } 16552 } 16553 16554 private static class MoveCallbacks extends Handler { 16555 private static final int MSG_CREATED = 1; 16556 private static final int MSG_STATUS_CHANGED = 2; 16557 16558 private final RemoteCallbackList<IPackageMoveObserver> 16559 mCallbacks = new RemoteCallbackList<>(); 16560 16561 private final SparseIntArray mLastStatus = new SparseIntArray(); 16562 16563 public MoveCallbacks(Looper looper) { 16564 super(looper); 16565 } 16566 16567 public void register(IPackageMoveObserver callback) { 16568 mCallbacks.register(callback); 16569 } 16570 16571 public void unregister(IPackageMoveObserver callback) { 16572 mCallbacks.unregister(callback); 16573 } 16574 16575 @Override 16576 public void handleMessage(Message msg) { 16577 final SomeArgs args = (SomeArgs) msg.obj; 16578 final int n = mCallbacks.beginBroadcast(); 16579 for (int i = 0; i < n; i++) { 16580 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16581 try { 16582 invokeCallback(callback, msg.what, args); 16583 } catch (RemoteException ignored) { 16584 } 16585 } 16586 mCallbacks.finishBroadcast(); 16587 args.recycle(); 16588 } 16589 16590 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16591 throws RemoteException { 16592 switch (what) { 16593 case MSG_CREATED: { 16594 callback.onCreated(args.argi1, (Bundle) args.arg2); 16595 break; 16596 } 16597 case MSG_STATUS_CHANGED: { 16598 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16599 break; 16600 } 16601 } 16602 } 16603 16604 private void notifyCreated(int moveId, Bundle extras) { 16605 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16606 16607 final SomeArgs args = SomeArgs.obtain(); 16608 args.argi1 = moveId; 16609 args.arg2 = extras; 16610 obtainMessage(MSG_CREATED, args).sendToTarget(); 16611 } 16612 16613 private void notifyStatusChanged(int moveId, int status) { 16614 notifyStatusChanged(moveId, status, -1); 16615 } 16616 16617 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16618 Slog.v(TAG, "Move " + moveId + " status " + status); 16619 16620 final SomeArgs args = SomeArgs.obtain(); 16621 args.argi1 = moveId; 16622 args.argi2 = status; 16623 args.arg3 = estMillis; 16624 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16625 16626 synchronized (mLastStatus) { 16627 mLastStatus.put(moveId, status); 16628 } 16629 } 16630 } 16631 16632 private final class OnPermissionChangeListeners extends Handler { 16633 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16634 16635 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16636 new RemoteCallbackList<>(); 16637 16638 public OnPermissionChangeListeners(Looper looper) { 16639 super(looper); 16640 } 16641 16642 @Override 16643 public void handleMessage(Message msg) { 16644 switch (msg.what) { 16645 case MSG_ON_PERMISSIONS_CHANGED: { 16646 final int uid = msg.arg1; 16647 handleOnPermissionsChanged(uid); 16648 } break; 16649 } 16650 } 16651 16652 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16653 mPermissionListeners.register(listener); 16654 16655 } 16656 16657 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16658 mPermissionListeners.unregister(listener); 16659 } 16660 16661 public void onPermissionsChanged(int uid) { 16662 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16663 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16664 } 16665 } 16666 16667 private void handleOnPermissionsChanged(int uid) { 16668 final int count = mPermissionListeners.beginBroadcast(); 16669 try { 16670 for (int i = 0; i < count; i++) { 16671 IOnPermissionsChangeListener callback = mPermissionListeners 16672 .getBroadcastItem(i); 16673 try { 16674 callback.onPermissionsChanged(uid); 16675 } catch (RemoteException e) { 16676 Log.e(TAG, "Permission listener is dead", e); 16677 } 16678 } 16679 } finally { 16680 mPermissionListeners.finishBroadcast(); 16681 } 16682 } 16683 } 16684 16685 private class PackageManagerInternalImpl extends PackageManagerInternal { 16686 @Override 16687 public void setLocationPackagesProvider(PackagesProvider provider) { 16688 synchronized (mPackages) { 16689 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16690 } 16691 } 16692 16693 @Override 16694 public void setImePackagesProvider(PackagesProvider provider) { 16695 synchronized (mPackages) { 16696 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16697 } 16698 } 16699 16700 @Override 16701 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16702 synchronized (mPackages) { 16703 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16704 } 16705 } 16706 16707 @Override 16708 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16709 synchronized (mPackages) { 16710 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16711 } 16712 } 16713 16714 @Override 16715 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16716 synchronized (mPackages) { 16717 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16718 } 16719 } 16720 16721 @Override 16722 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16723 synchronized (mPackages) { 16724 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16725 } 16726 } 16727 16728 @Override 16729 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16730 synchronized (mPackages) { 16731 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16732 } 16733 } 16734 16735 @Override 16736 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16737 synchronized (mPackages) { 16738 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16739 packageName, userId); 16740 } 16741 } 16742 16743 @Override 16744 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16745 synchronized (mPackages) { 16746 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16747 packageName, userId); 16748 } 16749 } 16750 @Override 16751 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16752 synchronized (mPackages) { 16753 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16754 packageName, userId); 16755 } 16756 } 16757 } 16758 16759 @Override 16760 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16761 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16762 synchronized (mPackages) { 16763 final long identity = Binder.clearCallingIdentity(); 16764 try { 16765 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16766 packageNames, userId); 16767 } finally { 16768 Binder.restoreCallingIdentity(identity); 16769 } 16770 } 16771 } 16772 16773 private static void enforceSystemOrPhoneCaller(String tag) { 16774 int callingUid = Binder.getCallingUid(); 16775 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16776 throw new SecurityException( 16777 "Cannot call " + tag + " from UID " + callingUid); 16778 } 16779 } 16780} 16781