PackageManagerService.java revision 598b03d1008fb416a597ae4b2e037c4492bf696d
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.MATCH_ALL; 60import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 61import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 62import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 63import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 64import static android.content.pm.PackageManager.PERMISSION_DENIED; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 70import static android.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.Trace; 168import android.os.UserHandle; 169import android.os.UserManager; 170import android.os.storage.IMountService; 171import android.os.storage.MountServiceInternal; 172import android.os.storage.StorageEventListener; 173import android.os.storage.StorageManager; 174import android.os.storage.VolumeInfo; 175import android.os.storage.VolumeRecord; 176import android.security.KeyStore; 177import android.security.SystemKeyStore; 178import android.system.ErrnoException; 179import android.system.Os; 180import android.system.StructStat; 181import android.text.TextUtils; 182import android.text.format.DateUtils; 183import android.util.ArrayMap; 184import android.util.ArraySet; 185import android.util.AtomicFile; 186import android.util.DisplayMetrics; 187import android.util.EventLog; 188import android.util.ExceptionUtils; 189import android.util.Log; 190import android.util.LogPrinter; 191import android.util.MathUtils; 192import android.util.PrintStreamPrinter; 193import android.util.Slog; 194import android.util.SparseArray; 195import android.util.SparseBooleanArray; 196import android.util.SparseIntArray; 197import android.util.Xml; 198import android.view.Display; 199 200import dalvik.system.DexFile; 201import dalvik.system.VMRuntime; 202 203import libcore.io.IoUtils; 204import libcore.util.EmptyArray; 205 206import com.android.internal.R; 207import com.android.internal.annotations.GuardedBy; 208import com.android.internal.app.IMediaContainerService; 209import com.android.internal.app.ResolverActivity; 210import com.android.internal.content.NativeLibraryHelper; 211import com.android.internal.content.PackageHelper; 212import com.android.internal.os.IParcelFileDescriptorFactory; 213import com.android.internal.os.SomeArgs; 214import com.android.internal.os.Zygote; 215import com.android.internal.util.ArrayUtils; 216import com.android.internal.util.FastPrintWriter; 217import com.android.internal.util.FastXmlSerializer; 218import com.android.internal.util.IndentingPrintWriter; 219import com.android.internal.util.Preconditions; 220import com.android.server.EventLogTags; 221import com.android.server.FgThread; 222import com.android.server.IntentResolver; 223import com.android.server.LocalServices; 224import com.android.server.ServiceThread; 225import com.android.server.SystemConfig; 226import com.android.server.Watchdog; 227import com.android.server.pm.PermissionsState.PermissionState; 228import com.android.server.pm.Settings.DatabaseVersion; 229import com.android.server.pm.Settings.VersionInfo; 230import com.android.server.storage.DeviceStorageMonitorInternal; 231 232import org.xmlpull.v1.XmlPullParser; 233import org.xmlpull.v1.XmlPullParserException; 234import org.xmlpull.v1.XmlSerializer; 235 236import java.io.BufferedInputStream; 237import java.io.BufferedOutputStream; 238import java.io.BufferedReader; 239import java.io.ByteArrayInputStream; 240import java.io.ByteArrayOutputStream; 241import java.io.File; 242import java.io.FileDescriptor; 243import java.io.FileNotFoundException; 244import java.io.FileOutputStream; 245import java.io.FileReader; 246import java.io.FilenameFilter; 247import java.io.IOException; 248import java.io.InputStream; 249import java.io.PrintWriter; 250import java.nio.charset.StandardCharsets; 251import java.security.NoSuchAlgorithmException; 252import java.security.PublicKey; 253import java.security.cert.CertificateEncodingException; 254import java.security.cert.CertificateException; 255import java.text.SimpleDateFormat; 256import java.util.ArrayList; 257import java.util.Arrays; 258import java.util.Collection; 259import java.util.Collections; 260import java.util.Comparator; 261import java.util.Date; 262import java.util.Iterator; 263import java.util.List; 264import java.util.Map; 265import java.util.Objects; 266import java.util.Set; 267import java.util.concurrent.CountDownLatch; 268import java.util.concurrent.TimeUnit; 269import java.util.concurrent.atomic.AtomicBoolean; 270import java.util.concurrent.atomic.AtomicInteger; 271import java.util.concurrent.atomic.AtomicLong; 272 273/** 274 * Keep track of all those .apks everywhere. 275 * 276 * This is very central to the platform's security; please run the unit 277 * tests whenever making modifications here: 278 * 279runtest -c android.content.pm.PackageManagerTests frameworks-core 280 * 281 * {@hide} 282 */ 283public class PackageManagerService extends IPackageManager.Stub { 284 static final String TAG = "PackageManager"; 285 static final boolean DEBUG_SETTINGS = false; 286 static final boolean DEBUG_PREFERRED = false; 287 static final boolean DEBUG_UPGRADE = false; 288 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 289 private static final boolean DEBUG_BACKUP = false; 290 private static final boolean DEBUG_INSTALL = false; 291 private static final boolean DEBUG_REMOVE = false; 292 private static final boolean DEBUG_BROADCASTS = false; 293 private static final boolean DEBUG_SHOW_INFO = false; 294 private static final boolean DEBUG_PACKAGE_INFO = false; 295 private static final boolean DEBUG_INTENT_MATCHING = false; 296 private static final boolean DEBUG_PACKAGE_SCANNING = false; 297 private static final boolean DEBUG_VERIFY = false; 298 private static final boolean DEBUG_DEXOPT = false; 299 private static final boolean DEBUG_ABI_SELECTION = false; 300 301 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 302 303 private static final int RADIO_UID = Process.PHONE_UID; 304 private static final int LOG_UID = Process.LOG_UID; 305 private static final int NFC_UID = Process.NFC_UID; 306 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 307 private static final int SHELL_UID = Process.SHELL_UID; 308 309 // Cap the size of permission trees that 3rd party apps can define 310 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 311 312 // Suffix used during package installation when copying/moving 313 // package apks to install directory. 314 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 315 316 static final int SCAN_NO_DEX = 1<<1; 317 static final int SCAN_FORCE_DEX = 1<<2; 318 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 319 static final int SCAN_NEW_INSTALL = 1<<4; 320 static final int SCAN_NO_PATHS = 1<<5; 321 static final int SCAN_UPDATE_TIME = 1<<6; 322 static final int SCAN_DEFER_DEX = 1<<7; 323 static final int SCAN_BOOTING = 1<<8; 324 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 325 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 326 static final int SCAN_REPLACING = 1<<11; 327 static final int SCAN_REQUIRE_KNOWN = 1<<12; 328 static final int SCAN_MOVE = 1<<13; 329 static final int SCAN_INITIAL = 1<<14; 330 331 static final int REMOVE_CHATTY = 1<<16; 332 333 private static final int[] EMPTY_INT_ARRAY = new int[0]; 334 335 /** 336 * Timeout (in milliseconds) after which the watchdog should declare that 337 * our handler thread is wedged. The usual default for such things is one 338 * minute but we sometimes do very lengthy I/O operations on this thread, 339 * such as installing multi-gigabyte applications, so ours needs to be longer. 340 */ 341 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 342 343 /** 344 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 345 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 346 * settings entry if available, otherwise we use the hardcoded default. If it's been 347 * more than this long since the last fstrim, we force one during the boot sequence. 348 * 349 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 350 * one gets run at the next available charging+idle time. This final mandatory 351 * no-fstrim check kicks in only of the other scheduling criteria is never met. 352 */ 353 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 354 355 /** 356 * Whether verification is enabled by default. 357 */ 358 private static final boolean DEFAULT_VERIFY_ENABLE = true; 359 360 /** 361 * The default maximum time to wait for the verification agent to return in 362 * milliseconds. 363 */ 364 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 365 366 /** 367 * The default response for package verification timeout. 368 * 369 * This can be either PackageManager.VERIFICATION_ALLOW or 370 * PackageManager.VERIFICATION_REJECT. 371 */ 372 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 373 374 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 375 376 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 377 DEFAULT_CONTAINER_PACKAGE, 378 "com.android.defcontainer.DefaultContainerService"); 379 380 private static final String KILL_APP_REASON_GIDS_CHANGED = 381 "permission grant or revoke changed gids"; 382 383 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 384 "permissions revoked"; 385 386 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 387 388 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 389 390 /** Permission grant: not grant the permission. */ 391 private static final int GRANT_DENIED = 1; 392 393 /** Permission grant: grant the permission as an install permission. */ 394 private static final int GRANT_INSTALL = 2; 395 396 /** Permission grant: grant the permission as an install permission for a legacy app. */ 397 private static final int GRANT_INSTALL_LEGACY = 3; 398 399 /** Permission grant: grant the permission as a runtime one. */ 400 private static final int GRANT_RUNTIME = 4; 401 402 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 403 private static final int GRANT_UPGRADE = 5; 404 405 /** Canonical intent used to identify what counts as a "web browser" app */ 406 private static final Intent sBrowserIntent; 407 static { 408 sBrowserIntent = new Intent(); 409 sBrowserIntent.setAction(Intent.ACTION_VIEW); 410 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 411 sBrowserIntent.setData(Uri.parse("http:")); 412 } 413 414 final ServiceThread mHandlerThread; 415 416 final PackageHandler mHandler; 417 418 /** 419 * Messages for {@link #mHandler} that need to wait for system ready before 420 * being dispatched. 421 */ 422 private ArrayList<Message> mPostSystemReadyMessages; 423 424 final int mSdkVersion = Build.VERSION.SDK_INT; 425 426 final Context mContext; 427 final boolean mFactoryTest; 428 final boolean mOnlyCore; 429 final boolean mLazyDexOpt; 430 final long mDexOptLRUThresholdInMills; 431 final DisplayMetrics mMetrics; 432 final int mDefParseFlags; 433 final String[] mSeparateProcesses; 434 final boolean mIsUpgrade; 435 436 // This is where all application persistent data goes. 437 final File mAppDataDir; 438 439 // This is where all application persistent data goes for secondary users. 440 final File mUserAppDataDir; 441 442 /** The location for ASEC container files on internal storage. */ 443 final String mAsecInternalPath; 444 445 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 446 // LOCK HELD. Can be called with mInstallLock held. 447 @GuardedBy("mInstallLock") 448 final Installer mInstaller; 449 450 /** Directory where installed third-party apps stored */ 451 final File mAppInstallDir; 452 453 /** 454 * Directory to which applications installed internally have their 455 * 32 bit native libraries copied. 456 */ 457 private File mAppLib32InstallDir; 458 459 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 460 // apps. 461 final File mDrmAppPrivateInstallDir; 462 463 // ---------------------------------------------------------------- 464 465 // Lock for state used when installing and doing other long running 466 // operations. Methods that must be called with this lock held have 467 // the suffix "LI". 468 final Object mInstallLock = new Object(); 469 470 // ---------------------------------------------------------------- 471 472 // Keys are String (package name), values are Package. This also serves 473 // as the lock for the global state. Methods that must be called with 474 // this lock held have the prefix "LP". 475 @GuardedBy("mPackages") 476 final ArrayMap<String, PackageParser.Package> mPackages = 477 new ArrayMap<String, PackageParser.Package>(); 478 479 // Tracks available target package names -> overlay package paths. 480 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 481 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 482 483 /** 484 * Tracks new system packages [receiving in an OTA] that we expect to 485 * find updated user-installed versions. Keys are package name, values 486 * are package location. 487 */ 488 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 489 490 final Settings mSettings; 491 boolean mRestoredSettings; 492 493 // System configuration read by SystemConfig. 494 final int[] mGlobalGids; 495 final SparseArray<ArraySet<String>> mSystemPermissions; 496 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 497 498 // If mac_permissions.xml was found for seinfo labeling. 499 boolean mFoundPolicyFile; 500 501 // If a recursive restorecon of /data/data/<pkg> is needed. 502 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 503 504 public static final class SharedLibraryEntry { 505 public final String path; 506 public final String apk; 507 508 SharedLibraryEntry(String _path, String _apk) { 509 path = _path; 510 apk = _apk; 511 } 512 } 513 514 // Currently known shared libraries. 515 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 516 new ArrayMap<String, SharedLibraryEntry>(); 517 518 // All available activities, for your resolving pleasure. 519 final ActivityIntentResolver mActivities = 520 new ActivityIntentResolver(); 521 522 // All available receivers, for your resolving pleasure. 523 final ActivityIntentResolver mReceivers = 524 new ActivityIntentResolver(); 525 526 // All available services, for your resolving pleasure. 527 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 528 529 // All available providers, for your resolving pleasure. 530 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 531 532 // Mapping from provider base names (first directory in content URI codePath) 533 // to the provider information. 534 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 535 new ArrayMap<String, PackageParser.Provider>(); 536 537 // Mapping from instrumentation class names to info about them. 538 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 539 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 540 541 // Mapping from permission names to info about them. 542 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 543 new ArrayMap<String, PackageParser.PermissionGroup>(); 544 545 // Packages whose data we have transfered into another package, thus 546 // should no longer exist. 547 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 548 549 // Broadcast actions that are only available to the system. 550 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 551 552 /** List of packages waiting for verification. */ 553 final SparseArray<PackageVerificationState> mPendingVerification 554 = new SparseArray<PackageVerificationState>(); 555 556 /** Set of packages associated with each app op permission. */ 557 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 558 559 final PackageInstallerService mInstallerService; 560 561 private final PackageDexOptimizer mPackageDexOptimizer; 562 563 private AtomicInteger mNextMoveId = new AtomicInteger(); 564 private final MoveCallbacks mMoveCallbacks; 565 566 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 567 568 // Cache of users who need badging. 569 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 570 571 /** Token for keys in mPendingVerification. */ 572 private int mPendingVerificationToken = 0; 573 574 volatile boolean mSystemReady; 575 volatile boolean mSafeMode; 576 volatile boolean mHasSystemUidErrors; 577 578 ApplicationInfo mAndroidApplication; 579 final ActivityInfo mResolveActivity = new ActivityInfo(); 580 final ResolveInfo mResolveInfo = new ResolveInfo(); 581 ComponentName mResolveComponentName; 582 PackageParser.Package mPlatformPackage; 583 ComponentName mCustomResolverComponentName; 584 585 boolean mResolverReplaced = false; 586 587 private final ComponentName mIntentFilterVerifierComponent; 588 private int mIntentFilterVerificationToken = 0; 589 590 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 591 = new SparseArray<IntentFilterVerificationState>(); 592 593 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 594 new DefaultPermissionGrantPolicy(this); 595 596 private static class IFVerificationParams { 597 PackageParser.Package pkg; 598 boolean replacing; 599 int userId; 600 int verifierUid; 601 602 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 603 int _userId, int _verifierUid) { 604 pkg = _pkg; 605 replacing = _replacing; 606 userId = _userId; 607 replacing = _replacing; 608 verifierUid = _verifierUid; 609 } 610 } 611 612 private interface IntentFilterVerifier<T extends IntentFilter> { 613 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 614 T filter, String packageName); 615 void startVerifications(int userId); 616 void receiveVerificationResponse(int verificationId); 617 } 618 619 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 620 private Context mContext; 621 private ComponentName mIntentFilterVerifierComponent; 622 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 623 624 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 625 mContext = context; 626 mIntentFilterVerifierComponent = verifierComponent; 627 } 628 629 private String getDefaultScheme() { 630 return IntentFilter.SCHEME_HTTPS; 631 } 632 633 @Override 634 public void startVerifications(int userId) { 635 // Launch verifications requests 636 int count = mCurrentIntentFilterVerifications.size(); 637 for (int n=0; n<count; n++) { 638 int verificationId = mCurrentIntentFilterVerifications.get(n); 639 final IntentFilterVerificationState ivs = 640 mIntentFilterVerificationStates.get(verificationId); 641 642 String packageName = ivs.getPackageName(); 643 644 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 645 final int filterCount = filters.size(); 646 ArraySet<String> domainsSet = new ArraySet<>(); 647 for (int m=0; m<filterCount; m++) { 648 PackageParser.ActivityIntentInfo filter = filters.get(m); 649 domainsSet.addAll(filter.getHostsList()); 650 } 651 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 652 synchronized (mPackages) { 653 if (mSettings.createIntentFilterVerificationIfNeededLPw( 654 packageName, domainsList) != null) { 655 scheduleWriteSettingsLocked(); 656 } 657 } 658 sendVerificationRequest(userId, verificationId, ivs); 659 } 660 mCurrentIntentFilterVerifications.clear(); 661 } 662 663 private void sendVerificationRequest(int userId, int verificationId, 664 IntentFilterVerificationState ivs) { 665 666 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 669 verificationId); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 672 getDefaultScheme()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 675 ivs.getHostsString()); 676 verificationIntent.putExtra( 677 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 678 ivs.getPackageName()); 679 verificationIntent.setComponent(mIntentFilterVerifierComponent); 680 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 681 682 UserHandle user = new UserHandle(userId); 683 mContext.sendBroadcastAsUser(verificationIntent, user); 684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 685 "Sending IntentFilter verification broadcast"); 686 } 687 688 public void receiveVerificationResponse(int verificationId) { 689 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 690 691 final boolean verified = ivs.isVerified(); 692 693 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 694 final int count = filters.size(); 695 if (DEBUG_DOMAIN_VERIFICATION) { 696 Slog.i(TAG, "Received verification response " + verificationId 697 + " for " + count + " filters, verified=" + verified); 698 } 699 for (int n=0; n<count; n++) { 700 PackageParser.ActivityIntentInfo filter = filters.get(n); 701 filter.setVerified(verified); 702 703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 704 + " verified with result:" + verified + " and hosts:" 705 + ivs.getHostsString()); 706 } 707 708 mIntentFilterVerificationStates.remove(verificationId); 709 710 final String packageName = ivs.getPackageName(); 711 IntentFilterVerificationInfo ivi = null; 712 713 synchronized (mPackages) { 714 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 715 } 716 if (ivi == null) { 717 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 718 + verificationId + " packageName:" + packageName); 719 return; 720 } 721 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 722 "Updating IntentFilterVerificationInfo for package " + packageName 723 +" verificationId:" + verificationId); 724 725 synchronized (mPackages) { 726 if (verified) { 727 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 728 } else { 729 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 730 } 731 scheduleWriteSettingsLocked(); 732 733 final int userId = ivs.getUserId(); 734 if (userId != UserHandle.USER_ALL) { 735 final int userStatus = 736 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 737 738 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 739 boolean needUpdate = false; 740 741 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 742 // already been set by the User thru the Disambiguation dialog 743 switch (userStatus) { 744 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 745 if (verified) { 746 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 747 } else { 748 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 749 } 750 needUpdate = true; 751 break; 752 753 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 754 if (verified) { 755 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 756 needUpdate = true; 757 } 758 break; 759 760 default: 761 // Nothing to do 762 } 763 764 if (needUpdate) { 765 mSettings.updateIntentFilterVerificationStatusLPw( 766 packageName, updatedStatus, userId); 767 scheduleWritePackageRestrictionsLocked(userId); 768 } 769 } 770 } 771 } 772 773 @Override 774 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 775 ActivityIntentInfo filter, String packageName) { 776 if (!hasValidDomains(filter)) { 777 return false; 778 } 779 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 780 if (ivs == null) { 781 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 782 packageName); 783 } 784 if (DEBUG_DOMAIN_VERIFICATION) { 785 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 786 } 787 ivs.addFilter(filter); 788 return true; 789 } 790 791 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 792 int userId, int verificationId, String packageName) { 793 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 794 verifierUid, userId, packageName); 795 ivs.setPendingState(); 796 synchronized (mPackages) { 797 mIntentFilterVerificationStates.append(verificationId, ivs); 798 mCurrentIntentFilterVerifications.add(verificationId); 799 } 800 return ivs; 801 } 802 } 803 804 private static boolean hasValidDomains(ActivityIntentInfo filter) { 805 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 806 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 807 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 808 } 809 810 private IntentFilterVerifier mIntentFilterVerifier; 811 812 // Set of pending broadcasts for aggregating enable/disable of components. 813 static class PendingPackageBroadcasts { 814 // for each user id, a map of <package name -> components within that package> 815 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 816 817 public PendingPackageBroadcasts() { 818 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 819 } 820 821 public ArrayList<String> get(int userId, String packageName) { 822 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 823 return packages.get(packageName); 824 } 825 826 public void put(int userId, String packageName, ArrayList<String> components) { 827 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 828 packages.put(packageName, components); 829 } 830 831 public void remove(int userId, String packageName) { 832 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 833 if (packages != null) { 834 packages.remove(packageName); 835 } 836 } 837 838 public void remove(int userId) { 839 mUidMap.remove(userId); 840 } 841 842 public int userIdCount() { 843 return mUidMap.size(); 844 } 845 846 public int userIdAt(int n) { 847 return mUidMap.keyAt(n); 848 } 849 850 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 851 return mUidMap.get(userId); 852 } 853 854 public int size() { 855 // total number of pending broadcast entries across all userIds 856 int num = 0; 857 for (int i = 0; i< mUidMap.size(); i++) { 858 num += mUidMap.valueAt(i).size(); 859 } 860 return num; 861 } 862 863 public void clear() { 864 mUidMap.clear(); 865 } 866 867 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 868 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 869 if (map == null) { 870 map = new ArrayMap<String, ArrayList<String>>(); 871 mUidMap.put(userId, map); 872 } 873 return map; 874 } 875 } 876 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 877 878 // Service Connection to remote media container service to copy 879 // package uri's from external media onto secure containers 880 // or internal storage. 881 private IMediaContainerService mContainerService = null; 882 883 static final int SEND_PENDING_BROADCAST = 1; 884 static final int MCS_BOUND = 3; 885 static final int END_COPY = 4; 886 static final int INIT_COPY = 5; 887 static final int MCS_UNBIND = 6; 888 static final int START_CLEANING_PACKAGE = 7; 889 static final int FIND_INSTALL_LOC = 8; 890 static final int POST_INSTALL = 9; 891 static final int MCS_RECONNECT = 10; 892 static final int MCS_GIVE_UP = 11; 893 static final int UPDATED_MEDIA_STATUS = 12; 894 static final int WRITE_SETTINGS = 13; 895 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 896 static final int PACKAGE_VERIFIED = 15; 897 static final int CHECK_PENDING_VERIFICATION = 16; 898 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 899 static final int INTENT_FILTER_VERIFIED = 18; 900 901 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 902 903 // Delay time in millisecs 904 static final int BROADCAST_DELAY = 10 * 1000; 905 906 static UserManagerService sUserManager; 907 908 // Stores a list of users whose package restrictions file needs to be updated 909 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 910 911 final private DefaultContainerConnection mDefContainerConn = 912 new DefaultContainerConnection(); 913 class DefaultContainerConnection implements ServiceConnection { 914 public void onServiceConnected(ComponentName name, IBinder service) { 915 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 916 IMediaContainerService imcs = 917 IMediaContainerService.Stub.asInterface(service); 918 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 919 } 920 921 public void onServiceDisconnected(ComponentName name) { 922 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 923 } 924 } 925 926 // Recordkeeping of restore-after-install operations that are currently in flight 927 // between the Package Manager and the Backup Manager 928 class PostInstallData { 929 public InstallArgs args; 930 public PackageInstalledInfo res; 931 932 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 933 args = _a; 934 res = _r; 935 } 936 } 937 938 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 939 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 940 941 // XML tags for backup/restore of various bits of state 942 private static final String TAG_PREFERRED_BACKUP = "pa"; 943 private static final String TAG_DEFAULT_APPS = "da"; 944 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 945 946 final String mRequiredVerifierPackage; 947 final String mRequiredInstallerPackage; 948 949 private final PackageUsage mPackageUsage = new PackageUsage(); 950 951 private class PackageUsage { 952 private static final int WRITE_INTERVAL 953 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 954 955 private final Object mFileLock = new Object(); 956 private final AtomicLong mLastWritten = new AtomicLong(0); 957 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 958 959 private boolean mIsHistoricalPackageUsageAvailable = true; 960 961 boolean isHistoricalPackageUsageAvailable() { 962 return mIsHistoricalPackageUsageAvailable; 963 } 964 965 void write(boolean force) { 966 if (force) { 967 writeInternal(); 968 return; 969 } 970 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 971 && !DEBUG_DEXOPT) { 972 return; 973 } 974 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 975 new Thread("PackageUsage_DiskWriter") { 976 @Override 977 public void run() { 978 try { 979 writeInternal(); 980 } finally { 981 mBackgroundWriteRunning.set(false); 982 } 983 } 984 }.start(); 985 } 986 } 987 988 private void writeInternal() { 989 synchronized (mPackages) { 990 synchronized (mFileLock) { 991 AtomicFile file = getFile(); 992 FileOutputStream f = null; 993 try { 994 f = file.startWrite(); 995 BufferedOutputStream out = new BufferedOutputStream(f); 996 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 997 StringBuilder sb = new StringBuilder(); 998 for (PackageParser.Package pkg : mPackages.values()) { 999 if (pkg.mLastPackageUsageTimeInMills == 0) { 1000 continue; 1001 } 1002 sb.setLength(0); 1003 sb.append(pkg.packageName); 1004 sb.append(' '); 1005 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1006 sb.append('\n'); 1007 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1008 } 1009 out.flush(); 1010 file.finishWrite(f); 1011 } catch (IOException e) { 1012 if (f != null) { 1013 file.failWrite(f); 1014 } 1015 Log.e(TAG, "Failed to write package usage times", e); 1016 } 1017 } 1018 } 1019 mLastWritten.set(SystemClock.elapsedRealtime()); 1020 } 1021 1022 void readLP() { 1023 synchronized (mFileLock) { 1024 AtomicFile file = getFile(); 1025 BufferedInputStream in = null; 1026 try { 1027 in = new BufferedInputStream(file.openRead()); 1028 StringBuffer sb = new StringBuffer(); 1029 while (true) { 1030 String packageName = readToken(in, sb, ' '); 1031 if (packageName == null) { 1032 break; 1033 } 1034 String timeInMillisString = readToken(in, sb, '\n'); 1035 if (timeInMillisString == null) { 1036 throw new IOException("Failed to find last usage time for package " 1037 + packageName); 1038 } 1039 PackageParser.Package pkg = mPackages.get(packageName); 1040 if (pkg == null) { 1041 continue; 1042 } 1043 long timeInMillis; 1044 try { 1045 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1046 } catch (NumberFormatException e) { 1047 throw new IOException("Failed to parse " + timeInMillisString 1048 + " as a long.", e); 1049 } 1050 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1051 } 1052 } catch (FileNotFoundException expected) { 1053 mIsHistoricalPackageUsageAvailable = false; 1054 } catch (IOException e) { 1055 Log.w(TAG, "Failed to read package usage times", e); 1056 } finally { 1057 IoUtils.closeQuietly(in); 1058 } 1059 } 1060 mLastWritten.set(SystemClock.elapsedRealtime()); 1061 } 1062 1063 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1064 throws IOException { 1065 sb.setLength(0); 1066 while (true) { 1067 int ch = in.read(); 1068 if (ch == -1) { 1069 if (sb.length() == 0) { 1070 return null; 1071 } 1072 throw new IOException("Unexpected EOF"); 1073 } 1074 if (ch == endOfToken) { 1075 return sb.toString(); 1076 } 1077 sb.append((char)ch); 1078 } 1079 } 1080 1081 private AtomicFile getFile() { 1082 File dataDir = Environment.getDataDirectory(); 1083 File systemDir = new File(dataDir, "system"); 1084 File fname = new File(systemDir, "package-usage.list"); 1085 return new AtomicFile(fname); 1086 } 1087 } 1088 1089 class PackageHandler extends Handler { 1090 private boolean mBound = false; 1091 final ArrayList<HandlerParams> mPendingInstalls = 1092 new ArrayList<HandlerParams>(); 1093 1094 private boolean connectToService() { 1095 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1096 " DefaultContainerService"); 1097 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1100 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1102 mBound = true; 1103 return true; 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 return false; 1107 } 1108 1109 private void disconnectService() { 1110 mContainerService = null; 1111 mBound = false; 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 mContext.unbindService(mDefContainerConn); 1114 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1115 } 1116 1117 PackageHandler(Looper looper) { 1118 super(looper); 1119 } 1120 1121 public void handleMessage(Message msg) { 1122 try { 1123 doHandleMessage(msg); 1124 } finally { 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 } 1128 1129 void doHandleMessage(Message msg) { 1130 switch (msg.what) { 1131 case INIT_COPY: { 1132 HandlerParams params = (HandlerParams) msg.obj; 1133 int idx = mPendingInstalls.size(); 1134 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1135 // If a bind was already initiated we dont really 1136 // need to do anything. The pending install 1137 // will be processed later on. 1138 if (!mBound) { 1139 try { 1140 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1141 System.identityHashCode(params)); 1142 // If this is the only one pending we might 1143 // have to bind to the service again. 1144 if (!connectToService()) { 1145 Slog.e(TAG, "Failed to bind to media container service"); 1146 params.serviceError(); 1147 return; 1148 } else { 1149 // Once we bind to the service, the first 1150 // pending request will be processed. 1151 mPendingInstalls.add(idx, params); 1152 } 1153 } finally { 1154 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindMCS", 1155 System.identityHashCode(params)); 1156 } 1157 } else { 1158 mPendingInstalls.add(idx, params); 1159 // Already bound to the service. Just make 1160 // sure we trigger off processing the first request. 1161 if (idx == 0) { 1162 mHandler.sendEmptyMessage(MCS_BOUND); 1163 } 1164 } 1165 break; 1166 } 1167 case MCS_BOUND: { 1168 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1169 if (msg.obj != null) { 1170 mContainerService = (IMediaContainerService) msg.obj; 1171 } 1172 if (mContainerService == null) { 1173 if (!mBound) { 1174 // Something seriously wrong since we are not bound and we are not 1175 // waiting for connection. Bail out. 1176 Slog.e(TAG, "Cannot bind to media container service"); 1177 for (HandlerParams params : mPendingInstalls) { 1178 // Indicate service bind error 1179 params.serviceError(); 1180 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1181 System.identityHashCode(params)); 1182 } 1183 mPendingInstalls.clear(); 1184 } else { 1185 Slog.w(TAG, "Waiting to connect to media container service"); 1186 } 1187 } else if (mPendingInstalls.size() > 0) { 1188 HandlerParams params = mPendingInstalls.get(0); 1189 if (params != null) { 1190 if (params.startCopy()) { 1191 // We are done... look for more work or to 1192 // go idle. 1193 if (DEBUG_SD_INSTALL) Log.i(TAG, 1194 "Checking for more work or unbind..."); 1195 // Delete pending install 1196 if (mPendingInstalls.size() > 0) { 1197 mPendingInstalls.remove(0); 1198 } 1199 if (mPendingInstalls.size() == 0) { 1200 if (mBound) { 1201 if (DEBUG_SD_INSTALL) Log.i(TAG, 1202 "Posting delayed MCS_UNBIND"); 1203 removeMessages(MCS_UNBIND); 1204 Message ubmsg = obtainMessage(MCS_UNBIND); 1205 // Unbind after a little delay, to avoid 1206 // continual thrashing. 1207 sendMessageDelayed(ubmsg, 10000); 1208 } 1209 } else { 1210 // There are more pending requests in queue. 1211 // Just post MCS_BOUND message to trigger processing 1212 // of next pending install. 1213 if (DEBUG_SD_INSTALL) Log.i(TAG, 1214 "Posting MCS_BOUND for next work"); 1215 mHandler.sendEmptyMessage(MCS_BOUND); 1216 } 1217 } 1218 } 1219 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1220 System.identityHashCode(params)); 1221 } else { 1222 // Should never happen ideally. 1223 Slog.w(TAG, "Empty queue"); 1224 } 1225 break; 1226 } 1227 case MCS_RECONNECT: { 1228 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1229 if (mPendingInstalls.size() > 0) { 1230 if (mBound) { 1231 disconnectService(); 1232 } 1233 if (!connectToService()) { 1234 Slog.e(TAG, "Failed to bind to media container service"); 1235 for (HandlerParams params : mPendingInstalls) { 1236 // Indicate service bind error 1237 params.serviceError(); 1238 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1239 System.identityHashCode(params)); 1240 } 1241 mPendingInstalls.clear(); 1242 } 1243 } 1244 break; 1245 } 1246 case MCS_UNBIND: { 1247 // If there is no actual work left, then time to unbind. 1248 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1249 1250 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1251 if (mBound) { 1252 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1253 1254 disconnectService(); 1255 } 1256 } else if (mPendingInstalls.size() > 0) { 1257 // There are more pending requests in queue. 1258 // Just post MCS_BOUND message to trigger processing 1259 // of next pending install. 1260 mHandler.sendEmptyMessage(MCS_BOUND); 1261 } 1262 1263 break; 1264 } 1265 case MCS_GIVE_UP: { 1266 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1267 HandlerParams params = mPendingInstalls.remove(0); 1268 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1269 System.identityHashCode(params)); 1270 break; 1271 } 1272 case SEND_PENDING_BROADCAST: { 1273 String packages[]; 1274 ArrayList<String> components[]; 1275 int size = 0; 1276 int uids[]; 1277 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1278 synchronized (mPackages) { 1279 if (mPendingBroadcasts == null) { 1280 return; 1281 } 1282 size = mPendingBroadcasts.size(); 1283 if (size <= 0) { 1284 // Nothing to be done. Just return 1285 return; 1286 } 1287 packages = new String[size]; 1288 components = new ArrayList[size]; 1289 uids = new int[size]; 1290 int i = 0; // filling out the above arrays 1291 1292 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1293 int packageUserId = mPendingBroadcasts.userIdAt(n); 1294 Iterator<Map.Entry<String, ArrayList<String>>> it 1295 = mPendingBroadcasts.packagesForUserId(packageUserId) 1296 .entrySet().iterator(); 1297 while (it.hasNext() && i < size) { 1298 Map.Entry<String, ArrayList<String>> ent = it.next(); 1299 packages[i] = ent.getKey(); 1300 components[i] = ent.getValue(); 1301 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1302 uids[i] = (ps != null) 1303 ? UserHandle.getUid(packageUserId, ps.appId) 1304 : -1; 1305 i++; 1306 } 1307 } 1308 size = i; 1309 mPendingBroadcasts.clear(); 1310 } 1311 // Send broadcasts 1312 for (int i = 0; i < size; i++) { 1313 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1314 } 1315 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1316 break; 1317 } 1318 case START_CLEANING_PACKAGE: { 1319 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1320 final String packageName = (String)msg.obj; 1321 final int userId = msg.arg1; 1322 final boolean andCode = msg.arg2 != 0; 1323 synchronized (mPackages) { 1324 if (userId == UserHandle.USER_ALL) { 1325 int[] users = sUserManager.getUserIds(); 1326 for (int user : users) { 1327 mSettings.addPackageToCleanLPw( 1328 new PackageCleanItem(user, packageName, andCode)); 1329 } 1330 } else { 1331 mSettings.addPackageToCleanLPw( 1332 new PackageCleanItem(userId, packageName, andCode)); 1333 } 1334 } 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 startCleaningPackages(); 1337 } break; 1338 case POST_INSTALL: { 1339 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1340 PostInstallData data = mRunningInstalls.get(msg.arg1); 1341 mRunningInstalls.delete(msg.arg1); 1342 boolean deleteOld = false; 1343 1344 if (data != null) { 1345 InstallArgs args = data.args; 1346 PackageInstalledInfo res = data.res; 1347 1348 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1349 final String packageName = res.pkg.applicationInfo.packageName; 1350 res.removedInfo.sendBroadcast(false, true, false); 1351 Bundle extras = new Bundle(1); 1352 extras.putInt(Intent.EXTRA_UID, res.uid); 1353 1354 // Now that we successfully installed the package, grant runtime 1355 // permissions if requested before broadcasting the install. 1356 if ((args.installFlags 1357 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1358 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1359 args.installGrantPermissions); 1360 } 1361 1362 // Determine the set of users who are adding this 1363 // package for the first time vs. those who are seeing 1364 // an update. 1365 int[] firstUsers; 1366 int[] updateUsers = new int[0]; 1367 if (res.origUsers == null || res.origUsers.length == 0) { 1368 firstUsers = res.newUsers; 1369 } else { 1370 firstUsers = new int[0]; 1371 for (int i=0; i<res.newUsers.length; i++) { 1372 int user = res.newUsers[i]; 1373 boolean isNew = true; 1374 for (int j=0; j<res.origUsers.length; j++) { 1375 if (res.origUsers[j] == user) { 1376 isNew = false; 1377 break; 1378 } 1379 } 1380 if (isNew) { 1381 int[] newFirst = new int[firstUsers.length+1]; 1382 System.arraycopy(firstUsers, 0, newFirst, 0, 1383 firstUsers.length); 1384 newFirst[firstUsers.length] = user; 1385 firstUsers = newFirst; 1386 } else { 1387 int[] newUpdate = new int[updateUsers.length+1]; 1388 System.arraycopy(updateUsers, 0, newUpdate, 0, 1389 updateUsers.length); 1390 newUpdate[updateUsers.length] = user; 1391 updateUsers = newUpdate; 1392 } 1393 } 1394 } 1395 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1396 packageName, extras, null, null, firstUsers); 1397 final boolean update = res.removedInfo.removedPackage != null; 1398 if (update) { 1399 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1400 } 1401 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1402 packageName, extras, null, null, updateUsers); 1403 if (update) { 1404 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1405 packageName, extras, null, null, updateUsers); 1406 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1407 null, null, packageName, null, updateUsers); 1408 1409 // treat asec-hosted packages like removable media on upgrade 1410 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1411 if (DEBUG_INSTALL) { 1412 Slog.i(TAG, "upgrading pkg " + res.pkg 1413 + " is ASEC-hosted -> AVAILABLE"); 1414 } 1415 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1416 ArrayList<String> pkgList = new ArrayList<String>(1); 1417 pkgList.add(packageName); 1418 sendResourcesChangedBroadcast(true, true, 1419 pkgList,uidArray, null); 1420 } 1421 } 1422 if (res.removedInfo.args != null) { 1423 // Remove the replaced package's older resources safely now 1424 deleteOld = true; 1425 } 1426 1427 // If this app is a browser and it's newly-installed for some 1428 // users, clear any default-browser state in those users 1429 if (firstUsers.length > 0) { 1430 // the app's nature doesn't depend on the user, so we can just 1431 // check its browser nature in any user and generalize. 1432 if (packageIsBrowser(packageName, firstUsers[0])) { 1433 synchronized (mPackages) { 1434 for (int userId : firstUsers) { 1435 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1436 } 1437 } 1438 } 1439 } 1440 // Log current value of "unknown sources" setting 1441 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1442 getUnknownSourcesSettings()); 1443 } 1444 // Force a gc to clear up things 1445 Runtime.getRuntime().gc(); 1446 // We delete after a gc for applications on sdcard. 1447 if (deleteOld) { 1448 synchronized (mInstallLock) { 1449 res.removedInfo.args.doPostDeleteLI(true); 1450 } 1451 } 1452 if (args.observer != null) { 1453 try { 1454 Bundle extras = extrasForInstallResult(res); 1455 args.observer.onPackageInstalled(res.name, res.returnCode, 1456 res.returnMsg, extras); 1457 } catch (RemoteException e) { 1458 Slog.i(TAG, "Observer no longer exists."); 1459 } 1460 } 1461 } else { 1462 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1463 } 1464 1465 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1466 } break; 1467 case UPDATED_MEDIA_STATUS: { 1468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1469 boolean reportStatus = msg.arg1 == 1; 1470 boolean doGc = msg.arg2 == 1; 1471 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1472 if (doGc) { 1473 // Force a gc to clear up stale containers. 1474 Runtime.getRuntime().gc(); 1475 } 1476 if (msg.obj != null) { 1477 @SuppressWarnings("unchecked") 1478 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1479 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1480 // Unload containers 1481 unloadAllContainers(args); 1482 } 1483 if (reportStatus) { 1484 try { 1485 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1486 PackageHelper.getMountService().finishMediaUpdate(); 1487 } catch (RemoteException e) { 1488 Log.e(TAG, "MountService not running?"); 1489 } 1490 } 1491 } break; 1492 case WRITE_SETTINGS: { 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1494 synchronized (mPackages) { 1495 removeMessages(WRITE_SETTINGS); 1496 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1497 mSettings.writeLPr(); 1498 mDirtyUsers.clear(); 1499 } 1500 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1501 } break; 1502 case WRITE_PACKAGE_RESTRICTIONS: { 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1504 synchronized (mPackages) { 1505 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1506 for (int userId : mDirtyUsers) { 1507 mSettings.writePackageRestrictionsLPr(userId); 1508 } 1509 mDirtyUsers.clear(); 1510 } 1511 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1512 } break; 1513 case CHECK_PENDING_VERIFICATION: { 1514 final int verificationId = msg.arg1; 1515 final PackageVerificationState state = mPendingVerification.get(verificationId); 1516 1517 if ((state != null) && !state.timeoutExtended()) { 1518 final InstallArgs args = state.getInstallArgs(); 1519 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1520 1521 Slog.i(TAG, "Verification timed out for " + originUri); 1522 mPendingVerification.remove(verificationId); 1523 1524 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1525 1526 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1527 Slog.i(TAG, "Continuing with installation of " + originUri); 1528 state.setVerifierResponse(Binder.getCallingUid(), 1529 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1530 broadcastPackageVerified(verificationId, originUri, 1531 PackageManager.VERIFICATION_ALLOW, 1532 state.getInstallArgs().getUser()); 1533 try { 1534 ret = args.copyApk(mContainerService, true); 1535 } catch (RemoteException e) { 1536 Slog.e(TAG, "Could not contact the ContainerService"); 1537 } 1538 } else { 1539 broadcastPackageVerified(verificationId, originUri, 1540 PackageManager.VERIFICATION_REJECT, 1541 state.getInstallArgs().getUser()); 1542 } 1543 1544 processPendingInstall(args, ret); 1545 mHandler.sendEmptyMessage(MCS_UNBIND); 1546 } 1547 Trace.asyncTraceEnd( 1548 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 1549 break; 1550 } 1551 case PACKAGE_VERIFIED: { 1552 final int verificationId = msg.arg1; 1553 1554 final PackageVerificationState state = mPendingVerification.get(verificationId); 1555 if (state == null) { 1556 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1557 break; 1558 } 1559 1560 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1561 1562 state.setVerifierResponse(response.callerUid, response.code); 1563 1564 if (state.isVerificationComplete()) { 1565 mPendingVerification.remove(verificationId); 1566 1567 final InstallArgs args = state.getInstallArgs(); 1568 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1569 1570 int ret; 1571 if (state.isInstallAllowed()) { 1572 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1573 broadcastPackageVerified(verificationId, originUri, 1574 response.code, state.getInstallArgs().getUser()); 1575 try { 1576 ret = args.copyApk(mContainerService, true); 1577 } catch (RemoteException e) { 1578 Slog.e(TAG, "Could not contact the ContainerService"); 1579 } 1580 } else { 1581 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1582 } 1583 1584 processPendingInstall(args, ret); 1585 1586 mHandler.sendEmptyMessage(MCS_UNBIND); 1587 } 1588 1589 break; 1590 } 1591 case START_INTENT_FILTER_VERIFICATIONS: { 1592 IFVerificationParams params = (IFVerificationParams) msg.obj; 1593 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1594 params.replacing, params.pkg); 1595 break; 1596 } 1597 case INTENT_FILTER_VERIFIED: { 1598 final int verificationId = msg.arg1; 1599 1600 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1601 verificationId); 1602 if (state == null) { 1603 Slog.w(TAG, "Invalid IntentFilter verification token " 1604 + verificationId + " received"); 1605 break; 1606 } 1607 1608 final int userId = state.getUserId(); 1609 1610 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1611 "Processing IntentFilter verification with token:" 1612 + verificationId + " and userId:" + userId); 1613 1614 final IntentFilterVerificationResponse response = 1615 (IntentFilterVerificationResponse) msg.obj; 1616 1617 state.setVerifierResponse(response.callerUid, response.code); 1618 1619 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1620 "IntentFilter verification with token:" + verificationId 1621 + " and userId:" + userId 1622 + " is settings verifier response with response code:" 1623 + response.code); 1624 1625 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1626 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1627 + response.getFailedDomainsString()); 1628 } 1629 1630 if (state.isVerificationComplete()) { 1631 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1632 } else { 1633 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1634 "IntentFilter verification with token:" + verificationId 1635 + " was not said to be complete"); 1636 } 1637 1638 break; 1639 } 1640 } 1641 } 1642 } 1643 1644 private StorageEventListener mStorageListener = new StorageEventListener() { 1645 @Override 1646 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1647 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1648 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1649 final String volumeUuid = vol.getFsUuid(); 1650 1651 // Clean up any users or apps that were removed or recreated 1652 // while this volume was missing 1653 reconcileUsers(volumeUuid); 1654 reconcileApps(volumeUuid); 1655 1656 // Clean up any install sessions that expired or were 1657 // cancelled while this volume was missing 1658 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1659 1660 loadPrivatePackages(vol); 1661 1662 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1663 unloadPrivatePackages(vol); 1664 } 1665 } 1666 1667 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1668 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1669 updateExternalMediaStatus(true, false); 1670 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1671 updateExternalMediaStatus(false, false); 1672 } 1673 } 1674 } 1675 1676 @Override 1677 public void onVolumeForgotten(String fsUuid) { 1678 if (TextUtils.isEmpty(fsUuid)) { 1679 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1680 return; 1681 } 1682 1683 // Remove any apps installed on the forgotten volume 1684 synchronized (mPackages) { 1685 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1686 for (PackageSetting ps : packages) { 1687 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1688 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1689 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1690 } 1691 1692 mSettings.onVolumeForgotten(fsUuid); 1693 mSettings.writeLPr(); 1694 } 1695 } 1696 }; 1697 1698 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1699 String[] grantedPermissions) { 1700 if (userId >= UserHandle.USER_OWNER) { 1701 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1702 } else if (userId == UserHandle.USER_ALL) { 1703 final int[] userIds; 1704 synchronized (mPackages) { 1705 userIds = UserManagerService.getInstance().getUserIds(); 1706 } 1707 for (int someUserId : userIds) { 1708 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1709 } 1710 } 1711 1712 // We could have touched GID membership, so flush out packages.list 1713 synchronized (mPackages) { 1714 mSettings.writePackageListLPr(); 1715 } 1716 } 1717 1718 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1719 String[] grantedPermissions) { 1720 SettingBase sb = (SettingBase) pkg.mExtras; 1721 if (sb == null) { 1722 return; 1723 } 1724 1725 PermissionsState permissionsState = sb.getPermissionsState(); 1726 1727 for (String permission : pkg.requestedPermissions) { 1728 BasePermission bp = mSettings.mPermissions.get(permission); 1729 if (bp != null && bp.isRuntime() && (grantedPermissions == null 1730 || ArrayUtils.contains(grantedPermissions, permission))) { 1731 permissionsState.grantRuntimePermission(bp, userId); 1732 } 1733 } 1734 } 1735 1736 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1737 Bundle extras = null; 1738 switch (res.returnCode) { 1739 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1740 extras = new Bundle(); 1741 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1742 res.origPermission); 1743 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1744 res.origPackage); 1745 break; 1746 } 1747 case PackageManager.INSTALL_SUCCEEDED: { 1748 extras = new Bundle(); 1749 extras.putBoolean(Intent.EXTRA_REPLACING, 1750 res.removedInfo != null && res.removedInfo.removedPackage != null); 1751 break; 1752 } 1753 } 1754 return extras; 1755 } 1756 1757 void scheduleWriteSettingsLocked() { 1758 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1759 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1760 } 1761 } 1762 1763 void scheduleWritePackageRestrictionsLocked(int userId) { 1764 if (!sUserManager.exists(userId)) return; 1765 mDirtyUsers.add(userId); 1766 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1767 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1768 } 1769 } 1770 1771 public static PackageManagerService main(Context context, Installer installer, 1772 boolean factoryTest, boolean onlyCore) { 1773 PackageManagerService m = new PackageManagerService(context, installer, 1774 factoryTest, onlyCore); 1775 ServiceManager.addService("package", m); 1776 return m; 1777 } 1778 1779 static String[] splitString(String str, char sep) { 1780 int count = 1; 1781 int i = 0; 1782 while ((i=str.indexOf(sep, i)) >= 0) { 1783 count++; 1784 i++; 1785 } 1786 1787 String[] res = new String[count]; 1788 i=0; 1789 count = 0; 1790 int lastI=0; 1791 while ((i=str.indexOf(sep, i)) >= 0) { 1792 res[count] = str.substring(lastI, i); 1793 count++; 1794 i++; 1795 lastI = i; 1796 } 1797 res[count] = str.substring(lastI, str.length()); 1798 return res; 1799 } 1800 1801 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1802 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1803 Context.DISPLAY_SERVICE); 1804 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1805 } 1806 1807 public PackageManagerService(Context context, Installer installer, 1808 boolean factoryTest, boolean onlyCore) { 1809 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1810 SystemClock.uptimeMillis()); 1811 1812 if (mSdkVersion <= 0) { 1813 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1814 } 1815 1816 mContext = context; 1817 mFactoryTest = factoryTest; 1818 mOnlyCore = onlyCore; 1819 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1820 mMetrics = new DisplayMetrics(); 1821 mSettings = new Settings(mPackages); 1822 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1823 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1824 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1825 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1826 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1827 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1828 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1829 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1830 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1831 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1832 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1833 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1834 1835 // TODO: add a property to control this? 1836 long dexOptLRUThresholdInMinutes; 1837 if (mLazyDexOpt) { 1838 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1839 } else { 1840 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1841 } 1842 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1843 1844 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1845 if (separateProcesses != null && separateProcesses.length() > 0) { 1846 if ("*".equals(separateProcesses)) { 1847 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1848 mSeparateProcesses = null; 1849 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1850 } else { 1851 mDefParseFlags = 0; 1852 mSeparateProcesses = separateProcesses.split(","); 1853 Slog.w(TAG, "Running with debug.separate_processes: " 1854 + separateProcesses); 1855 } 1856 } else { 1857 mDefParseFlags = 0; 1858 mSeparateProcesses = null; 1859 } 1860 1861 mInstaller = installer; 1862 mPackageDexOptimizer = new PackageDexOptimizer(this); 1863 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1864 1865 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1866 FgThread.get().getLooper()); 1867 1868 getDefaultDisplayMetrics(context, mMetrics); 1869 1870 SystemConfig systemConfig = SystemConfig.getInstance(); 1871 mGlobalGids = systemConfig.getGlobalGids(); 1872 mSystemPermissions = systemConfig.getSystemPermissions(); 1873 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1874 1875 synchronized (mInstallLock) { 1876 // writer 1877 synchronized (mPackages) { 1878 mHandlerThread = new ServiceThread(TAG, 1879 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1880 mHandlerThread.start(); 1881 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1882 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1883 1884 File dataDir = Environment.getDataDirectory(); 1885 mAppDataDir = new File(dataDir, "data"); 1886 mAppInstallDir = new File(dataDir, "app"); 1887 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1888 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1889 mUserAppDataDir = new File(dataDir, "user"); 1890 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1891 1892 sUserManager = new UserManagerService(context, this, 1893 mInstallLock, mPackages); 1894 1895 // Propagate permission configuration in to package manager. 1896 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1897 = systemConfig.getPermissions(); 1898 for (int i=0; i<permConfig.size(); i++) { 1899 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1900 BasePermission bp = mSettings.mPermissions.get(perm.name); 1901 if (bp == null) { 1902 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1903 mSettings.mPermissions.put(perm.name, bp); 1904 } 1905 if (perm.gids != null) { 1906 bp.setGids(perm.gids, perm.perUser); 1907 } 1908 } 1909 1910 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1911 for (int i=0; i<libConfig.size(); i++) { 1912 mSharedLibraries.put(libConfig.keyAt(i), 1913 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1914 } 1915 1916 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1917 1918 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1919 mSdkVersion, mOnlyCore); 1920 1921 String customResolverActivity = Resources.getSystem().getString( 1922 R.string.config_customResolverActivity); 1923 if (TextUtils.isEmpty(customResolverActivity)) { 1924 customResolverActivity = null; 1925 } else { 1926 mCustomResolverComponentName = ComponentName.unflattenFromString( 1927 customResolverActivity); 1928 } 1929 1930 long startTime = SystemClock.uptimeMillis(); 1931 1932 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1933 startTime); 1934 1935 // Set flag to monitor and not change apk file paths when 1936 // scanning install directories. 1937 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1938 1939 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1940 1941 /** 1942 * Add everything in the in the boot class path to the 1943 * list of process files because dexopt will have been run 1944 * if necessary during zygote startup. 1945 */ 1946 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1947 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1948 1949 if (bootClassPath != null) { 1950 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1951 for (String element : bootClassPathElements) { 1952 alreadyDexOpted.add(element); 1953 } 1954 } else { 1955 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1956 } 1957 1958 if (systemServerClassPath != null) { 1959 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1960 for (String element : systemServerClassPathElements) { 1961 alreadyDexOpted.add(element); 1962 } 1963 } else { 1964 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1965 } 1966 1967 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1968 final String[] dexCodeInstructionSets = 1969 getDexCodeInstructionSets( 1970 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1971 1972 /** 1973 * Ensure all external libraries have had dexopt run on them. 1974 */ 1975 if (mSharedLibraries.size() > 0) { 1976 // NOTE: For now, we're compiling these system "shared libraries" 1977 // (and framework jars) into all available architectures. It's possible 1978 // to compile them only when we come across an app that uses them (there's 1979 // already logic for that in scanPackageLI) but that adds some complexity. 1980 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1981 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1982 final String lib = libEntry.path; 1983 if (lib == null) { 1984 continue; 1985 } 1986 1987 try { 1988 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1989 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1990 alreadyDexOpted.add(lib); 1991 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1992 } 1993 } catch (FileNotFoundException e) { 1994 Slog.w(TAG, "Library not found: " + lib); 1995 } catch (IOException e) { 1996 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1997 + e.getMessage()); 1998 } 1999 } 2000 } 2001 } 2002 2003 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2004 2005 // Gross hack for now: we know this file doesn't contain any 2006 // code, so don't dexopt it to avoid the resulting log spew. 2007 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2008 2009 // Gross hack for now: we know this file is only part of 2010 // the boot class path for art, so don't dexopt it to 2011 // avoid the resulting log spew. 2012 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2013 2014 /** 2015 * There are a number of commands implemented in Java, which 2016 * we currently need to do the dexopt on so that they can be 2017 * run from a non-root shell. 2018 */ 2019 String[] frameworkFiles = frameworkDir.list(); 2020 if (frameworkFiles != null) { 2021 // TODO: We could compile these only for the most preferred ABI. We should 2022 // first double check that the dex files for these commands are not referenced 2023 // by other system apps. 2024 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2025 for (int i=0; i<frameworkFiles.length; i++) { 2026 File libPath = new File(frameworkDir, frameworkFiles[i]); 2027 String path = libPath.getPath(); 2028 // Skip the file if we already did it. 2029 if (alreadyDexOpted.contains(path)) { 2030 continue; 2031 } 2032 // Skip the file if it is not a type we want to dexopt. 2033 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2034 continue; 2035 } 2036 try { 2037 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2038 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2039 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2040 } 2041 } catch (FileNotFoundException e) { 2042 Slog.w(TAG, "Jar not found: " + path); 2043 } catch (IOException e) { 2044 Slog.w(TAG, "Exception reading jar: " + path, e); 2045 } 2046 } 2047 } 2048 } 2049 2050 // Collect vendor overlay packages. 2051 // (Do this before scanning any apps.) 2052 // For security and version matching reason, only consider 2053 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2054 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2055 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2056 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2057 2058 // Find base frameworks (resource packages without code). 2059 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2060 | PackageParser.PARSE_IS_SYSTEM_DIR 2061 | PackageParser.PARSE_IS_PRIVILEGED, 2062 scanFlags | SCAN_NO_DEX, 0); 2063 2064 // Collected privileged system packages. 2065 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2066 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2067 | PackageParser.PARSE_IS_SYSTEM_DIR 2068 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2069 2070 // Collect ordinary system packages. 2071 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2072 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2073 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2074 2075 // Collect all vendor packages. 2076 File vendorAppDir = new File("/vendor/app"); 2077 try { 2078 vendorAppDir = vendorAppDir.getCanonicalFile(); 2079 } catch (IOException e) { 2080 // failed to look up canonical path, continue with original one 2081 } 2082 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2083 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2084 2085 // Collect all OEM packages. 2086 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2087 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2088 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2089 2090 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2091 mInstaller.moveFiles(); 2092 2093 // Prune any system packages that no longer exist. 2094 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2095 if (!mOnlyCore) { 2096 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2097 while (psit.hasNext()) { 2098 PackageSetting ps = psit.next(); 2099 2100 /* 2101 * If this is not a system app, it can't be a 2102 * disable system app. 2103 */ 2104 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2105 continue; 2106 } 2107 2108 /* 2109 * If the package is scanned, it's not erased. 2110 */ 2111 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2112 if (scannedPkg != null) { 2113 /* 2114 * If the system app is both scanned and in the 2115 * disabled packages list, then it must have been 2116 * added via OTA. Remove it from the currently 2117 * scanned package so the previously user-installed 2118 * application can be scanned. 2119 */ 2120 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2121 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2122 + ps.name + "; removing system app. Last known codePath=" 2123 + ps.codePathString + ", installStatus=" + ps.installStatus 2124 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2125 + scannedPkg.mVersionCode); 2126 removePackageLI(ps, true); 2127 mExpectingBetter.put(ps.name, ps.codePath); 2128 } 2129 2130 continue; 2131 } 2132 2133 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2134 psit.remove(); 2135 logCriticalInfo(Log.WARN, "System package " + ps.name 2136 + " no longer exists; wiping its data"); 2137 removeDataDirsLI(null, ps.name); 2138 } else { 2139 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2140 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2141 possiblyDeletedUpdatedSystemApps.add(ps.name); 2142 } 2143 } 2144 } 2145 } 2146 2147 //look for any incomplete package installations 2148 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2149 //clean up list 2150 for(int i = 0; i < deletePkgsList.size(); i++) { 2151 //clean up here 2152 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2153 } 2154 //delete tmp files 2155 deleteTempPackageFiles(); 2156 2157 // Remove any shared userIDs that have no associated packages 2158 mSettings.pruneSharedUsersLPw(); 2159 2160 if (!mOnlyCore) { 2161 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2162 SystemClock.uptimeMillis()); 2163 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2164 2165 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2166 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2167 2168 /** 2169 * Remove disable package settings for any updated system 2170 * apps that were removed via an OTA. If they're not a 2171 * previously-updated app, remove them completely. 2172 * Otherwise, just revoke their system-level permissions. 2173 */ 2174 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2175 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2176 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2177 2178 String msg; 2179 if (deletedPkg == null) { 2180 msg = "Updated system package " + deletedAppName 2181 + " no longer exists; wiping its data"; 2182 removeDataDirsLI(null, deletedAppName); 2183 } else { 2184 msg = "Updated system app + " + deletedAppName 2185 + " no longer present; removing system privileges for " 2186 + deletedAppName; 2187 2188 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2189 2190 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2191 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2192 } 2193 logCriticalInfo(Log.WARN, msg); 2194 } 2195 2196 /** 2197 * Make sure all system apps that we expected to appear on 2198 * the userdata partition actually showed up. If they never 2199 * appeared, crawl back and revive the system version. 2200 */ 2201 for (int i = 0; i < mExpectingBetter.size(); i++) { 2202 final String packageName = mExpectingBetter.keyAt(i); 2203 if (!mPackages.containsKey(packageName)) { 2204 final File scanFile = mExpectingBetter.valueAt(i); 2205 2206 logCriticalInfo(Log.WARN, "Expected better " + packageName 2207 + " but never showed up; reverting to system"); 2208 2209 final int reparseFlags; 2210 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2211 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2212 | PackageParser.PARSE_IS_SYSTEM_DIR 2213 | PackageParser.PARSE_IS_PRIVILEGED; 2214 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2215 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2216 | PackageParser.PARSE_IS_SYSTEM_DIR; 2217 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2218 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2219 | PackageParser.PARSE_IS_SYSTEM_DIR; 2220 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2221 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2222 | PackageParser.PARSE_IS_SYSTEM_DIR; 2223 } else { 2224 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2225 continue; 2226 } 2227 2228 mSettings.enableSystemPackageLPw(packageName); 2229 2230 try { 2231 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2232 } catch (PackageManagerException e) { 2233 Slog.e(TAG, "Failed to parse original system package: " 2234 + e.getMessage()); 2235 } 2236 } 2237 } 2238 } 2239 mExpectingBetter.clear(); 2240 2241 // Now that we know all of the shared libraries, update all clients to have 2242 // the correct library paths. 2243 updateAllSharedLibrariesLPw(); 2244 2245 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2246 // NOTE: We ignore potential failures here during a system scan (like 2247 // the rest of the commands above) because there's precious little we 2248 // can do about it. A settings error is reported, though. 2249 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2250 false /* force dexopt */, false /* defer dexopt */); 2251 } 2252 2253 // Now that we know all the packages we are keeping, 2254 // read and update their last usage times. 2255 mPackageUsage.readLP(); 2256 2257 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2258 SystemClock.uptimeMillis()); 2259 Slog.i(TAG, "Time to scan packages: " 2260 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2261 + " seconds"); 2262 2263 // If the platform SDK has changed since the last time we booted, 2264 // we need to re-grant app permission to catch any new ones that 2265 // appear. This is really a hack, and means that apps can in some 2266 // cases get permissions that the user didn't initially explicitly 2267 // allow... it would be nice to have some better way to handle 2268 // this situation. 2269 final VersionInfo ver = mSettings.getInternalVersion(); 2270 2271 int updateFlags = UPDATE_PERMISSIONS_ALL; 2272 if (ver.sdkVersion != mSdkVersion) { 2273 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2274 + mSdkVersion + "; regranting permissions for internal storage"); 2275 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2276 } 2277 updatePermissionsLPw(null, null, updateFlags); 2278 ver.sdkVersion = mSdkVersion; 2279 2280 // If this is the first boot, and it is a normal boot, then 2281 // we need to initialize the default preferred apps. 2282 if (!mRestoredSettings && !onlyCore) { 2283 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2284 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2285 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2286 } 2287 2288 // If this is first boot after an OTA, and a normal boot, then 2289 // we need to clear code cache directories. 2290 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2291 if (mIsUpgrade && !onlyCore) { 2292 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2293 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2294 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2295 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2296 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2297 } 2298 } 2299 ver.fingerprint = Build.FINGERPRINT; 2300 } 2301 2302 checkDefaultBrowser(); 2303 2304 // All the changes are done during package scanning. 2305 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2306 2307 // can downgrade to reader 2308 mSettings.writeLPr(); 2309 2310 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2311 SystemClock.uptimeMillis()); 2312 2313 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2314 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2315 2316 mInstallerService = new PackageInstallerService(context, this); 2317 2318 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2319 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2320 mIntentFilterVerifierComponent); 2321 2322 } // synchronized (mPackages) 2323 } // synchronized (mInstallLock) 2324 2325 // Now after opening every single application zip, make sure they 2326 // are all flushed. Not really needed, but keeps things nice and 2327 // tidy. 2328 Runtime.getRuntime().gc(); 2329 2330 // Expose private service for system components to use. 2331 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2332 } 2333 2334 @Override 2335 public boolean isFirstBoot() { 2336 return !mRestoredSettings; 2337 } 2338 2339 @Override 2340 public boolean isOnlyCoreApps() { 2341 return mOnlyCore; 2342 } 2343 2344 @Override 2345 public boolean isUpgrade() { 2346 return mIsUpgrade; 2347 } 2348 2349 private String getRequiredVerifierLPr() { 2350 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2351 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2352 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2353 2354 String requiredVerifier = null; 2355 2356 final int N = receivers.size(); 2357 for (int i = 0; i < N; i++) { 2358 final ResolveInfo info = receivers.get(i); 2359 2360 if (info.activityInfo == null) { 2361 continue; 2362 } 2363 2364 final String packageName = info.activityInfo.packageName; 2365 2366 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2367 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2368 continue; 2369 } 2370 2371 if (requiredVerifier != null) { 2372 throw new RuntimeException("There can be only one required verifier"); 2373 } 2374 2375 requiredVerifier = packageName; 2376 } 2377 2378 return requiredVerifier; 2379 } 2380 2381 private String getRequiredInstallerLPr() { 2382 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2383 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2384 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2385 2386 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2387 PACKAGE_MIME_TYPE, 0, 0); 2388 2389 String requiredInstaller = null; 2390 2391 final int N = installers.size(); 2392 for (int i = 0; i < N; i++) { 2393 final ResolveInfo info = installers.get(i); 2394 final String packageName = info.activityInfo.packageName; 2395 2396 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2397 continue; 2398 } 2399 2400 if (requiredInstaller != null) { 2401 throw new RuntimeException("There must be one required installer"); 2402 } 2403 2404 requiredInstaller = packageName; 2405 } 2406 2407 if (requiredInstaller == null) { 2408 throw new RuntimeException("There must be one required installer"); 2409 } 2410 2411 return requiredInstaller; 2412 } 2413 2414 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2415 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2416 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2417 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2418 2419 ComponentName verifierComponentName = null; 2420 2421 int priority = -1000; 2422 final int N = receivers.size(); 2423 for (int i = 0; i < N; i++) { 2424 final ResolveInfo info = receivers.get(i); 2425 2426 if (info.activityInfo == null) { 2427 continue; 2428 } 2429 2430 final String packageName = info.activityInfo.packageName; 2431 2432 final PackageSetting ps = mSettings.mPackages.get(packageName); 2433 if (ps == null) { 2434 continue; 2435 } 2436 2437 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2438 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2439 continue; 2440 } 2441 2442 // Select the IntentFilterVerifier with the highest priority 2443 if (priority < info.priority) { 2444 priority = info.priority; 2445 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2446 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2447 + verifierComponentName + " with priority: " + info.priority); 2448 } 2449 } 2450 2451 return verifierComponentName; 2452 } 2453 2454 private void primeDomainVerificationsLPw(int userId) { 2455 if (DEBUG_DOMAIN_VERIFICATION) { 2456 Slog.d(TAG, "Priming domain verifications in user " + userId); 2457 } 2458 2459 SystemConfig systemConfig = SystemConfig.getInstance(); 2460 ArraySet<String> packages = systemConfig.getLinkedApps(); 2461 ArraySet<String> domains = new ArraySet<String>(); 2462 2463 for (String packageName : packages) { 2464 PackageParser.Package pkg = mPackages.get(packageName); 2465 if (pkg != null) { 2466 if (!pkg.isSystemApp()) { 2467 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2468 continue; 2469 } 2470 2471 domains.clear(); 2472 for (PackageParser.Activity a : pkg.activities) { 2473 for (ActivityIntentInfo filter : a.intents) { 2474 if (hasValidDomains(filter)) { 2475 domains.addAll(filter.getHostsList()); 2476 } 2477 } 2478 } 2479 2480 if (domains.size() > 0) { 2481 if (DEBUG_DOMAIN_VERIFICATION) { 2482 Slog.v(TAG, " + " + packageName); 2483 } 2484 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2485 // state w.r.t. the formal app-linkage "no verification attempted" state; 2486 // and then 'always' in the per-user state actually used for intent resolution. 2487 final IntentFilterVerificationInfo ivi; 2488 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2489 new ArrayList<String>(domains)); 2490 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2491 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2492 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2493 } else { 2494 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2495 + "' does not handle web links"); 2496 } 2497 } else { 2498 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2499 } 2500 } 2501 2502 scheduleWritePackageRestrictionsLocked(userId); 2503 scheduleWriteSettingsLocked(); 2504 } 2505 2506 private void applyFactoryDefaultBrowserLPw(int userId) { 2507 // The default browser app's package name is stored in a string resource, 2508 // with a product-specific overlay used for vendor customization. 2509 String browserPkg = mContext.getResources().getString( 2510 com.android.internal.R.string.default_browser); 2511 if (!TextUtils.isEmpty(browserPkg)) { 2512 // non-empty string => required to be a known package 2513 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2514 if (ps == null) { 2515 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2516 browserPkg = null; 2517 } else { 2518 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2519 } 2520 } 2521 2522 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2523 // default. If there's more than one, just leave everything alone. 2524 if (browserPkg == null) { 2525 calculateDefaultBrowserLPw(userId); 2526 } 2527 } 2528 2529 private void calculateDefaultBrowserLPw(int userId) { 2530 List<String> allBrowsers = resolveAllBrowserApps(userId); 2531 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2532 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2533 } 2534 2535 private List<String> resolveAllBrowserApps(int userId) { 2536 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2537 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2538 PackageManager.MATCH_ALL, userId); 2539 2540 final int count = list.size(); 2541 List<String> result = new ArrayList<String>(count); 2542 for (int i=0; i<count; i++) { 2543 ResolveInfo info = list.get(i); 2544 if (info.activityInfo == null 2545 || !info.handleAllWebDataURI 2546 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2547 || result.contains(info.activityInfo.packageName)) { 2548 continue; 2549 } 2550 result.add(info.activityInfo.packageName); 2551 } 2552 2553 return result; 2554 } 2555 2556 private boolean packageIsBrowser(String packageName, int userId) { 2557 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2558 PackageManager.MATCH_ALL, userId); 2559 final int N = list.size(); 2560 for (int i = 0; i < N; i++) { 2561 ResolveInfo info = list.get(i); 2562 if (packageName.equals(info.activityInfo.packageName)) { 2563 return true; 2564 } 2565 } 2566 return false; 2567 } 2568 2569 private void checkDefaultBrowser() { 2570 final int myUserId = UserHandle.myUserId(); 2571 final String packageName = getDefaultBrowserPackageName(myUserId); 2572 if (packageName != null) { 2573 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2574 if (info == null) { 2575 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2576 synchronized (mPackages) { 2577 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2578 } 2579 } 2580 } 2581 } 2582 2583 @Override 2584 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2585 throws RemoteException { 2586 try { 2587 return super.onTransact(code, data, reply, flags); 2588 } catch (RuntimeException e) { 2589 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2590 Slog.wtf(TAG, "Package Manager Crash", e); 2591 } 2592 throw e; 2593 } 2594 } 2595 2596 void cleanupInstallFailedPackage(PackageSetting ps) { 2597 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2598 2599 removeDataDirsLI(ps.volumeUuid, ps.name); 2600 if (ps.codePath != null) { 2601 if (ps.codePath.isDirectory()) { 2602 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2603 } else { 2604 ps.codePath.delete(); 2605 } 2606 } 2607 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2608 if (ps.resourcePath.isDirectory()) { 2609 FileUtils.deleteContents(ps.resourcePath); 2610 } 2611 ps.resourcePath.delete(); 2612 } 2613 mSettings.removePackageLPw(ps.name); 2614 } 2615 2616 static int[] appendInts(int[] cur, int[] add) { 2617 if (add == null) return cur; 2618 if (cur == null) return add; 2619 final int N = add.length; 2620 for (int i=0; i<N; i++) { 2621 cur = appendInt(cur, add[i]); 2622 } 2623 return cur; 2624 } 2625 2626 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2627 if (!sUserManager.exists(userId)) return null; 2628 final PackageSetting ps = (PackageSetting) p.mExtras; 2629 if (ps == null) { 2630 return null; 2631 } 2632 2633 final PermissionsState permissionsState = ps.getPermissionsState(); 2634 2635 final int[] gids = permissionsState.computeGids(userId); 2636 final Set<String> permissions = permissionsState.getPermissions(userId); 2637 final PackageUserState state = ps.readUserState(userId); 2638 2639 return PackageParser.generatePackageInfo(p, gids, flags, 2640 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2641 } 2642 2643 @Override 2644 public boolean isPackageFrozen(String packageName) { 2645 synchronized (mPackages) { 2646 final PackageSetting ps = mSettings.mPackages.get(packageName); 2647 if (ps != null) { 2648 return ps.frozen; 2649 } 2650 } 2651 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2652 return true; 2653 } 2654 2655 @Override 2656 public boolean isPackageAvailable(String packageName, int userId) { 2657 if (!sUserManager.exists(userId)) return false; 2658 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2659 synchronized (mPackages) { 2660 PackageParser.Package p = mPackages.get(packageName); 2661 if (p != null) { 2662 final PackageSetting ps = (PackageSetting) p.mExtras; 2663 if (ps != null) { 2664 final PackageUserState state = ps.readUserState(userId); 2665 if (state != null) { 2666 return PackageParser.isAvailable(state); 2667 } 2668 } 2669 } 2670 } 2671 return false; 2672 } 2673 2674 @Override 2675 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2676 if (!sUserManager.exists(userId)) return null; 2677 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2678 // reader 2679 synchronized (mPackages) { 2680 PackageParser.Package p = mPackages.get(packageName); 2681 if (DEBUG_PACKAGE_INFO) 2682 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2683 if (p != null) { 2684 return generatePackageInfo(p, flags, userId); 2685 } 2686 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2687 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2688 } 2689 } 2690 return null; 2691 } 2692 2693 @Override 2694 public String[] currentToCanonicalPackageNames(String[] names) { 2695 String[] out = new String[names.length]; 2696 // reader 2697 synchronized (mPackages) { 2698 for (int i=names.length-1; i>=0; i--) { 2699 PackageSetting ps = mSettings.mPackages.get(names[i]); 2700 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2701 } 2702 } 2703 return out; 2704 } 2705 2706 @Override 2707 public String[] canonicalToCurrentPackageNames(String[] names) { 2708 String[] out = new String[names.length]; 2709 // reader 2710 synchronized (mPackages) { 2711 for (int i=names.length-1; i>=0; i--) { 2712 String cur = mSettings.mRenamedPackages.get(names[i]); 2713 out[i] = cur != null ? cur : names[i]; 2714 } 2715 } 2716 return out; 2717 } 2718 2719 @Override 2720 public int getPackageUid(String packageName, int userId) { 2721 if (!sUserManager.exists(userId)) return -1; 2722 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2723 2724 // reader 2725 synchronized (mPackages) { 2726 PackageParser.Package p = mPackages.get(packageName); 2727 if(p != null) { 2728 return UserHandle.getUid(userId, p.applicationInfo.uid); 2729 } 2730 PackageSetting ps = mSettings.mPackages.get(packageName); 2731 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2732 return -1; 2733 } 2734 p = ps.pkg; 2735 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2736 } 2737 } 2738 2739 @Override 2740 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2741 if (!sUserManager.exists(userId)) { 2742 return null; 2743 } 2744 2745 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2746 "getPackageGids"); 2747 2748 // reader 2749 synchronized (mPackages) { 2750 PackageParser.Package p = mPackages.get(packageName); 2751 if (DEBUG_PACKAGE_INFO) { 2752 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2753 } 2754 if (p != null) { 2755 PackageSetting ps = (PackageSetting) p.mExtras; 2756 return ps.getPermissionsState().computeGids(userId); 2757 } 2758 } 2759 2760 return null; 2761 } 2762 2763 static PermissionInfo generatePermissionInfo( 2764 BasePermission bp, int flags) { 2765 if (bp.perm != null) { 2766 return PackageParser.generatePermissionInfo(bp.perm, flags); 2767 } 2768 PermissionInfo pi = new PermissionInfo(); 2769 pi.name = bp.name; 2770 pi.packageName = bp.sourcePackage; 2771 pi.nonLocalizedLabel = bp.name; 2772 pi.protectionLevel = bp.protectionLevel; 2773 return pi; 2774 } 2775 2776 @Override 2777 public PermissionInfo getPermissionInfo(String name, int flags) { 2778 // reader 2779 synchronized (mPackages) { 2780 final BasePermission p = mSettings.mPermissions.get(name); 2781 if (p != null) { 2782 return generatePermissionInfo(p, flags); 2783 } 2784 return null; 2785 } 2786 } 2787 2788 @Override 2789 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2790 // reader 2791 synchronized (mPackages) { 2792 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2793 for (BasePermission p : mSettings.mPermissions.values()) { 2794 if (group == null) { 2795 if (p.perm == null || p.perm.info.group == null) { 2796 out.add(generatePermissionInfo(p, flags)); 2797 } 2798 } else { 2799 if (p.perm != null && group.equals(p.perm.info.group)) { 2800 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2801 } 2802 } 2803 } 2804 2805 if (out.size() > 0) { 2806 return out; 2807 } 2808 return mPermissionGroups.containsKey(group) ? out : null; 2809 } 2810 } 2811 2812 @Override 2813 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2814 // reader 2815 synchronized (mPackages) { 2816 return PackageParser.generatePermissionGroupInfo( 2817 mPermissionGroups.get(name), flags); 2818 } 2819 } 2820 2821 @Override 2822 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2823 // reader 2824 synchronized (mPackages) { 2825 final int N = mPermissionGroups.size(); 2826 ArrayList<PermissionGroupInfo> out 2827 = new ArrayList<PermissionGroupInfo>(N); 2828 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2829 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2830 } 2831 return out; 2832 } 2833 } 2834 2835 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2836 int userId) { 2837 if (!sUserManager.exists(userId)) return null; 2838 PackageSetting ps = mSettings.mPackages.get(packageName); 2839 if (ps != null) { 2840 if (ps.pkg == null) { 2841 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2842 flags, userId); 2843 if (pInfo != null) { 2844 return pInfo.applicationInfo; 2845 } 2846 return null; 2847 } 2848 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2849 ps.readUserState(userId), userId); 2850 } 2851 return null; 2852 } 2853 2854 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2855 int userId) { 2856 if (!sUserManager.exists(userId)) return null; 2857 PackageSetting ps = mSettings.mPackages.get(packageName); 2858 if (ps != null) { 2859 PackageParser.Package pkg = ps.pkg; 2860 if (pkg == null) { 2861 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2862 return null; 2863 } 2864 // Only data remains, so we aren't worried about code paths 2865 pkg = new PackageParser.Package(packageName); 2866 pkg.applicationInfo.packageName = packageName; 2867 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2868 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2869 pkg.applicationInfo.dataDir = Environment 2870 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2871 .getAbsolutePath(); 2872 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2873 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2874 } 2875 return generatePackageInfo(pkg, flags, userId); 2876 } 2877 return null; 2878 } 2879 2880 @Override 2881 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2882 if (!sUserManager.exists(userId)) return null; 2883 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2884 // writer 2885 synchronized (mPackages) { 2886 PackageParser.Package p = mPackages.get(packageName); 2887 if (DEBUG_PACKAGE_INFO) Log.v( 2888 TAG, "getApplicationInfo " + packageName 2889 + ": " + p); 2890 if (p != null) { 2891 PackageSetting ps = mSettings.mPackages.get(packageName); 2892 if (ps == null) return null; 2893 // Note: isEnabledLP() does not apply here - always return info 2894 return PackageParser.generateApplicationInfo( 2895 p, flags, ps.readUserState(userId), userId); 2896 } 2897 if ("android".equals(packageName)||"system".equals(packageName)) { 2898 return mAndroidApplication; 2899 } 2900 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2901 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2902 } 2903 } 2904 return null; 2905 } 2906 2907 @Override 2908 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2909 final IPackageDataObserver observer) { 2910 mContext.enforceCallingOrSelfPermission( 2911 android.Manifest.permission.CLEAR_APP_CACHE, null); 2912 // Queue up an async operation since clearing cache may take a little while. 2913 mHandler.post(new Runnable() { 2914 public void run() { 2915 mHandler.removeCallbacks(this); 2916 int retCode = -1; 2917 synchronized (mInstallLock) { 2918 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2919 if (retCode < 0) { 2920 Slog.w(TAG, "Couldn't clear application caches"); 2921 } 2922 } 2923 if (observer != null) { 2924 try { 2925 observer.onRemoveCompleted(null, (retCode >= 0)); 2926 } catch (RemoteException e) { 2927 Slog.w(TAG, "RemoveException when invoking call back"); 2928 } 2929 } 2930 } 2931 }); 2932 } 2933 2934 @Override 2935 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2936 final IntentSender pi) { 2937 mContext.enforceCallingOrSelfPermission( 2938 android.Manifest.permission.CLEAR_APP_CACHE, null); 2939 // Queue up an async operation since clearing cache may take a little while. 2940 mHandler.post(new Runnable() { 2941 public void run() { 2942 mHandler.removeCallbacks(this); 2943 int retCode = -1; 2944 synchronized (mInstallLock) { 2945 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2946 if (retCode < 0) { 2947 Slog.w(TAG, "Couldn't clear application caches"); 2948 } 2949 } 2950 if(pi != null) { 2951 try { 2952 // Callback via pending intent 2953 int code = (retCode >= 0) ? 1 : 0; 2954 pi.sendIntent(null, code, null, 2955 null, null); 2956 } catch (SendIntentException e1) { 2957 Slog.i(TAG, "Failed to send pending intent"); 2958 } 2959 } 2960 } 2961 }); 2962 } 2963 2964 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2965 synchronized (mInstallLock) { 2966 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2967 throw new IOException("Failed to free enough space"); 2968 } 2969 } 2970 } 2971 2972 @Override 2973 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2974 if (!sUserManager.exists(userId)) return null; 2975 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2976 synchronized (mPackages) { 2977 PackageParser.Activity a = mActivities.mActivities.get(component); 2978 2979 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2980 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2981 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2982 if (ps == null) return null; 2983 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2984 userId); 2985 } 2986 if (mResolveComponentName.equals(component)) { 2987 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2988 new PackageUserState(), userId); 2989 } 2990 } 2991 return null; 2992 } 2993 2994 @Override 2995 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2996 String resolvedType) { 2997 synchronized (mPackages) { 2998 if (component.equals(mResolveComponentName)) { 2999 // The resolver supports EVERYTHING! 3000 return true; 3001 } 3002 PackageParser.Activity a = mActivities.mActivities.get(component); 3003 if (a == null) { 3004 return false; 3005 } 3006 for (int i=0; i<a.intents.size(); i++) { 3007 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3008 intent.getData(), intent.getCategories(), TAG) >= 0) { 3009 return true; 3010 } 3011 } 3012 return false; 3013 } 3014 } 3015 3016 @Override 3017 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3018 if (!sUserManager.exists(userId)) return null; 3019 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3020 synchronized (mPackages) { 3021 PackageParser.Activity a = mReceivers.mActivities.get(component); 3022 if (DEBUG_PACKAGE_INFO) Log.v( 3023 TAG, "getReceiverInfo " + component + ": " + a); 3024 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3025 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3026 if (ps == null) return null; 3027 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3028 userId); 3029 } 3030 } 3031 return null; 3032 } 3033 3034 @Override 3035 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3036 if (!sUserManager.exists(userId)) return null; 3037 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3038 synchronized (mPackages) { 3039 PackageParser.Service s = mServices.mServices.get(component); 3040 if (DEBUG_PACKAGE_INFO) Log.v( 3041 TAG, "getServiceInfo " + component + ": " + s); 3042 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3043 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3044 if (ps == null) return null; 3045 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3046 userId); 3047 } 3048 } 3049 return null; 3050 } 3051 3052 @Override 3053 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3054 if (!sUserManager.exists(userId)) return null; 3055 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3056 synchronized (mPackages) { 3057 PackageParser.Provider p = mProviders.mProviders.get(component); 3058 if (DEBUG_PACKAGE_INFO) Log.v( 3059 TAG, "getProviderInfo " + component + ": " + p); 3060 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3061 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3062 if (ps == null) return null; 3063 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3064 userId); 3065 } 3066 } 3067 return null; 3068 } 3069 3070 @Override 3071 public String[] getSystemSharedLibraryNames() { 3072 Set<String> libSet; 3073 synchronized (mPackages) { 3074 libSet = mSharedLibraries.keySet(); 3075 int size = libSet.size(); 3076 if (size > 0) { 3077 String[] libs = new String[size]; 3078 libSet.toArray(libs); 3079 return libs; 3080 } 3081 } 3082 return null; 3083 } 3084 3085 /** 3086 * @hide 3087 */ 3088 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3089 synchronized (mPackages) { 3090 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3091 if (lib != null && lib.apk != null) { 3092 return mPackages.get(lib.apk); 3093 } 3094 } 3095 return null; 3096 } 3097 3098 @Override 3099 public FeatureInfo[] getSystemAvailableFeatures() { 3100 Collection<FeatureInfo> featSet; 3101 synchronized (mPackages) { 3102 featSet = mAvailableFeatures.values(); 3103 int size = featSet.size(); 3104 if (size > 0) { 3105 FeatureInfo[] features = new FeatureInfo[size+1]; 3106 featSet.toArray(features); 3107 FeatureInfo fi = new FeatureInfo(); 3108 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3109 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3110 features[size] = fi; 3111 return features; 3112 } 3113 } 3114 return null; 3115 } 3116 3117 @Override 3118 public boolean hasSystemFeature(String name) { 3119 synchronized (mPackages) { 3120 return mAvailableFeatures.containsKey(name); 3121 } 3122 } 3123 3124 private void checkValidCaller(int uid, int userId) { 3125 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3126 return; 3127 3128 throw new SecurityException("Caller uid=" + uid 3129 + " is not privileged to communicate with user=" + userId); 3130 } 3131 3132 @Override 3133 public int checkPermission(String permName, String pkgName, int userId) { 3134 if (!sUserManager.exists(userId)) { 3135 return PackageManager.PERMISSION_DENIED; 3136 } 3137 3138 synchronized (mPackages) { 3139 final PackageParser.Package p = mPackages.get(pkgName); 3140 if (p != null && p.mExtras != null) { 3141 final PackageSetting ps = (PackageSetting) p.mExtras; 3142 final PermissionsState permissionsState = ps.getPermissionsState(); 3143 if (permissionsState.hasPermission(permName, userId)) { 3144 return PackageManager.PERMISSION_GRANTED; 3145 } 3146 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3147 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3148 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3149 return PackageManager.PERMISSION_GRANTED; 3150 } 3151 } 3152 } 3153 3154 return PackageManager.PERMISSION_DENIED; 3155 } 3156 3157 @Override 3158 public int checkUidPermission(String permName, int uid) { 3159 final int userId = UserHandle.getUserId(uid); 3160 3161 if (!sUserManager.exists(userId)) { 3162 return PackageManager.PERMISSION_DENIED; 3163 } 3164 3165 synchronized (mPackages) { 3166 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3167 if (obj != null) { 3168 final SettingBase ps = (SettingBase) obj; 3169 final PermissionsState permissionsState = ps.getPermissionsState(); 3170 if (permissionsState.hasPermission(permName, userId)) { 3171 return PackageManager.PERMISSION_GRANTED; 3172 } 3173 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3174 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3175 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3176 return PackageManager.PERMISSION_GRANTED; 3177 } 3178 } else { 3179 ArraySet<String> perms = mSystemPermissions.get(uid); 3180 if (perms != null) { 3181 if (perms.contains(permName)) { 3182 return PackageManager.PERMISSION_GRANTED; 3183 } 3184 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3185 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3186 return PackageManager.PERMISSION_GRANTED; 3187 } 3188 } 3189 } 3190 } 3191 3192 return PackageManager.PERMISSION_DENIED; 3193 } 3194 3195 @Override 3196 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3197 if (UserHandle.getCallingUserId() != userId) { 3198 mContext.enforceCallingPermission( 3199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3200 "isPermissionRevokedByPolicy for user " + userId); 3201 } 3202 3203 if (checkPermission(permission, packageName, userId) 3204 == PackageManager.PERMISSION_GRANTED) { 3205 return false; 3206 } 3207 3208 final long identity = Binder.clearCallingIdentity(); 3209 try { 3210 final int flags = getPermissionFlags(permission, packageName, userId); 3211 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3212 } finally { 3213 Binder.restoreCallingIdentity(identity); 3214 } 3215 } 3216 3217 @Override 3218 public String getPermissionControllerPackageName() { 3219 synchronized (mPackages) { 3220 return mRequiredInstallerPackage; 3221 } 3222 } 3223 3224 /** 3225 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3226 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3227 * @param checkShell TODO(yamasani): 3228 * @param message the message to log on security exception 3229 */ 3230 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3231 boolean checkShell, String message) { 3232 if (userId < 0) { 3233 throw new IllegalArgumentException("Invalid userId " + userId); 3234 } 3235 if (checkShell) { 3236 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3237 } 3238 if (userId == UserHandle.getUserId(callingUid)) return; 3239 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3240 if (requireFullPermission) { 3241 mContext.enforceCallingOrSelfPermission( 3242 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3243 } else { 3244 try { 3245 mContext.enforceCallingOrSelfPermission( 3246 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3247 } catch (SecurityException se) { 3248 mContext.enforceCallingOrSelfPermission( 3249 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3250 } 3251 } 3252 } 3253 } 3254 3255 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3256 if (callingUid == Process.SHELL_UID) { 3257 if (userHandle >= 0 3258 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3259 throw new SecurityException("Shell does not have permission to access user " 3260 + userHandle); 3261 } else if (userHandle < 0) { 3262 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3263 + Debug.getCallers(3)); 3264 } 3265 } 3266 } 3267 3268 private BasePermission findPermissionTreeLP(String permName) { 3269 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3270 if (permName.startsWith(bp.name) && 3271 permName.length() > bp.name.length() && 3272 permName.charAt(bp.name.length()) == '.') { 3273 return bp; 3274 } 3275 } 3276 return null; 3277 } 3278 3279 private BasePermission checkPermissionTreeLP(String permName) { 3280 if (permName != null) { 3281 BasePermission bp = findPermissionTreeLP(permName); 3282 if (bp != null) { 3283 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3284 return bp; 3285 } 3286 throw new SecurityException("Calling uid " 3287 + Binder.getCallingUid() 3288 + " is not allowed to add to permission tree " 3289 + bp.name + " owned by uid " + bp.uid); 3290 } 3291 } 3292 throw new SecurityException("No permission tree found for " + permName); 3293 } 3294 3295 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3296 if (s1 == null) { 3297 return s2 == null; 3298 } 3299 if (s2 == null) { 3300 return false; 3301 } 3302 if (s1.getClass() != s2.getClass()) { 3303 return false; 3304 } 3305 return s1.equals(s2); 3306 } 3307 3308 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3309 if (pi1.icon != pi2.icon) return false; 3310 if (pi1.logo != pi2.logo) return false; 3311 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3312 if (!compareStrings(pi1.name, pi2.name)) return false; 3313 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3314 // We'll take care of setting this one. 3315 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3316 // These are not currently stored in settings. 3317 //if (!compareStrings(pi1.group, pi2.group)) return false; 3318 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3319 //if (pi1.labelRes != pi2.labelRes) return false; 3320 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3321 return true; 3322 } 3323 3324 int permissionInfoFootprint(PermissionInfo info) { 3325 int size = info.name.length(); 3326 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3327 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3328 return size; 3329 } 3330 3331 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3332 int size = 0; 3333 for (BasePermission perm : mSettings.mPermissions.values()) { 3334 if (perm.uid == tree.uid) { 3335 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3336 } 3337 } 3338 return size; 3339 } 3340 3341 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3342 // We calculate the max size of permissions defined by this uid and throw 3343 // if that plus the size of 'info' would exceed our stated maximum. 3344 if (tree.uid != Process.SYSTEM_UID) { 3345 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3346 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3347 throw new SecurityException("Permission tree size cap exceeded"); 3348 } 3349 } 3350 } 3351 3352 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3353 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3354 throw new SecurityException("Label must be specified in permission"); 3355 } 3356 BasePermission tree = checkPermissionTreeLP(info.name); 3357 BasePermission bp = mSettings.mPermissions.get(info.name); 3358 boolean added = bp == null; 3359 boolean changed = true; 3360 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3361 if (added) { 3362 enforcePermissionCapLocked(info, tree); 3363 bp = new BasePermission(info.name, tree.sourcePackage, 3364 BasePermission.TYPE_DYNAMIC); 3365 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3366 throw new SecurityException( 3367 "Not allowed to modify non-dynamic permission " 3368 + info.name); 3369 } else { 3370 if (bp.protectionLevel == fixedLevel 3371 && bp.perm.owner.equals(tree.perm.owner) 3372 && bp.uid == tree.uid 3373 && comparePermissionInfos(bp.perm.info, info)) { 3374 changed = false; 3375 } 3376 } 3377 bp.protectionLevel = fixedLevel; 3378 info = new PermissionInfo(info); 3379 info.protectionLevel = fixedLevel; 3380 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3381 bp.perm.info.packageName = tree.perm.info.packageName; 3382 bp.uid = tree.uid; 3383 if (added) { 3384 mSettings.mPermissions.put(info.name, bp); 3385 } 3386 if (changed) { 3387 if (!async) { 3388 mSettings.writeLPr(); 3389 } else { 3390 scheduleWriteSettingsLocked(); 3391 } 3392 } 3393 return added; 3394 } 3395 3396 @Override 3397 public boolean addPermission(PermissionInfo info) { 3398 synchronized (mPackages) { 3399 return addPermissionLocked(info, false); 3400 } 3401 } 3402 3403 @Override 3404 public boolean addPermissionAsync(PermissionInfo info) { 3405 synchronized (mPackages) { 3406 return addPermissionLocked(info, true); 3407 } 3408 } 3409 3410 @Override 3411 public void removePermission(String name) { 3412 synchronized (mPackages) { 3413 checkPermissionTreeLP(name); 3414 BasePermission bp = mSettings.mPermissions.get(name); 3415 if (bp != null) { 3416 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3417 throw new SecurityException( 3418 "Not allowed to modify non-dynamic permission " 3419 + name); 3420 } 3421 mSettings.mPermissions.remove(name); 3422 mSettings.writeLPr(); 3423 } 3424 } 3425 } 3426 3427 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3428 BasePermission bp) { 3429 int index = pkg.requestedPermissions.indexOf(bp.name); 3430 if (index == -1) { 3431 throw new SecurityException("Package " + pkg.packageName 3432 + " has not requested permission " + bp.name); 3433 } 3434 if (!bp.isRuntime()) { 3435 throw new SecurityException("Permission " + bp.name 3436 + " is not a changeable permission type"); 3437 } 3438 } 3439 3440 @Override 3441 public void grantRuntimePermission(String packageName, String name, final int userId) { 3442 if (!sUserManager.exists(userId)) { 3443 Log.e(TAG, "No such user:" + userId); 3444 return; 3445 } 3446 3447 mContext.enforceCallingOrSelfPermission( 3448 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3449 "grantRuntimePermission"); 3450 3451 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3452 "grantRuntimePermission"); 3453 3454 final int uid; 3455 final SettingBase sb; 3456 3457 synchronized (mPackages) { 3458 final PackageParser.Package pkg = mPackages.get(packageName); 3459 if (pkg == null) { 3460 throw new IllegalArgumentException("Unknown package: " + packageName); 3461 } 3462 3463 final BasePermission bp = mSettings.mPermissions.get(name); 3464 if (bp == null) { 3465 throw new IllegalArgumentException("Unknown permission: " + name); 3466 } 3467 3468 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3469 3470 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3471 sb = (SettingBase) pkg.mExtras; 3472 if (sb == null) { 3473 throw new IllegalArgumentException("Unknown package: " + packageName); 3474 } 3475 3476 final PermissionsState permissionsState = sb.getPermissionsState(); 3477 3478 final int flags = permissionsState.getPermissionFlags(name, userId); 3479 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3480 throw new SecurityException("Cannot grant system fixed permission: " 3481 + name + " for package: " + packageName); 3482 } 3483 3484 final int result = permissionsState.grantRuntimePermission(bp, userId); 3485 switch (result) { 3486 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3487 return; 3488 } 3489 3490 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3491 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3492 mHandler.post(new Runnable() { 3493 @Override 3494 public void run() { 3495 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3496 } 3497 }); 3498 } break; 3499 } 3500 3501 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3502 3503 // Not critical if that is lost - app has to request again. 3504 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3505 } 3506 3507 // Only need to do this if user is initialized. Otherwise it's a new user 3508 // and there are no processes running as the user yet and there's no need 3509 // to make an expensive call to remount processes for the changed permissions. 3510 if (READ_EXTERNAL_STORAGE.equals(name) 3511 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3512 final long token = Binder.clearCallingIdentity(); 3513 try { 3514 if (sUserManager.isInitialized(userId)) { 3515 MountServiceInternal mountServiceInternal = LocalServices.getService( 3516 MountServiceInternal.class); 3517 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3518 } 3519 } finally { 3520 Binder.restoreCallingIdentity(token); 3521 } 3522 } 3523 } 3524 3525 @Override 3526 public void revokeRuntimePermission(String packageName, String name, int userId) { 3527 if (!sUserManager.exists(userId)) { 3528 Log.e(TAG, "No such user:" + userId); 3529 return; 3530 } 3531 3532 mContext.enforceCallingOrSelfPermission( 3533 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3534 "revokeRuntimePermission"); 3535 3536 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3537 "revokeRuntimePermission"); 3538 3539 final int appId; 3540 3541 synchronized (mPackages) { 3542 final PackageParser.Package pkg = mPackages.get(packageName); 3543 if (pkg == null) { 3544 throw new IllegalArgumentException("Unknown package: " + packageName); 3545 } 3546 3547 final BasePermission bp = mSettings.mPermissions.get(name); 3548 if (bp == null) { 3549 throw new IllegalArgumentException("Unknown permission: " + name); 3550 } 3551 3552 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3553 3554 SettingBase sb = (SettingBase) pkg.mExtras; 3555 if (sb == null) { 3556 throw new IllegalArgumentException("Unknown package: " + packageName); 3557 } 3558 3559 final PermissionsState permissionsState = sb.getPermissionsState(); 3560 3561 final int flags = permissionsState.getPermissionFlags(name, userId); 3562 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3563 throw new SecurityException("Cannot revoke system fixed permission: " 3564 + name + " for package: " + packageName); 3565 } 3566 3567 if (permissionsState.revokeRuntimePermission(bp, userId) == 3568 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3569 return; 3570 } 3571 3572 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3573 3574 // Critical, after this call app should never have the permission. 3575 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3576 3577 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3578 } 3579 3580 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3581 } 3582 3583 @Override 3584 public void resetRuntimePermissions() { 3585 mContext.enforceCallingOrSelfPermission( 3586 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3587 "revokeRuntimePermission"); 3588 3589 int callingUid = Binder.getCallingUid(); 3590 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3591 mContext.enforceCallingOrSelfPermission( 3592 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3593 "resetRuntimePermissions"); 3594 } 3595 3596 synchronized (mPackages) { 3597 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3598 for (int userId : UserManagerService.getInstance().getUserIds()) { 3599 final int packageCount = mPackages.size(); 3600 for (int i = 0; i < packageCount; i++) { 3601 PackageParser.Package pkg = mPackages.valueAt(i); 3602 if (!(pkg.mExtras instanceof PackageSetting)) { 3603 continue; 3604 } 3605 PackageSetting ps = (PackageSetting) pkg.mExtras; 3606 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3607 } 3608 } 3609 } 3610 } 3611 3612 @Override 3613 public int getPermissionFlags(String name, String packageName, int userId) { 3614 if (!sUserManager.exists(userId)) { 3615 return 0; 3616 } 3617 3618 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3619 3620 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3621 "getPermissionFlags"); 3622 3623 synchronized (mPackages) { 3624 final PackageParser.Package pkg = mPackages.get(packageName); 3625 if (pkg == null) { 3626 throw new IllegalArgumentException("Unknown package: " + packageName); 3627 } 3628 3629 final BasePermission bp = mSettings.mPermissions.get(name); 3630 if (bp == null) { 3631 throw new IllegalArgumentException("Unknown permission: " + name); 3632 } 3633 3634 SettingBase sb = (SettingBase) pkg.mExtras; 3635 if (sb == null) { 3636 throw new IllegalArgumentException("Unknown package: " + packageName); 3637 } 3638 3639 PermissionsState permissionsState = sb.getPermissionsState(); 3640 return permissionsState.getPermissionFlags(name, userId); 3641 } 3642 } 3643 3644 @Override 3645 public void updatePermissionFlags(String name, String packageName, int flagMask, 3646 int flagValues, int userId) { 3647 if (!sUserManager.exists(userId)) { 3648 return; 3649 } 3650 3651 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3652 3653 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3654 "updatePermissionFlags"); 3655 3656 // Only the system can change these flags and nothing else. 3657 if (getCallingUid() != Process.SYSTEM_UID) { 3658 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3659 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3660 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3661 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3662 } 3663 3664 synchronized (mPackages) { 3665 final PackageParser.Package pkg = mPackages.get(packageName); 3666 if (pkg == null) { 3667 throw new IllegalArgumentException("Unknown package: " + packageName); 3668 } 3669 3670 final BasePermission bp = mSettings.mPermissions.get(name); 3671 if (bp == null) { 3672 throw new IllegalArgumentException("Unknown permission: " + name); 3673 } 3674 3675 SettingBase sb = (SettingBase) pkg.mExtras; 3676 if (sb == null) { 3677 throw new IllegalArgumentException("Unknown package: " + packageName); 3678 } 3679 3680 PermissionsState permissionsState = sb.getPermissionsState(); 3681 3682 // Only the package manager can change flags for system component permissions. 3683 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3684 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3685 return; 3686 } 3687 3688 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3689 3690 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3691 // Install and runtime permissions are stored in different places, 3692 // so figure out what permission changed and persist the change. 3693 if (permissionsState.getInstallPermissionState(name) != null) { 3694 scheduleWriteSettingsLocked(); 3695 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3696 || hadState) { 3697 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3698 } 3699 } 3700 } 3701 } 3702 3703 /** 3704 * Update the permission flags for all packages and runtime permissions of a user in order 3705 * to allow device or profile owner to remove POLICY_FIXED. 3706 */ 3707 @Override 3708 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3709 if (!sUserManager.exists(userId)) { 3710 return; 3711 } 3712 3713 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3714 3715 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3716 "updatePermissionFlagsForAllApps"); 3717 3718 // Only the system can change system fixed flags. 3719 if (getCallingUid() != Process.SYSTEM_UID) { 3720 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3721 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3722 } 3723 3724 synchronized (mPackages) { 3725 boolean changed = false; 3726 final int packageCount = mPackages.size(); 3727 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3728 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3729 SettingBase sb = (SettingBase) pkg.mExtras; 3730 if (sb == null) { 3731 continue; 3732 } 3733 PermissionsState permissionsState = sb.getPermissionsState(); 3734 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3735 userId, flagMask, flagValues); 3736 } 3737 if (changed) { 3738 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3739 } 3740 } 3741 } 3742 3743 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3744 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3745 != PackageManager.PERMISSION_GRANTED 3746 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3747 != PackageManager.PERMISSION_GRANTED) { 3748 throw new SecurityException(message + " requires " 3749 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3750 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3751 } 3752 } 3753 3754 @Override 3755 public boolean shouldShowRequestPermissionRationale(String permissionName, 3756 String packageName, int userId) { 3757 if (UserHandle.getCallingUserId() != userId) { 3758 mContext.enforceCallingPermission( 3759 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3760 "canShowRequestPermissionRationale for user " + userId); 3761 } 3762 3763 final int uid = getPackageUid(packageName, userId); 3764 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3765 return false; 3766 } 3767 3768 if (checkPermission(permissionName, packageName, userId) 3769 == PackageManager.PERMISSION_GRANTED) { 3770 return false; 3771 } 3772 3773 final int flags; 3774 3775 final long identity = Binder.clearCallingIdentity(); 3776 try { 3777 flags = getPermissionFlags(permissionName, 3778 packageName, userId); 3779 } finally { 3780 Binder.restoreCallingIdentity(identity); 3781 } 3782 3783 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3784 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3785 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3786 3787 if ((flags & fixedFlags) != 0) { 3788 return false; 3789 } 3790 3791 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3792 } 3793 3794 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3795 BasePermission bp = mSettings.mPermissions.get(permission); 3796 if (bp == null) { 3797 throw new SecurityException("Missing " + permission + " permission"); 3798 } 3799 3800 SettingBase sb = (SettingBase) pkg.mExtras; 3801 PermissionsState permissionsState = sb.getPermissionsState(); 3802 3803 if (permissionsState.grantInstallPermission(bp) != 3804 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3805 scheduleWriteSettingsLocked(); 3806 } 3807 } 3808 3809 @Override 3810 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3811 mContext.enforceCallingOrSelfPermission( 3812 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3813 "addOnPermissionsChangeListener"); 3814 3815 synchronized (mPackages) { 3816 mOnPermissionChangeListeners.addListenerLocked(listener); 3817 } 3818 } 3819 3820 @Override 3821 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3822 synchronized (mPackages) { 3823 mOnPermissionChangeListeners.removeListenerLocked(listener); 3824 } 3825 } 3826 3827 @Override 3828 public boolean isProtectedBroadcast(String actionName) { 3829 synchronized (mPackages) { 3830 return mProtectedBroadcasts.contains(actionName); 3831 } 3832 } 3833 3834 @Override 3835 public int checkSignatures(String pkg1, String pkg2) { 3836 synchronized (mPackages) { 3837 final PackageParser.Package p1 = mPackages.get(pkg1); 3838 final PackageParser.Package p2 = mPackages.get(pkg2); 3839 if (p1 == null || p1.mExtras == null 3840 || p2 == null || p2.mExtras == null) { 3841 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3842 } 3843 return compareSignatures(p1.mSignatures, p2.mSignatures); 3844 } 3845 } 3846 3847 @Override 3848 public int checkUidSignatures(int uid1, int uid2) { 3849 // Map to base uids. 3850 uid1 = UserHandle.getAppId(uid1); 3851 uid2 = UserHandle.getAppId(uid2); 3852 // reader 3853 synchronized (mPackages) { 3854 Signature[] s1; 3855 Signature[] s2; 3856 Object obj = mSettings.getUserIdLPr(uid1); 3857 if (obj != null) { 3858 if (obj instanceof SharedUserSetting) { 3859 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3860 } else if (obj instanceof PackageSetting) { 3861 s1 = ((PackageSetting)obj).signatures.mSignatures; 3862 } else { 3863 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3864 } 3865 } else { 3866 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3867 } 3868 obj = mSettings.getUserIdLPr(uid2); 3869 if (obj != null) { 3870 if (obj instanceof SharedUserSetting) { 3871 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3872 } else if (obj instanceof PackageSetting) { 3873 s2 = ((PackageSetting)obj).signatures.mSignatures; 3874 } else { 3875 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3876 } 3877 } else { 3878 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3879 } 3880 return compareSignatures(s1, s2); 3881 } 3882 } 3883 3884 private void killUid(int appId, int userId, String reason) { 3885 final long identity = Binder.clearCallingIdentity(); 3886 try { 3887 IActivityManager am = ActivityManagerNative.getDefault(); 3888 if (am != null) { 3889 try { 3890 am.killUid(appId, userId, reason); 3891 } catch (RemoteException e) { 3892 /* ignore - same process */ 3893 } 3894 } 3895 } finally { 3896 Binder.restoreCallingIdentity(identity); 3897 } 3898 } 3899 3900 /** 3901 * Compares two sets of signatures. Returns: 3902 * <br /> 3903 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3904 * <br /> 3905 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3906 * <br /> 3907 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3908 * <br /> 3909 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3910 * <br /> 3911 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3912 */ 3913 static int compareSignatures(Signature[] s1, Signature[] s2) { 3914 if (s1 == null) { 3915 return s2 == null 3916 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3917 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3918 } 3919 3920 if (s2 == null) { 3921 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3922 } 3923 3924 if (s1.length != s2.length) { 3925 return PackageManager.SIGNATURE_NO_MATCH; 3926 } 3927 3928 // Since both signature sets are of size 1, we can compare without HashSets. 3929 if (s1.length == 1) { 3930 return s1[0].equals(s2[0]) ? 3931 PackageManager.SIGNATURE_MATCH : 3932 PackageManager.SIGNATURE_NO_MATCH; 3933 } 3934 3935 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3936 for (Signature sig : s1) { 3937 set1.add(sig); 3938 } 3939 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3940 for (Signature sig : s2) { 3941 set2.add(sig); 3942 } 3943 // Make sure s2 contains all signatures in s1. 3944 if (set1.equals(set2)) { 3945 return PackageManager.SIGNATURE_MATCH; 3946 } 3947 return PackageManager.SIGNATURE_NO_MATCH; 3948 } 3949 3950 /** 3951 * If the database version for this type of package (internal storage or 3952 * external storage) is less than the version where package signatures 3953 * were updated, return true. 3954 */ 3955 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3956 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 3957 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 3958 } 3959 3960 /** 3961 * Used for backward compatibility to make sure any packages with 3962 * certificate chains get upgraded to the new style. {@code existingSigs} 3963 * will be in the old format (since they were stored on disk from before the 3964 * system upgrade) and {@code scannedSigs} will be in the newer format. 3965 */ 3966 private int compareSignaturesCompat(PackageSignatures existingSigs, 3967 PackageParser.Package scannedPkg) { 3968 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3969 return PackageManager.SIGNATURE_NO_MATCH; 3970 } 3971 3972 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3973 for (Signature sig : existingSigs.mSignatures) { 3974 existingSet.add(sig); 3975 } 3976 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3977 for (Signature sig : scannedPkg.mSignatures) { 3978 try { 3979 Signature[] chainSignatures = sig.getChainSignatures(); 3980 for (Signature chainSig : chainSignatures) { 3981 scannedCompatSet.add(chainSig); 3982 } 3983 } catch (CertificateEncodingException e) { 3984 scannedCompatSet.add(sig); 3985 } 3986 } 3987 /* 3988 * Make sure the expanded scanned set contains all signatures in the 3989 * existing one. 3990 */ 3991 if (scannedCompatSet.equals(existingSet)) { 3992 // Migrate the old signatures to the new scheme. 3993 existingSigs.assignSignatures(scannedPkg.mSignatures); 3994 // The new KeySets will be re-added later in the scanning process. 3995 synchronized (mPackages) { 3996 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3997 } 3998 return PackageManager.SIGNATURE_MATCH; 3999 } 4000 return PackageManager.SIGNATURE_NO_MATCH; 4001 } 4002 4003 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4004 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4005 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4006 } 4007 4008 private int compareSignaturesRecover(PackageSignatures existingSigs, 4009 PackageParser.Package scannedPkg) { 4010 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4011 return PackageManager.SIGNATURE_NO_MATCH; 4012 } 4013 4014 String msg = null; 4015 try { 4016 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4017 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4018 + scannedPkg.packageName); 4019 return PackageManager.SIGNATURE_MATCH; 4020 } 4021 } catch (CertificateException e) { 4022 msg = e.getMessage(); 4023 } 4024 4025 logCriticalInfo(Log.INFO, 4026 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4027 return PackageManager.SIGNATURE_NO_MATCH; 4028 } 4029 4030 @Override 4031 public String[] getPackagesForUid(int uid) { 4032 uid = UserHandle.getAppId(uid); 4033 // reader 4034 synchronized (mPackages) { 4035 Object obj = mSettings.getUserIdLPr(uid); 4036 if (obj instanceof SharedUserSetting) { 4037 final SharedUserSetting sus = (SharedUserSetting) obj; 4038 final int N = sus.packages.size(); 4039 final String[] res = new String[N]; 4040 final Iterator<PackageSetting> it = sus.packages.iterator(); 4041 int i = 0; 4042 while (it.hasNext()) { 4043 res[i++] = it.next().name; 4044 } 4045 return res; 4046 } else if (obj instanceof PackageSetting) { 4047 final PackageSetting ps = (PackageSetting) obj; 4048 return new String[] { ps.name }; 4049 } 4050 } 4051 return null; 4052 } 4053 4054 @Override 4055 public String getNameForUid(int uid) { 4056 // reader 4057 synchronized (mPackages) { 4058 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4059 if (obj instanceof SharedUserSetting) { 4060 final SharedUserSetting sus = (SharedUserSetting) obj; 4061 return sus.name + ":" + sus.userId; 4062 } else if (obj instanceof PackageSetting) { 4063 final PackageSetting ps = (PackageSetting) obj; 4064 return ps.name; 4065 } 4066 } 4067 return null; 4068 } 4069 4070 @Override 4071 public int getUidForSharedUser(String sharedUserName) { 4072 if(sharedUserName == null) { 4073 return -1; 4074 } 4075 // reader 4076 synchronized (mPackages) { 4077 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4078 if (suid == null) { 4079 return -1; 4080 } 4081 return suid.userId; 4082 } 4083 } 4084 4085 @Override 4086 public int getFlagsForUid(int uid) { 4087 synchronized (mPackages) { 4088 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4089 if (obj instanceof SharedUserSetting) { 4090 final SharedUserSetting sus = (SharedUserSetting) obj; 4091 return sus.pkgFlags; 4092 } else if (obj instanceof PackageSetting) { 4093 final PackageSetting ps = (PackageSetting) obj; 4094 return ps.pkgFlags; 4095 } 4096 } 4097 return 0; 4098 } 4099 4100 @Override 4101 public int getPrivateFlagsForUid(int uid) { 4102 synchronized (mPackages) { 4103 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4104 if (obj instanceof SharedUserSetting) { 4105 final SharedUserSetting sus = (SharedUserSetting) obj; 4106 return sus.pkgPrivateFlags; 4107 } else if (obj instanceof PackageSetting) { 4108 final PackageSetting ps = (PackageSetting) obj; 4109 return ps.pkgPrivateFlags; 4110 } 4111 } 4112 return 0; 4113 } 4114 4115 @Override 4116 public boolean isUidPrivileged(int uid) { 4117 uid = UserHandle.getAppId(uid); 4118 // reader 4119 synchronized (mPackages) { 4120 Object obj = mSettings.getUserIdLPr(uid); 4121 if (obj instanceof SharedUserSetting) { 4122 final SharedUserSetting sus = (SharedUserSetting) obj; 4123 final Iterator<PackageSetting> it = sus.packages.iterator(); 4124 while (it.hasNext()) { 4125 if (it.next().isPrivileged()) { 4126 return true; 4127 } 4128 } 4129 } else if (obj instanceof PackageSetting) { 4130 final PackageSetting ps = (PackageSetting) obj; 4131 return ps.isPrivileged(); 4132 } 4133 } 4134 return false; 4135 } 4136 4137 @Override 4138 public String[] getAppOpPermissionPackages(String permissionName) { 4139 synchronized (mPackages) { 4140 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4141 if (pkgs == null) { 4142 return null; 4143 } 4144 return pkgs.toArray(new String[pkgs.size()]); 4145 } 4146 } 4147 4148 @Override 4149 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4150 int flags, int userId) { 4151 if (!sUserManager.exists(userId)) return null; 4152 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4153 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4154 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4155 } 4156 4157 @Override 4158 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4159 IntentFilter filter, int match, ComponentName activity) { 4160 final int userId = UserHandle.getCallingUserId(); 4161 if (DEBUG_PREFERRED) { 4162 Log.v(TAG, "setLastChosenActivity intent=" + intent 4163 + " resolvedType=" + resolvedType 4164 + " flags=" + flags 4165 + " filter=" + filter 4166 + " match=" + match 4167 + " activity=" + activity); 4168 filter.dump(new PrintStreamPrinter(System.out), " "); 4169 } 4170 intent.setComponent(null); 4171 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4172 // Find any earlier preferred or last chosen entries and nuke them 4173 findPreferredActivity(intent, resolvedType, 4174 flags, query, 0, false, true, false, userId); 4175 // Add the new activity as the last chosen for this filter 4176 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4177 "Setting last chosen"); 4178 } 4179 4180 @Override 4181 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4182 final int userId = UserHandle.getCallingUserId(); 4183 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4184 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4185 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4186 false, false, false, userId); 4187 } 4188 4189 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4190 int flags, List<ResolveInfo> query, int userId) { 4191 if (query != null) { 4192 final int N = query.size(); 4193 if (N == 1) { 4194 return query.get(0); 4195 } else if (N > 1) { 4196 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4197 // If there is more than one activity with the same priority, 4198 // then let the user decide between them. 4199 ResolveInfo r0 = query.get(0); 4200 ResolveInfo r1 = query.get(1); 4201 if (DEBUG_INTENT_MATCHING || debug) { 4202 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4203 + r1.activityInfo.name + "=" + r1.priority); 4204 } 4205 // If the first activity has a higher priority, or a different 4206 // default, then it is always desireable to pick it. 4207 if (r0.priority != r1.priority 4208 || r0.preferredOrder != r1.preferredOrder 4209 || r0.isDefault != r1.isDefault) { 4210 return query.get(0); 4211 } 4212 // If we have saved a preference for a preferred activity for 4213 // this Intent, use that. 4214 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4215 flags, query, r0.priority, true, false, debug, userId); 4216 if (ri != null) { 4217 return ri; 4218 } 4219 if (userId != 0) { 4220 ri = new ResolveInfo(mResolveInfo); 4221 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4222 ri.activityInfo.applicationInfo = new ApplicationInfo( 4223 ri.activityInfo.applicationInfo); 4224 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4225 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4226 return ri; 4227 } 4228 return mResolveInfo; 4229 } 4230 } 4231 return null; 4232 } 4233 4234 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4235 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4236 final int N = query.size(); 4237 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4238 .get(userId); 4239 // Get the list of persistent preferred activities that handle the intent 4240 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4241 List<PersistentPreferredActivity> pprefs = ppir != null 4242 ? ppir.queryIntent(intent, resolvedType, 4243 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4244 : null; 4245 if (pprefs != null && pprefs.size() > 0) { 4246 final int M = pprefs.size(); 4247 for (int i=0; i<M; i++) { 4248 final PersistentPreferredActivity ppa = pprefs.get(i); 4249 if (DEBUG_PREFERRED || debug) { 4250 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4251 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4252 + "\n component=" + ppa.mComponent); 4253 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4254 } 4255 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4256 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4257 if (DEBUG_PREFERRED || debug) { 4258 Slog.v(TAG, "Found persistent preferred activity:"); 4259 if (ai != null) { 4260 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4261 } else { 4262 Slog.v(TAG, " null"); 4263 } 4264 } 4265 if (ai == null) { 4266 // This previously registered persistent preferred activity 4267 // component is no longer known. Ignore it and do NOT remove it. 4268 continue; 4269 } 4270 for (int j=0; j<N; j++) { 4271 final ResolveInfo ri = query.get(j); 4272 if (!ri.activityInfo.applicationInfo.packageName 4273 .equals(ai.applicationInfo.packageName)) { 4274 continue; 4275 } 4276 if (!ri.activityInfo.name.equals(ai.name)) { 4277 continue; 4278 } 4279 // Found a persistent preference that can handle the intent. 4280 if (DEBUG_PREFERRED || debug) { 4281 Slog.v(TAG, "Returning persistent preferred activity: " + 4282 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4283 } 4284 return ri; 4285 } 4286 } 4287 } 4288 return null; 4289 } 4290 4291 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4292 List<ResolveInfo> query, int priority, boolean always, 4293 boolean removeMatches, boolean debug, int userId) { 4294 if (!sUserManager.exists(userId)) return null; 4295 // writer 4296 synchronized (mPackages) { 4297 if (intent.getSelector() != null) { 4298 intent = intent.getSelector(); 4299 } 4300 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4301 4302 // Try to find a matching persistent preferred activity. 4303 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4304 debug, userId); 4305 4306 // If a persistent preferred activity matched, use it. 4307 if (pri != null) { 4308 return pri; 4309 } 4310 4311 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4312 // Get the list of preferred activities that handle the intent 4313 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4314 List<PreferredActivity> prefs = pir != null 4315 ? pir.queryIntent(intent, resolvedType, 4316 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4317 : null; 4318 if (prefs != null && prefs.size() > 0) { 4319 boolean changed = false; 4320 try { 4321 // First figure out how good the original match set is. 4322 // We will only allow preferred activities that came 4323 // from the same match quality. 4324 int match = 0; 4325 4326 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4327 4328 final int N = query.size(); 4329 for (int j=0; j<N; j++) { 4330 final ResolveInfo ri = query.get(j); 4331 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4332 + ": 0x" + Integer.toHexString(match)); 4333 if (ri.match > match) { 4334 match = ri.match; 4335 } 4336 } 4337 4338 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4339 + Integer.toHexString(match)); 4340 4341 match &= IntentFilter.MATCH_CATEGORY_MASK; 4342 final int M = prefs.size(); 4343 for (int i=0; i<M; i++) { 4344 final PreferredActivity pa = prefs.get(i); 4345 if (DEBUG_PREFERRED || debug) { 4346 Slog.v(TAG, "Checking PreferredActivity ds=" 4347 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4348 + "\n component=" + pa.mPref.mComponent); 4349 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4350 } 4351 if (pa.mPref.mMatch != match) { 4352 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4353 + Integer.toHexString(pa.mPref.mMatch)); 4354 continue; 4355 } 4356 // If it's not an "always" type preferred activity and that's what we're 4357 // looking for, skip it. 4358 if (always && !pa.mPref.mAlways) { 4359 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4360 continue; 4361 } 4362 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4363 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4364 if (DEBUG_PREFERRED || debug) { 4365 Slog.v(TAG, "Found preferred activity:"); 4366 if (ai != null) { 4367 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4368 } else { 4369 Slog.v(TAG, " null"); 4370 } 4371 } 4372 if (ai == null) { 4373 // This previously registered preferred activity 4374 // component is no longer known. Most likely an update 4375 // to the app was installed and in the new version this 4376 // component no longer exists. Clean it up by removing 4377 // it from the preferred activities list, and skip it. 4378 Slog.w(TAG, "Removing dangling preferred activity: " 4379 + pa.mPref.mComponent); 4380 pir.removeFilter(pa); 4381 changed = true; 4382 continue; 4383 } 4384 for (int j=0; j<N; j++) { 4385 final ResolveInfo ri = query.get(j); 4386 if (!ri.activityInfo.applicationInfo.packageName 4387 .equals(ai.applicationInfo.packageName)) { 4388 continue; 4389 } 4390 if (!ri.activityInfo.name.equals(ai.name)) { 4391 continue; 4392 } 4393 4394 if (removeMatches) { 4395 pir.removeFilter(pa); 4396 changed = true; 4397 if (DEBUG_PREFERRED) { 4398 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4399 } 4400 break; 4401 } 4402 4403 // Okay we found a previously set preferred or last chosen app. 4404 // If the result set is different from when this 4405 // was created, we need to clear it and re-ask the 4406 // user their preference, if we're looking for an "always" type entry. 4407 if (always && !pa.mPref.sameSet(query)) { 4408 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4409 + intent + " type " + resolvedType); 4410 if (DEBUG_PREFERRED) { 4411 Slog.v(TAG, "Removing preferred activity since set changed " 4412 + pa.mPref.mComponent); 4413 } 4414 pir.removeFilter(pa); 4415 // Re-add the filter as a "last chosen" entry (!always) 4416 PreferredActivity lastChosen = new PreferredActivity( 4417 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4418 pir.addFilter(lastChosen); 4419 changed = true; 4420 return null; 4421 } 4422 4423 // Yay! Either the set matched or we're looking for the last chosen 4424 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4425 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4426 return ri; 4427 } 4428 } 4429 } finally { 4430 if (changed) { 4431 if (DEBUG_PREFERRED) { 4432 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4433 } 4434 scheduleWritePackageRestrictionsLocked(userId); 4435 } 4436 } 4437 } 4438 } 4439 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4440 return null; 4441 } 4442 4443 /* 4444 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4445 */ 4446 @Override 4447 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4448 int targetUserId) { 4449 mContext.enforceCallingOrSelfPermission( 4450 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4451 List<CrossProfileIntentFilter> matches = 4452 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4453 if (matches != null) { 4454 int size = matches.size(); 4455 for (int i = 0; i < size; i++) { 4456 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4457 } 4458 } 4459 if (hasWebURI(intent)) { 4460 // cross-profile app linking works only towards the parent. 4461 final UserInfo parent = getProfileParent(sourceUserId); 4462 synchronized(mPackages) { 4463 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4464 intent, resolvedType, 0, sourceUserId, parent.id); 4465 return xpDomainInfo != null; 4466 } 4467 } 4468 return false; 4469 } 4470 4471 private UserInfo getProfileParent(int userId) { 4472 final long identity = Binder.clearCallingIdentity(); 4473 try { 4474 return sUserManager.getProfileParent(userId); 4475 } finally { 4476 Binder.restoreCallingIdentity(identity); 4477 } 4478 } 4479 4480 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4481 String resolvedType, int userId) { 4482 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4483 if (resolver != null) { 4484 return resolver.queryIntent(intent, resolvedType, false, userId); 4485 } 4486 return null; 4487 } 4488 4489 @Override 4490 public List<ResolveInfo> queryIntentActivities(Intent intent, 4491 String resolvedType, int flags, int userId) { 4492 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4493 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4494 ComponentName comp = intent.getComponent(); 4495 if (comp == null) { 4496 if (intent.getSelector() != null) { 4497 intent = intent.getSelector(); 4498 comp = intent.getComponent(); 4499 } 4500 } 4501 4502 if (comp != null) { 4503 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4504 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4505 if (ai != null) { 4506 final ResolveInfo ri = new ResolveInfo(); 4507 ri.activityInfo = ai; 4508 list.add(ri); 4509 } 4510 return list; 4511 } 4512 4513 // reader 4514 synchronized (mPackages) { 4515 final String pkgName = intent.getPackage(); 4516 if (pkgName == null) { 4517 List<CrossProfileIntentFilter> matchingFilters = 4518 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4519 // Check for results that need to skip the current profile. 4520 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4521 resolvedType, flags, userId); 4522 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4523 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4524 result.add(xpResolveInfo); 4525 return filterIfNotPrimaryUser(result, userId); 4526 } 4527 4528 // Check for results in the current profile. 4529 List<ResolveInfo> result = mActivities.queryIntent( 4530 intent, resolvedType, flags, userId); 4531 4532 // Check for cross profile results. 4533 xpResolveInfo = queryCrossProfileIntents( 4534 matchingFilters, intent, resolvedType, flags, userId); 4535 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4536 result.add(xpResolveInfo); 4537 Collections.sort(result, mResolvePrioritySorter); 4538 } 4539 result = filterIfNotPrimaryUser(result, userId); 4540 if (hasWebURI(intent)) { 4541 CrossProfileDomainInfo xpDomainInfo = null; 4542 final UserInfo parent = getProfileParent(userId); 4543 if (parent != null) { 4544 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4545 flags, userId, parent.id); 4546 } 4547 if (xpDomainInfo != null) { 4548 if (xpResolveInfo != null) { 4549 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4550 // in the result. 4551 result.remove(xpResolveInfo); 4552 } 4553 if (result.size() == 0) { 4554 result.add(xpDomainInfo.resolveInfo); 4555 return result; 4556 } 4557 } else if (result.size() <= 1) { 4558 return result; 4559 } 4560 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4561 xpDomainInfo, userId); 4562 Collections.sort(result, mResolvePrioritySorter); 4563 } 4564 return result; 4565 } 4566 final PackageParser.Package pkg = mPackages.get(pkgName); 4567 if (pkg != null) { 4568 return filterIfNotPrimaryUser( 4569 mActivities.queryIntentForPackage( 4570 intent, resolvedType, flags, pkg.activities, userId), 4571 userId); 4572 } 4573 return new ArrayList<ResolveInfo>(); 4574 } 4575 } 4576 4577 private static class CrossProfileDomainInfo { 4578 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4579 ResolveInfo resolveInfo; 4580 /* Best domain verification status of the activities found in the other profile */ 4581 int bestDomainVerificationStatus; 4582 } 4583 4584 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4585 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4586 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4587 sourceUserId)) { 4588 return null; 4589 } 4590 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4591 resolvedType, flags, parentUserId); 4592 4593 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4594 return null; 4595 } 4596 CrossProfileDomainInfo result = null; 4597 int size = resultTargetUser.size(); 4598 for (int i = 0; i < size; i++) { 4599 ResolveInfo riTargetUser = resultTargetUser.get(i); 4600 // Intent filter verification is only for filters that specify a host. So don't return 4601 // those that handle all web uris. 4602 if (riTargetUser.handleAllWebDataURI) { 4603 continue; 4604 } 4605 String packageName = riTargetUser.activityInfo.packageName; 4606 PackageSetting ps = mSettings.mPackages.get(packageName); 4607 if (ps == null) { 4608 continue; 4609 } 4610 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4611 int status = (int)(verificationState >> 32); 4612 if (result == null) { 4613 result = new CrossProfileDomainInfo(); 4614 result.resolveInfo = 4615 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4616 result.bestDomainVerificationStatus = status; 4617 } else { 4618 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4619 result.bestDomainVerificationStatus); 4620 } 4621 } 4622 // Don't consider matches with status NEVER across profiles. 4623 if (result != null && result.bestDomainVerificationStatus 4624 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4625 return null; 4626 } 4627 return result; 4628 } 4629 4630 /** 4631 * Verification statuses are ordered from the worse to the best, except for 4632 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4633 */ 4634 private int bestDomainVerificationStatus(int status1, int status2) { 4635 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4636 return status2; 4637 } 4638 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4639 return status1; 4640 } 4641 return (int) MathUtils.max(status1, status2); 4642 } 4643 4644 private boolean isUserEnabled(int userId) { 4645 long callingId = Binder.clearCallingIdentity(); 4646 try { 4647 UserInfo userInfo = sUserManager.getUserInfo(userId); 4648 return userInfo != null && userInfo.isEnabled(); 4649 } finally { 4650 Binder.restoreCallingIdentity(callingId); 4651 } 4652 } 4653 4654 /** 4655 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4656 * 4657 * @return filtered list 4658 */ 4659 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4660 if (userId == UserHandle.USER_OWNER) { 4661 return resolveInfos; 4662 } 4663 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4664 ResolveInfo info = resolveInfos.get(i); 4665 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4666 resolveInfos.remove(i); 4667 } 4668 } 4669 return resolveInfos; 4670 } 4671 4672 private static boolean hasWebURI(Intent intent) { 4673 if (intent.getData() == null) { 4674 return false; 4675 } 4676 final String scheme = intent.getScheme(); 4677 if (TextUtils.isEmpty(scheme)) { 4678 return false; 4679 } 4680 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4681 } 4682 4683 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4684 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4685 int userId) { 4686 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4687 4688 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4689 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4690 candidates.size()); 4691 } 4692 4693 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4694 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4695 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4696 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4697 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4698 4699 synchronized (mPackages) { 4700 final int count = candidates.size(); 4701 // First, try to use linked apps. Partition the candidates into four lists: 4702 // one for the final results, one for the "do not use ever", one for "undefined status" 4703 // and finally one for "browser app type". 4704 for (int n=0; n<count; n++) { 4705 ResolveInfo info = candidates.get(n); 4706 String packageName = info.activityInfo.packageName; 4707 PackageSetting ps = mSettings.mPackages.get(packageName); 4708 if (ps != null) { 4709 // Add to the special match all list (Browser use case) 4710 if (info.handleAllWebDataURI) { 4711 matchAllList.add(info); 4712 continue; 4713 } 4714 // Try to get the status from User settings first 4715 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4716 int status = (int)(packedStatus >> 32); 4717 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4718 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4719 if (DEBUG_DOMAIN_VERIFICATION) { 4720 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4721 + " : linkgen=" + linkGeneration); 4722 } 4723 // Use link-enabled generation as preferredOrder, i.e. 4724 // prefer newly-enabled over earlier-enabled. 4725 info.preferredOrder = linkGeneration; 4726 alwaysList.add(info); 4727 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4728 if (DEBUG_DOMAIN_VERIFICATION) { 4729 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4730 } 4731 neverList.add(info); 4732 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4733 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4734 if (DEBUG_DOMAIN_VERIFICATION) { 4735 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4736 } 4737 undefinedList.add(info); 4738 } 4739 } 4740 } 4741 // First try to add the "always" resolution(s) for the current user, if any 4742 if (alwaysList.size() > 0) { 4743 result.addAll(alwaysList); 4744 // if there is an "always" for the parent user, add it. 4745 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4746 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4747 result.add(xpDomainInfo.resolveInfo); 4748 } else { 4749 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4750 result.addAll(undefinedList); 4751 if (xpDomainInfo != null && ( 4752 xpDomainInfo.bestDomainVerificationStatus 4753 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4754 || xpDomainInfo.bestDomainVerificationStatus 4755 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4756 result.add(xpDomainInfo.resolveInfo); 4757 } 4758 // Also add Browsers (all of them or only the default one) 4759 if ((matchFlags & MATCH_ALL) != 0) { 4760 result.addAll(matchAllList); 4761 } else { 4762 // Browser/generic handling case. If there's a default browser, go straight 4763 // to that (but only if there is no other higher-priority match). 4764 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4765 int maxMatchPrio = 0; 4766 ResolveInfo defaultBrowserMatch = null; 4767 final int numCandidates = matchAllList.size(); 4768 for (int n = 0; n < numCandidates; n++) { 4769 ResolveInfo info = matchAllList.get(n); 4770 // track the highest overall match priority... 4771 if (info.priority > maxMatchPrio) { 4772 maxMatchPrio = info.priority; 4773 } 4774 // ...and the highest-priority default browser match 4775 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4776 if (defaultBrowserMatch == null 4777 || (defaultBrowserMatch.priority < info.priority)) { 4778 if (debug) { 4779 Slog.v(TAG, "Considering default browser match " + info); 4780 } 4781 defaultBrowserMatch = info; 4782 } 4783 } 4784 } 4785 if (defaultBrowserMatch != null 4786 && defaultBrowserMatch.priority >= maxMatchPrio 4787 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4788 { 4789 if (debug) { 4790 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4791 } 4792 result.add(defaultBrowserMatch); 4793 } else { 4794 result.addAll(matchAllList); 4795 } 4796 } 4797 4798 // If there is nothing selected, add all candidates and remove the ones that the user 4799 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4800 if (result.size() == 0) { 4801 result.addAll(candidates); 4802 result.removeAll(neverList); 4803 } 4804 } 4805 } 4806 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4807 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4808 result.size()); 4809 for (ResolveInfo info : result) { 4810 Slog.v(TAG, " + " + info.activityInfo); 4811 } 4812 } 4813 return result; 4814 } 4815 4816 // Returns a packed value as a long: 4817 // 4818 // high 'int'-sized word: link status: undefined/ask/never/always. 4819 // low 'int'-sized word: relative priority among 'always' results. 4820 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4821 long result = ps.getDomainVerificationStatusForUser(userId); 4822 // if none available, get the master status 4823 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4824 if (ps.getIntentFilterVerificationInfo() != null) { 4825 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4826 } 4827 } 4828 return result; 4829 } 4830 4831 private ResolveInfo querySkipCurrentProfileIntents( 4832 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4833 int flags, int sourceUserId) { 4834 if (matchingFilters != null) { 4835 int size = matchingFilters.size(); 4836 for (int i = 0; i < size; i ++) { 4837 CrossProfileIntentFilter filter = matchingFilters.get(i); 4838 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4839 // Checking if there are activities in the target user that can handle the 4840 // intent. 4841 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4842 flags, sourceUserId); 4843 if (resolveInfo != null) { 4844 return resolveInfo; 4845 } 4846 } 4847 } 4848 } 4849 return null; 4850 } 4851 4852 // Return matching ResolveInfo if any for skip current profile intent filters. 4853 private ResolveInfo queryCrossProfileIntents( 4854 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4855 int flags, int sourceUserId) { 4856 if (matchingFilters != null) { 4857 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4858 // match the same intent. For performance reasons, it is better not to 4859 // run queryIntent twice for the same userId 4860 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4861 int size = matchingFilters.size(); 4862 for (int i = 0; i < size; i++) { 4863 CrossProfileIntentFilter filter = matchingFilters.get(i); 4864 int targetUserId = filter.getTargetUserId(); 4865 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4866 && !alreadyTriedUserIds.get(targetUserId)) { 4867 // Checking if there are activities in the target user that can handle the 4868 // intent. 4869 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4870 flags, sourceUserId); 4871 if (resolveInfo != null) return resolveInfo; 4872 alreadyTriedUserIds.put(targetUserId, true); 4873 } 4874 } 4875 } 4876 return null; 4877 } 4878 4879 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4880 String resolvedType, int flags, int sourceUserId) { 4881 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4882 resolvedType, flags, filter.getTargetUserId()); 4883 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4884 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4885 } 4886 return null; 4887 } 4888 4889 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4890 int sourceUserId, int targetUserId) { 4891 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4892 String className; 4893 if (targetUserId == UserHandle.USER_OWNER) { 4894 className = FORWARD_INTENT_TO_USER_OWNER; 4895 } else { 4896 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4897 } 4898 ComponentName forwardingActivityComponentName = new ComponentName( 4899 mAndroidApplication.packageName, className); 4900 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4901 sourceUserId); 4902 if (targetUserId == UserHandle.USER_OWNER) { 4903 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4904 forwardingResolveInfo.noResourceId = true; 4905 } 4906 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4907 forwardingResolveInfo.priority = 0; 4908 forwardingResolveInfo.preferredOrder = 0; 4909 forwardingResolveInfo.match = 0; 4910 forwardingResolveInfo.isDefault = true; 4911 forwardingResolveInfo.filter = filter; 4912 forwardingResolveInfo.targetUserId = targetUserId; 4913 return forwardingResolveInfo; 4914 } 4915 4916 @Override 4917 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4918 Intent[] specifics, String[] specificTypes, Intent intent, 4919 String resolvedType, int flags, int userId) { 4920 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4921 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4922 false, "query intent activity options"); 4923 final String resultsAction = intent.getAction(); 4924 4925 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4926 | PackageManager.GET_RESOLVED_FILTER, userId); 4927 4928 if (DEBUG_INTENT_MATCHING) { 4929 Log.v(TAG, "Query " + intent + ": " + results); 4930 } 4931 4932 int specificsPos = 0; 4933 int N; 4934 4935 // todo: note that the algorithm used here is O(N^2). This 4936 // isn't a problem in our current environment, but if we start running 4937 // into situations where we have more than 5 or 10 matches then this 4938 // should probably be changed to something smarter... 4939 4940 // First we go through and resolve each of the specific items 4941 // that were supplied, taking care of removing any corresponding 4942 // duplicate items in the generic resolve list. 4943 if (specifics != null) { 4944 for (int i=0; i<specifics.length; i++) { 4945 final Intent sintent = specifics[i]; 4946 if (sintent == null) { 4947 continue; 4948 } 4949 4950 if (DEBUG_INTENT_MATCHING) { 4951 Log.v(TAG, "Specific #" + i + ": " + sintent); 4952 } 4953 4954 String action = sintent.getAction(); 4955 if (resultsAction != null && resultsAction.equals(action)) { 4956 // If this action was explicitly requested, then don't 4957 // remove things that have it. 4958 action = null; 4959 } 4960 4961 ResolveInfo ri = null; 4962 ActivityInfo ai = null; 4963 4964 ComponentName comp = sintent.getComponent(); 4965 if (comp == null) { 4966 ri = resolveIntent( 4967 sintent, 4968 specificTypes != null ? specificTypes[i] : null, 4969 flags, userId); 4970 if (ri == null) { 4971 continue; 4972 } 4973 if (ri == mResolveInfo) { 4974 // ACK! Must do something better with this. 4975 } 4976 ai = ri.activityInfo; 4977 comp = new ComponentName(ai.applicationInfo.packageName, 4978 ai.name); 4979 } else { 4980 ai = getActivityInfo(comp, flags, userId); 4981 if (ai == null) { 4982 continue; 4983 } 4984 } 4985 4986 // Look for any generic query activities that are duplicates 4987 // of this specific one, and remove them from the results. 4988 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4989 N = results.size(); 4990 int j; 4991 for (j=specificsPos; j<N; j++) { 4992 ResolveInfo sri = results.get(j); 4993 if ((sri.activityInfo.name.equals(comp.getClassName()) 4994 && sri.activityInfo.applicationInfo.packageName.equals( 4995 comp.getPackageName())) 4996 || (action != null && sri.filter.matchAction(action))) { 4997 results.remove(j); 4998 if (DEBUG_INTENT_MATCHING) Log.v( 4999 TAG, "Removing duplicate item from " + j 5000 + " due to specific " + specificsPos); 5001 if (ri == null) { 5002 ri = sri; 5003 } 5004 j--; 5005 N--; 5006 } 5007 } 5008 5009 // Add this specific item to its proper place. 5010 if (ri == null) { 5011 ri = new ResolveInfo(); 5012 ri.activityInfo = ai; 5013 } 5014 results.add(specificsPos, ri); 5015 ri.specificIndex = i; 5016 specificsPos++; 5017 } 5018 } 5019 5020 // Now we go through the remaining generic results and remove any 5021 // duplicate actions that are found here. 5022 N = results.size(); 5023 for (int i=specificsPos; i<N-1; i++) { 5024 final ResolveInfo rii = results.get(i); 5025 if (rii.filter == null) { 5026 continue; 5027 } 5028 5029 // Iterate over all of the actions of this result's intent 5030 // filter... typically this should be just one. 5031 final Iterator<String> it = rii.filter.actionsIterator(); 5032 if (it == null) { 5033 continue; 5034 } 5035 while (it.hasNext()) { 5036 final String action = it.next(); 5037 if (resultsAction != null && resultsAction.equals(action)) { 5038 // If this action was explicitly requested, then don't 5039 // remove things that have it. 5040 continue; 5041 } 5042 for (int j=i+1; j<N; j++) { 5043 final ResolveInfo rij = results.get(j); 5044 if (rij.filter != null && rij.filter.hasAction(action)) { 5045 results.remove(j); 5046 if (DEBUG_INTENT_MATCHING) Log.v( 5047 TAG, "Removing duplicate item from " + j 5048 + " due to action " + action + " at " + i); 5049 j--; 5050 N--; 5051 } 5052 } 5053 } 5054 5055 // If the caller didn't request filter information, drop it now 5056 // so we don't have to marshall/unmarshall it. 5057 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5058 rii.filter = null; 5059 } 5060 } 5061 5062 // Filter out the caller activity if so requested. 5063 if (caller != null) { 5064 N = results.size(); 5065 for (int i=0; i<N; i++) { 5066 ActivityInfo ainfo = results.get(i).activityInfo; 5067 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5068 && caller.getClassName().equals(ainfo.name)) { 5069 results.remove(i); 5070 break; 5071 } 5072 } 5073 } 5074 5075 // If the caller didn't request filter information, 5076 // drop them now so we don't have to 5077 // marshall/unmarshall it. 5078 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5079 N = results.size(); 5080 for (int i=0; i<N; i++) { 5081 results.get(i).filter = null; 5082 } 5083 } 5084 5085 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5086 return results; 5087 } 5088 5089 @Override 5090 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5091 int userId) { 5092 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5093 ComponentName comp = intent.getComponent(); 5094 if (comp == null) { 5095 if (intent.getSelector() != null) { 5096 intent = intent.getSelector(); 5097 comp = intent.getComponent(); 5098 } 5099 } 5100 if (comp != null) { 5101 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5102 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5103 if (ai != null) { 5104 ResolveInfo ri = new ResolveInfo(); 5105 ri.activityInfo = ai; 5106 list.add(ri); 5107 } 5108 return list; 5109 } 5110 5111 // reader 5112 synchronized (mPackages) { 5113 String pkgName = intent.getPackage(); 5114 if (pkgName == null) { 5115 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5116 } 5117 final PackageParser.Package pkg = mPackages.get(pkgName); 5118 if (pkg != null) { 5119 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5120 userId); 5121 } 5122 return null; 5123 } 5124 } 5125 5126 @Override 5127 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5128 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5129 if (!sUserManager.exists(userId)) return null; 5130 if (query != null) { 5131 if (query.size() >= 1) { 5132 // If there is more than one service with the same priority, 5133 // just arbitrarily pick the first one. 5134 return query.get(0); 5135 } 5136 } 5137 return null; 5138 } 5139 5140 @Override 5141 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5142 int userId) { 5143 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5144 ComponentName comp = intent.getComponent(); 5145 if (comp == null) { 5146 if (intent.getSelector() != null) { 5147 intent = intent.getSelector(); 5148 comp = intent.getComponent(); 5149 } 5150 } 5151 if (comp != null) { 5152 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5153 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5154 if (si != null) { 5155 final ResolveInfo ri = new ResolveInfo(); 5156 ri.serviceInfo = si; 5157 list.add(ri); 5158 } 5159 return list; 5160 } 5161 5162 // reader 5163 synchronized (mPackages) { 5164 String pkgName = intent.getPackage(); 5165 if (pkgName == null) { 5166 return mServices.queryIntent(intent, resolvedType, flags, userId); 5167 } 5168 final PackageParser.Package pkg = mPackages.get(pkgName); 5169 if (pkg != null) { 5170 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5171 userId); 5172 } 5173 return null; 5174 } 5175 } 5176 5177 @Override 5178 public List<ResolveInfo> queryIntentContentProviders( 5179 Intent intent, String resolvedType, int flags, int userId) { 5180 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5181 ComponentName comp = intent.getComponent(); 5182 if (comp == null) { 5183 if (intent.getSelector() != null) { 5184 intent = intent.getSelector(); 5185 comp = intent.getComponent(); 5186 } 5187 } 5188 if (comp != null) { 5189 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5190 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5191 if (pi != null) { 5192 final ResolveInfo ri = new ResolveInfo(); 5193 ri.providerInfo = pi; 5194 list.add(ri); 5195 } 5196 return list; 5197 } 5198 5199 // reader 5200 synchronized (mPackages) { 5201 String pkgName = intent.getPackage(); 5202 if (pkgName == null) { 5203 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5204 } 5205 final PackageParser.Package pkg = mPackages.get(pkgName); 5206 if (pkg != null) { 5207 return mProviders.queryIntentForPackage( 5208 intent, resolvedType, flags, pkg.providers, userId); 5209 } 5210 return null; 5211 } 5212 } 5213 5214 @Override 5215 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5216 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5217 5218 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5219 5220 // writer 5221 synchronized (mPackages) { 5222 ArrayList<PackageInfo> list; 5223 if (listUninstalled) { 5224 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5225 for (PackageSetting ps : mSettings.mPackages.values()) { 5226 PackageInfo pi; 5227 if (ps.pkg != null) { 5228 pi = generatePackageInfo(ps.pkg, flags, userId); 5229 } else { 5230 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5231 } 5232 if (pi != null) { 5233 list.add(pi); 5234 } 5235 } 5236 } else { 5237 list = new ArrayList<PackageInfo>(mPackages.size()); 5238 for (PackageParser.Package p : mPackages.values()) { 5239 PackageInfo pi = generatePackageInfo(p, flags, userId); 5240 if (pi != null) { 5241 list.add(pi); 5242 } 5243 } 5244 } 5245 5246 return new ParceledListSlice<PackageInfo>(list); 5247 } 5248 } 5249 5250 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5251 String[] permissions, boolean[] tmp, int flags, int userId) { 5252 int numMatch = 0; 5253 final PermissionsState permissionsState = ps.getPermissionsState(); 5254 for (int i=0; i<permissions.length; i++) { 5255 final String permission = permissions[i]; 5256 if (permissionsState.hasPermission(permission, userId)) { 5257 tmp[i] = true; 5258 numMatch++; 5259 } else { 5260 tmp[i] = false; 5261 } 5262 } 5263 if (numMatch == 0) { 5264 return; 5265 } 5266 PackageInfo pi; 5267 if (ps.pkg != null) { 5268 pi = generatePackageInfo(ps.pkg, flags, userId); 5269 } else { 5270 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5271 } 5272 // The above might return null in cases of uninstalled apps or install-state 5273 // skew across users/profiles. 5274 if (pi != null) { 5275 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5276 if (numMatch == permissions.length) { 5277 pi.requestedPermissions = permissions; 5278 } else { 5279 pi.requestedPermissions = new String[numMatch]; 5280 numMatch = 0; 5281 for (int i=0; i<permissions.length; i++) { 5282 if (tmp[i]) { 5283 pi.requestedPermissions[numMatch] = permissions[i]; 5284 numMatch++; 5285 } 5286 } 5287 } 5288 } 5289 list.add(pi); 5290 } 5291 } 5292 5293 @Override 5294 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5295 String[] permissions, int flags, int userId) { 5296 if (!sUserManager.exists(userId)) return null; 5297 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5298 5299 // writer 5300 synchronized (mPackages) { 5301 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5302 boolean[] tmpBools = new boolean[permissions.length]; 5303 if (listUninstalled) { 5304 for (PackageSetting ps : mSettings.mPackages.values()) { 5305 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5306 } 5307 } else { 5308 for (PackageParser.Package pkg : mPackages.values()) { 5309 PackageSetting ps = (PackageSetting)pkg.mExtras; 5310 if (ps != null) { 5311 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5312 userId); 5313 } 5314 } 5315 } 5316 5317 return new ParceledListSlice<PackageInfo>(list); 5318 } 5319 } 5320 5321 @Override 5322 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5323 if (!sUserManager.exists(userId)) return null; 5324 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5325 5326 // writer 5327 synchronized (mPackages) { 5328 ArrayList<ApplicationInfo> list; 5329 if (listUninstalled) { 5330 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5331 for (PackageSetting ps : mSettings.mPackages.values()) { 5332 ApplicationInfo ai; 5333 if (ps.pkg != null) { 5334 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5335 ps.readUserState(userId), userId); 5336 } else { 5337 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5338 } 5339 if (ai != null) { 5340 list.add(ai); 5341 } 5342 } 5343 } else { 5344 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5345 for (PackageParser.Package p : mPackages.values()) { 5346 if (p.mExtras != null) { 5347 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5348 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5349 if (ai != null) { 5350 list.add(ai); 5351 } 5352 } 5353 } 5354 } 5355 5356 return new ParceledListSlice<ApplicationInfo>(list); 5357 } 5358 } 5359 5360 public List<ApplicationInfo> getPersistentApplications(int flags) { 5361 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5362 5363 // reader 5364 synchronized (mPackages) { 5365 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5366 final int userId = UserHandle.getCallingUserId(); 5367 while (i.hasNext()) { 5368 final PackageParser.Package p = i.next(); 5369 if (p.applicationInfo != null 5370 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5371 && (!mSafeMode || isSystemApp(p))) { 5372 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5373 if (ps != null) { 5374 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5375 ps.readUserState(userId), userId); 5376 if (ai != null) { 5377 finalList.add(ai); 5378 } 5379 } 5380 } 5381 } 5382 } 5383 5384 return finalList; 5385 } 5386 5387 @Override 5388 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5389 if (!sUserManager.exists(userId)) return null; 5390 // reader 5391 synchronized (mPackages) { 5392 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5393 PackageSetting ps = provider != null 5394 ? mSettings.mPackages.get(provider.owner.packageName) 5395 : null; 5396 return ps != null 5397 && mSettings.isEnabledLPr(provider.info, flags, userId) 5398 && (!mSafeMode || (provider.info.applicationInfo.flags 5399 &ApplicationInfo.FLAG_SYSTEM) != 0) 5400 ? PackageParser.generateProviderInfo(provider, flags, 5401 ps.readUserState(userId), userId) 5402 : null; 5403 } 5404 } 5405 5406 /** 5407 * @deprecated 5408 */ 5409 @Deprecated 5410 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5411 // reader 5412 synchronized (mPackages) { 5413 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5414 .entrySet().iterator(); 5415 final int userId = UserHandle.getCallingUserId(); 5416 while (i.hasNext()) { 5417 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5418 PackageParser.Provider p = entry.getValue(); 5419 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5420 5421 if (ps != null && p.syncable 5422 && (!mSafeMode || (p.info.applicationInfo.flags 5423 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5424 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5425 ps.readUserState(userId), userId); 5426 if (info != null) { 5427 outNames.add(entry.getKey()); 5428 outInfo.add(info); 5429 } 5430 } 5431 } 5432 } 5433 } 5434 5435 @Override 5436 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5437 int uid, int flags) { 5438 ArrayList<ProviderInfo> finalList = null; 5439 // reader 5440 synchronized (mPackages) { 5441 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5442 final int userId = processName != null ? 5443 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5444 while (i.hasNext()) { 5445 final PackageParser.Provider p = i.next(); 5446 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5447 if (ps != null && p.info.authority != null 5448 && (processName == null 5449 || (p.info.processName.equals(processName) 5450 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5451 && mSettings.isEnabledLPr(p.info, flags, userId) 5452 && (!mSafeMode 5453 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5454 if (finalList == null) { 5455 finalList = new ArrayList<ProviderInfo>(3); 5456 } 5457 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5458 ps.readUserState(userId), userId); 5459 if (info != null) { 5460 finalList.add(info); 5461 } 5462 } 5463 } 5464 } 5465 5466 if (finalList != null) { 5467 Collections.sort(finalList, mProviderInitOrderSorter); 5468 return new ParceledListSlice<ProviderInfo>(finalList); 5469 } 5470 5471 return null; 5472 } 5473 5474 @Override 5475 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5476 int flags) { 5477 // reader 5478 synchronized (mPackages) { 5479 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5480 return PackageParser.generateInstrumentationInfo(i, flags); 5481 } 5482 } 5483 5484 @Override 5485 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5486 int flags) { 5487 ArrayList<InstrumentationInfo> finalList = 5488 new ArrayList<InstrumentationInfo>(); 5489 5490 // reader 5491 synchronized (mPackages) { 5492 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5493 while (i.hasNext()) { 5494 final PackageParser.Instrumentation p = i.next(); 5495 if (targetPackage == null 5496 || targetPackage.equals(p.info.targetPackage)) { 5497 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5498 flags); 5499 if (ii != null) { 5500 finalList.add(ii); 5501 } 5502 } 5503 } 5504 } 5505 5506 return finalList; 5507 } 5508 5509 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5510 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5511 if (overlays == null) { 5512 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5513 return; 5514 } 5515 for (PackageParser.Package opkg : overlays.values()) { 5516 // Not much to do if idmap fails: we already logged the error 5517 // and we certainly don't want to abort installation of pkg simply 5518 // because an overlay didn't fit properly. For these reasons, 5519 // ignore the return value of createIdmapForPackagePairLI. 5520 createIdmapForPackagePairLI(pkg, opkg); 5521 } 5522 } 5523 5524 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5525 PackageParser.Package opkg) { 5526 if (!opkg.mTrustedOverlay) { 5527 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5528 opkg.baseCodePath + ": overlay not trusted"); 5529 return false; 5530 } 5531 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5532 if (overlaySet == null) { 5533 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5534 opkg.baseCodePath + " but target package has no known overlays"); 5535 return false; 5536 } 5537 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5538 // TODO: generate idmap for split APKs 5539 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5540 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5541 + opkg.baseCodePath); 5542 return false; 5543 } 5544 PackageParser.Package[] overlayArray = 5545 overlaySet.values().toArray(new PackageParser.Package[0]); 5546 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5547 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5548 return p1.mOverlayPriority - p2.mOverlayPriority; 5549 } 5550 }; 5551 Arrays.sort(overlayArray, cmp); 5552 5553 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5554 int i = 0; 5555 for (PackageParser.Package p : overlayArray) { 5556 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5557 } 5558 return true; 5559 } 5560 5561 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5562 final File[] files = dir.listFiles(); 5563 if (ArrayUtils.isEmpty(files)) { 5564 Log.d(TAG, "No files in app dir " + dir); 5565 return; 5566 } 5567 5568 if (DEBUG_PACKAGE_SCANNING) { 5569 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5570 + " flags=0x" + Integer.toHexString(parseFlags)); 5571 } 5572 5573 for (File file : files) { 5574 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5575 && !PackageInstallerService.isStageName(file.getName()); 5576 if (!isPackage) { 5577 // Ignore entries which are not packages 5578 continue; 5579 } 5580 try { 5581 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5582 scanFlags, currentTime, null); 5583 } catch (PackageManagerException e) { 5584 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5585 5586 // Delete invalid userdata apps 5587 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5588 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5589 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5590 if (file.isDirectory()) { 5591 mInstaller.rmPackageDir(file.getAbsolutePath()); 5592 } else { 5593 file.delete(); 5594 } 5595 } 5596 } 5597 } 5598 } 5599 5600 private static File getSettingsProblemFile() { 5601 File dataDir = Environment.getDataDirectory(); 5602 File systemDir = new File(dataDir, "system"); 5603 File fname = new File(systemDir, "uiderrors.txt"); 5604 return fname; 5605 } 5606 5607 static void reportSettingsProblem(int priority, String msg) { 5608 logCriticalInfo(priority, msg); 5609 } 5610 5611 static void logCriticalInfo(int priority, String msg) { 5612 Slog.println(priority, TAG, msg); 5613 EventLogTags.writePmCriticalInfo(msg); 5614 try { 5615 File fname = getSettingsProblemFile(); 5616 FileOutputStream out = new FileOutputStream(fname, true); 5617 PrintWriter pw = new FastPrintWriter(out); 5618 SimpleDateFormat formatter = new SimpleDateFormat(); 5619 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5620 pw.println(dateString + ": " + msg); 5621 pw.close(); 5622 FileUtils.setPermissions( 5623 fname.toString(), 5624 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5625 -1, -1); 5626 } catch (java.io.IOException e) { 5627 } 5628 } 5629 5630 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5631 PackageParser.Package pkg, File srcFile, int parseFlags) 5632 throws PackageManagerException { 5633 if (ps != null 5634 && ps.codePath.equals(srcFile) 5635 && ps.timeStamp == srcFile.lastModified() 5636 && !isCompatSignatureUpdateNeeded(pkg) 5637 && !isRecoverSignatureUpdateNeeded(pkg)) { 5638 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5639 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5640 ArraySet<PublicKey> signingKs; 5641 synchronized (mPackages) { 5642 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5643 } 5644 if (ps.signatures.mSignatures != null 5645 && ps.signatures.mSignatures.length != 0 5646 && signingKs != null) { 5647 // Optimization: reuse the existing cached certificates 5648 // if the package appears to be unchanged. 5649 pkg.mSignatures = ps.signatures.mSignatures; 5650 pkg.mSigningKeys = signingKs; 5651 return; 5652 } 5653 5654 Slog.w(TAG, "PackageSetting for " + ps.name 5655 + " is missing signatures. Collecting certs again to recover them."); 5656 } else { 5657 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5658 } 5659 5660 try { 5661 pp.collectCertificates(pkg, parseFlags); 5662 pp.collectManifestDigest(pkg); 5663 } catch (PackageParserException e) { 5664 throw PackageManagerException.from(e); 5665 } 5666 } 5667 5668 /** 5669 * Traces a package scan. 5670 * @see #scanPackageLI(File, int, int, long, UserHandle) 5671 */ 5672 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5673 long currentTime, UserHandle user) throws PackageManagerException { 5674 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5675 try { 5676 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5677 } finally { 5678 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5679 } 5680 } 5681 5682 /** 5683 * Scans a package and returns the newly parsed package. 5684 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5685 */ 5686 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5687 long currentTime, UserHandle user) throws PackageManagerException { 5688 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5689 parseFlags |= mDefParseFlags; 5690 PackageParser pp = new PackageParser(); 5691 pp.setSeparateProcesses(mSeparateProcesses); 5692 pp.setOnlyCoreApps(mOnlyCore); 5693 pp.setDisplayMetrics(mMetrics); 5694 5695 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5696 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5697 } 5698 5699 final PackageParser.Package pkg; 5700 try { 5701 pkg = pp.parsePackage(scanFile, parseFlags); 5702 } catch (PackageParserException e) { 5703 throw PackageManagerException.from(e); 5704 } 5705 5706 PackageSetting ps = null; 5707 PackageSetting updatedPkg; 5708 // reader 5709 synchronized (mPackages) { 5710 // Look to see if we already know about this package. 5711 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5712 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5713 // This package has been renamed to its original name. Let's 5714 // use that. 5715 ps = mSettings.peekPackageLPr(oldName); 5716 } 5717 // If there was no original package, see one for the real package name. 5718 if (ps == null) { 5719 ps = mSettings.peekPackageLPr(pkg.packageName); 5720 } 5721 // Check to see if this package could be hiding/updating a system 5722 // package. Must look for it either under the original or real 5723 // package name depending on our state. 5724 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5725 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5726 } 5727 boolean updatedPkgBetter = false; 5728 // First check if this is a system package that may involve an update 5729 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5730 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5731 // it needs to drop FLAG_PRIVILEGED. 5732 if (locationIsPrivileged(scanFile)) { 5733 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5734 } else { 5735 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5736 } 5737 5738 if (ps != null && !ps.codePath.equals(scanFile)) { 5739 // The path has changed from what was last scanned... check the 5740 // version of the new path against what we have stored to determine 5741 // what to do. 5742 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5743 if (pkg.mVersionCode <= ps.versionCode) { 5744 // The system package has been updated and the code path does not match 5745 // Ignore entry. Skip it. 5746 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5747 + " ignored: updated version " + ps.versionCode 5748 + " better than this " + pkg.mVersionCode); 5749 if (!updatedPkg.codePath.equals(scanFile)) { 5750 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5751 + ps.name + " changing from " + updatedPkg.codePathString 5752 + " to " + scanFile); 5753 updatedPkg.codePath = scanFile; 5754 updatedPkg.codePathString = scanFile.toString(); 5755 updatedPkg.resourcePath = scanFile; 5756 updatedPkg.resourcePathString = scanFile.toString(); 5757 } 5758 updatedPkg.pkg = pkg; 5759 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5760 "Package " + ps.name + " at " + scanFile 5761 + " ignored: updated version " + ps.versionCode 5762 + " better than this " + pkg.mVersionCode); 5763 } else { 5764 // The current app on the system partition is better than 5765 // what we have updated to on the data partition; switch 5766 // back to the system partition version. 5767 // At this point, its safely assumed that package installation for 5768 // apps in system partition will go through. If not there won't be a working 5769 // version of the app 5770 // writer 5771 synchronized (mPackages) { 5772 // Just remove the loaded entries from package lists. 5773 mPackages.remove(ps.name); 5774 } 5775 5776 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5777 + " reverting from " + ps.codePathString 5778 + ": new version " + pkg.mVersionCode 5779 + " better than installed " + ps.versionCode); 5780 5781 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5782 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5783 synchronized (mInstallLock) { 5784 args.cleanUpResourcesLI(); 5785 } 5786 synchronized (mPackages) { 5787 mSettings.enableSystemPackageLPw(ps.name); 5788 } 5789 updatedPkgBetter = true; 5790 } 5791 } 5792 } 5793 5794 if (updatedPkg != null) { 5795 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5796 // initially 5797 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5798 5799 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5800 // flag set initially 5801 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5802 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5803 } 5804 } 5805 5806 // Verify certificates against what was last scanned 5807 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5808 5809 /* 5810 * A new system app appeared, but we already had a non-system one of the 5811 * same name installed earlier. 5812 */ 5813 boolean shouldHideSystemApp = false; 5814 if (updatedPkg == null && ps != null 5815 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5816 /* 5817 * Check to make sure the signatures match first. If they don't, 5818 * wipe the installed application and its data. 5819 */ 5820 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5821 != PackageManager.SIGNATURE_MATCH) { 5822 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5823 + " signatures don't match existing userdata copy; removing"); 5824 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5825 ps = null; 5826 } else { 5827 /* 5828 * If the newly-added system app is an older version than the 5829 * already installed version, hide it. It will be scanned later 5830 * and re-added like an update. 5831 */ 5832 if (pkg.mVersionCode <= ps.versionCode) { 5833 shouldHideSystemApp = true; 5834 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5835 + " but new version " + pkg.mVersionCode + " better than installed " 5836 + ps.versionCode + "; hiding system"); 5837 } else { 5838 /* 5839 * The newly found system app is a newer version that the 5840 * one previously installed. Simply remove the 5841 * already-installed application and replace it with our own 5842 * while keeping the application data. 5843 */ 5844 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5845 + " reverting from " + ps.codePathString + ": new version " 5846 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5847 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5848 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5849 synchronized (mInstallLock) { 5850 args.cleanUpResourcesLI(); 5851 } 5852 } 5853 } 5854 } 5855 5856 // The apk is forward locked (not public) if its code and resources 5857 // are kept in different files. (except for app in either system or 5858 // vendor path). 5859 // TODO grab this value from PackageSettings 5860 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5861 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5862 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5863 } 5864 } 5865 5866 // TODO: extend to support forward-locked splits 5867 String resourcePath = null; 5868 String baseResourcePath = null; 5869 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5870 if (ps != null && ps.resourcePathString != null) { 5871 resourcePath = ps.resourcePathString; 5872 baseResourcePath = ps.resourcePathString; 5873 } else { 5874 // Should not happen at all. Just log an error. 5875 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5876 } 5877 } else { 5878 resourcePath = pkg.codePath; 5879 baseResourcePath = pkg.baseCodePath; 5880 } 5881 5882 // Set application objects path explicitly. 5883 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5884 pkg.applicationInfo.setCodePath(pkg.codePath); 5885 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5886 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5887 pkg.applicationInfo.setResourcePath(resourcePath); 5888 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5889 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5890 5891 // Note that we invoke the following method only if we are about to unpack an application 5892 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5893 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5894 5895 /* 5896 * If the system app should be overridden by a previously installed 5897 * data, hide the system app now and let the /data/app scan pick it up 5898 * again. 5899 */ 5900 if (shouldHideSystemApp) { 5901 synchronized (mPackages) { 5902 /* 5903 * We have to grant systems permissions before we hide, because 5904 * grantPermissions will assume the package update is trying to 5905 * expand its permissions. 5906 */ 5907 grantPermissionsLPw(pkg, true, pkg.packageName); 5908 mSettings.disableSystemPackageLPw(pkg.packageName); 5909 } 5910 } 5911 5912 return scannedPkg; 5913 } 5914 5915 private static String fixProcessName(String defProcessName, 5916 String processName, int uid) { 5917 if (processName == null) { 5918 return defProcessName; 5919 } 5920 return processName; 5921 } 5922 5923 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5924 throws PackageManagerException { 5925 if (pkgSetting.signatures.mSignatures != null) { 5926 // Already existing package. Make sure signatures match 5927 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5928 == PackageManager.SIGNATURE_MATCH; 5929 if (!match) { 5930 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5931 == PackageManager.SIGNATURE_MATCH; 5932 } 5933 if (!match) { 5934 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5935 == PackageManager.SIGNATURE_MATCH; 5936 } 5937 if (!match) { 5938 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5939 + pkg.packageName + " signatures do not match the " 5940 + "previously installed version; ignoring!"); 5941 } 5942 } 5943 5944 // Check for shared user signatures 5945 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5946 // Already existing package. Make sure signatures match 5947 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5948 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5949 if (!match) { 5950 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5951 == PackageManager.SIGNATURE_MATCH; 5952 } 5953 if (!match) { 5954 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5955 == PackageManager.SIGNATURE_MATCH; 5956 } 5957 if (!match) { 5958 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5959 "Package " + pkg.packageName 5960 + " has no signatures that match those in shared user " 5961 + pkgSetting.sharedUser.name + "; ignoring!"); 5962 } 5963 } 5964 } 5965 5966 /** 5967 * Enforces that only the system UID or root's UID can call a method exposed 5968 * via Binder. 5969 * 5970 * @param message used as message if SecurityException is thrown 5971 * @throws SecurityException if the caller is not system or root 5972 */ 5973 private static final void enforceSystemOrRoot(String message) { 5974 final int uid = Binder.getCallingUid(); 5975 if (uid != Process.SYSTEM_UID && uid != 0) { 5976 throw new SecurityException(message); 5977 } 5978 } 5979 5980 @Override 5981 public void performBootDexOpt() { 5982 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5983 5984 // Before everything else, see whether we need to fstrim. 5985 try { 5986 IMountService ms = PackageHelper.getMountService(); 5987 if (ms != null) { 5988 final boolean isUpgrade = isUpgrade(); 5989 boolean doTrim = isUpgrade; 5990 if (doTrim) { 5991 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5992 } else { 5993 final long interval = android.provider.Settings.Global.getLong( 5994 mContext.getContentResolver(), 5995 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5996 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5997 if (interval > 0) { 5998 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5999 if (timeSinceLast > interval) { 6000 doTrim = true; 6001 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6002 + "; running immediately"); 6003 } 6004 } 6005 } 6006 if (doTrim) { 6007 if (!isFirstBoot()) { 6008 try { 6009 ActivityManagerNative.getDefault().showBootMessage( 6010 mContext.getResources().getString( 6011 R.string.android_upgrading_fstrim), true); 6012 } catch (RemoteException e) { 6013 } 6014 } 6015 ms.runMaintenance(); 6016 } 6017 } else { 6018 Slog.e(TAG, "Mount service unavailable!"); 6019 } 6020 } catch (RemoteException e) { 6021 // Can't happen; MountService is local 6022 } 6023 6024 final ArraySet<PackageParser.Package> pkgs; 6025 synchronized (mPackages) { 6026 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6027 } 6028 6029 if (pkgs != null) { 6030 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6031 // in case the device runs out of space. 6032 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6033 // Give priority to core apps. 6034 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6035 PackageParser.Package pkg = it.next(); 6036 if (pkg.coreApp) { 6037 if (DEBUG_DEXOPT) { 6038 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6039 } 6040 sortedPkgs.add(pkg); 6041 it.remove(); 6042 } 6043 } 6044 // Give priority to system apps that listen for pre boot complete. 6045 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6046 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 6047 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6048 PackageParser.Package pkg = it.next(); 6049 if (pkgNames.contains(pkg.packageName)) { 6050 if (DEBUG_DEXOPT) { 6051 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6052 } 6053 sortedPkgs.add(pkg); 6054 it.remove(); 6055 } 6056 } 6057 // Give priority to system apps. 6058 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6059 PackageParser.Package pkg = it.next(); 6060 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6061 if (DEBUG_DEXOPT) { 6062 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6063 } 6064 sortedPkgs.add(pkg); 6065 it.remove(); 6066 } 6067 } 6068 // Give priority to updated system apps. 6069 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6070 PackageParser.Package pkg = it.next(); 6071 if (pkg.isUpdatedSystemApp()) { 6072 if (DEBUG_DEXOPT) { 6073 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6074 } 6075 sortedPkgs.add(pkg); 6076 it.remove(); 6077 } 6078 } 6079 // Give priority to apps that listen for boot complete. 6080 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6081 pkgNames = getPackageNamesForIntent(intent); 6082 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6083 PackageParser.Package pkg = it.next(); 6084 if (pkgNames.contains(pkg.packageName)) { 6085 if (DEBUG_DEXOPT) { 6086 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6087 } 6088 sortedPkgs.add(pkg); 6089 it.remove(); 6090 } 6091 } 6092 // Filter out packages that aren't recently used. 6093 filterRecentlyUsedApps(pkgs); 6094 // Add all remaining apps. 6095 for (PackageParser.Package pkg : pkgs) { 6096 if (DEBUG_DEXOPT) { 6097 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6098 } 6099 sortedPkgs.add(pkg); 6100 } 6101 6102 // If we want to be lazy, filter everything that wasn't recently used. 6103 if (mLazyDexOpt) { 6104 filterRecentlyUsedApps(sortedPkgs); 6105 } 6106 6107 int i = 0; 6108 int total = sortedPkgs.size(); 6109 File dataDir = Environment.getDataDirectory(); 6110 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6111 if (lowThreshold == 0) { 6112 throw new IllegalStateException("Invalid low memory threshold"); 6113 } 6114 for (PackageParser.Package pkg : sortedPkgs) { 6115 long usableSpace = dataDir.getUsableSpace(); 6116 if (usableSpace < lowThreshold) { 6117 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6118 break; 6119 } 6120 performBootDexOpt(pkg, ++i, total); 6121 } 6122 } 6123 } 6124 6125 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6126 // Filter out packages that aren't recently used. 6127 // 6128 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6129 // should do a full dexopt. 6130 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6131 int total = pkgs.size(); 6132 int skipped = 0; 6133 long now = System.currentTimeMillis(); 6134 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6135 PackageParser.Package pkg = i.next(); 6136 long then = pkg.mLastPackageUsageTimeInMills; 6137 if (then + mDexOptLRUThresholdInMills < now) { 6138 if (DEBUG_DEXOPT) { 6139 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6140 ((then == 0) ? "never" : new Date(then))); 6141 } 6142 i.remove(); 6143 skipped++; 6144 } 6145 } 6146 if (DEBUG_DEXOPT) { 6147 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6148 } 6149 } 6150 } 6151 6152 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6153 List<ResolveInfo> ris = null; 6154 try { 6155 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6156 intent, null, 0, UserHandle.USER_OWNER); 6157 } catch (RemoteException e) { 6158 } 6159 ArraySet<String> pkgNames = new ArraySet<String>(); 6160 if (ris != null) { 6161 for (ResolveInfo ri : ris) { 6162 pkgNames.add(ri.activityInfo.packageName); 6163 } 6164 } 6165 return pkgNames; 6166 } 6167 6168 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6169 if (DEBUG_DEXOPT) { 6170 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6171 } 6172 if (!isFirstBoot()) { 6173 try { 6174 ActivityManagerNative.getDefault().showBootMessage( 6175 mContext.getResources().getString(R.string.android_upgrading_apk, 6176 curr, total), true); 6177 } catch (RemoteException e) { 6178 } 6179 } 6180 PackageParser.Package p = pkg; 6181 synchronized (mInstallLock) { 6182 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6183 false /* force dex */, false /* defer */, true /* include dependencies */); 6184 } 6185 } 6186 6187 @Override 6188 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6189 return performDexOpt(packageName, instructionSet, false); 6190 } 6191 6192 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6193 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6194 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6195 if (!dexopt && !updateUsage) { 6196 // We aren't going to dexopt or update usage, so bail early. 6197 return false; 6198 } 6199 PackageParser.Package p; 6200 final String targetInstructionSet; 6201 synchronized (mPackages) { 6202 p = mPackages.get(packageName); 6203 if (p == null) { 6204 return false; 6205 } 6206 if (updateUsage) { 6207 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6208 } 6209 mPackageUsage.write(false); 6210 if (!dexopt) { 6211 // We aren't going to dexopt, so bail early. 6212 return false; 6213 } 6214 6215 targetInstructionSet = instructionSet != null ? instructionSet : 6216 getPrimaryInstructionSet(p.applicationInfo); 6217 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6218 return false; 6219 } 6220 } 6221 long callingId = Binder.clearCallingIdentity(); 6222 try { 6223 synchronized (mInstallLock) { 6224 final String[] instructionSets = new String[] { targetInstructionSet }; 6225 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6226 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6227 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6228 } 6229 } finally { 6230 Binder.restoreCallingIdentity(callingId); 6231 } 6232 } 6233 6234 public ArraySet<String> getPackagesThatNeedDexOpt() { 6235 ArraySet<String> pkgs = null; 6236 synchronized (mPackages) { 6237 for (PackageParser.Package p : mPackages.values()) { 6238 if (DEBUG_DEXOPT) { 6239 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6240 } 6241 if (!p.mDexOptPerformed.isEmpty()) { 6242 continue; 6243 } 6244 if (pkgs == null) { 6245 pkgs = new ArraySet<String>(); 6246 } 6247 pkgs.add(p.packageName); 6248 } 6249 } 6250 return pkgs; 6251 } 6252 6253 public void shutdown() { 6254 mPackageUsage.write(true); 6255 } 6256 6257 @Override 6258 public void forceDexOpt(String packageName) { 6259 enforceSystemOrRoot("forceDexOpt"); 6260 6261 PackageParser.Package pkg; 6262 synchronized (mPackages) { 6263 pkg = mPackages.get(packageName); 6264 if (pkg == null) { 6265 throw new IllegalArgumentException("Missing package: " + packageName); 6266 } 6267 } 6268 6269 synchronized (mInstallLock) { 6270 final String[] instructionSets = new String[] { 6271 getPrimaryInstructionSet(pkg.applicationInfo) }; 6272 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6273 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6274 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6275 throw new IllegalStateException("Failed to dexopt: " + res); 6276 } 6277 } 6278 } 6279 6280 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6281 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6282 Slog.w(TAG, "Unable to update from " + oldPkg.name 6283 + " to " + newPkg.packageName 6284 + ": old package not in system partition"); 6285 return false; 6286 } else if (mPackages.get(oldPkg.name) != null) { 6287 Slog.w(TAG, "Unable to update from " + oldPkg.name 6288 + " to " + newPkg.packageName 6289 + ": old package still exists"); 6290 return false; 6291 } 6292 return true; 6293 } 6294 6295 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6296 int[] users = sUserManager.getUserIds(); 6297 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6298 if (res < 0) { 6299 return res; 6300 } 6301 for (int user : users) { 6302 if (user != 0) { 6303 res = mInstaller.createUserData(volumeUuid, packageName, 6304 UserHandle.getUid(user, uid), user, seinfo); 6305 if (res < 0) { 6306 return res; 6307 } 6308 } 6309 } 6310 return res; 6311 } 6312 6313 private int removeDataDirsLI(String volumeUuid, String packageName) { 6314 int[] users = sUserManager.getUserIds(); 6315 int res = 0; 6316 for (int user : users) { 6317 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6318 if (resInner < 0) { 6319 res = resInner; 6320 } 6321 } 6322 6323 return res; 6324 } 6325 6326 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6327 int[] users = sUserManager.getUserIds(); 6328 int res = 0; 6329 for (int user : users) { 6330 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6331 if (resInner < 0) { 6332 res = resInner; 6333 } 6334 } 6335 return res; 6336 } 6337 6338 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6339 PackageParser.Package changingLib) { 6340 if (file.path != null) { 6341 usesLibraryFiles.add(file.path); 6342 return; 6343 } 6344 PackageParser.Package p = mPackages.get(file.apk); 6345 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6346 // If we are doing this while in the middle of updating a library apk, 6347 // then we need to make sure to use that new apk for determining the 6348 // dependencies here. (We haven't yet finished committing the new apk 6349 // to the package manager state.) 6350 if (p == null || p.packageName.equals(changingLib.packageName)) { 6351 p = changingLib; 6352 } 6353 } 6354 if (p != null) { 6355 usesLibraryFiles.addAll(p.getAllCodePaths()); 6356 } 6357 } 6358 6359 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6360 PackageParser.Package changingLib) throws PackageManagerException { 6361 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6362 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6363 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6364 for (int i=0; i<N; i++) { 6365 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6366 if (file == null) { 6367 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6368 "Package " + pkg.packageName + " requires unavailable shared library " 6369 + pkg.usesLibraries.get(i) + "; failing!"); 6370 } 6371 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6372 } 6373 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6374 for (int i=0; i<N; i++) { 6375 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6376 if (file == null) { 6377 Slog.w(TAG, "Package " + pkg.packageName 6378 + " desires unavailable shared library " 6379 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6380 } else { 6381 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6382 } 6383 } 6384 N = usesLibraryFiles.size(); 6385 if (N > 0) { 6386 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6387 } else { 6388 pkg.usesLibraryFiles = null; 6389 } 6390 } 6391 } 6392 6393 private static boolean hasString(List<String> list, List<String> which) { 6394 if (list == null) { 6395 return false; 6396 } 6397 for (int i=list.size()-1; i>=0; i--) { 6398 for (int j=which.size()-1; j>=0; j--) { 6399 if (which.get(j).equals(list.get(i))) { 6400 return true; 6401 } 6402 } 6403 } 6404 return false; 6405 } 6406 6407 private void updateAllSharedLibrariesLPw() { 6408 for (PackageParser.Package pkg : mPackages.values()) { 6409 try { 6410 updateSharedLibrariesLPw(pkg, null); 6411 } catch (PackageManagerException e) { 6412 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6413 } 6414 } 6415 } 6416 6417 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6418 PackageParser.Package changingPkg) { 6419 ArrayList<PackageParser.Package> res = null; 6420 for (PackageParser.Package pkg : mPackages.values()) { 6421 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6422 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6423 if (res == null) { 6424 res = new ArrayList<PackageParser.Package>(); 6425 } 6426 res.add(pkg); 6427 try { 6428 updateSharedLibrariesLPw(pkg, changingPkg); 6429 } catch (PackageManagerException e) { 6430 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6431 } 6432 } 6433 } 6434 return res; 6435 } 6436 6437 /** 6438 * Derive the value of the {@code cpuAbiOverride} based on the provided 6439 * value and an optional stored value from the package settings. 6440 */ 6441 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6442 String cpuAbiOverride = null; 6443 6444 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6445 cpuAbiOverride = null; 6446 } else if (abiOverride != null) { 6447 cpuAbiOverride = abiOverride; 6448 } else if (settings != null) { 6449 cpuAbiOverride = settings.cpuAbiOverrideString; 6450 } 6451 6452 return cpuAbiOverride; 6453 } 6454 6455 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6456 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6457 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6458 try { 6459 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6460 } finally { 6461 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6462 } 6463 } 6464 6465 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6466 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6467 boolean success = false; 6468 try { 6469 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6470 currentTime, user); 6471 success = true; 6472 return res; 6473 } finally { 6474 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6475 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6476 } 6477 } 6478 } 6479 6480 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6481 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6482 final File scanFile = new File(pkg.codePath); 6483 if (pkg.applicationInfo.getCodePath() == null || 6484 pkg.applicationInfo.getResourcePath() == null) { 6485 // Bail out. The resource and code paths haven't been set. 6486 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6487 "Code and resource paths haven't been set correctly"); 6488 } 6489 6490 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6491 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6492 } else { 6493 // Only allow system apps to be flagged as core apps. 6494 pkg.coreApp = false; 6495 } 6496 6497 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6498 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6499 } 6500 6501 if (mCustomResolverComponentName != null && 6502 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6503 setUpCustomResolverActivity(pkg); 6504 } 6505 6506 if (pkg.packageName.equals("android")) { 6507 synchronized (mPackages) { 6508 if (mAndroidApplication != null) { 6509 Slog.w(TAG, "*************************************************"); 6510 Slog.w(TAG, "Core android package being redefined. Skipping."); 6511 Slog.w(TAG, " file=" + scanFile); 6512 Slog.w(TAG, "*************************************************"); 6513 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6514 "Core android package being redefined. Skipping."); 6515 } 6516 6517 // Set up information for our fall-back user intent resolution activity. 6518 mPlatformPackage = pkg; 6519 pkg.mVersionCode = mSdkVersion; 6520 mAndroidApplication = pkg.applicationInfo; 6521 6522 if (!mResolverReplaced) { 6523 mResolveActivity.applicationInfo = mAndroidApplication; 6524 mResolveActivity.name = ResolverActivity.class.getName(); 6525 mResolveActivity.packageName = mAndroidApplication.packageName; 6526 mResolveActivity.processName = "system:ui"; 6527 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6528 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6529 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6530 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6531 mResolveActivity.exported = true; 6532 mResolveActivity.enabled = true; 6533 mResolveInfo.activityInfo = mResolveActivity; 6534 mResolveInfo.priority = 0; 6535 mResolveInfo.preferredOrder = 0; 6536 mResolveInfo.match = 0; 6537 mResolveComponentName = new ComponentName( 6538 mAndroidApplication.packageName, mResolveActivity.name); 6539 } 6540 } 6541 } 6542 6543 if (DEBUG_PACKAGE_SCANNING) { 6544 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6545 Log.d(TAG, "Scanning package " + pkg.packageName); 6546 } 6547 6548 if (mPackages.containsKey(pkg.packageName) 6549 || mSharedLibraries.containsKey(pkg.packageName)) { 6550 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6551 "Application package " + pkg.packageName 6552 + " already installed. Skipping duplicate."); 6553 } 6554 6555 // If we're only installing presumed-existing packages, require that the 6556 // scanned APK is both already known and at the path previously established 6557 // for it. Previously unknown packages we pick up normally, but if we have an 6558 // a priori expectation about this package's install presence, enforce it. 6559 // With a singular exception for new system packages. When an OTA contains 6560 // a new system package, we allow the codepath to change from a system location 6561 // to the user-installed location. If we don't allow this change, any newer, 6562 // user-installed version of the application will be ignored. 6563 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6564 if (mExpectingBetter.containsKey(pkg.packageName)) { 6565 logCriticalInfo(Log.WARN, 6566 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6567 } else { 6568 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6569 if (known != null) { 6570 if (DEBUG_PACKAGE_SCANNING) { 6571 Log.d(TAG, "Examining " + pkg.codePath 6572 + " and requiring known paths " + known.codePathString 6573 + " & " + known.resourcePathString); 6574 } 6575 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6576 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6577 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6578 "Application package " + pkg.packageName 6579 + " found at " + pkg.applicationInfo.getCodePath() 6580 + " but expected at " + known.codePathString + "; ignoring."); 6581 } 6582 } 6583 } 6584 } 6585 6586 // Initialize package source and resource directories 6587 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6588 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6589 6590 SharedUserSetting suid = null; 6591 PackageSetting pkgSetting = null; 6592 6593 if (!isSystemApp(pkg)) { 6594 // Only system apps can use these features. 6595 pkg.mOriginalPackages = null; 6596 pkg.mRealPackage = null; 6597 pkg.mAdoptPermissions = null; 6598 } 6599 6600 // writer 6601 synchronized (mPackages) { 6602 if (pkg.mSharedUserId != null) { 6603 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6604 if (suid == null) { 6605 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6606 "Creating application package " + pkg.packageName 6607 + " for shared user failed"); 6608 } 6609 if (DEBUG_PACKAGE_SCANNING) { 6610 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6611 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6612 + "): packages=" + suid.packages); 6613 } 6614 } 6615 6616 // Check if we are renaming from an original package name. 6617 PackageSetting origPackage = null; 6618 String realName = null; 6619 if (pkg.mOriginalPackages != null) { 6620 // This package may need to be renamed to a previously 6621 // installed name. Let's check on that... 6622 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6623 if (pkg.mOriginalPackages.contains(renamed)) { 6624 // This package had originally been installed as the 6625 // original name, and we have already taken care of 6626 // transitioning to the new one. Just update the new 6627 // one to continue using the old name. 6628 realName = pkg.mRealPackage; 6629 if (!pkg.packageName.equals(renamed)) { 6630 // Callers into this function may have already taken 6631 // care of renaming the package; only do it here if 6632 // it is not already done. 6633 pkg.setPackageName(renamed); 6634 } 6635 6636 } else { 6637 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6638 if ((origPackage = mSettings.peekPackageLPr( 6639 pkg.mOriginalPackages.get(i))) != null) { 6640 // We do have the package already installed under its 6641 // original name... should we use it? 6642 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6643 // New package is not compatible with original. 6644 origPackage = null; 6645 continue; 6646 } else if (origPackage.sharedUser != null) { 6647 // Make sure uid is compatible between packages. 6648 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6649 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6650 + " to " + pkg.packageName + ": old uid " 6651 + origPackage.sharedUser.name 6652 + " differs from " + pkg.mSharedUserId); 6653 origPackage = null; 6654 continue; 6655 } 6656 } else { 6657 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6658 + pkg.packageName + " to old name " + origPackage.name); 6659 } 6660 break; 6661 } 6662 } 6663 } 6664 } 6665 6666 if (mTransferedPackages.contains(pkg.packageName)) { 6667 Slog.w(TAG, "Package " + pkg.packageName 6668 + " was transferred to another, but its .apk remains"); 6669 } 6670 6671 // Just create the setting, don't add it yet. For already existing packages 6672 // the PkgSetting exists already and doesn't have to be created. 6673 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6674 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6675 pkg.applicationInfo.primaryCpuAbi, 6676 pkg.applicationInfo.secondaryCpuAbi, 6677 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6678 user, false); 6679 if (pkgSetting == null) { 6680 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6681 "Creating application package " + pkg.packageName + " failed"); 6682 } 6683 6684 if (pkgSetting.origPackage != null) { 6685 // If we are first transitioning from an original package, 6686 // fix up the new package's name now. We need to do this after 6687 // looking up the package under its new name, so getPackageLP 6688 // can take care of fiddling things correctly. 6689 pkg.setPackageName(origPackage.name); 6690 6691 // File a report about this. 6692 String msg = "New package " + pkgSetting.realName 6693 + " renamed to replace old package " + pkgSetting.name; 6694 reportSettingsProblem(Log.WARN, msg); 6695 6696 // Make a note of it. 6697 mTransferedPackages.add(origPackage.name); 6698 6699 // No longer need to retain this. 6700 pkgSetting.origPackage = null; 6701 } 6702 6703 if (realName != null) { 6704 // Make a note of it. 6705 mTransferedPackages.add(pkg.packageName); 6706 } 6707 6708 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6709 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6710 } 6711 6712 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6713 // Check all shared libraries and map to their actual file path. 6714 // We only do this here for apps not on a system dir, because those 6715 // are the only ones that can fail an install due to this. We 6716 // will take care of the system apps by updating all of their 6717 // library paths after the scan is done. 6718 updateSharedLibrariesLPw(pkg, null); 6719 } 6720 6721 if (mFoundPolicyFile) { 6722 SELinuxMMAC.assignSeinfoValue(pkg); 6723 } 6724 6725 pkg.applicationInfo.uid = pkgSetting.appId; 6726 pkg.mExtras = pkgSetting; 6727 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6728 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6729 // We just determined the app is signed correctly, so bring 6730 // over the latest parsed certs. 6731 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6732 } else { 6733 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6734 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6735 "Package " + pkg.packageName + " upgrade keys do not match the " 6736 + "previously installed version"); 6737 } else { 6738 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6739 String msg = "System package " + pkg.packageName 6740 + " signature changed; retaining data."; 6741 reportSettingsProblem(Log.WARN, msg); 6742 } 6743 } 6744 } else { 6745 try { 6746 verifySignaturesLP(pkgSetting, pkg); 6747 // We just determined the app is signed correctly, so bring 6748 // over the latest parsed certs. 6749 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6750 } catch (PackageManagerException e) { 6751 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6752 throw e; 6753 } 6754 // The signature has changed, but this package is in the system 6755 // image... let's recover! 6756 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6757 // However... if this package is part of a shared user, but it 6758 // doesn't match the signature of the shared user, let's fail. 6759 // What this means is that you can't change the signatures 6760 // associated with an overall shared user, which doesn't seem all 6761 // that unreasonable. 6762 if (pkgSetting.sharedUser != null) { 6763 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6764 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6765 throw new PackageManagerException( 6766 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6767 "Signature mismatch for shared user : " 6768 + pkgSetting.sharedUser); 6769 } 6770 } 6771 // File a report about this. 6772 String msg = "System package " + pkg.packageName 6773 + " signature changed; retaining data."; 6774 reportSettingsProblem(Log.WARN, msg); 6775 } 6776 } 6777 // Verify that this new package doesn't have any content providers 6778 // that conflict with existing packages. Only do this if the 6779 // package isn't already installed, since we don't want to break 6780 // things that are installed. 6781 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6782 final int N = pkg.providers.size(); 6783 int i; 6784 for (i=0; i<N; i++) { 6785 PackageParser.Provider p = pkg.providers.get(i); 6786 if (p.info.authority != null) { 6787 String names[] = p.info.authority.split(";"); 6788 for (int j = 0; j < names.length; j++) { 6789 if (mProvidersByAuthority.containsKey(names[j])) { 6790 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6791 final String otherPackageName = 6792 ((other != null && other.getComponentName() != null) ? 6793 other.getComponentName().getPackageName() : "?"); 6794 throw new PackageManagerException( 6795 INSTALL_FAILED_CONFLICTING_PROVIDER, 6796 "Can't install because provider name " + names[j] 6797 + " (in package " + pkg.applicationInfo.packageName 6798 + ") is already used by " + otherPackageName); 6799 } 6800 } 6801 } 6802 } 6803 } 6804 6805 if (pkg.mAdoptPermissions != null) { 6806 // This package wants to adopt ownership of permissions from 6807 // another package. 6808 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6809 final String origName = pkg.mAdoptPermissions.get(i); 6810 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6811 if (orig != null) { 6812 if (verifyPackageUpdateLPr(orig, pkg)) { 6813 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6814 + pkg.packageName); 6815 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6816 } 6817 } 6818 } 6819 } 6820 } 6821 6822 final String pkgName = pkg.packageName; 6823 6824 final long scanFileTime = scanFile.lastModified(); 6825 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6826 pkg.applicationInfo.processName = fixProcessName( 6827 pkg.applicationInfo.packageName, 6828 pkg.applicationInfo.processName, 6829 pkg.applicationInfo.uid); 6830 6831 File dataPath; 6832 if (mPlatformPackage == pkg) { 6833 // The system package is special. 6834 dataPath = new File(Environment.getDataDirectory(), "system"); 6835 6836 pkg.applicationInfo.dataDir = dataPath.getPath(); 6837 6838 } else { 6839 // This is a normal package, need to make its data directory. 6840 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6841 UserHandle.USER_OWNER, pkg.packageName); 6842 6843 boolean uidError = false; 6844 if (dataPath.exists()) { 6845 int currentUid = 0; 6846 try { 6847 StructStat stat = Os.stat(dataPath.getPath()); 6848 currentUid = stat.st_uid; 6849 } catch (ErrnoException e) { 6850 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6851 } 6852 6853 // If we have mismatched owners for the data path, we have a problem. 6854 if (currentUid != pkg.applicationInfo.uid) { 6855 boolean recovered = false; 6856 if (currentUid == 0) { 6857 // The directory somehow became owned by root. Wow. 6858 // This is probably because the system was stopped while 6859 // installd was in the middle of messing with its libs 6860 // directory. Ask installd to fix that. 6861 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6862 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6863 if (ret >= 0) { 6864 recovered = true; 6865 String msg = "Package " + pkg.packageName 6866 + " unexpectedly changed to uid 0; recovered to " + 6867 + pkg.applicationInfo.uid; 6868 reportSettingsProblem(Log.WARN, msg); 6869 } 6870 } 6871 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6872 || (scanFlags&SCAN_BOOTING) != 0)) { 6873 // If this is a system app, we can at least delete its 6874 // current data so the application will still work. 6875 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6876 if (ret >= 0) { 6877 // TODO: Kill the processes first 6878 // Old data gone! 6879 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6880 ? "System package " : "Third party package "; 6881 String msg = prefix + pkg.packageName 6882 + " has changed from uid: " 6883 + currentUid + " to " 6884 + pkg.applicationInfo.uid + "; old data erased"; 6885 reportSettingsProblem(Log.WARN, msg); 6886 recovered = true; 6887 6888 // And now re-install the app. 6889 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6890 pkg.applicationInfo.seinfo); 6891 if (ret == -1) { 6892 // Ack should not happen! 6893 msg = prefix + pkg.packageName 6894 + " could not have data directory re-created after delete."; 6895 reportSettingsProblem(Log.WARN, msg); 6896 throw new PackageManagerException( 6897 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6898 } 6899 } 6900 if (!recovered) { 6901 mHasSystemUidErrors = true; 6902 } 6903 } else if (!recovered) { 6904 // If we allow this install to proceed, we will be broken. 6905 // Abort, abort! 6906 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6907 "scanPackageLI"); 6908 } 6909 if (!recovered) { 6910 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6911 + pkg.applicationInfo.uid + "/fs_" 6912 + currentUid; 6913 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6914 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6915 String msg = "Package " + pkg.packageName 6916 + " has mismatched uid: " 6917 + currentUid + " on disk, " 6918 + pkg.applicationInfo.uid + " in settings"; 6919 // writer 6920 synchronized (mPackages) { 6921 mSettings.mReadMessages.append(msg); 6922 mSettings.mReadMessages.append('\n'); 6923 uidError = true; 6924 if (!pkgSetting.uidError) { 6925 reportSettingsProblem(Log.ERROR, msg); 6926 } 6927 } 6928 } 6929 } 6930 pkg.applicationInfo.dataDir = dataPath.getPath(); 6931 if (mShouldRestoreconData) { 6932 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6933 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6934 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6935 } 6936 } else { 6937 if (DEBUG_PACKAGE_SCANNING) { 6938 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6939 Log.v(TAG, "Want this data dir: " + dataPath); 6940 } 6941 //invoke installer to do the actual installation 6942 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6943 pkg.applicationInfo.seinfo); 6944 if (ret < 0) { 6945 // Error from installer 6946 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6947 "Unable to create data dirs [errorCode=" + ret + "]"); 6948 } 6949 6950 if (dataPath.exists()) { 6951 pkg.applicationInfo.dataDir = dataPath.getPath(); 6952 } else { 6953 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6954 pkg.applicationInfo.dataDir = null; 6955 } 6956 } 6957 6958 pkgSetting.uidError = uidError; 6959 } 6960 6961 final String path = scanFile.getPath(); 6962 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6963 6964 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6965 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6966 6967 // Some system apps still use directory structure for native libraries 6968 // in which case we might end up not detecting abi solely based on apk 6969 // structure. Try to detect abi based on directory structure. 6970 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6971 pkg.applicationInfo.primaryCpuAbi == null) { 6972 setBundledAppAbisAndRoots(pkg, pkgSetting); 6973 setNativeLibraryPaths(pkg); 6974 } 6975 6976 } else { 6977 if ((scanFlags & SCAN_MOVE) != 0) { 6978 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6979 // but we already have this packages package info in the PackageSetting. We just 6980 // use that and derive the native library path based on the new codepath. 6981 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6982 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6983 } 6984 6985 // Set native library paths again. For moves, the path will be updated based on the 6986 // ABIs we've determined above. For non-moves, the path will be updated based on the 6987 // ABIs we determined during compilation, but the path will depend on the final 6988 // package path (after the rename away from the stage path). 6989 setNativeLibraryPaths(pkg); 6990 } 6991 6992 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6993 final int[] userIds = sUserManager.getUserIds(); 6994 synchronized (mInstallLock) { 6995 // Make sure all user data directories are ready to roll; we're okay 6996 // if they already exist 6997 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6998 for (int userId : userIds) { 6999 if (userId != 0) { 7000 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7001 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7002 pkg.applicationInfo.seinfo); 7003 } 7004 } 7005 } 7006 7007 // Create a native library symlink only if we have native libraries 7008 // and if the native libraries are 32 bit libraries. We do not provide 7009 // this symlink for 64 bit libraries. 7010 if (pkg.applicationInfo.primaryCpuAbi != null && 7011 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7012 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7013 try { 7014 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7015 for (int userId : userIds) { 7016 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7017 nativeLibPath, userId) < 0) { 7018 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7019 "Failed linking native library dir (user=" + userId + ")"); 7020 } 7021 } 7022 } finally { 7023 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7024 } 7025 } 7026 } 7027 7028 // This is a special case for the "system" package, where the ABI is 7029 // dictated by the zygote configuration (and init.rc). We should keep track 7030 // of this ABI so that we can deal with "normal" applications that run under 7031 // the same UID correctly. 7032 if (mPlatformPackage == pkg) { 7033 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7034 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7035 } 7036 7037 // If there's a mismatch between the abi-override in the package setting 7038 // and the abiOverride specified for the install. Warn about this because we 7039 // would've already compiled the app without taking the package setting into 7040 // account. 7041 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7042 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7043 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7044 " for package: " + pkg.packageName); 7045 } 7046 } 7047 7048 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7049 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7050 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7051 7052 // Copy the derived override back to the parsed package, so that we can 7053 // update the package settings accordingly. 7054 pkg.cpuAbiOverride = cpuAbiOverride; 7055 7056 if (DEBUG_ABI_SELECTION) { 7057 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7058 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7059 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7060 } 7061 7062 // Push the derived path down into PackageSettings so we know what to 7063 // clean up at uninstall time. 7064 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7065 7066 if (DEBUG_ABI_SELECTION) { 7067 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7068 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7069 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7070 } 7071 7072 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7073 // We don't do this here during boot because we can do it all 7074 // at once after scanning all existing packages. 7075 // 7076 // We also do this *before* we perform dexopt on this package, so that 7077 // we can avoid redundant dexopts, and also to make sure we've got the 7078 // code and package path correct. 7079 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7080 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7081 } 7082 7083 if ((scanFlags & SCAN_NO_DEX) == 0) { 7084 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7085 7086 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7087 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7088 7089 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7090 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7091 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7092 } 7093 } 7094 if (mFactoryTest && pkg.requestedPermissions.contains( 7095 android.Manifest.permission.FACTORY_TEST)) { 7096 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7097 } 7098 7099 ArrayList<PackageParser.Package> clientLibPkgs = null; 7100 7101 // writer 7102 synchronized (mPackages) { 7103 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7104 // Only system apps can add new shared libraries. 7105 if (pkg.libraryNames != null) { 7106 for (int i=0; i<pkg.libraryNames.size(); i++) { 7107 String name = pkg.libraryNames.get(i); 7108 boolean allowed = false; 7109 if (pkg.isUpdatedSystemApp()) { 7110 // New library entries can only be added through the 7111 // system image. This is important to get rid of a lot 7112 // of nasty edge cases: for example if we allowed a non- 7113 // system update of the app to add a library, then uninstalling 7114 // the update would make the library go away, and assumptions 7115 // we made such as through app install filtering would now 7116 // have allowed apps on the device which aren't compatible 7117 // with it. Better to just have the restriction here, be 7118 // conservative, and create many fewer cases that can negatively 7119 // impact the user experience. 7120 final PackageSetting sysPs = mSettings 7121 .getDisabledSystemPkgLPr(pkg.packageName); 7122 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7123 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7124 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7125 allowed = true; 7126 allowed = true; 7127 break; 7128 } 7129 } 7130 } 7131 } else { 7132 allowed = true; 7133 } 7134 if (allowed) { 7135 if (!mSharedLibraries.containsKey(name)) { 7136 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7137 } else if (!name.equals(pkg.packageName)) { 7138 Slog.w(TAG, "Package " + pkg.packageName + " library " 7139 + name + " already exists; skipping"); 7140 } 7141 } else { 7142 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7143 + name + " that is not declared on system image; skipping"); 7144 } 7145 } 7146 if ((scanFlags&SCAN_BOOTING) == 0) { 7147 // If we are not booting, we need to update any applications 7148 // that are clients of our shared library. If we are booting, 7149 // this will all be done once the scan is complete. 7150 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7151 } 7152 } 7153 } 7154 } 7155 7156 // We also need to dexopt any apps that are dependent on this library. Note that 7157 // if these fail, we should abort the install since installing the library will 7158 // result in some apps being broken. 7159 if (clientLibPkgs != null) { 7160 if ((scanFlags & SCAN_NO_DEX) == 0) { 7161 for (int i = 0; i < clientLibPkgs.size(); i++) { 7162 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7163 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7164 null /* instruction sets */, forceDex, 7165 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7166 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7167 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7168 "scanPackageLI failed to dexopt clientLibPkgs"); 7169 } 7170 } 7171 } 7172 } 7173 7174 // Request the ActivityManager to kill the process(only for existing packages) 7175 // so that we do not end up in a confused state while the user is still using the older 7176 // version of the application while the new one gets installed. 7177 if ((scanFlags & SCAN_REPLACING) != 0) { 7178 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7179 7180 killApplication(pkg.applicationInfo.packageName, 7181 pkg.applicationInfo.uid, "replace pkg"); 7182 7183 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7184 } 7185 7186 // Also need to kill any apps that are dependent on the library. 7187 if (clientLibPkgs != null) { 7188 for (int i=0; i<clientLibPkgs.size(); i++) { 7189 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7190 killApplication(clientPkg.applicationInfo.packageName, 7191 clientPkg.applicationInfo.uid, "update lib"); 7192 } 7193 } 7194 7195 // Make sure we're not adding any bogus keyset info 7196 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7197 ksms.assertScannedPackageValid(pkg); 7198 7199 // writer 7200 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7201 7202 boolean createIdmapFailed = false; 7203 synchronized (mPackages) { 7204 // We don't expect installation to fail beyond this point 7205 7206 // Add the new setting to mSettings 7207 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7208 // Add the new setting to mPackages 7209 mPackages.put(pkg.applicationInfo.packageName, pkg); 7210 // Make sure we don't accidentally delete its data. 7211 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7212 while (iter.hasNext()) { 7213 PackageCleanItem item = iter.next(); 7214 if (pkgName.equals(item.packageName)) { 7215 iter.remove(); 7216 } 7217 } 7218 7219 // Take care of first install / last update times. 7220 if (currentTime != 0) { 7221 if (pkgSetting.firstInstallTime == 0) { 7222 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7223 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7224 pkgSetting.lastUpdateTime = currentTime; 7225 } 7226 } else if (pkgSetting.firstInstallTime == 0) { 7227 // We need *something*. Take time time stamp of the file. 7228 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7229 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7230 if (scanFileTime != pkgSetting.timeStamp) { 7231 // A package on the system image has changed; consider this 7232 // to be an update. 7233 pkgSetting.lastUpdateTime = scanFileTime; 7234 } 7235 } 7236 7237 // Add the package's KeySets to the global KeySetManagerService 7238 ksms.addScannedPackageLPw(pkg); 7239 7240 int N = pkg.providers.size(); 7241 StringBuilder r = null; 7242 int i; 7243 for (i=0; i<N; i++) { 7244 PackageParser.Provider p = pkg.providers.get(i); 7245 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7246 p.info.processName, pkg.applicationInfo.uid); 7247 mProviders.addProvider(p); 7248 p.syncable = p.info.isSyncable; 7249 if (p.info.authority != null) { 7250 String names[] = p.info.authority.split(";"); 7251 p.info.authority = null; 7252 for (int j = 0; j < names.length; j++) { 7253 if (j == 1 && p.syncable) { 7254 // We only want the first authority for a provider to possibly be 7255 // syncable, so if we already added this provider using a different 7256 // authority clear the syncable flag. We copy the provider before 7257 // changing it because the mProviders object contains a reference 7258 // to a provider that we don't want to change. 7259 // Only do this for the second authority since the resulting provider 7260 // object can be the same for all future authorities for this provider. 7261 p = new PackageParser.Provider(p); 7262 p.syncable = false; 7263 } 7264 if (!mProvidersByAuthority.containsKey(names[j])) { 7265 mProvidersByAuthority.put(names[j], p); 7266 if (p.info.authority == null) { 7267 p.info.authority = names[j]; 7268 } else { 7269 p.info.authority = p.info.authority + ";" + names[j]; 7270 } 7271 if (DEBUG_PACKAGE_SCANNING) { 7272 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7273 Log.d(TAG, "Registered content provider: " + names[j] 7274 + ", className = " + p.info.name + ", isSyncable = " 7275 + p.info.isSyncable); 7276 } 7277 } else { 7278 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7279 Slog.w(TAG, "Skipping provider name " + names[j] + 7280 " (in package " + pkg.applicationInfo.packageName + 7281 "): name already used by " 7282 + ((other != null && other.getComponentName() != null) 7283 ? other.getComponentName().getPackageName() : "?")); 7284 } 7285 } 7286 } 7287 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7288 if (r == null) { 7289 r = new StringBuilder(256); 7290 } else { 7291 r.append(' '); 7292 } 7293 r.append(p.info.name); 7294 } 7295 } 7296 if (r != null) { 7297 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7298 } 7299 7300 N = pkg.services.size(); 7301 r = null; 7302 for (i=0; i<N; i++) { 7303 PackageParser.Service s = pkg.services.get(i); 7304 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7305 s.info.processName, pkg.applicationInfo.uid); 7306 mServices.addService(s); 7307 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7308 if (r == null) { 7309 r = new StringBuilder(256); 7310 } else { 7311 r.append(' '); 7312 } 7313 r.append(s.info.name); 7314 } 7315 } 7316 if (r != null) { 7317 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7318 } 7319 7320 N = pkg.receivers.size(); 7321 r = null; 7322 for (i=0; i<N; i++) { 7323 PackageParser.Activity a = pkg.receivers.get(i); 7324 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7325 a.info.processName, pkg.applicationInfo.uid); 7326 mReceivers.addActivity(a, "receiver"); 7327 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7328 if (r == null) { 7329 r = new StringBuilder(256); 7330 } else { 7331 r.append(' '); 7332 } 7333 r.append(a.info.name); 7334 } 7335 } 7336 if (r != null) { 7337 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7338 } 7339 7340 N = pkg.activities.size(); 7341 r = null; 7342 for (i=0; i<N; i++) { 7343 PackageParser.Activity a = pkg.activities.get(i); 7344 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7345 a.info.processName, pkg.applicationInfo.uid); 7346 mActivities.addActivity(a, "activity"); 7347 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7348 if (r == null) { 7349 r = new StringBuilder(256); 7350 } else { 7351 r.append(' '); 7352 } 7353 r.append(a.info.name); 7354 } 7355 } 7356 if (r != null) { 7357 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7358 } 7359 7360 N = pkg.permissionGroups.size(); 7361 r = null; 7362 for (i=0; i<N; i++) { 7363 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7364 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7365 if (cur == null) { 7366 mPermissionGroups.put(pg.info.name, pg); 7367 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7368 if (r == null) { 7369 r = new StringBuilder(256); 7370 } else { 7371 r.append(' '); 7372 } 7373 r.append(pg.info.name); 7374 } 7375 } else { 7376 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7377 + pg.info.packageName + " ignored: original from " 7378 + cur.info.packageName); 7379 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7380 if (r == null) { 7381 r = new StringBuilder(256); 7382 } else { 7383 r.append(' '); 7384 } 7385 r.append("DUP:"); 7386 r.append(pg.info.name); 7387 } 7388 } 7389 } 7390 if (r != null) { 7391 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7392 } 7393 7394 N = pkg.permissions.size(); 7395 r = null; 7396 for (i=0; i<N; i++) { 7397 PackageParser.Permission p = pkg.permissions.get(i); 7398 7399 // Assume by default that we did not install this permission into the system. 7400 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7401 7402 // Now that permission groups have a special meaning, we ignore permission 7403 // groups for legacy apps to prevent unexpected behavior. In particular, 7404 // permissions for one app being granted to someone just becuase they happen 7405 // to be in a group defined by another app (before this had no implications). 7406 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7407 p.group = mPermissionGroups.get(p.info.group); 7408 // Warn for a permission in an unknown group. 7409 if (p.info.group != null && p.group == null) { 7410 Slog.w(TAG, "Permission " + p.info.name + " from package " 7411 + p.info.packageName + " in an unknown group " + p.info.group); 7412 } 7413 } 7414 7415 ArrayMap<String, BasePermission> permissionMap = 7416 p.tree ? mSettings.mPermissionTrees 7417 : mSettings.mPermissions; 7418 BasePermission bp = permissionMap.get(p.info.name); 7419 7420 // Allow system apps to redefine non-system permissions 7421 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7422 final boolean currentOwnerIsSystem = (bp.perm != null 7423 && isSystemApp(bp.perm.owner)); 7424 if (isSystemApp(p.owner)) { 7425 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7426 // It's a built-in permission and no owner, take ownership now 7427 bp.packageSetting = pkgSetting; 7428 bp.perm = p; 7429 bp.uid = pkg.applicationInfo.uid; 7430 bp.sourcePackage = p.info.packageName; 7431 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7432 } else if (!currentOwnerIsSystem) { 7433 String msg = "New decl " + p.owner + " of permission " 7434 + p.info.name + " is system; overriding " + bp.sourcePackage; 7435 reportSettingsProblem(Log.WARN, msg); 7436 bp = null; 7437 } 7438 } 7439 } 7440 7441 if (bp == null) { 7442 bp = new BasePermission(p.info.name, p.info.packageName, 7443 BasePermission.TYPE_NORMAL); 7444 permissionMap.put(p.info.name, bp); 7445 } 7446 7447 if (bp.perm == null) { 7448 if (bp.sourcePackage == null 7449 || bp.sourcePackage.equals(p.info.packageName)) { 7450 BasePermission tree = findPermissionTreeLP(p.info.name); 7451 if (tree == null 7452 || tree.sourcePackage.equals(p.info.packageName)) { 7453 bp.packageSetting = pkgSetting; 7454 bp.perm = p; 7455 bp.uid = pkg.applicationInfo.uid; 7456 bp.sourcePackage = p.info.packageName; 7457 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7458 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7459 if (r == null) { 7460 r = new StringBuilder(256); 7461 } else { 7462 r.append(' '); 7463 } 7464 r.append(p.info.name); 7465 } 7466 } else { 7467 Slog.w(TAG, "Permission " + p.info.name + " from package " 7468 + p.info.packageName + " ignored: base tree " 7469 + tree.name + " is from package " 7470 + tree.sourcePackage); 7471 } 7472 } else { 7473 Slog.w(TAG, "Permission " + p.info.name + " from package " 7474 + p.info.packageName + " ignored: original from " 7475 + bp.sourcePackage); 7476 } 7477 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7478 if (r == null) { 7479 r = new StringBuilder(256); 7480 } else { 7481 r.append(' '); 7482 } 7483 r.append("DUP:"); 7484 r.append(p.info.name); 7485 } 7486 if (bp.perm == p) { 7487 bp.protectionLevel = p.info.protectionLevel; 7488 } 7489 } 7490 7491 if (r != null) { 7492 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7493 } 7494 7495 N = pkg.instrumentation.size(); 7496 r = null; 7497 for (i=0; i<N; i++) { 7498 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7499 a.info.packageName = pkg.applicationInfo.packageName; 7500 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7501 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7502 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7503 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7504 a.info.dataDir = pkg.applicationInfo.dataDir; 7505 7506 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7507 // need other information about the application, like the ABI and what not ? 7508 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7509 mInstrumentation.put(a.getComponentName(), a); 7510 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7511 if (r == null) { 7512 r = new StringBuilder(256); 7513 } else { 7514 r.append(' '); 7515 } 7516 r.append(a.info.name); 7517 } 7518 } 7519 if (r != null) { 7520 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7521 } 7522 7523 if (pkg.protectedBroadcasts != null) { 7524 N = pkg.protectedBroadcasts.size(); 7525 for (i=0; i<N; i++) { 7526 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7527 } 7528 } 7529 7530 pkgSetting.setTimeStamp(scanFileTime); 7531 7532 // Create idmap files for pairs of (packages, overlay packages). 7533 // Note: "android", ie framework-res.apk, is handled by native layers. 7534 if (pkg.mOverlayTarget != null) { 7535 // This is an overlay package. 7536 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7537 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7538 mOverlays.put(pkg.mOverlayTarget, 7539 new ArrayMap<String, PackageParser.Package>()); 7540 } 7541 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7542 map.put(pkg.packageName, pkg); 7543 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7544 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7545 createIdmapFailed = true; 7546 } 7547 } 7548 } else if (mOverlays.containsKey(pkg.packageName) && 7549 !pkg.packageName.equals("android")) { 7550 // This is a regular package, with one or more known overlay packages. 7551 createIdmapsForPackageLI(pkg); 7552 } 7553 } 7554 7555 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7556 7557 if (createIdmapFailed) { 7558 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7559 "scanPackageLI failed to createIdmap"); 7560 } 7561 return pkg; 7562 } 7563 7564 /** 7565 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7566 * is derived purely on the basis of the contents of {@code scanFile} and 7567 * {@code cpuAbiOverride}. 7568 * 7569 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7570 */ 7571 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7572 String cpuAbiOverride, boolean extractLibs) 7573 throws PackageManagerException { 7574 // TODO: We can probably be smarter about this stuff. For installed apps, 7575 // we can calculate this information at install time once and for all. For 7576 // system apps, we can probably assume that this information doesn't change 7577 // after the first boot scan. As things stand, we do lots of unnecessary work. 7578 7579 // Give ourselves some initial paths; we'll come back for another 7580 // pass once we've determined ABI below. 7581 setNativeLibraryPaths(pkg); 7582 7583 // We would never need to extract libs for forward-locked and external packages, 7584 // since the container service will do it for us. We shouldn't attempt to 7585 // extract libs from system app when it was not updated. 7586 if (pkg.isForwardLocked() || isExternal(pkg) || 7587 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7588 extractLibs = false; 7589 } 7590 7591 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7592 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7593 7594 NativeLibraryHelper.Handle handle = null; 7595 try { 7596 handle = NativeLibraryHelper.Handle.create(pkg); 7597 // TODO(multiArch): This can be null for apps that didn't go through the 7598 // usual installation process. We can calculate it again, like we 7599 // do during install time. 7600 // 7601 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7602 // unnecessary. 7603 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7604 7605 // Null out the abis so that they can be recalculated. 7606 pkg.applicationInfo.primaryCpuAbi = null; 7607 pkg.applicationInfo.secondaryCpuAbi = null; 7608 if (isMultiArch(pkg.applicationInfo)) { 7609 // Warn if we've set an abiOverride for multi-lib packages.. 7610 // By definition, we need to copy both 32 and 64 bit libraries for 7611 // such packages. 7612 if (pkg.cpuAbiOverride != null 7613 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7614 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7615 } 7616 7617 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7618 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7619 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7620 if (extractLibs) { 7621 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7622 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7623 useIsaSpecificSubdirs); 7624 } else { 7625 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7626 } 7627 } 7628 7629 maybeThrowExceptionForMultiArchCopy( 7630 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7631 7632 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7633 if (extractLibs) { 7634 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7635 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7636 useIsaSpecificSubdirs); 7637 } else { 7638 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7639 } 7640 } 7641 7642 maybeThrowExceptionForMultiArchCopy( 7643 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7644 7645 if (abi64 >= 0) { 7646 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7647 } 7648 7649 if (abi32 >= 0) { 7650 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7651 if (abi64 >= 0) { 7652 pkg.applicationInfo.secondaryCpuAbi = abi; 7653 } else { 7654 pkg.applicationInfo.primaryCpuAbi = abi; 7655 } 7656 } 7657 } else { 7658 String[] abiList = (cpuAbiOverride != null) ? 7659 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7660 7661 // Enable gross and lame hacks for apps that are built with old 7662 // SDK tools. We must scan their APKs for renderscript bitcode and 7663 // not launch them if it's present. Don't bother checking on devices 7664 // that don't have 64 bit support. 7665 boolean needsRenderScriptOverride = false; 7666 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7667 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7668 abiList = Build.SUPPORTED_32_BIT_ABIS; 7669 needsRenderScriptOverride = true; 7670 } 7671 7672 final int copyRet; 7673 if (extractLibs) { 7674 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7675 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7676 } else { 7677 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7678 } 7679 7680 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7681 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7682 "Error unpackaging native libs for app, errorCode=" + copyRet); 7683 } 7684 7685 if (copyRet >= 0) { 7686 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7687 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7688 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7689 } else if (needsRenderScriptOverride) { 7690 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7691 } 7692 } 7693 } catch (IOException ioe) { 7694 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7695 } finally { 7696 IoUtils.closeQuietly(handle); 7697 } 7698 7699 // Now that we've calculated the ABIs and determined if it's an internal app, 7700 // we will go ahead and populate the nativeLibraryPath. 7701 setNativeLibraryPaths(pkg); 7702 } 7703 7704 /** 7705 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7706 * i.e, so that all packages can be run inside a single process if required. 7707 * 7708 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7709 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7710 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7711 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7712 * updating a package that belongs to a shared user. 7713 * 7714 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7715 * adds unnecessary complexity. 7716 */ 7717 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7718 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7719 String requiredInstructionSet = null; 7720 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7721 requiredInstructionSet = VMRuntime.getInstructionSet( 7722 scannedPackage.applicationInfo.primaryCpuAbi); 7723 } 7724 7725 PackageSetting requirer = null; 7726 for (PackageSetting ps : packagesForUser) { 7727 // If packagesForUser contains scannedPackage, we skip it. This will happen 7728 // when scannedPackage is an update of an existing package. Without this check, 7729 // we will never be able to change the ABI of any package belonging to a shared 7730 // user, even if it's compatible with other packages. 7731 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7732 if (ps.primaryCpuAbiString == null) { 7733 continue; 7734 } 7735 7736 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7737 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7738 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7739 // this but there's not much we can do. 7740 String errorMessage = "Instruction set mismatch, " 7741 + ((requirer == null) ? "[caller]" : requirer) 7742 + " requires " + requiredInstructionSet + " whereas " + ps 7743 + " requires " + instructionSet; 7744 Slog.w(TAG, errorMessage); 7745 } 7746 7747 if (requiredInstructionSet == null) { 7748 requiredInstructionSet = instructionSet; 7749 requirer = ps; 7750 } 7751 } 7752 } 7753 7754 if (requiredInstructionSet != null) { 7755 String adjustedAbi; 7756 if (requirer != null) { 7757 // requirer != null implies that either scannedPackage was null or that scannedPackage 7758 // did not require an ABI, in which case we have to adjust scannedPackage to match 7759 // the ABI of the set (which is the same as requirer's ABI) 7760 adjustedAbi = requirer.primaryCpuAbiString; 7761 if (scannedPackage != null) { 7762 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7763 } 7764 } else { 7765 // requirer == null implies that we're updating all ABIs in the set to 7766 // match scannedPackage. 7767 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7768 } 7769 7770 for (PackageSetting ps : packagesForUser) { 7771 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7772 if (ps.primaryCpuAbiString != null) { 7773 continue; 7774 } 7775 7776 ps.primaryCpuAbiString = adjustedAbi; 7777 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7778 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7779 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7780 7781 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7782 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7783 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7784 ps.primaryCpuAbiString = null; 7785 ps.pkg.applicationInfo.primaryCpuAbi = null; 7786 return; 7787 } else { 7788 mInstaller.rmdex(ps.codePathString, 7789 getDexCodeInstructionSet(getPreferredInstructionSet())); 7790 } 7791 } 7792 } 7793 } 7794 } 7795 } 7796 7797 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7798 synchronized (mPackages) { 7799 mResolverReplaced = true; 7800 // Set up information for custom user intent resolution activity. 7801 mResolveActivity.applicationInfo = pkg.applicationInfo; 7802 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7803 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7804 mResolveActivity.processName = pkg.applicationInfo.packageName; 7805 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7806 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7807 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7808 mResolveActivity.theme = 0; 7809 mResolveActivity.exported = true; 7810 mResolveActivity.enabled = true; 7811 mResolveInfo.activityInfo = mResolveActivity; 7812 mResolveInfo.priority = 0; 7813 mResolveInfo.preferredOrder = 0; 7814 mResolveInfo.match = 0; 7815 mResolveComponentName = mCustomResolverComponentName; 7816 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7817 mResolveComponentName); 7818 } 7819 } 7820 7821 private static String calculateBundledApkRoot(final String codePathString) { 7822 final File codePath = new File(codePathString); 7823 final File codeRoot; 7824 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7825 codeRoot = Environment.getRootDirectory(); 7826 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7827 codeRoot = Environment.getOemDirectory(); 7828 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7829 codeRoot = Environment.getVendorDirectory(); 7830 } else { 7831 // Unrecognized code path; take its top real segment as the apk root: 7832 // e.g. /something/app/blah.apk => /something 7833 try { 7834 File f = codePath.getCanonicalFile(); 7835 File parent = f.getParentFile(); // non-null because codePath is a file 7836 File tmp; 7837 while ((tmp = parent.getParentFile()) != null) { 7838 f = parent; 7839 parent = tmp; 7840 } 7841 codeRoot = f; 7842 Slog.w(TAG, "Unrecognized code path " 7843 + codePath + " - using " + codeRoot); 7844 } catch (IOException e) { 7845 // Can't canonicalize the code path -- shenanigans? 7846 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7847 return Environment.getRootDirectory().getPath(); 7848 } 7849 } 7850 return codeRoot.getPath(); 7851 } 7852 7853 /** 7854 * Derive and set the location of native libraries for the given package, 7855 * which varies depending on where and how the package was installed. 7856 */ 7857 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7858 final ApplicationInfo info = pkg.applicationInfo; 7859 final String codePath = pkg.codePath; 7860 final File codeFile = new File(codePath); 7861 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7862 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7863 7864 info.nativeLibraryRootDir = null; 7865 info.nativeLibraryRootRequiresIsa = false; 7866 info.nativeLibraryDir = null; 7867 info.secondaryNativeLibraryDir = null; 7868 7869 if (isApkFile(codeFile)) { 7870 // Monolithic install 7871 if (bundledApp) { 7872 // If "/system/lib64/apkname" exists, assume that is the per-package 7873 // native library directory to use; otherwise use "/system/lib/apkname". 7874 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7875 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7876 getPrimaryInstructionSet(info)); 7877 7878 // This is a bundled system app so choose the path based on the ABI. 7879 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7880 // is just the default path. 7881 final String apkName = deriveCodePathName(codePath); 7882 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7883 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7884 apkName).getAbsolutePath(); 7885 7886 if (info.secondaryCpuAbi != null) { 7887 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7888 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7889 secondaryLibDir, apkName).getAbsolutePath(); 7890 } 7891 } else if (asecApp) { 7892 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7893 .getAbsolutePath(); 7894 } else { 7895 final String apkName = deriveCodePathName(codePath); 7896 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7897 .getAbsolutePath(); 7898 } 7899 7900 info.nativeLibraryRootRequiresIsa = false; 7901 info.nativeLibraryDir = info.nativeLibraryRootDir; 7902 } else { 7903 // Cluster install 7904 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7905 info.nativeLibraryRootRequiresIsa = true; 7906 7907 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7908 getPrimaryInstructionSet(info)).getAbsolutePath(); 7909 7910 if (info.secondaryCpuAbi != null) { 7911 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7912 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7913 } 7914 } 7915 } 7916 7917 /** 7918 * Calculate the abis and roots for a bundled app. These can uniquely 7919 * be determined from the contents of the system partition, i.e whether 7920 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7921 * of this information, and instead assume that the system was built 7922 * sensibly. 7923 */ 7924 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7925 PackageSetting pkgSetting) { 7926 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7927 7928 // If "/system/lib64/apkname" exists, assume that is the per-package 7929 // native library directory to use; otherwise use "/system/lib/apkname". 7930 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7931 setBundledAppAbi(pkg, apkRoot, apkName); 7932 // pkgSetting might be null during rescan following uninstall of updates 7933 // to a bundled app, so accommodate that possibility. The settings in 7934 // that case will be established later from the parsed package. 7935 // 7936 // If the settings aren't null, sync them up with what we've just derived. 7937 // note that apkRoot isn't stored in the package settings. 7938 if (pkgSetting != null) { 7939 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7940 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7941 } 7942 } 7943 7944 /** 7945 * Deduces the ABI of a bundled app and sets the relevant fields on the 7946 * parsed pkg object. 7947 * 7948 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7949 * under which system libraries are installed. 7950 * @param apkName the name of the installed package. 7951 */ 7952 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7953 final File codeFile = new File(pkg.codePath); 7954 7955 final boolean has64BitLibs; 7956 final boolean has32BitLibs; 7957 if (isApkFile(codeFile)) { 7958 // Monolithic install 7959 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7960 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7961 } else { 7962 // Cluster install 7963 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7964 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7965 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7966 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7967 has64BitLibs = (new File(rootDir, isa)).exists(); 7968 } else { 7969 has64BitLibs = false; 7970 } 7971 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7972 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7973 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7974 has32BitLibs = (new File(rootDir, isa)).exists(); 7975 } else { 7976 has32BitLibs = false; 7977 } 7978 } 7979 7980 if (has64BitLibs && !has32BitLibs) { 7981 // The package has 64 bit libs, but not 32 bit libs. Its primary 7982 // ABI should be 64 bit. We can safely assume here that the bundled 7983 // native libraries correspond to the most preferred ABI in the list. 7984 7985 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7986 pkg.applicationInfo.secondaryCpuAbi = null; 7987 } else if (has32BitLibs && !has64BitLibs) { 7988 // The package has 32 bit libs but not 64 bit libs. Its primary 7989 // ABI should be 32 bit. 7990 7991 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7992 pkg.applicationInfo.secondaryCpuAbi = null; 7993 } else if (has32BitLibs && has64BitLibs) { 7994 // The application has both 64 and 32 bit bundled libraries. We check 7995 // here that the app declares multiArch support, and warn if it doesn't. 7996 // 7997 // We will be lenient here and record both ABIs. The primary will be the 7998 // ABI that's higher on the list, i.e, a device that's configured to prefer 7999 // 64 bit apps will see a 64 bit primary ABI, 8000 8001 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8002 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8003 } 8004 8005 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8006 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8007 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8008 } else { 8009 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8010 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8011 } 8012 } else { 8013 pkg.applicationInfo.primaryCpuAbi = null; 8014 pkg.applicationInfo.secondaryCpuAbi = null; 8015 } 8016 } 8017 8018 private void killApplication(String pkgName, int appId, String reason) { 8019 // Request the ActivityManager to kill the process(only for existing packages) 8020 // so that we do not end up in a confused state while the user is still using the older 8021 // version of the application while the new one gets installed. 8022 IActivityManager am = ActivityManagerNative.getDefault(); 8023 if (am != null) { 8024 try { 8025 am.killApplicationWithAppId(pkgName, appId, reason); 8026 } catch (RemoteException e) { 8027 } 8028 } 8029 } 8030 8031 void removePackageLI(PackageSetting ps, boolean chatty) { 8032 if (DEBUG_INSTALL) { 8033 if (chatty) 8034 Log.d(TAG, "Removing package " + ps.name); 8035 } 8036 8037 // writer 8038 synchronized (mPackages) { 8039 mPackages.remove(ps.name); 8040 final PackageParser.Package pkg = ps.pkg; 8041 if (pkg != null) { 8042 cleanPackageDataStructuresLILPw(pkg, chatty); 8043 } 8044 } 8045 } 8046 8047 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8048 if (DEBUG_INSTALL) { 8049 if (chatty) 8050 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8051 } 8052 8053 // writer 8054 synchronized (mPackages) { 8055 mPackages.remove(pkg.applicationInfo.packageName); 8056 cleanPackageDataStructuresLILPw(pkg, chatty); 8057 } 8058 } 8059 8060 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8061 int N = pkg.providers.size(); 8062 StringBuilder r = null; 8063 int i; 8064 for (i=0; i<N; i++) { 8065 PackageParser.Provider p = pkg.providers.get(i); 8066 mProviders.removeProvider(p); 8067 if (p.info.authority == null) { 8068 8069 /* There was another ContentProvider with this authority when 8070 * this app was installed so this authority is null, 8071 * Ignore it as we don't have to unregister the provider. 8072 */ 8073 continue; 8074 } 8075 String names[] = p.info.authority.split(";"); 8076 for (int j = 0; j < names.length; j++) { 8077 if (mProvidersByAuthority.get(names[j]) == p) { 8078 mProvidersByAuthority.remove(names[j]); 8079 if (DEBUG_REMOVE) { 8080 if (chatty) 8081 Log.d(TAG, "Unregistered content provider: " + names[j] 8082 + ", className = " + p.info.name + ", isSyncable = " 8083 + p.info.isSyncable); 8084 } 8085 } 8086 } 8087 if (DEBUG_REMOVE && chatty) { 8088 if (r == null) { 8089 r = new StringBuilder(256); 8090 } else { 8091 r.append(' '); 8092 } 8093 r.append(p.info.name); 8094 } 8095 } 8096 if (r != null) { 8097 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8098 } 8099 8100 N = pkg.services.size(); 8101 r = null; 8102 for (i=0; i<N; i++) { 8103 PackageParser.Service s = pkg.services.get(i); 8104 mServices.removeService(s); 8105 if (chatty) { 8106 if (r == null) { 8107 r = new StringBuilder(256); 8108 } else { 8109 r.append(' '); 8110 } 8111 r.append(s.info.name); 8112 } 8113 } 8114 if (r != null) { 8115 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8116 } 8117 8118 N = pkg.receivers.size(); 8119 r = null; 8120 for (i=0; i<N; i++) { 8121 PackageParser.Activity a = pkg.receivers.get(i); 8122 mReceivers.removeActivity(a, "receiver"); 8123 if (DEBUG_REMOVE && chatty) { 8124 if (r == null) { 8125 r = new StringBuilder(256); 8126 } else { 8127 r.append(' '); 8128 } 8129 r.append(a.info.name); 8130 } 8131 } 8132 if (r != null) { 8133 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8134 } 8135 8136 N = pkg.activities.size(); 8137 r = null; 8138 for (i=0; i<N; i++) { 8139 PackageParser.Activity a = pkg.activities.get(i); 8140 mActivities.removeActivity(a, "activity"); 8141 if (DEBUG_REMOVE && chatty) { 8142 if (r == null) { 8143 r = new StringBuilder(256); 8144 } else { 8145 r.append(' '); 8146 } 8147 r.append(a.info.name); 8148 } 8149 } 8150 if (r != null) { 8151 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8152 } 8153 8154 N = pkg.permissions.size(); 8155 r = null; 8156 for (i=0; i<N; i++) { 8157 PackageParser.Permission p = pkg.permissions.get(i); 8158 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8159 if (bp == null) { 8160 bp = mSettings.mPermissionTrees.get(p.info.name); 8161 } 8162 if (bp != null && bp.perm == p) { 8163 bp.perm = null; 8164 if (DEBUG_REMOVE && chatty) { 8165 if (r == null) { 8166 r = new StringBuilder(256); 8167 } else { 8168 r.append(' '); 8169 } 8170 r.append(p.info.name); 8171 } 8172 } 8173 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8174 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8175 if (appOpPerms != null) { 8176 appOpPerms.remove(pkg.packageName); 8177 } 8178 } 8179 } 8180 if (r != null) { 8181 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8182 } 8183 8184 N = pkg.requestedPermissions.size(); 8185 r = null; 8186 for (i=0; i<N; i++) { 8187 String perm = pkg.requestedPermissions.get(i); 8188 BasePermission bp = mSettings.mPermissions.get(perm); 8189 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8190 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8191 if (appOpPerms != null) { 8192 appOpPerms.remove(pkg.packageName); 8193 if (appOpPerms.isEmpty()) { 8194 mAppOpPermissionPackages.remove(perm); 8195 } 8196 } 8197 } 8198 } 8199 if (r != null) { 8200 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8201 } 8202 8203 N = pkg.instrumentation.size(); 8204 r = null; 8205 for (i=0; i<N; i++) { 8206 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8207 mInstrumentation.remove(a.getComponentName()); 8208 if (DEBUG_REMOVE && chatty) { 8209 if (r == null) { 8210 r = new StringBuilder(256); 8211 } else { 8212 r.append(' '); 8213 } 8214 r.append(a.info.name); 8215 } 8216 } 8217 if (r != null) { 8218 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8219 } 8220 8221 r = null; 8222 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8223 // Only system apps can hold shared libraries. 8224 if (pkg.libraryNames != null) { 8225 for (i=0; i<pkg.libraryNames.size(); i++) { 8226 String name = pkg.libraryNames.get(i); 8227 SharedLibraryEntry cur = mSharedLibraries.get(name); 8228 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8229 mSharedLibraries.remove(name); 8230 if (DEBUG_REMOVE && chatty) { 8231 if (r == null) { 8232 r = new StringBuilder(256); 8233 } else { 8234 r.append(' '); 8235 } 8236 r.append(name); 8237 } 8238 } 8239 } 8240 } 8241 } 8242 if (r != null) { 8243 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8244 } 8245 } 8246 8247 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8248 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8249 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8250 return true; 8251 } 8252 } 8253 return false; 8254 } 8255 8256 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8257 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8258 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8259 8260 private void updatePermissionsLPw(String changingPkg, 8261 PackageParser.Package pkgInfo, int flags) { 8262 // Make sure there are no dangling permission trees. 8263 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8264 while (it.hasNext()) { 8265 final BasePermission bp = it.next(); 8266 if (bp.packageSetting == null) { 8267 // We may not yet have parsed the package, so just see if 8268 // we still know about its settings. 8269 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8270 } 8271 if (bp.packageSetting == null) { 8272 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8273 + " from package " + bp.sourcePackage); 8274 it.remove(); 8275 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8276 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8277 Slog.i(TAG, "Removing old permission tree: " + bp.name 8278 + " from package " + bp.sourcePackage); 8279 flags |= UPDATE_PERMISSIONS_ALL; 8280 it.remove(); 8281 } 8282 } 8283 } 8284 8285 // Make sure all dynamic permissions have been assigned to a package, 8286 // and make sure there are no dangling permissions. 8287 it = mSettings.mPermissions.values().iterator(); 8288 while (it.hasNext()) { 8289 final BasePermission bp = it.next(); 8290 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8291 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8292 + bp.name + " pkg=" + bp.sourcePackage 8293 + " info=" + bp.pendingInfo); 8294 if (bp.packageSetting == null && bp.pendingInfo != null) { 8295 final BasePermission tree = findPermissionTreeLP(bp.name); 8296 if (tree != null && tree.perm != null) { 8297 bp.packageSetting = tree.packageSetting; 8298 bp.perm = new PackageParser.Permission(tree.perm.owner, 8299 new PermissionInfo(bp.pendingInfo)); 8300 bp.perm.info.packageName = tree.perm.info.packageName; 8301 bp.perm.info.name = bp.name; 8302 bp.uid = tree.uid; 8303 } 8304 } 8305 } 8306 if (bp.packageSetting == null) { 8307 // We may not yet have parsed the package, so just see if 8308 // we still know about its settings. 8309 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8310 } 8311 if (bp.packageSetting == null) { 8312 Slog.w(TAG, "Removing dangling permission: " + bp.name 8313 + " from package " + bp.sourcePackage); 8314 it.remove(); 8315 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8316 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8317 Slog.i(TAG, "Removing old permission: " + bp.name 8318 + " from package " + bp.sourcePackage); 8319 flags |= UPDATE_PERMISSIONS_ALL; 8320 it.remove(); 8321 } 8322 } 8323 } 8324 8325 // Now update the permissions for all packages, in particular 8326 // replace the granted permissions of the system packages. 8327 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8328 for (PackageParser.Package pkg : mPackages.values()) { 8329 if (pkg != pkgInfo) { 8330 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8331 changingPkg); 8332 } 8333 } 8334 } 8335 8336 if (pkgInfo != null) { 8337 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8338 } 8339 } 8340 8341 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8342 String packageOfInterest) { 8343 // IMPORTANT: There are two types of permissions: install and runtime. 8344 // Install time permissions are granted when the app is installed to 8345 // all device users and users added in the future. Runtime permissions 8346 // are granted at runtime explicitly to specific users. Normal and signature 8347 // protected permissions are install time permissions. Dangerous permissions 8348 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8349 // otherwise they are runtime permissions. This function does not manage 8350 // runtime permissions except for the case an app targeting Lollipop MR1 8351 // being upgraded to target a newer SDK, in which case dangerous permissions 8352 // are transformed from install time to runtime ones. 8353 8354 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8355 if (ps == null) { 8356 return; 8357 } 8358 8359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8360 8361 PermissionsState permissionsState = ps.getPermissionsState(); 8362 PermissionsState origPermissions = permissionsState; 8363 8364 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8365 8366 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8367 8368 boolean changedInstallPermission = false; 8369 8370 if (replace) { 8371 ps.installPermissionsFixed = false; 8372 if (!ps.isSharedUser()) { 8373 origPermissions = new PermissionsState(permissionsState); 8374 permissionsState.reset(); 8375 } 8376 } 8377 8378 permissionsState.setGlobalGids(mGlobalGids); 8379 8380 final int N = pkg.requestedPermissions.size(); 8381 for (int i=0; i<N; i++) { 8382 final String name = pkg.requestedPermissions.get(i); 8383 final BasePermission bp = mSettings.mPermissions.get(name); 8384 8385 if (DEBUG_INSTALL) { 8386 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8387 } 8388 8389 if (bp == null || bp.packageSetting == null) { 8390 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8391 Slog.w(TAG, "Unknown permission " + name 8392 + " in package " + pkg.packageName); 8393 } 8394 continue; 8395 } 8396 8397 final String perm = bp.name; 8398 boolean allowedSig = false; 8399 int grant = GRANT_DENIED; 8400 8401 // Keep track of app op permissions. 8402 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8403 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8404 if (pkgs == null) { 8405 pkgs = new ArraySet<>(); 8406 mAppOpPermissionPackages.put(bp.name, pkgs); 8407 } 8408 pkgs.add(pkg.packageName); 8409 } 8410 8411 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8412 switch (level) { 8413 case PermissionInfo.PROTECTION_NORMAL: { 8414 // For all apps normal permissions are install time ones. 8415 grant = GRANT_INSTALL; 8416 } break; 8417 8418 case PermissionInfo.PROTECTION_DANGEROUS: { 8419 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8420 // For legacy apps dangerous permissions are install time ones. 8421 grant = GRANT_INSTALL_LEGACY; 8422 } else if (origPermissions.hasInstallPermission(bp.name)) { 8423 // For legacy apps that became modern, install becomes runtime. 8424 grant = GRANT_UPGRADE; 8425 } else { 8426 // For modern apps keep runtime permissions unchanged. 8427 grant = GRANT_RUNTIME; 8428 } 8429 } break; 8430 8431 case PermissionInfo.PROTECTION_SIGNATURE: { 8432 // For all apps signature permissions are install time ones. 8433 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8434 if (allowedSig) { 8435 grant = GRANT_INSTALL; 8436 } 8437 } break; 8438 } 8439 8440 if (DEBUG_INSTALL) { 8441 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8442 } 8443 8444 if (grant != GRANT_DENIED) { 8445 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8446 // If this is an existing, non-system package, then 8447 // we can't add any new permissions to it. 8448 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8449 // Except... if this is a permission that was added 8450 // to the platform (note: need to only do this when 8451 // updating the platform). 8452 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8453 grant = GRANT_DENIED; 8454 } 8455 } 8456 } 8457 8458 switch (grant) { 8459 case GRANT_INSTALL: { 8460 // Revoke this as runtime permission to handle the case of 8461 // a runtime permission being downgraded to an install one. 8462 for (int userId : UserManagerService.getInstance().getUserIds()) { 8463 if (origPermissions.getRuntimePermissionState( 8464 bp.name, userId) != null) { 8465 // Revoke the runtime permission and clear the flags. 8466 origPermissions.revokeRuntimePermission(bp, userId); 8467 origPermissions.updatePermissionFlags(bp, userId, 8468 PackageManager.MASK_PERMISSION_FLAGS, 0); 8469 // If we revoked a permission permission, we have to write. 8470 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8471 changedRuntimePermissionUserIds, userId); 8472 } 8473 } 8474 // Grant an install permission. 8475 if (permissionsState.grantInstallPermission(bp) != 8476 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8477 changedInstallPermission = true; 8478 } 8479 } break; 8480 8481 case GRANT_INSTALL_LEGACY: { 8482 // Grant an install permission. 8483 if (permissionsState.grantInstallPermission(bp) != 8484 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8485 changedInstallPermission = true; 8486 } 8487 } break; 8488 8489 case GRANT_RUNTIME: { 8490 // Grant previously granted runtime permissions. 8491 for (int userId : UserManagerService.getInstance().getUserIds()) { 8492 PermissionState permissionState = origPermissions 8493 .getRuntimePermissionState(bp.name, userId); 8494 final int flags = permissionState != null 8495 ? permissionState.getFlags() : 0; 8496 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8497 if (permissionsState.grantRuntimePermission(bp, userId) == 8498 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8499 // If we cannot put the permission as it was, we have to write. 8500 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8501 changedRuntimePermissionUserIds, userId); 8502 } 8503 } 8504 // Propagate the permission flags. 8505 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8506 } 8507 } break; 8508 8509 case GRANT_UPGRADE: { 8510 // Grant runtime permissions for a previously held install permission. 8511 PermissionState permissionState = origPermissions 8512 .getInstallPermissionState(bp.name); 8513 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8514 8515 if (origPermissions.revokeInstallPermission(bp) 8516 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8517 // We will be transferring the permission flags, so clear them. 8518 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8519 PackageManager.MASK_PERMISSION_FLAGS, 0); 8520 changedInstallPermission = true; 8521 } 8522 8523 // If the permission is not to be promoted to runtime we ignore it and 8524 // also its other flags as they are not applicable to install permissions. 8525 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8526 for (int userId : currentUserIds) { 8527 if (permissionsState.grantRuntimePermission(bp, userId) != 8528 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8529 // Transfer the permission flags. 8530 permissionsState.updatePermissionFlags(bp, userId, 8531 flags, flags); 8532 // If we granted the permission, we have to write. 8533 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8534 changedRuntimePermissionUserIds, userId); 8535 } 8536 } 8537 } 8538 } break; 8539 8540 default: { 8541 if (packageOfInterest == null 8542 || packageOfInterest.equals(pkg.packageName)) { 8543 Slog.w(TAG, "Not granting permission " + perm 8544 + " to package " + pkg.packageName 8545 + " because it was previously installed without"); 8546 } 8547 } break; 8548 } 8549 } else { 8550 if (permissionsState.revokeInstallPermission(bp) != 8551 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8552 // Also drop the permission flags. 8553 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8554 PackageManager.MASK_PERMISSION_FLAGS, 0); 8555 changedInstallPermission = true; 8556 Slog.i(TAG, "Un-granting permission " + perm 8557 + " from package " + pkg.packageName 8558 + " (protectionLevel=" + bp.protectionLevel 8559 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8560 + ")"); 8561 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8562 // Don't print warning for app op permissions, since it is fine for them 8563 // not to be granted, there is a UI for the user to decide. 8564 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8565 Slog.w(TAG, "Not granting permission " + perm 8566 + " to package " + pkg.packageName 8567 + " (protectionLevel=" + bp.protectionLevel 8568 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8569 + ")"); 8570 } 8571 } 8572 } 8573 } 8574 8575 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8576 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8577 // This is the first that we have heard about this package, so the 8578 // permissions we have now selected are fixed until explicitly 8579 // changed. 8580 ps.installPermissionsFixed = true; 8581 } 8582 8583 // Persist the runtime permissions state for users with changes. 8584 for (int userId : changedRuntimePermissionUserIds) { 8585 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8586 } 8587 8588 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8589 } 8590 8591 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8592 boolean allowed = false; 8593 final int NP = PackageParser.NEW_PERMISSIONS.length; 8594 for (int ip=0; ip<NP; ip++) { 8595 final PackageParser.NewPermissionInfo npi 8596 = PackageParser.NEW_PERMISSIONS[ip]; 8597 if (npi.name.equals(perm) 8598 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8599 allowed = true; 8600 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8601 + pkg.packageName); 8602 break; 8603 } 8604 } 8605 return allowed; 8606 } 8607 8608 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8609 BasePermission bp, PermissionsState origPermissions) { 8610 boolean allowed; 8611 allowed = (compareSignatures( 8612 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8613 == PackageManager.SIGNATURE_MATCH) 8614 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8615 == PackageManager.SIGNATURE_MATCH); 8616 if (!allowed && (bp.protectionLevel 8617 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8618 if (isSystemApp(pkg)) { 8619 // For updated system applications, a system permission 8620 // is granted only if it had been defined by the original application. 8621 if (pkg.isUpdatedSystemApp()) { 8622 final PackageSetting sysPs = mSettings 8623 .getDisabledSystemPkgLPr(pkg.packageName); 8624 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8625 // If the original was granted this permission, we take 8626 // that grant decision as read and propagate it to the 8627 // update. 8628 if (sysPs.isPrivileged()) { 8629 allowed = true; 8630 } 8631 } else { 8632 // The system apk may have been updated with an older 8633 // version of the one on the data partition, but which 8634 // granted a new system permission that it didn't have 8635 // before. In this case we do want to allow the app to 8636 // now get the new permission if the ancestral apk is 8637 // privileged to get it. 8638 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8639 for (int j=0; 8640 j<sysPs.pkg.requestedPermissions.size(); j++) { 8641 if (perm.equals( 8642 sysPs.pkg.requestedPermissions.get(j))) { 8643 allowed = true; 8644 break; 8645 } 8646 } 8647 } 8648 } 8649 } else { 8650 allowed = isPrivilegedApp(pkg); 8651 } 8652 } 8653 } 8654 if (!allowed) { 8655 if (!allowed && (bp.protectionLevel 8656 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8657 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8658 // If this was a previously normal/dangerous permission that got moved 8659 // to a system permission as part of the runtime permission redesign, then 8660 // we still want to blindly grant it to old apps. 8661 allowed = true; 8662 } 8663 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8664 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8665 // If this permission is to be granted to the system installer and 8666 // this app is an installer, then it gets the permission. 8667 allowed = true; 8668 } 8669 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8670 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8671 // If this permission is to be granted to the system verifier and 8672 // this app is a verifier, then it gets the permission. 8673 allowed = true; 8674 } 8675 if (!allowed && (bp.protectionLevel 8676 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8677 && isSystemApp(pkg)) { 8678 // Any pre-installed system app is allowed to get this permission. 8679 allowed = true; 8680 } 8681 if (!allowed && (bp.protectionLevel 8682 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8683 // For development permissions, a development permission 8684 // is granted only if it was already granted. 8685 allowed = origPermissions.hasInstallPermission(perm); 8686 } 8687 } 8688 return allowed; 8689 } 8690 8691 final class ActivityIntentResolver 8692 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8693 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8694 boolean defaultOnly, int userId) { 8695 if (!sUserManager.exists(userId)) return null; 8696 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8697 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8698 } 8699 8700 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8701 int userId) { 8702 if (!sUserManager.exists(userId)) return null; 8703 mFlags = flags; 8704 return super.queryIntent(intent, resolvedType, 8705 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8706 } 8707 8708 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8709 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8710 if (!sUserManager.exists(userId)) return null; 8711 if (packageActivities == null) { 8712 return null; 8713 } 8714 mFlags = flags; 8715 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8716 final int N = packageActivities.size(); 8717 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8718 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8719 8720 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8721 for (int i = 0; i < N; ++i) { 8722 intentFilters = packageActivities.get(i).intents; 8723 if (intentFilters != null && intentFilters.size() > 0) { 8724 PackageParser.ActivityIntentInfo[] array = 8725 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8726 intentFilters.toArray(array); 8727 listCut.add(array); 8728 } 8729 } 8730 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8731 } 8732 8733 public final void addActivity(PackageParser.Activity a, String type) { 8734 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8735 mActivities.put(a.getComponentName(), a); 8736 if (DEBUG_SHOW_INFO) 8737 Log.v( 8738 TAG, " " + type + " " + 8739 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8740 if (DEBUG_SHOW_INFO) 8741 Log.v(TAG, " Class=" + a.info.name); 8742 final int NI = a.intents.size(); 8743 for (int j=0; j<NI; j++) { 8744 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8745 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8746 intent.setPriority(0); 8747 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8748 + a.className + " with priority > 0, forcing to 0"); 8749 } 8750 if (DEBUG_SHOW_INFO) { 8751 Log.v(TAG, " IntentFilter:"); 8752 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8753 } 8754 if (!intent.debugCheck()) { 8755 Log.w(TAG, "==> For Activity " + a.info.name); 8756 } 8757 addFilter(intent); 8758 } 8759 } 8760 8761 public final void removeActivity(PackageParser.Activity a, String type) { 8762 mActivities.remove(a.getComponentName()); 8763 if (DEBUG_SHOW_INFO) { 8764 Log.v(TAG, " " + type + " " 8765 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8766 : a.info.name) + ":"); 8767 Log.v(TAG, " Class=" + a.info.name); 8768 } 8769 final int NI = a.intents.size(); 8770 for (int j=0; j<NI; j++) { 8771 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8772 if (DEBUG_SHOW_INFO) { 8773 Log.v(TAG, " IntentFilter:"); 8774 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8775 } 8776 removeFilter(intent); 8777 } 8778 } 8779 8780 @Override 8781 protected boolean allowFilterResult( 8782 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8783 ActivityInfo filterAi = filter.activity.info; 8784 for (int i=dest.size()-1; i>=0; i--) { 8785 ActivityInfo destAi = dest.get(i).activityInfo; 8786 if (destAi.name == filterAi.name 8787 && destAi.packageName == filterAi.packageName) { 8788 return false; 8789 } 8790 } 8791 return true; 8792 } 8793 8794 @Override 8795 protected ActivityIntentInfo[] newArray(int size) { 8796 return new ActivityIntentInfo[size]; 8797 } 8798 8799 @Override 8800 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8801 if (!sUserManager.exists(userId)) return true; 8802 PackageParser.Package p = filter.activity.owner; 8803 if (p != null) { 8804 PackageSetting ps = (PackageSetting)p.mExtras; 8805 if (ps != null) { 8806 // System apps are never considered stopped for purposes of 8807 // filtering, because there may be no way for the user to 8808 // actually re-launch them. 8809 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8810 && ps.getStopped(userId); 8811 } 8812 } 8813 return false; 8814 } 8815 8816 @Override 8817 protected boolean isPackageForFilter(String packageName, 8818 PackageParser.ActivityIntentInfo info) { 8819 return packageName.equals(info.activity.owner.packageName); 8820 } 8821 8822 @Override 8823 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8824 int match, int userId) { 8825 if (!sUserManager.exists(userId)) return null; 8826 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8827 return null; 8828 } 8829 final PackageParser.Activity activity = info.activity; 8830 if (mSafeMode && (activity.info.applicationInfo.flags 8831 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8832 return null; 8833 } 8834 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8835 if (ps == null) { 8836 return null; 8837 } 8838 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8839 ps.readUserState(userId), userId); 8840 if (ai == null) { 8841 return null; 8842 } 8843 final ResolveInfo res = new ResolveInfo(); 8844 res.activityInfo = ai; 8845 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8846 res.filter = info; 8847 } 8848 if (info != null) { 8849 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8850 } 8851 res.priority = info.getPriority(); 8852 res.preferredOrder = activity.owner.mPreferredOrder; 8853 //System.out.println("Result: " + res.activityInfo.className + 8854 // " = " + res.priority); 8855 res.match = match; 8856 res.isDefault = info.hasDefault; 8857 res.labelRes = info.labelRes; 8858 res.nonLocalizedLabel = info.nonLocalizedLabel; 8859 if (userNeedsBadging(userId)) { 8860 res.noResourceId = true; 8861 } else { 8862 res.icon = info.icon; 8863 } 8864 res.iconResourceId = info.icon; 8865 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8866 return res; 8867 } 8868 8869 @Override 8870 protected void sortResults(List<ResolveInfo> results) { 8871 Collections.sort(results, mResolvePrioritySorter); 8872 } 8873 8874 @Override 8875 protected void dumpFilter(PrintWriter out, String prefix, 8876 PackageParser.ActivityIntentInfo filter) { 8877 out.print(prefix); out.print( 8878 Integer.toHexString(System.identityHashCode(filter.activity))); 8879 out.print(' '); 8880 filter.activity.printComponentShortName(out); 8881 out.print(" filter "); 8882 out.println(Integer.toHexString(System.identityHashCode(filter))); 8883 } 8884 8885 @Override 8886 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8887 return filter.activity; 8888 } 8889 8890 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8891 PackageParser.Activity activity = (PackageParser.Activity)label; 8892 out.print(prefix); out.print( 8893 Integer.toHexString(System.identityHashCode(activity))); 8894 out.print(' '); 8895 activity.printComponentShortName(out); 8896 if (count > 1) { 8897 out.print(" ("); out.print(count); out.print(" filters)"); 8898 } 8899 out.println(); 8900 } 8901 8902// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8903// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8904// final List<ResolveInfo> retList = Lists.newArrayList(); 8905// while (i.hasNext()) { 8906// final ResolveInfo resolveInfo = i.next(); 8907// if (isEnabledLP(resolveInfo.activityInfo)) { 8908// retList.add(resolveInfo); 8909// } 8910// } 8911// return retList; 8912// } 8913 8914 // Keys are String (activity class name), values are Activity. 8915 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8916 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8917 private int mFlags; 8918 } 8919 8920 private final class ServiceIntentResolver 8921 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8922 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8923 boolean defaultOnly, int userId) { 8924 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8925 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8926 } 8927 8928 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8929 int userId) { 8930 if (!sUserManager.exists(userId)) return null; 8931 mFlags = flags; 8932 return super.queryIntent(intent, resolvedType, 8933 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8934 } 8935 8936 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8937 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8938 if (!sUserManager.exists(userId)) return null; 8939 if (packageServices == null) { 8940 return null; 8941 } 8942 mFlags = flags; 8943 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8944 final int N = packageServices.size(); 8945 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8946 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8947 8948 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8949 for (int i = 0; i < N; ++i) { 8950 intentFilters = packageServices.get(i).intents; 8951 if (intentFilters != null && intentFilters.size() > 0) { 8952 PackageParser.ServiceIntentInfo[] array = 8953 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8954 intentFilters.toArray(array); 8955 listCut.add(array); 8956 } 8957 } 8958 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8959 } 8960 8961 public final void addService(PackageParser.Service s) { 8962 mServices.put(s.getComponentName(), s); 8963 if (DEBUG_SHOW_INFO) { 8964 Log.v(TAG, " " 8965 + (s.info.nonLocalizedLabel != null 8966 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8967 Log.v(TAG, " Class=" + s.info.name); 8968 } 8969 final int NI = s.intents.size(); 8970 int j; 8971 for (j=0; j<NI; j++) { 8972 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8973 if (DEBUG_SHOW_INFO) { 8974 Log.v(TAG, " IntentFilter:"); 8975 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8976 } 8977 if (!intent.debugCheck()) { 8978 Log.w(TAG, "==> For Service " + s.info.name); 8979 } 8980 addFilter(intent); 8981 } 8982 } 8983 8984 public final void removeService(PackageParser.Service s) { 8985 mServices.remove(s.getComponentName()); 8986 if (DEBUG_SHOW_INFO) { 8987 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8988 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8989 Log.v(TAG, " Class=" + s.info.name); 8990 } 8991 final int NI = s.intents.size(); 8992 int j; 8993 for (j=0; j<NI; j++) { 8994 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8995 if (DEBUG_SHOW_INFO) { 8996 Log.v(TAG, " IntentFilter:"); 8997 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8998 } 8999 removeFilter(intent); 9000 } 9001 } 9002 9003 @Override 9004 protected boolean allowFilterResult( 9005 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9006 ServiceInfo filterSi = filter.service.info; 9007 for (int i=dest.size()-1; i>=0; i--) { 9008 ServiceInfo destAi = dest.get(i).serviceInfo; 9009 if (destAi.name == filterSi.name 9010 && destAi.packageName == filterSi.packageName) { 9011 return false; 9012 } 9013 } 9014 return true; 9015 } 9016 9017 @Override 9018 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9019 return new PackageParser.ServiceIntentInfo[size]; 9020 } 9021 9022 @Override 9023 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9024 if (!sUserManager.exists(userId)) return true; 9025 PackageParser.Package p = filter.service.owner; 9026 if (p != null) { 9027 PackageSetting ps = (PackageSetting)p.mExtras; 9028 if (ps != null) { 9029 // System apps are never considered stopped for purposes of 9030 // filtering, because there may be no way for the user to 9031 // actually re-launch them. 9032 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9033 && ps.getStopped(userId); 9034 } 9035 } 9036 return false; 9037 } 9038 9039 @Override 9040 protected boolean isPackageForFilter(String packageName, 9041 PackageParser.ServiceIntentInfo info) { 9042 return packageName.equals(info.service.owner.packageName); 9043 } 9044 9045 @Override 9046 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9047 int match, int userId) { 9048 if (!sUserManager.exists(userId)) return null; 9049 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9050 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9051 return null; 9052 } 9053 final PackageParser.Service service = info.service; 9054 if (mSafeMode && (service.info.applicationInfo.flags 9055 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9056 return null; 9057 } 9058 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9059 if (ps == null) { 9060 return null; 9061 } 9062 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9063 ps.readUserState(userId), userId); 9064 if (si == null) { 9065 return null; 9066 } 9067 final ResolveInfo res = new ResolveInfo(); 9068 res.serviceInfo = si; 9069 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9070 res.filter = filter; 9071 } 9072 res.priority = info.getPriority(); 9073 res.preferredOrder = service.owner.mPreferredOrder; 9074 res.match = match; 9075 res.isDefault = info.hasDefault; 9076 res.labelRes = info.labelRes; 9077 res.nonLocalizedLabel = info.nonLocalizedLabel; 9078 res.icon = info.icon; 9079 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9080 return res; 9081 } 9082 9083 @Override 9084 protected void sortResults(List<ResolveInfo> results) { 9085 Collections.sort(results, mResolvePrioritySorter); 9086 } 9087 9088 @Override 9089 protected void dumpFilter(PrintWriter out, String prefix, 9090 PackageParser.ServiceIntentInfo filter) { 9091 out.print(prefix); out.print( 9092 Integer.toHexString(System.identityHashCode(filter.service))); 9093 out.print(' '); 9094 filter.service.printComponentShortName(out); 9095 out.print(" filter "); 9096 out.println(Integer.toHexString(System.identityHashCode(filter))); 9097 } 9098 9099 @Override 9100 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9101 return filter.service; 9102 } 9103 9104 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9105 PackageParser.Service service = (PackageParser.Service)label; 9106 out.print(prefix); out.print( 9107 Integer.toHexString(System.identityHashCode(service))); 9108 out.print(' '); 9109 service.printComponentShortName(out); 9110 if (count > 1) { 9111 out.print(" ("); out.print(count); out.print(" filters)"); 9112 } 9113 out.println(); 9114 } 9115 9116// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9117// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9118// final List<ResolveInfo> retList = Lists.newArrayList(); 9119// while (i.hasNext()) { 9120// final ResolveInfo resolveInfo = (ResolveInfo) i; 9121// if (isEnabledLP(resolveInfo.serviceInfo)) { 9122// retList.add(resolveInfo); 9123// } 9124// } 9125// return retList; 9126// } 9127 9128 // Keys are String (activity class name), values are Activity. 9129 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9130 = new ArrayMap<ComponentName, PackageParser.Service>(); 9131 private int mFlags; 9132 }; 9133 9134 private final class ProviderIntentResolver 9135 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9136 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9137 boolean defaultOnly, int userId) { 9138 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9139 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9140 } 9141 9142 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9143 int userId) { 9144 if (!sUserManager.exists(userId)) 9145 return null; 9146 mFlags = flags; 9147 return super.queryIntent(intent, resolvedType, 9148 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9149 } 9150 9151 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9152 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9153 if (!sUserManager.exists(userId)) 9154 return null; 9155 if (packageProviders == null) { 9156 return null; 9157 } 9158 mFlags = flags; 9159 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9160 final int N = packageProviders.size(); 9161 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9162 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9163 9164 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9165 for (int i = 0; i < N; ++i) { 9166 intentFilters = packageProviders.get(i).intents; 9167 if (intentFilters != null && intentFilters.size() > 0) { 9168 PackageParser.ProviderIntentInfo[] array = 9169 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9170 intentFilters.toArray(array); 9171 listCut.add(array); 9172 } 9173 } 9174 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9175 } 9176 9177 public final void addProvider(PackageParser.Provider p) { 9178 if (mProviders.containsKey(p.getComponentName())) { 9179 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9180 return; 9181 } 9182 9183 mProviders.put(p.getComponentName(), p); 9184 if (DEBUG_SHOW_INFO) { 9185 Log.v(TAG, " " 9186 + (p.info.nonLocalizedLabel != null 9187 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9188 Log.v(TAG, " Class=" + p.info.name); 9189 } 9190 final int NI = p.intents.size(); 9191 int j; 9192 for (j = 0; j < NI; j++) { 9193 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9194 if (DEBUG_SHOW_INFO) { 9195 Log.v(TAG, " IntentFilter:"); 9196 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9197 } 9198 if (!intent.debugCheck()) { 9199 Log.w(TAG, "==> For Provider " + p.info.name); 9200 } 9201 addFilter(intent); 9202 } 9203 } 9204 9205 public final void removeProvider(PackageParser.Provider p) { 9206 mProviders.remove(p.getComponentName()); 9207 if (DEBUG_SHOW_INFO) { 9208 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9209 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9210 Log.v(TAG, " Class=" + p.info.name); 9211 } 9212 final int NI = p.intents.size(); 9213 int j; 9214 for (j = 0; j < NI; j++) { 9215 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9216 if (DEBUG_SHOW_INFO) { 9217 Log.v(TAG, " IntentFilter:"); 9218 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9219 } 9220 removeFilter(intent); 9221 } 9222 } 9223 9224 @Override 9225 protected boolean allowFilterResult( 9226 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9227 ProviderInfo filterPi = filter.provider.info; 9228 for (int i = dest.size() - 1; i >= 0; i--) { 9229 ProviderInfo destPi = dest.get(i).providerInfo; 9230 if (destPi.name == filterPi.name 9231 && destPi.packageName == filterPi.packageName) { 9232 return false; 9233 } 9234 } 9235 return true; 9236 } 9237 9238 @Override 9239 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9240 return new PackageParser.ProviderIntentInfo[size]; 9241 } 9242 9243 @Override 9244 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9245 if (!sUserManager.exists(userId)) 9246 return true; 9247 PackageParser.Package p = filter.provider.owner; 9248 if (p != null) { 9249 PackageSetting ps = (PackageSetting) p.mExtras; 9250 if (ps != null) { 9251 // System apps are never considered stopped for purposes of 9252 // filtering, because there may be no way for the user to 9253 // actually re-launch them. 9254 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9255 && ps.getStopped(userId); 9256 } 9257 } 9258 return false; 9259 } 9260 9261 @Override 9262 protected boolean isPackageForFilter(String packageName, 9263 PackageParser.ProviderIntentInfo info) { 9264 return packageName.equals(info.provider.owner.packageName); 9265 } 9266 9267 @Override 9268 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9269 int match, int userId) { 9270 if (!sUserManager.exists(userId)) 9271 return null; 9272 final PackageParser.ProviderIntentInfo info = filter; 9273 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9274 return null; 9275 } 9276 final PackageParser.Provider provider = info.provider; 9277 if (mSafeMode && (provider.info.applicationInfo.flags 9278 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9279 return null; 9280 } 9281 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9282 if (ps == null) { 9283 return null; 9284 } 9285 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9286 ps.readUserState(userId), userId); 9287 if (pi == null) { 9288 return null; 9289 } 9290 final ResolveInfo res = new ResolveInfo(); 9291 res.providerInfo = pi; 9292 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9293 res.filter = filter; 9294 } 9295 res.priority = info.getPriority(); 9296 res.preferredOrder = provider.owner.mPreferredOrder; 9297 res.match = match; 9298 res.isDefault = info.hasDefault; 9299 res.labelRes = info.labelRes; 9300 res.nonLocalizedLabel = info.nonLocalizedLabel; 9301 res.icon = info.icon; 9302 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9303 return res; 9304 } 9305 9306 @Override 9307 protected void sortResults(List<ResolveInfo> results) { 9308 Collections.sort(results, mResolvePrioritySorter); 9309 } 9310 9311 @Override 9312 protected void dumpFilter(PrintWriter out, String prefix, 9313 PackageParser.ProviderIntentInfo filter) { 9314 out.print(prefix); 9315 out.print( 9316 Integer.toHexString(System.identityHashCode(filter.provider))); 9317 out.print(' '); 9318 filter.provider.printComponentShortName(out); 9319 out.print(" filter "); 9320 out.println(Integer.toHexString(System.identityHashCode(filter))); 9321 } 9322 9323 @Override 9324 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9325 return filter.provider; 9326 } 9327 9328 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9329 PackageParser.Provider provider = (PackageParser.Provider)label; 9330 out.print(prefix); out.print( 9331 Integer.toHexString(System.identityHashCode(provider))); 9332 out.print(' '); 9333 provider.printComponentShortName(out); 9334 if (count > 1) { 9335 out.print(" ("); out.print(count); out.print(" filters)"); 9336 } 9337 out.println(); 9338 } 9339 9340 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9341 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9342 private int mFlags; 9343 }; 9344 9345 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9346 new Comparator<ResolveInfo>() { 9347 public int compare(ResolveInfo r1, ResolveInfo r2) { 9348 int v1 = r1.priority; 9349 int v2 = r2.priority; 9350 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9351 if (v1 != v2) { 9352 return (v1 > v2) ? -1 : 1; 9353 } 9354 v1 = r1.preferredOrder; 9355 v2 = r2.preferredOrder; 9356 if (v1 != v2) { 9357 return (v1 > v2) ? -1 : 1; 9358 } 9359 if (r1.isDefault != r2.isDefault) { 9360 return r1.isDefault ? -1 : 1; 9361 } 9362 v1 = r1.match; 9363 v2 = r2.match; 9364 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9365 if (v1 != v2) { 9366 return (v1 > v2) ? -1 : 1; 9367 } 9368 if (r1.system != r2.system) { 9369 return r1.system ? -1 : 1; 9370 } 9371 return 0; 9372 } 9373 }; 9374 9375 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9376 new Comparator<ProviderInfo>() { 9377 public int compare(ProviderInfo p1, ProviderInfo p2) { 9378 final int v1 = p1.initOrder; 9379 final int v2 = p2.initOrder; 9380 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9381 } 9382 }; 9383 9384 final void sendPackageBroadcast(final String action, final String pkg, 9385 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9386 final int[] userIds) { 9387 mHandler.post(new Runnable() { 9388 @Override 9389 public void run() { 9390 try { 9391 final IActivityManager am = ActivityManagerNative.getDefault(); 9392 if (am == null) return; 9393 final int[] resolvedUserIds; 9394 if (userIds == null) { 9395 resolvedUserIds = am.getRunningUserIds(); 9396 } else { 9397 resolvedUserIds = userIds; 9398 } 9399 for (int id : resolvedUserIds) { 9400 final Intent intent = new Intent(action, 9401 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9402 if (extras != null) { 9403 intent.putExtras(extras); 9404 } 9405 if (targetPkg != null) { 9406 intent.setPackage(targetPkg); 9407 } 9408 // Modify the UID when posting to other users 9409 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9410 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9411 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9412 intent.putExtra(Intent.EXTRA_UID, uid); 9413 } 9414 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9415 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9416 if (DEBUG_BROADCASTS) { 9417 RuntimeException here = new RuntimeException("here"); 9418 here.fillInStackTrace(); 9419 Slog.d(TAG, "Sending to user " + id + ": " 9420 + intent.toShortString(false, true, false, false) 9421 + " " + intent.getExtras(), here); 9422 } 9423 am.broadcastIntent(null, intent, null, finishedReceiver, 9424 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9425 null, finishedReceiver != null, false, id); 9426 } 9427 } catch (RemoteException ex) { 9428 } 9429 } 9430 }); 9431 } 9432 9433 /** 9434 * Check if the external storage media is available. This is true if there 9435 * is a mounted external storage medium or if the external storage is 9436 * emulated. 9437 */ 9438 private boolean isExternalMediaAvailable() { 9439 return mMediaMounted || Environment.isExternalStorageEmulated(); 9440 } 9441 9442 @Override 9443 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9444 // writer 9445 synchronized (mPackages) { 9446 if (!isExternalMediaAvailable()) { 9447 // If the external storage is no longer mounted at this point, 9448 // the caller may not have been able to delete all of this 9449 // packages files and can not delete any more. Bail. 9450 return null; 9451 } 9452 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9453 if (lastPackage != null) { 9454 pkgs.remove(lastPackage); 9455 } 9456 if (pkgs.size() > 0) { 9457 return pkgs.get(0); 9458 } 9459 } 9460 return null; 9461 } 9462 9463 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9464 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9465 userId, andCode ? 1 : 0, packageName); 9466 if (mSystemReady) { 9467 msg.sendToTarget(); 9468 } else { 9469 if (mPostSystemReadyMessages == null) { 9470 mPostSystemReadyMessages = new ArrayList<>(); 9471 } 9472 mPostSystemReadyMessages.add(msg); 9473 } 9474 } 9475 9476 void startCleaningPackages() { 9477 // reader 9478 synchronized (mPackages) { 9479 if (!isExternalMediaAvailable()) { 9480 return; 9481 } 9482 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9483 return; 9484 } 9485 } 9486 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9487 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9488 IActivityManager am = ActivityManagerNative.getDefault(); 9489 if (am != null) { 9490 try { 9491 am.startService(null, intent, null, mContext.getOpPackageName(), 9492 UserHandle.USER_OWNER); 9493 } catch (RemoteException e) { 9494 } 9495 } 9496 } 9497 9498 @Override 9499 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9500 int installFlags, String installerPackageName, VerificationParams verificationParams, 9501 String packageAbiOverride) { 9502 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9503 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9504 } 9505 9506 @Override 9507 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9508 int installFlags, String installerPackageName, VerificationParams verificationParams, 9509 String packageAbiOverride, int userId) { 9510 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9511 9512 final int callingUid = Binder.getCallingUid(); 9513 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9514 9515 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9516 try { 9517 if (observer != null) { 9518 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9519 } 9520 } catch (RemoteException re) { 9521 } 9522 return; 9523 } 9524 9525 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9526 installFlags |= PackageManager.INSTALL_FROM_ADB; 9527 9528 } else { 9529 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9530 // about installerPackageName. 9531 9532 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9533 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9534 } 9535 9536 UserHandle user; 9537 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9538 user = UserHandle.ALL; 9539 } else { 9540 user = new UserHandle(userId); 9541 } 9542 9543 // Only system components can circumvent runtime permissions when installing. 9544 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9545 && mContext.checkCallingOrSelfPermission(Manifest.permission 9546 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9547 throw new SecurityException("You need the " 9548 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9549 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9550 } 9551 9552 verificationParams.setInstallerUid(callingUid); 9553 9554 final File originFile = new File(originPath); 9555 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9556 9557 final Message msg = mHandler.obtainMessage(INIT_COPY); 9558 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9559 null, verificationParams, user, packageAbiOverride, null); 9560 mHandler.sendMessage(msg); 9561 } 9562 9563 void installStage(String packageName, File stagedDir, String stagedCid, 9564 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9565 String installerPackageName, int installerUid, UserHandle user) { 9566 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9567 params.referrerUri, installerUid, null); 9568 verifParams.setInstallerUid(installerUid); 9569 9570 final OriginInfo origin; 9571 if (stagedDir != null) { 9572 origin = OriginInfo.fromStagedFile(stagedDir); 9573 } else { 9574 origin = OriginInfo.fromStagedContainer(stagedCid); 9575 } 9576 9577 final Message msg = mHandler.obtainMessage(INIT_COPY); 9578 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9579 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride, 9580 params.grantedRuntimePermissions); 9581 9582 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9583 System.identityHashCode(msg.obj)); 9584 9585 mHandler.sendMessage(msg); 9586 } 9587 9588 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9589 Bundle extras = new Bundle(1); 9590 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9591 9592 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9593 packageName, extras, null, null, new int[] {userId}); 9594 try { 9595 IActivityManager am = ActivityManagerNative.getDefault(); 9596 final boolean isSystem = 9597 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9598 if (isSystem && am.isUserRunning(userId, false)) { 9599 // The just-installed/enabled app is bundled on the system, so presumed 9600 // to be able to run automatically without needing an explicit launch. 9601 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9602 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9603 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9604 .setPackage(packageName); 9605 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9606 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9607 } 9608 } catch (RemoteException e) { 9609 // shouldn't happen 9610 Slog.w(TAG, "Unable to bootstrap installed package", e); 9611 } 9612 } 9613 9614 @Override 9615 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9616 int userId) { 9617 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9618 PackageSetting pkgSetting; 9619 final int uid = Binder.getCallingUid(); 9620 enforceCrossUserPermission(uid, userId, true, true, 9621 "setApplicationHiddenSetting for user " + userId); 9622 9623 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9624 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9625 return false; 9626 } 9627 9628 long callingId = Binder.clearCallingIdentity(); 9629 try { 9630 boolean sendAdded = false; 9631 boolean sendRemoved = false; 9632 // writer 9633 synchronized (mPackages) { 9634 pkgSetting = mSettings.mPackages.get(packageName); 9635 if (pkgSetting == null) { 9636 return false; 9637 } 9638 if (pkgSetting.getHidden(userId) != hidden) { 9639 pkgSetting.setHidden(hidden, userId); 9640 mSettings.writePackageRestrictionsLPr(userId); 9641 if (hidden) { 9642 sendRemoved = true; 9643 } else { 9644 sendAdded = true; 9645 } 9646 } 9647 } 9648 if (sendAdded) { 9649 sendPackageAddedForUser(packageName, pkgSetting, userId); 9650 return true; 9651 } 9652 if (sendRemoved) { 9653 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9654 "hiding pkg"); 9655 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9656 return true; 9657 } 9658 } finally { 9659 Binder.restoreCallingIdentity(callingId); 9660 } 9661 return false; 9662 } 9663 9664 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9665 int userId) { 9666 final PackageRemovedInfo info = new PackageRemovedInfo(); 9667 info.removedPackage = packageName; 9668 info.removedUsers = new int[] {userId}; 9669 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9670 info.sendBroadcast(false, false, false); 9671 } 9672 9673 /** 9674 * Returns true if application is not found or there was an error. Otherwise it returns 9675 * the hidden state of the package for the given user. 9676 */ 9677 @Override 9678 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9679 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9680 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9681 false, "getApplicationHidden for user " + userId); 9682 PackageSetting pkgSetting; 9683 long callingId = Binder.clearCallingIdentity(); 9684 try { 9685 // writer 9686 synchronized (mPackages) { 9687 pkgSetting = mSettings.mPackages.get(packageName); 9688 if (pkgSetting == null) { 9689 return true; 9690 } 9691 return pkgSetting.getHidden(userId); 9692 } 9693 } finally { 9694 Binder.restoreCallingIdentity(callingId); 9695 } 9696 } 9697 9698 /** 9699 * @hide 9700 */ 9701 @Override 9702 public int installExistingPackageAsUser(String packageName, int userId) { 9703 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9704 null); 9705 PackageSetting pkgSetting; 9706 final int uid = Binder.getCallingUid(); 9707 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9708 + userId); 9709 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9710 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9711 } 9712 9713 long callingId = Binder.clearCallingIdentity(); 9714 try { 9715 boolean sendAdded = false; 9716 9717 // writer 9718 synchronized (mPackages) { 9719 pkgSetting = mSettings.mPackages.get(packageName); 9720 if (pkgSetting == null) { 9721 return PackageManager.INSTALL_FAILED_INVALID_URI; 9722 } 9723 if (!pkgSetting.getInstalled(userId)) { 9724 pkgSetting.setInstalled(true, userId); 9725 pkgSetting.setHidden(false, userId); 9726 mSettings.writePackageRestrictionsLPr(userId); 9727 sendAdded = true; 9728 } 9729 } 9730 9731 if (sendAdded) { 9732 sendPackageAddedForUser(packageName, pkgSetting, userId); 9733 } 9734 } finally { 9735 Binder.restoreCallingIdentity(callingId); 9736 } 9737 9738 return PackageManager.INSTALL_SUCCEEDED; 9739 } 9740 9741 boolean isUserRestricted(int userId, String restrictionKey) { 9742 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9743 if (restrictions.getBoolean(restrictionKey, false)) { 9744 Log.w(TAG, "User is restricted: " + restrictionKey); 9745 return true; 9746 } 9747 return false; 9748 } 9749 9750 @Override 9751 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9752 mContext.enforceCallingOrSelfPermission( 9753 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9754 "Only package verification agents can verify applications"); 9755 9756 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9757 final PackageVerificationResponse response = new PackageVerificationResponse( 9758 verificationCode, Binder.getCallingUid()); 9759 msg.arg1 = id; 9760 msg.obj = response; 9761 mHandler.sendMessage(msg); 9762 } 9763 9764 @Override 9765 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9766 long millisecondsToDelay) { 9767 mContext.enforceCallingOrSelfPermission( 9768 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9769 "Only package verification agents can extend verification timeouts"); 9770 9771 final PackageVerificationState state = mPendingVerification.get(id); 9772 final PackageVerificationResponse response = new PackageVerificationResponse( 9773 verificationCodeAtTimeout, Binder.getCallingUid()); 9774 9775 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9776 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9777 } 9778 if (millisecondsToDelay < 0) { 9779 millisecondsToDelay = 0; 9780 } 9781 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9782 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9783 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9784 } 9785 9786 if ((state != null) && !state.timeoutExtended()) { 9787 state.extendTimeout(); 9788 9789 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9790 msg.arg1 = id; 9791 msg.obj = response; 9792 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9793 } 9794 } 9795 9796 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9797 int verificationCode, UserHandle user) { 9798 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9799 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9800 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9801 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9802 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9803 9804 mContext.sendBroadcastAsUser(intent, user, 9805 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9806 } 9807 9808 private ComponentName matchComponentForVerifier(String packageName, 9809 List<ResolveInfo> receivers) { 9810 ActivityInfo targetReceiver = null; 9811 9812 final int NR = receivers.size(); 9813 for (int i = 0; i < NR; i++) { 9814 final ResolveInfo info = receivers.get(i); 9815 if (info.activityInfo == null) { 9816 continue; 9817 } 9818 9819 if (packageName.equals(info.activityInfo.packageName)) { 9820 targetReceiver = info.activityInfo; 9821 break; 9822 } 9823 } 9824 9825 if (targetReceiver == null) { 9826 return null; 9827 } 9828 9829 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9830 } 9831 9832 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9833 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9834 if (pkgInfo.verifiers.length == 0) { 9835 return null; 9836 } 9837 9838 final int N = pkgInfo.verifiers.length; 9839 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9840 for (int i = 0; i < N; i++) { 9841 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9842 9843 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9844 receivers); 9845 if (comp == null) { 9846 continue; 9847 } 9848 9849 final int verifierUid = getUidForVerifier(verifierInfo); 9850 if (verifierUid == -1) { 9851 continue; 9852 } 9853 9854 if (DEBUG_VERIFY) { 9855 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9856 + " with the correct signature"); 9857 } 9858 sufficientVerifiers.add(comp); 9859 verificationState.addSufficientVerifier(verifierUid); 9860 } 9861 9862 return sufficientVerifiers; 9863 } 9864 9865 private int getUidForVerifier(VerifierInfo verifierInfo) { 9866 synchronized (mPackages) { 9867 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9868 if (pkg == null) { 9869 return -1; 9870 } else if (pkg.mSignatures.length != 1) { 9871 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9872 + " has more than one signature; ignoring"); 9873 return -1; 9874 } 9875 9876 /* 9877 * If the public key of the package's signature does not match 9878 * our expected public key, then this is a different package and 9879 * we should skip. 9880 */ 9881 9882 final byte[] expectedPublicKey; 9883 try { 9884 final Signature verifierSig = pkg.mSignatures[0]; 9885 final PublicKey publicKey = verifierSig.getPublicKey(); 9886 expectedPublicKey = publicKey.getEncoded(); 9887 } catch (CertificateException e) { 9888 return -1; 9889 } 9890 9891 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9892 9893 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9894 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9895 + " does not have the expected public key; ignoring"); 9896 return -1; 9897 } 9898 9899 return pkg.applicationInfo.uid; 9900 } 9901 } 9902 9903 @Override 9904 public void finishPackageInstall(int token) { 9905 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9906 9907 if (DEBUG_INSTALL) { 9908 Slog.v(TAG, "BM finishing package install for " + token); 9909 } 9910 9911 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9912 mHandler.sendMessage(msg); 9913 } 9914 9915 /** 9916 * Get the verification agent timeout. 9917 * 9918 * @return verification timeout in milliseconds 9919 */ 9920 private long getVerificationTimeout() { 9921 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9922 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9923 DEFAULT_VERIFICATION_TIMEOUT); 9924 } 9925 9926 /** 9927 * Get the default verification agent response code. 9928 * 9929 * @return default verification response code 9930 */ 9931 private int getDefaultVerificationResponse() { 9932 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9933 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9934 DEFAULT_VERIFICATION_RESPONSE); 9935 } 9936 9937 /** 9938 * Check whether or not package verification has been enabled. 9939 * 9940 * @return true if verification should be performed 9941 */ 9942 private boolean isVerificationEnabled(int userId, int installFlags) { 9943 if (!DEFAULT_VERIFY_ENABLE) { 9944 return false; 9945 } 9946 9947 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9948 9949 // Check if installing from ADB 9950 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9951 // Do not run verification in a test harness environment 9952 if (ActivityManager.isRunningInTestHarness()) { 9953 return false; 9954 } 9955 if (ensureVerifyAppsEnabled) { 9956 return true; 9957 } 9958 // Check if the developer does not want package verification for ADB installs 9959 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9960 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9961 return false; 9962 } 9963 } 9964 9965 if (ensureVerifyAppsEnabled) { 9966 return true; 9967 } 9968 9969 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9970 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9971 } 9972 9973 @Override 9974 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9975 throws RemoteException { 9976 mContext.enforceCallingOrSelfPermission( 9977 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9978 "Only intentfilter verification agents can verify applications"); 9979 9980 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9981 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9982 Binder.getCallingUid(), verificationCode, failedDomains); 9983 msg.arg1 = id; 9984 msg.obj = response; 9985 mHandler.sendMessage(msg); 9986 } 9987 9988 @Override 9989 public int getIntentVerificationStatus(String packageName, int userId) { 9990 synchronized (mPackages) { 9991 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9992 } 9993 } 9994 9995 @Override 9996 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9997 mContext.enforceCallingOrSelfPermission( 9998 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9999 10000 boolean result = false; 10001 synchronized (mPackages) { 10002 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10003 } 10004 if (result) { 10005 scheduleWritePackageRestrictionsLocked(userId); 10006 } 10007 return result; 10008 } 10009 10010 @Override 10011 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10012 synchronized (mPackages) { 10013 return mSettings.getIntentFilterVerificationsLPr(packageName); 10014 } 10015 } 10016 10017 @Override 10018 public List<IntentFilter> getAllIntentFilters(String packageName) { 10019 if (TextUtils.isEmpty(packageName)) { 10020 return Collections.<IntentFilter>emptyList(); 10021 } 10022 synchronized (mPackages) { 10023 PackageParser.Package pkg = mPackages.get(packageName); 10024 if (pkg == null || pkg.activities == null) { 10025 return Collections.<IntentFilter>emptyList(); 10026 } 10027 final int count = pkg.activities.size(); 10028 ArrayList<IntentFilter> result = new ArrayList<>(); 10029 for (int n=0; n<count; n++) { 10030 PackageParser.Activity activity = pkg.activities.get(n); 10031 if (activity.intents != null || activity.intents.size() > 0) { 10032 result.addAll(activity.intents); 10033 } 10034 } 10035 return result; 10036 } 10037 } 10038 10039 @Override 10040 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10041 mContext.enforceCallingOrSelfPermission( 10042 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10043 10044 synchronized (mPackages) { 10045 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10046 if (packageName != null) { 10047 result |= updateIntentVerificationStatus(packageName, 10048 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10049 userId); 10050 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10051 packageName, userId); 10052 } 10053 return result; 10054 } 10055 } 10056 10057 @Override 10058 public String getDefaultBrowserPackageName(int userId) { 10059 synchronized (mPackages) { 10060 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10061 } 10062 } 10063 10064 /** 10065 * Get the "allow unknown sources" setting. 10066 * 10067 * @return the current "allow unknown sources" setting 10068 */ 10069 private int getUnknownSourcesSettings() { 10070 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10071 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10072 -1); 10073 } 10074 10075 @Override 10076 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10077 final int uid = Binder.getCallingUid(); 10078 // writer 10079 synchronized (mPackages) { 10080 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10081 if (targetPackageSetting == null) { 10082 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10083 } 10084 10085 PackageSetting installerPackageSetting; 10086 if (installerPackageName != null) { 10087 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10088 if (installerPackageSetting == null) { 10089 throw new IllegalArgumentException("Unknown installer package: " 10090 + installerPackageName); 10091 } 10092 } else { 10093 installerPackageSetting = null; 10094 } 10095 10096 Signature[] callerSignature; 10097 Object obj = mSettings.getUserIdLPr(uid); 10098 if (obj != null) { 10099 if (obj instanceof SharedUserSetting) { 10100 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10101 } else if (obj instanceof PackageSetting) { 10102 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10103 } else { 10104 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10105 } 10106 } else { 10107 throw new SecurityException("Unknown calling uid " + uid); 10108 } 10109 10110 // Verify: can't set installerPackageName to a package that is 10111 // not signed with the same cert as the caller. 10112 if (installerPackageSetting != null) { 10113 if (compareSignatures(callerSignature, 10114 installerPackageSetting.signatures.mSignatures) 10115 != PackageManager.SIGNATURE_MATCH) { 10116 throw new SecurityException( 10117 "Caller does not have same cert as new installer package " 10118 + installerPackageName); 10119 } 10120 } 10121 10122 // Verify: if target already has an installer package, it must 10123 // be signed with the same cert as the caller. 10124 if (targetPackageSetting.installerPackageName != null) { 10125 PackageSetting setting = mSettings.mPackages.get( 10126 targetPackageSetting.installerPackageName); 10127 // If the currently set package isn't valid, then it's always 10128 // okay to change it. 10129 if (setting != null) { 10130 if (compareSignatures(callerSignature, 10131 setting.signatures.mSignatures) 10132 != PackageManager.SIGNATURE_MATCH) { 10133 throw new SecurityException( 10134 "Caller does not have same cert as old installer package " 10135 + targetPackageSetting.installerPackageName); 10136 } 10137 } 10138 } 10139 10140 // Okay! 10141 targetPackageSetting.installerPackageName = installerPackageName; 10142 scheduleWriteSettingsLocked(); 10143 } 10144 } 10145 10146 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10147 // Queue up an async operation since the package installation may take a little while. 10148 mHandler.post(new Runnable() { 10149 public void run() { 10150 mHandler.removeCallbacks(this); 10151 // Result object to be returned 10152 PackageInstalledInfo res = new PackageInstalledInfo(); 10153 res.returnCode = currentStatus; 10154 res.uid = -1; 10155 res.pkg = null; 10156 res.removedInfo = new PackageRemovedInfo(); 10157 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10158 args.doPreInstall(res.returnCode); 10159 synchronized (mInstallLock) { 10160 installPackageTracedLI(args, res); 10161 } 10162 args.doPostInstall(res.returnCode, res.uid); 10163 } 10164 10165 // A restore should be performed at this point if (a) the install 10166 // succeeded, (b) the operation is not an update, and (c) the new 10167 // package has not opted out of backup participation. 10168 final boolean update = res.removedInfo.removedPackage != null; 10169 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10170 boolean doRestore = !update 10171 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10172 10173 // Set up the post-install work request bookkeeping. This will be used 10174 // and cleaned up by the post-install event handling regardless of whether 10175 // there's a restore pass performed. Token values are >= 1. 10176 int token; 10177 if (mNextInstallToken < 0) mNextInstallToken = 1; 10178 token = mNextInstallToken++; 10179 10180 PostInstallData data = new PostInstallData(args, res); 10181 mRunningInstalls.put(token, data); 10182 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10183 10184 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10185 // Pass responsibility to the Backup Manager. It will perform a 10186 // restore if appropriate, then pass responsibility back to the 10187 // Package Manager to run the post-install observer callbacks 10188 // and broadcasts. 10189 IBackupManager bm = IBackupManager.Stub.asInterface( 10190 ServiceManager.getService(Context.BACKUP_SERVICE)); 10191 if (bm != null) { 10192 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10193 + " to BM for possible restore"); 10194 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10195 try { 10196 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10197 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10198 } else { 10199 doRestore = false; 10200 } 10201 } catch (RemoteException e) { 10202 // can't happen; the backup manager is local 10203 } catch (Exception e) { 10204 Slog.e(TAG, "Exception trying to enqueue restore", e); 10205 doRestore = false; 10206 } finally { 10207 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10208 } 10209 } else { 10210 Slog.e(TAG, "Backup Manager not found!"); 10211 doRestore = false; 10212 } 10213 } 10214 10215 if (!doRestore) { 10216 // No restore possible, or the Backup Manager was mysteriously not 10217 // available -- just fire the post-install work request directly. 10218 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10219 10220 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10221 10222 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10223 mHandler.sendMessage(msg); 10224 } 10225 } 10226 }); 10227 } 10228 10229 private abstract class HandlerParams { 10230 private static final int MAX_RETRIES = 4; 10231 10232 /** 10233 * Number of times startCopy() has been attempted and had a non-fatal 10234 * error. 10235 */ 10236 private int mRetries = 0; 10237 10238 /** User handle for the user requesting the information or installation. */ 10239 private final UserHandle mUser; 10240 10241 HandlerParams(UserHandle user) { 10242 mUser = user; 10243 } 10244 10245 UserHandle getUser() { 10246 return mUser; 10247 } 10248 10249 final boolean startCopy() { 10250 boolean res; 10251 try { 10252 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10253 10254 if (++mRetries > MAX_RETRIES) { 10255 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10256 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10257 handleServiceError(); 10258 return false; 10259 } else { 10260 handleStartCopy(); 10261 res = true; 10262 } 10263 } catch (RemoteException e) { 10264 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10265 mHandler.sendEmptyMessage(MCS_RECONNECT); 10266 res = false; 10267 } 10268 handleReturnCode(); 10269 return res; 10270 } 10271 10272 final void serviceError() { 10273 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10274 handleServiceError(); 10275 handleReturnCode(); 10276 } 10277 10278 abstract void handleStartCopy() throws RemoteException; 10279 abstract void handleServiceError(); 10280 abstract void handleReturnCode(); 10281 } 10282 10283 class MeasureParams extends HandlerParams { 10284 private final PackageStats mStats; 10285 private boolean mSuccess; 10286 10287 private final IPackageStatsObserver mObserver; 10288 10289 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10290 super(new UserHandle(stats.userHandle)); 10291 mObserver = observer; 10292 mStats = stats; 10293 } 10294 10295 @Override 10296 public String toString() { 10297 return "MeasureParams{" 10298 + Integer.toHexString(System.identityHashCode(this)) 10299 + " " + mStats.packageName + "}"; 10300 } 10301 10302 @Override 10303 void handleStartCopy() throws RemoteException { 10304 synchronized (mInstallLock) { 10305 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10306 } 10307 10308 if (mSuccess) { 10309 final boolean mounted; 10310 if (Environment.isExternalStorageEmulated()) { 10311 mounted = true; 10312 } else { 10313 final String status = Environment.getExternalStorageState(); 10314 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10315 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10316 } 10317 10318 if (mounted) { 10319 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10320 10321 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10322 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10323 10324 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10325 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10326 10327 // Always subtract cache size, since it's a subdirectory 10328 mStats.externalDataSize -= mStats.externalCacheSize; 10329 10330 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10331 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10332 10333 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10334 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10335 } 10336 } 10337 } 10338 10339 @Override 10340 void handleReturnCode() { 10341 if (mObserver != null) { 10342 try { 10343 mObserver.onGetStatsCompleted(mStats, mSuccess); 10344 } catch (RemoteException e) { 10345 Slog.i(TAG, "Observer no longer exists."); 10346 } 10347 } 10348 } 10349 10350 @Override 10351 void handleServiceError() { 10352 Slog.e(TAG, "Could not measure application " + mStats.packageName 10353 + " external storage"); 10354 } 10355 } 10356 10357 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10358 throws RemoteException { 10359 long result = 0; 10360 for (File path : paths) { 10361 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10362 } 10363 return result; 10364 } 10365 10366 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10367 for (File path : paths) { 10368 try { 10369 mcs.clearDirectory(path.getAbsolutePath()); 10370 } catch (RemoteException e) { 10371 } 10372 } 10373 } 10374 10375 static class OriginInfo { 10376 /** 10377 * Location where install is coming from, before it has been 10378 * copied/renamed into place. This could be a single monolithic APK 10379 * file, or a cluster directory. This location may be untrusted. 10380 */ 10381 final File file; 10382 final String cid; 10383 10384 /** 10385 * Flag indicating that {@link #file} or {@link #cid} has already been 10386 * staged, meaning downstream users don't need to defensively copy the 10387 * contents. 10388 */ 10389 final boolean staged; 10390 10391 /** 10392 * Flag indicating that {@link #file} or {@link #cid} is an already 10393 * installed app that is being moved. 10394 */ 10395 final boolean existing; 10396 10397 final String resolvedPath; 10398 final File resolvedFile; 10399 10400 static OriginInfo fromNothing() { 10401 return new OriginInfo(null, null, false, false); 10402 } 10403 10404 static OriginInfo fromUntrustedFile(File file) { 10405 return new OriginInfo(file, null, false, false); 10406 } 10407 10408 static OriginInfo fromExistingFile(File file) { 10409 return new OriginInfo(file, null, false, true); 10410 } 10411 10412 static OriginInfo fromStagedFile(File file) { 10413 return new OriginInfo(file, null, true, false); 10414 } 10415 10416 static OriginInfo fromStagedContainer(String cid) { 10417 return new OriginInfo(null, cid, true, false); 10418 } 10419 10420 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10421 this.file = file; 10422 this.cid = cid; 10423 this.staged = staged; 10424 this.existing = existing; 10425 10426 if (cid != null) { 10427 resolvedPath = PackageHelper.getSdDir(cid); 10428 resolvedFile = new File(resolvedPath); 10429 } else if (file != null) { 10430 resolvedPath = file.getAbsolutePath(); 10431 resolvedFile = file; 10432 } else { 10433 resolvedPath = null; 10434 resolvedFile = null; 10435 } 10436 } 10437 } 10438 10439 class MoveInfo { 10440 final int moveId; 10441 final String fromUuid; 10442 final String toUuid; 10443 final String packageName; 10444 final String dataAppName; 10445 final int appId; 10446 final String seinfo; 10447 10448 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10449 String dataAppName, int appId, String seinfo) { 10450 this.moveId = moveId; 10451 this.fromUuid = fromUuid; 10452 this.toUuid = toUuid; 10453 this.packageName = packageName; 10454 this.dataAppName = dataAppName; 10455 this.appId = appId; 10456 this.seinfo = seinfo; 10457 } 10458 } 10459 10460 class InstallParams extends HandlerParams { 10461 final OriginInfo origin; 10462 final MoveInfo move; 10463 final IPackageInstallObserver2 observer; 10464 int installFlags; 10465 final String installerPackageName; 10466 final String volumeUuid; 10467 final VerificationParams verificationParams; 10468 private InstallArgs mArgs; 10469 private int mRet; 10470 final String packageAbiOverride; 10471 final String[] grantedRuntimePermissions; 10472 10473 10474 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10475 int installFlags, String installerPackageName, String volumeUuid, 10476 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10477 String[] grantedPermissions) { 10478 super(user); 10479 this.origin = origin; 10480 this.move = move; 10481 this.observer = observer; 10482 this.installFlags = installFlags; 10483 this.installerPackageName = installerPackageName; 10484 this.volumeUuid = volumeUuid; 10485 this.verificationParams = verificationParams; 10486 this.packageAbiOverride = packageAbiOverride; 10487 this.grantedRuntimePermissions = grantedPermissions; 10488 } 10489 10490 @Override 10491 public String toString() { 10492 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10493 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10494 } 10495 10496 public ManifestDigest getManifestDigest() { 10497 if (verificationParams == null) { 10498 return null; 10499 } 10500 return verificationParams.getManifestDigest(); 10501 } 10502 10503 private int installLocationPolicy(PackageInfoLite pkgLite) { 10504 String packageName = pkgLite.packageName; 10505 int installLocation = pkgLite.installLocation; 10506 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10507 // reader 10508 synchronized (mPackages) { 10509 PackageParser.Package pkg = mPackages.get(packageName); 10510 if (pkg != null) { 10511 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10512 // Check for downgrading. 10513 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10514 try { 10515 checkDowngrade(pkg, pkgLite); 10516 } catch (PackageManagerException e) { 10517 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10518 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10519 } 10520 } 10521 // Check for updated system application. 10522 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10523 if (onSd) { 10524 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10525 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10526 } 10527 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10528 } else { 10529 if (onSd) { 10530 // Install flag overrides everything. 10531 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10532 } 10533 // If current upgrade specifies particular preference 10534 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10535 // Application explicitly specified internal. 10536 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10537 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10538 // App explictly prefers external. Let policy decide 10539 } else { 10540 // Prefer previous location 10541 if (isExternal(pkg)) { 10542 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10543 } 10544 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10545 } 10546 } 10547 } else { 10548 // Invalid install. Return error code 10549 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10550 } 10551 } 10552 } 10553 // All the special cases have been taken care of. 10554 // Return result based on recommended install location. 10555 if (onSd) { 10556 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10557 } 10558 return pkgLite.recommendedInstallLocation; 10559 } 10560 10561 /* 10562 * Invoke remote method to get package information and install 10563 * location values. Override install location based on default 10564 * policy if needed and then create install arguments based 10565 * on the install location. 10566 */ 10567 public void handleStartCopy() throws RemoteException { 10568 int ret = PackageManager.INSTALL_SUCCEEDED; 10569 10570 // If we're already staged, we've firmly committed to an install location 10571 if (origin.staged) { 10572 if (origin.file != null) { 10573 installFlags |= PackageManager.INSTALL_INTERNAL; 10574 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10575 } else if (origin.cid != null) { 10576 installFlags |= PackageManager.INSTALL_EXTERNAL; 10577 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10578 } else { 10579 throw new IllegalStateException("Invalid stage location"); 10580 } 10581 } 10582 10583 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10584 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10585 PackageInfoLite pkgLite = null; 10586 10587 if (onInt && onSd) { 10588 // Check if both bits are set. 10589 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10590 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10591 } else { 10592 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10593 packageAbiOverride); 10594 10595 /* 10596 * If we have too little free space, try to free cache 10597 * before giving up. 10598 */ 10599 if (!origin.staged && pkgLite.recommendedInstallLocation 10600 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10601 // TODO: focus freeing disk space on the target device 10602 final StorageManager storage = StorageManager.from(mContext); 10603 final long lowThreshold = storage.getStorageLowBytes( 10604 Environment.getDataDirectory()); 10605 10606 final long sizeBytes = mContainerService.calculateInstalledSize( 10607 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10608 10609 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10610 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10611 installFlags, packageAbiOverride); 10612 } 10613 10614 /* 10615 * The cache free must have deleted the file we 10616 * downloaded to install. 10617 * 10618 * TODO: fix the "freeCache" call to not delete 10619 * the file we care about. 10620 */ 10621 if (pkgLite.recommendedInstallLocation 10622 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10623 pkgLite.recommendedInstallLocation 10624 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10625 } 10626 } 10627 } 10628 10629 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10630 int loc = pkgLite.recommendedInstallLocation; 10631 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10632 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10633 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10634 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10635 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10636 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10637 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10638 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10639 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10640 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10641 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10642 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10643 } else { 10644 // Override with defaults if needed. 10645 loc = installLocationPolicy(pkgLite); 10646 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10647 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10648 } else if (!onSd && !onInt) { 10649 // Override install location with flags 10650 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10651 // Set the flag to install on external media. 10652 installFlags |= PackageManager.INSTALL_EXTERNAL; 10653 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10654 } else { 10655 // Make sure the flag for installing on external 10656 // media is unset 10657 installFlags |= PackageManager.INSTALL_INTERNAL; 10658 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10659 } 10660 } 10661 } 10662 } 10663 10664 final InstallArgs args = createInstallArgs(this); 10665 mArgs = args; 10666 10667 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10668 /* 10669 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10670 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10671 */ 10672 int userIdentifier = getUser().getIdentifier(); 10673 if (userIdentifier == UserHandle.USER_ALL 10674 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10675 userIdentifier = UserHandle.USER_OWNER; 10676 } 10677 10678 /* 10679 * Determine if we have any installed package verifiers. If we 10680 * do, then we'll defer to them to verify the packages. 10681 */ 10682 final int requiredUid = mRequiredVerifierPackage == null ? -1 10683 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10684 if (!origin.existing && requiredUid != -1 10685 && isVerificationEnabled(userIdentifier, installFlags)) { 10686 final Intent verification = new Intent( 10687 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10688 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10689 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10690 PACKAGE_MIME_TYPE); 10691 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10692 10693 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10694 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10695 0 /* TODO: Which userId? */); 10696 10697 if (DEBUG_VERIFY) { 10698 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10699 + verification.toString() + " with " + pkgLite.verifiers.length 10700 + " optional verifiers"); 10701 } 10702 10703 final int verificationId = mPendingVerificationToken++; 10704 10705 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10706 10707 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10708 installerPackageName); 10709 10710 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10711 installFlags); 10712 10713 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10714 pkgLite.packageName); 10715 10716 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10717 pkgLite.versionCode); 10718 10719 if (verificationParams != null) { 10720 if (verificationParams.getVerificationURI() != null) { 10721 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10722 verificationParams.getVerificationURI()); 10723 } 10724 if (verificationParams.getOriginatingURI() != null) { 10725 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10726 verificationParams.getOriginatingURI()); 10727 } 10728 if (verificationParams.getReferrer() != null) { 10729 verification.putExtra(Intent.EXTRA_REFERRER, 10730 verificationParams.getReferrer()); 10731 } 10732 if (verificationParams.getOriginatingUid() >= 0) { 10733 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10734 verificationParams.getOriginatingUid()); 10735 } 10736 if (verificationParams.getInstallerUid() >= 0) { 10737 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10738 verificationParams.getInstallerUid()); 10739 } 10740 } 10741 10742 final PackageVerificationState verificationState = new PackageVerificationState( 10743 requiredUid, args); 10744 10745 mPendingVerification.append(verificationId, verificationState); 10746 10747 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10748 receivers, verificationState); 10749 10750 // Apps installed for "all" users use the device owner to verify the app 10751 UserHandle verifierUser = getUser(); 10752 if (verifierUser == UserHandle.ALL) { 10753 verifierUser = UserHandle.OWNER; 10754 } 10755 10756 /* 10757 * If any sufficient verifiers were listed in the package 10758 * manifest, attempt to ask them. 10759 */ 10760 if (sufficientVerifiers != null) { 10761 final int N = sufficientVerifiers.size(); 10762 if (N == 0) { 10763 Slog.i(TAG, "Additional verifiers required, but none installed."); 10764 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10765 } else { 10766 for (int i = 0; i < N; i++) { 10767 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10768 10769 final Intent sufficientIntent = new Intent(verification); 10770 sufficientIntent.setComponent(verifierComponent); 10771 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10772 } 10773 } 10774 } 10775 10776 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10777 mRequiredVerifierPackage, receivers); 10778 if (ret == PackageManager.INSTALL_SUCCEEDED 10779 && mRequiredVerifierPackage != null) { 10780 Trace.asyncTraceBegin( 10781 TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId); 10782 /* 10783 * Send the intent to the required verification agent, 10784 * but only start the verification timeout after the 10785 * target BroadcastReceivers have run. 10786 */ 10787 verification.setComponent(requiredVerifierComponent); 10788 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10789 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10790 new BroadcastReceiver() { 10791 @Override 10792 public void onReceive(Context context, Intent intent) { 10793 final Message msg = mHandler 10794 .obtainMessage(CHECK_PENDING_VERIFICATION); 10795 msg.arg1 = verificationId; 10796 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10797 } 10798 }, null, 0, null, null); 10799 10800 /* 10801 * We don't want the copy to proceed until verification 10802 * succeeds, so null out this field. 10803 */ 10804 mArgs = null; 10805 } 10806 } else { 10807 /* 10808 * No package verification is enabled, so immediately start 10809 * the remote call to initiate copy using temporary file. 10810 */ 10811 ret = args.copyApk(mContainerService, true); 10812 } 10813 } 10814 10815 mRet = ret; 10816 } 10817 10818 @Override 10819 void handleReturnCode() { 10820 // If mArgs is null, then MCS couldn't be reached. When it 10821 // reconnects, it will try again to install. At that point, this 10822 // will succeed. 10823 if (mArgs != null) { 10824 processPendingInstall(mArgs, mRet); 10825 } 10826 } 10827 10828 @Override 10829 void handleServiceError() { 10830 mArgs = createInstallArgs(this); 10831 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10832 } 10833 10834 public boolean isForwardLocked() { 10835 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10836 } 10837 } 10838 10839 /** 10840 * Used during creation of InstallArgs 10841 * 10842 * @param installFlags package installation flags 10843 * @return true if should be installed on external storage 10844 */ 10845 private static boolean installOnExternalAsec(int installFlags) { 10846 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10847 return false; 10848 } 10849 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10850 return true; 10851 } 10852 return false; 10853 } 10854 10855 /** 10856 * Used during creation of InstallArgs 10857 * 10858 * @param installFlags package installation flags 10859 * @return true if should be installed as forward locked 10860 */ 10861 private static boolean installForwardLocked(int installFlags) { 10862 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10863 } 10864 10865 private InstallArgs createInstallArgs(InstallParams params) { 10866 if (params.move != null) { 10867 return new MoveInstallArgs(params); 10868 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10869 return new AsecInstallArgs(params); 10870 } else { 10871 return new FileInstallArgs(params); 10872 } 10873 } 10874 10875 /** 10876 * Create args that describe an existing installed package. Typically used 10877 * when cleaning up old installs, or used as a move source. 10878 */ 10879 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10880 String resourcePath, String[] instructionSets) { 10881 final boolean isInAsec; 10882 if (installOnExternalAsec(installFlags)) { 10883 /* Apps on SD card are always in ASEC containers. */ 10884 isInAsec = true; 10885 } else if (installForwardLocked(installFlags) 10886 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10887 /* 10888 * Forward-locked apps are only in ASEC containers if they're the 10889 * new style 10890 */ 10891 isInAsec = true; 10892 } else { 10893 isInAsec = false; 10894 } 10895 10896 if (isInAsec) { 10897 return new AsecInstallArgs(codePath, instructionSets, 10898 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10899 } else { 10900 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10901 } 10902 } 10903 10904 static abstract class InstallArgs { 10905 /** @see InstallParams#origin */ 10906 final OriginInfo origin; 10907 /** @see InstallParams#move */ 10908 final MoveInfo move; 10909 10910 final IPackageInstallObserver2 observer; 10911 // Always refers to PackageManager flags only 10912 final int installFlags; 10913 final String installerPackageName; 10914 final String volumeUuid; 10915 final ManifestDigest manifestDigest; 10916 final UserHandle user; 10917 final String abiOverride; 10918 final String[] installGrantPermissions; 10919 10920 // The list of instruction sets supported by this app. This is currently 10921 // only used during the rmdex() phase to clean up resources. We can get rid of this 10922 // if we move dex files under the common app path. 10923 /* nullable */ String[] instructionSets; 10924 10925 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10926 int installFlags, String installerPackageName, String volumeUuid, 10927 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10928 String abiOverride, String[] installGrantPermissions) { 10929 this.origin = origin; 10930 this.move = move; 10931 this.installFlags = installFlags; 10932 this.observer = observer; 10933 this.installerPackageName = installerPackageName; 10934 this.volumeUuid = volumeUuid; 10935 this.manifestDigest = manifestDigest; 10936 this.user = user; 10937 this.instructionSets = instructionSets; 10938 this.abiOverride = abiOverride; 10939 this.installGrantPermissions = installGrantPermissions; 10940 } 10941 10942 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10943 abstract int doPreInstall(int status); 10944 10945 /** 10946 * Rename package into final resting place. All paths on the given 10947 * scanned package should be updated to reflect the rename. 10948 */ 10949 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10950 abstract int doPostInstall(int status, int uid); 10951 10952 /** @see PackageSettingBase#codePathString */ 10953 abstract String getCodePath(); 10954 /** @see PackageSettingBase#resourcePathString */ 10955 abstract String getResourcePath(); 10956 10957 // Need installer lock especially for dex file removal. 10958 abstract void cleanUpResourcesLI(); 10959 abstract boolean doPostDeleteLI(boolean delete); 10960 10961 /** 10962 * Called before the source arguments are copied. This is used mostly 10963 * for MoveParams when it needs to read the source file to put it in the 10964 * destination. 10965 */ 10966 int doPreCopy() { 10967 return PackageManager.INSTALL_SUCCEEDED; 10968 } 10969 10970 /** 10971 * Called after the source arguments are copied. This is used mostly for 10972 * MoveParams when it needs to read the source file to put it in the 10973 * destination. 10974 * 10975 * @return 10976 */ 10977 int doPostCopy(int uid) { 10978 return PackageManager.INSTALL_SUCCEEDED; 10979 } 10980 10981 protected boolean isFwdLocked() { 10982 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10983 } 10984 10985 protected boolean isExternalAsec() { 10986 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10987 } 10988 10989 UserHandle getUser() { 10990 return user; 10991 } 10992 } 10993 10994 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10995 if (!allCodePaths.isEmpty()) { 10996 if (instructionSets == null) { 10997 throw new IllegalStateException("instructionSet == null"); 10998 } 10999 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11000 for (String codePath : allCodePaths) { 11001 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11002 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11003 if (retCode < 0) { 11004 Slog.w(TAG, "Couldn't remove dex file for package: " 11005 + " at location " + codePath + ", retcode=" + retCode); 11006 // we don't consider this to be a failure of the core package deletion 11007 } 11008 } 11009 } 11010 } 11011 } 11012 11013 /** 11014 * Logic to handle installation of non-ASEC applications, including copying 11015 * and renaming logic. 11016 */ 11017 class FileInstallArgs extends InstallArgs { 11018 private File codeFile; 11019 private File resourceFile; 11020 11021 // Example topology: 11022 // /data/app/com.example/base.apk 11023 // /data/app/com.example/split_foo.apk 11024 // /data/app/com.example/lib/arm/libfoo.so 11025 // /data/app/com.example/lib/arm64/libfoo.so 11026 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11027 11028 /** New install */ 11029 FileInstallArgs(InstallParams params) { 11030 super(params.origin, params.move, params.observer, params.installFlags, 11031 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11032 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11033 params.grantedRuntimePermissions); 11034 if (isFwdLocked()) { 11035 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11036 } 11037 } 11038 11039 /** Existing install */ 11040 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11041 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11042 null, null); 11043 this.codeFile = (codePath != null) ? new File(codePath) : null; 11044 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11045 } 11046 11047 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11048 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11049 try { 11050 return doCopyApk(imcs, temp); 11051 } finally { 11052 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11053 } 11054 } 11055 11056 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11057 if (origin.staged) { 11058 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11059 codeFile = origin.file; 11060 resourceFile = origin.file; 11061 return PackageManager.INSTALL_SUCCEEDED; 11062 } 11063 11064 try { 11065 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11066 codeFile = tempDir; 11067 resourceFile = tempDir; 11068 } catch (IOException e) { 11069 Slog.w(TAG, "Failed to create copy file: " + e); 11070 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11071 } 11072 11073 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11074 @Override 11075 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11076 if (!FileUtils.isValidExtFilename(name)) { 11077 throw new IllegalArgumentException("Invalid filename: " + name); 11078 } 11079 try { 11080 final File file = new File(codeFile, name); 11081 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11082 O_RDWR | O_CREAT, 0644); 11083 Os.chmod(file.getAbsolutePath(), 0644); 11084 return new ParcelFileDescriptor(fd); 11085 } catch (ErrnoException e) { 11086 throw new RemoteException("Failed to open: " + e.getMessage()); 11087 } 11088 } 11089 }; 11090 11091 int ret = PackageManager.INSTALL_SUCCEEDED; 11092 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11093 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11094 Slog.e(TAG, "Failed to copy package"); 11095 return ret; 11096 } 11097 11098 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11099 NativeLibraryHelper.Handle handle = null; 11100 try { 11101 handle = NativeLibraryHelper.Handle.create(codeFile); 11102 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11103 abiOverride); 11104 } catch (IOException e) { 11105 Slog.e(TAG, "Copying native libraries failed", e); 11106 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11107 } finally { 11108 IoUtils.closeQuietly(handle); 11109 } 11110 11111 return ret; 11112 } 11113 11114 int doPreInstall(int status) { 11115 if (status != PackageManager.INSTALL_SUCCEEDED) { 11116 cleanUp(); 11117 } 11118 return status; 11119 } 11120 11121 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11122 if (status != PackageManager.INSTALL_SUCCEEDED) { 11123 cleanUp(); 11124 return false; 11125 } 11126 11127 final File targetDir = codeFile.getParentFile(); 11128 final File beforeCodeFile = codeFile; 11129 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11130 11131 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11132 try { 11133 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11134 } catch (ErrnoException e) { 11135 Slog.w(TAG, "Failed to rename", e); 11136 return false; 11137 } 11138 11139 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11140 Slog.w(TAG, "Failed to restorecon"); 11141 return false; 11142 } 11143 11144 // Reflect the rename internally 11145 codeFile = afterCodeFile; 11146 resourceFile = afterCodeFile; 11147 11148 // Reflect the rename in scanned details 11149 pkg.codePath = afterCodeFile.getAbsolutePath(); 11150 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11151 pkg.baseCodePath); 11152 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11153 pkg.splitCodePaths); 11154 11155 // Reflect the rename in app info 11156 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11157 pkg.applicationInfo.setCodePath(pkg.codePath); 11158 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11159 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11160 pkg.applicationInfo.setResourcePath(pkg.codePath); 11161 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11162 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11163 11164 return true; 11165 } 11166 11167 int doPostInstall(int status, int uid) { 11168 if (status != PackageManager.INSTALL_SUCCEEDED) { 11169 cleanUp(); 11170 } 11171 return status; 11172 } 11173 11174 @Override 11175 String getCodePath() { 11176 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11177 } 11178 11179 @Override 11180 String getResourcePath() { 11181 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11182 } 11183 11184 private boolean cleanUp() { 11185 if (codeFile == null || !codeFile.exists()) { 11186 return false; 11187 } 11188 11189 if (codeFile.isDirectory()) { 11190 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11191 } else { 11192 codeFile.delete(); 11193 } 11194 11195 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11196 resourceFile.delete(); 11197 } 11198 11199 return true; 11200 } 11201 11202 void cleanUpResourcesLI() { 11203 // Try enumerating all code paths before deleting 11204 List<String> allCodePaths = Collections.EMPTY_LIST; 11205 if (codeFile != null && codeFile.exists()) { 11206 try { 11207 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11208 allCodePaths = pkg.getAllCodePaths(); 11209 } catch (PackageParserException e) { 11210 // Ignored; we tried our best 11211 } 11212 } 11213 11214 cleanUp(); 11215 removeDexFiles(allCodePaths, instructionSets); 11216 } 11217 11218 boolean doPostDeleteLI(boolean delete) { 11219 // XXX err, shouldn't we respect the delete flag? 11220 cleanUpResourcesLI(); 11221 return true; 11222 } 11223 } 11224 11225 private boolean isAsecExternal(String cid) { 11226 final String asecPath = PackageHelper.getSdFilesystem(cid); 11227 return !asecPath.startsWith(mAsecInternalPath); 11228 } 11229 11230 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11231 PackageManagerException { 11232 if (copyRet < 0) { 11233 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11234 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11235 throw new PackageManagerException(copyRet, message); 11236 } 11237 } 11238 } 11239 11240 /** 11241 * Extract the MountService "container ID" from the full code path of an 11242 * .apk. 11243 */ 11244 static String cidFromCodePath(String fullCodePath) { 11245 int eidx = fullCodePath.lastIndexOf("/"); 11246 String subStr1 = fullCodePath.substring(0, eidx); 11247 int sidx = subStr1.lastIndexOf("/"); 11248 return subStr1.substring(sidx+1, eidx); 11249 } 11250 11251 /** 11252 * Logic to handle installation of ASEC applications, including copying and 11253 * renaming logic. 11254 */ 11255 class AsecInstallArgs extends InstallArgs { 11256 static final String RES_FILE_NAME = "pkg.apk"; 11257 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11258 11259 String cid; 11260 String packagePath; 11261 String resourcePath; 11262 11263 /** New install */ 11264 AsecInstallArgs(InstallParams params) { 11265 super(params.origin, params.move, params.observer, params.installFlags, 11266 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11267 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11268 params.grantedRuntimePermissions); 11269 } 11270 11271 /** Existing install */ 11272 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11273 boolean isExternal, boolean isForwardLocked) { 11274 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11275 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11276 instructionSets, null, null); 11277 // Hackily pretend we're still looking at a full code path 11278 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11279 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11280 } 11281 11282 // Extract cid from fullCodePath 11283 int eidx = fullCodePath.lastIndexOf("/"); 11284 String subStr1 = fullCodePath.substring(0, eidx); 11285 int sidx = subStr1.lastIndexOf("/"); 11286 cid = subStr1.substring(sidx+1, eidx); 11287 setMountPath(subStr1); 11288 } 11289 11290 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11291 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11292 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11293 instructionSets, null, null); 11294 this.cid = cid; 11295 setMountPath(PackageHelper.getSdDir(cid)); 11296 } 11297 11298 void createCopyFile() { 11299 cid = mInstallerService.allocateExternalStageCidLegacy(); 11300 } 11301 11302 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11303 if (origin.staged) { 11304 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11305 cid = origin.cid; 11306 setMountPath(PackageHelper.getSdDir(cid)); 11307 return PackageManager.INSTALL_SUCCEEDED; 11308 } 11309 11310 if (temp) { 11311 createCopyFile(); 11312 } else { 11313 /* 11314 * Pre-emptively destroy the container since it's destroyed if 11315 * copying fails due to it existing anyway. 11316 */ 11317 PackageHelper.destroySdDir(cid); 11318 } 11319 11320 final String newMountPath = imcs.copyPackageToContainer( 11321 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11322 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11323 11324 if (newMountPath != null) { 11325 setMountPath(newMountPath); 11326 return PackageManager.INSTALL_SUCCEEDED; 11327 } else { 11328 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11329 } 11330 } 11331 11332 @Override 11333 String getCodePath() { 11334 return packagePath; 11335 } 11336 11337 @Override 11338 String getResourcePath() { 11339 return resourcePath; 11340 } 11341 11342 int doPreInstall(int status) { 11343 if (status != PackageManager.INSTALL_SUCCEEDED) { 11344 // Destroy container 11345 PackageHelper.destroySdDir(cid); 11346 } else { 11347 boolean mounted = PackageHelper.isContainerMounted(cid); 11348 if (!mounted) { 11349 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11350 Process.SYSTEM_UID); 11351 if (newMountPath != null) { 11352 setMountPath(newMountPath); 11353 } else { 11354 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11355 } 11356 } 11357 } 11358 return status; 11359 } 11360 11361 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11362 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11363 String newMountPath = null; 11364 if (PackageHelper.isContainerMounted(cid)) { 11365 // Unmount the container 11366 if (!PackageHelper.unMountSdDir(cid)) { 11367 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11368 return false; 11369 } 11370 } 11371 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11372 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11373 " which might be stale. Will try to clean up."); 11374 // Clean up the stale container and proceed to recreate. 11375 if (!PackageHelper.destroySdDir(newCacheId)) { 11376 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11377 return false; 11378 } 11379 // Successfully cleaned up stale container. Try to rename again. 11380 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11381 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11382 + " inspite of cleaning it up."); 11383 return false; 11384 } 11385 } 11386 if (!PackageHelper.isContainerMounted(newCacheId)) { 11387 Slog.w(TAG, "Mounting container " + newCacheId); 11388 newMountPath = PackageHelper.mountSdDir(newCacheId, 11389 getEncryptKey(), Process.SYSTEM_UID); 11390 } else { 11391 newMountPath = PackageHelper.getSdDir(newCacheId); 11392 } 11393 if (newMountPath == null) { 11394 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11395 return false; 11396 } 11397 Log.i(TAG, "Succesfully renamed " + cid + 11398 " to " + newCacheId + 11399 " at new path: " + newMountPath); 11400 cid = newCacheId; 11401 11402 final File beforeCodeFile = new File(packagePath); 11403 setMountPath(newMountPath); 11404 final File afterCodeFile = new File(packagePath); 11405 11406 // Reflect the rename in scanned details 11407 pkg.codePath = afterCodeFile.getAbsolutePath(); 11408 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11409 pkg.baseCodePath); 11410 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11411 pkg.splitCodePaths); 11412 11413 // Reflect the rename in app info 11414 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11415 pkg.applicationInfo.setCodePath(pkg.codePath); 11416 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11417 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11418 pkg.applicationInfo.setResourcePath(pkg.codePath); 11419 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11420 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11421 11422 return true; 11423 } 11424 11425 private void setMountPath(String mountPath) { 11426 final File mountFile = new File(mountPath); 11427 11428 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11429 if (monolithicFile.exists()) { 11430 packagePath = monolithicFile.getAbsolutePath(); 11431 if (isFwdLocked()) { 11432 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11433 } else { 11434 resourcePath = packagePath; 11435 } 11436 } else { 11437 packagePath = mountFile.getAbsolutePath(); 11438 resourcePath = packagePath; 11439 } 11440 } 11441 11442 int doPostInstall(int status, int uid) { 11443 if (status != PackageManager.INSTALL_SUCCEEDED) { 11444 cleanUp(); 11445 } else { 11446 final int groupOwner; 11447 final String protectedFile; 11448 if (isFwdLocked()) { 11449 groupOwner = UserHandle.getSharedAppGid(uid); 11450 protectedFile = RES_FILE_NAME; 11451 } else { 11452 groupOwner = -1; 11453 protectedFile = null; 11454 } 11455 11456 if (uid < Process.FIRST_APPLICATION_UID 11457 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11458 Slog.e(TAG, "Failed to finalize " + cid); 11459 PackageHelper.destroySdDir(cid); 11460 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11461 } 11462 11463 boolean mounted = PackageHelper.isContainerMounted(cid); 11464 if (!mounted) { 11465 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11466 } 11467 } 11468 return status; 11469 } 11470 11471 private void cleanUp() { 11472 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11473 11474 // Destroy secure container 11475 PackageHelper.destroySdDir(cid); 11476 } 11477 11478 private List<String> getAllCodePaths() { 11479 final File codeFile = new File(getCodePath()); 11480 if (codeFile != null && codeFile.exists()) { 11481 try { 11482 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11483 return pkg.getAllCodePaths(); 11484 } catch (PackageParserException e) { 11485 // Ignored; we tried our best 11486 } 11487 } 11488 return Collections.EMPTY_LIST; 11489 } 11490 11491 void cleanUpResourcesLI() { 11492 // Enumerate all code paths before deleting 11493 cleanUpResourcesLI(getAllCodePaths()); 11494 } 11495 11496 private void cleanUpResourcesLI(List<String> allCodePaths) { 11497 cleanUp(); 11498 removeDexFiles(allCodePaths, instructionSets); 11499 } 11500 11501 String getPackageName() { 11502 return getAsecPackageName(cid); 11503 } 11504 11505 boolean doPostDeleteLI(boolean delete) { 11506 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11507 final List<String> allCodePaths = getAllCodePaths(); 11508 boolean mounted = PackageHelper.isContainerMounted(cid); 11509 if (mounted) { 11510 // Unmount first 11511 if (PackageHelper.unMountSdDir(cid)) { 11512 mounted = false; 11513 } 11514 } 11515 if (!mounted && delete) { 11516 cleanUpResourcesLI(allCodePaths); 11517 } 11518 return !mounted; 11519 } 11520 11521 @Override 11522 int doPreCopy() { 11523 if (isFwdLocked()) { 11524 if (!PackageHelper.fixSdPermissions(cid, 11525 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11526 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11527 } 11528 } 11529 11530 return PackageManager.INSTALL_SUCCEEDED; 11531 } 11532 11533 @Override 11534 int doPostCopy(int uid) { 11535 if (isFwdLocked()) { 11536 if (uid < Process.FIRST_APPLICATION_UID 11537 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11538 RES_FILE_NAME)) { 11539 Slog.e(TAG, "Failed to finalize " + cid); 11540 PackageHelper.destroySdDir(cid); 11541 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11542 } 11543 } 11544 11545 return PackageManager.INSTALL_SUCCEEDED; 11546 } 11547 } 11548 11549 /** 11550 * Logic to handle movement of existing installed applications. 11551 */ 11552 class MoveInstallArgs extends InstallArgs { 11553 private File codeFile; 11554 private File resourceFile; 11555 11556 /** New install */ 11557 MoveInstallArgs(InstallParams params) { 11558 super(params.origin, params.move, params.observer, params.installFlags, 11559 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11560 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11561 params.grantedRuntimePermissions); 11562 } 11563 11564 int copyApk(IMediaContainerService imcs, boolean temp) { 11565 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11566 + move.fromUuid + " to " + move.toUuid); 11567 synchronized (mInstaller) { 11568 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11569 move.dataAppName, move.appId, move.seinfo) != 0) { 11570 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11571 } 11572 } 11573 11574 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11575 resourceFile = codeFile; 11576 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11577 11578 return PackageManager.INSTALL_SUCCEEDED; 11579 } 11580 11581 int doPreInstall(int status) { 11582 if (status != PackageManager.INSTALL_SUCCEEDED) { 11583 cleanUp(move.toUuid); 11584 } 11585 return status; 11586 } 11587 11588 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11589 if (status != PackageManager.INSTALL_SUCCEEDED) { 11590 cleanUp(move.toUuid); 11591 return false; 11592 } 11593 11594 // Reflect the move in app info 11595 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11596 pkg.applicationInfo.setCodePath(pkg.codePath); 11597 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11598 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11599 pkg.applicationInfo.setResourcePath(pkg.codePath); 11600 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11601 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11602 11603 return true; 11604 } 11605 11606 int doPostInstall(int status, int uid) { 11607 if (status == PackageManager.INSTALL_SUCCEEDED) { 11608 cleanUp(move.fromUuid); 11609 } else { 11610 cleanUp(move.toUuid); 11611 } 11612 return status; 11613 } 11614 11615 @Override 11616 String getCodePath() { 11617 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11618 } 11619 11620 @Override 11621 String getResourcePath() { 11622 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11623 } 11624 11625 private boolean cleanUp(String volumeUuid) { 11626 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11627 move.dataAppName); 11628 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11629 synchronized (mInstallLock) { 11630 // Clean up both app data and code 11631 removeDataDirsLI(volumeUuid, move.packageName); 11632 if (codeFile.isDirectory()) { 11633 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11634 } else { 11635 codeFile.delete(); 11636 } 11637 } 11638 return true; 11639 } 11640 11641 void cleanUpResourcesLI() { 11642 throw new UnsupportedOperationException(); 11643 } 11644 11645 boolean doPostDeleteLI(boolean delete) { 11646 throw new UnsupportedOperationException(); 11647 } 11648 } 11649 11650 static String getAsecPackageName(String packageCid) { 11651 int idx = packageCid.lastIndexOf("-"); 11652 if (idx == -1) { 11653 return packageCid; 11654 } 11655 return packageCid.substring(0, idx); 11656 } 11657 11658 // Utility method used to create code paths based on package name and available index. 11659 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11660 String idxStr = ""; 11661 int idx = 1; 11662 // Fall back to default value of idx=1 if prefix is not 11663 // part of oldCodePath 11664 if (oldCodePath != null) { 11665 String subStr = oldCodePath; 11666 // Drop the suffix right away 11667 if (suffix != null && subStr.endsWith(suffix)) { 11668 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11669 } 11670 // If oldCodePath already contains prefix find out the 11671 // ending index to either increment or decrement. 11672 int sidx = subStr.lastIndexOf(prefix); 11673 if (sidx != -1) { 11674 subStr = subStr.substring(sidx + prefix.length()); 11675 if (subStr != null) { 11676 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11677 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11678 } 11679 try { 11680 idx = Integer.parseInt(subStr); 11681 if (idx <= 1) { 11682 idx++; 11683 } else { 11684 idx--; 11685 } 11686 } catch(NumberFormatException e) { 11687 } 11688 } 11689 } 11690 } 11691 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11692 return prefix + idxStr; 11693 } 11694 11695 private File getNextCodePath(File targetDir, String packageName) { 11696 int suffix = 1; 11697 File result; 11698 do { 11699 result = new File(targetDir, packageName + "-" + suffix); 11700 suffix++; 11701 } while (result.exists()); 11702 return result; 11703 } 11704 11705 // Utility method that returns the relative package path with respect 11706 // to the installation directory. Like say for /data/data/com.test-1.apk 11707 // string com.test-1 is returned. 11708 static String deriveCodePathName(String codePath) { 11709 if (codePath == null) { 11710 return null; 11711 } 11712 final File codeFile = new File(codePath); 11713 final String name = codeFile.getName(); 11714 if (codeFile.isDirectory()) { 11715 return name; 11716 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11717 final int lastDot = name.lastIndexOf('.'); 11718 return name.substring(0, lastDot); 11719 } else { 11720 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11721 return null; 11722 } 11723 } 11724 11725 class PackageInstalledInfo { 11726 String name; 11727 int uid; 11728 // The set of users that originally had this package installed. 11729 int[] origUsers; 11730 // The set of users that now have this package installed. 11731 int[] newUsers; 11732 PackageParser.Package pkg; 11733 int returnCode; 11734 String returnMsg; 11735 PackageRemovedInfo removedInfo; 11736 11737 public void setError(int code, String msg) { 11738 returnCode = code; 11739 returnMsg = msg; 11740 Slog.w(TAG, msg); 11741 } 11742 11743 public void setError(String msg, PackageParserException e) { 11744 returnCode = e.error; 11745 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11746 Slog.w(TAG, msg, e); 11747 } 11748 11749 public void setError(String msg, PackageManagerException e) { 11750 returnCode = e.error; 11751 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11752 Slog.w(TAG, msg, e); 11753 } 11754 11755 // In some error cases we want to convey more info back to the observer 11756 String origPackage; 11757 String origPermission; 11758 } 11759 11760 /* 11761 * Install a non-existing package. 11762 */ 11763 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11764 UserHandle user, String installerPackageName, String volumeUuid, 11765 PackageInstalledInfo res) { 11766 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11767 11768 // Remember this for later, in case we need to rollback this install 11769 String pkgName = pkg.packageName; 11770 11771 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11772 final boolean dataDirExists = Environment 11773 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11774 11775 synchronized(mPackages) { 11776 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11777 // A package with the same name is already installed, though 11778 // it has been renamed to an older name. The package we 11779 // are trying to install should be installed as an update to 11780 // the existing one, but that has not been requested, so bail. 11781 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11782 + " without first uninstalling package running as " 11783 + mSettings.mRenamedPackages.get(pkgName)); 11784 return; 11785 } 11786 if (mPackages.containsKey(pkgName)) { 11787 // Don't allow installation over an existing package with the same name. 11788 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11789 + " without first uninstalling."); 11790 return; 11791 } 11792 } 11793 11794 try { 11795 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11796 System.currentTimeMillis(), user); 11797 11798 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11799 // delete the partially installed application. the data directory will have to be 11800 // restored if it was already existing 11801 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11802 // remove package from internal structures. Note that we want deletePackageX to 11803 // delete the package data and cache directories that it created in 11804 // scanPackageLocked, unless those directories existed before we even tried to 11805 // install. 11806 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11807 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11808 res.removedInfo, true); 11809 } 11810 11811 } catch (PackageManagerException e) { 11812 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11813 } 11814 11815 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11816 } 11817 11818 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11819 // Can't rotate keys during boot or if sharedUser. 11820 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11821 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11822 return false; 11823 } 11824 // app is using upgradeKeySets; make sure all are valid 11825 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11826 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11827 for (int i = 0; i < upgradeKeySets.length; i++) { 11828 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11829 Slog.wtf(TAG, "Package " 11830 + (oldPs.name != null ? oldPs.name : "<null>") 11831 + " contains upgrade-key-set reference to unknown key-set: " 11832 + upgradeKeySets[i] 11833 + " reverting to signatures check."); 11834 return false; 11835 } 11836 } 11837 return true; 11838 } 11839 11840 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11841 // Upgrade keysets are being used. Determine if new package has a superset of the 11842 // required keys. 11843 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11844 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11845 for (int i = 0; i < upgradeKeySets.length; i++) { 11846 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11847 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11848 return true; 11849 } 11850 } 11851 return false; 11852 } 11853 11854 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11855 UserHandle user, String installerPackageName, String volumeUuid, 11856 PackageInstalledInfo res) { 11857 final PackageParser.Package oldPackage; 11858 final String pkgName = pkg.packageName; 11859 final int[] allUsers; 11860 final boolean[] perUserInstalled; 11861 11862 // First find the old package info and check signatures 11863 synchronized(mPackages) { 11864 oldPackage = mPackages.get(pkgName); 11865 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11866 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11867 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11868 if(!checkUpgradeKeySetLP(ps, pkg)) { 11869 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11870 "New package not signed by keys specified by upgrade-keysets: " 11871 + pkgName); 11872 return; 11873 } 11874 } else { 11875 // default to original signature matching 11876 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11877 != PackageManager.SIGNATURE_MATCH) { 11878 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11879 "New package has a different signature: " + pkgName); 11880 return; 11881 } 11882 } 11883 11884 // In case of rollback, remember per-user/profile install state 11885 allUsers = sUserManager.getUserIds(); 11886 perUserInstalled = new boolean[allUsers.length]; 11887 for (int i = 0; i < allUsers.length; i++) { 11888 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11889 } 11890 } 11891 11892 boolean sysPkg = (isSystemApp(oldPackage)); 11893 if (sysPkg) { 11894 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11895 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11896 } else { 11897 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11898 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11899 } 11900 } 11901 11902 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11903 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11904 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11905 String volumeUuid, PackageInstalledInfo res) { 11906 String pkgName = deletedPackage.packageName; 11907 boolean deletedPkg = true; 11908 boolean updatedSettings = false; 11909 11910 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11911 + deletedPackage); 11912 long origUpdateTime; 11913 if (pkg.mExtras != null) { 11914 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11915 } else { 11916 origUpdateTime = 0; 11917 } 11918 11919 // First delete the existing package while retaining the data directory 11920 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11921 res.removedInfo, true)) { 11922 // If the existing package wasn't successfully deleted 11923 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11924 deletedPkg = false; 11925 } else { 11926 // Successfully deleted the old package; proceed with replace. 11927 11928 // If deleted package lived in a container, give users a chance to 11929 // relinquish resources before killing. 11930 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11931 if (DEBUG_INSTALL) { 11932 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11933 } 11934 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11935 final ArrayList<String> pkgList = new ArrayList<String>(1); 11936 pkgList.add(deletedPackage.applicationInfo.packageName); 11937 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11938 } 11939 11940 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11941 try { 11942 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 11943 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11944 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11945 perUserInstalled, res, user); 11946 updatedSettings = true; 11947 } catch (PackageManagerException e) { 11948 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11949 } 11950 } 11951 11952 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11953 // remove package from internal structures. Note that we want deletePackageX to 11954 // delete the package data and cache directories that it created in 11955 // scanPackageLocked, unless those directories existed before we even tried to 11956 // install. 11957 if(updatedSettings) { 11958 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11959 deletePackageLI( 11960 pkgName, null, true, allUsers, perUserInstalled, 11961 PackageManager.DELETE_KEEP_DATA, 11962 res.removedInfo, true); 11963 } 11964 // Since we failed to install the new package we need to restore the old 11965 // package that we deleted. 11966 if (deletedPkg) { 11967 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11968 File restoreFile = new File(deletedPackage.codePath); 11969 // Parse old package 11970 boolean oldExternal = isExternal(deletedPackage); 11971 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11972 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11973 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11974 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11975 try { 11976 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11977 } catch (PackageManagerException e) { 11978 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11979 + e.getMessage()); 11980 return; 11981 } 11982 // Restore of old package succeeded. Update permissions. 11983 // writer 11984 synchronized (mPackages) { 11985 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11986 UPDATE_PERMISSIONS_ALL); 11987 // can downgrade to reader 11988 mSettings.writeLPr(); 11989 } 11990 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11991 } 11992 } 11993 } 11994 11995 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11996 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11997 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11998 String volumeUuid, PackageInstalledInfo res) { 11999 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12000 + ", old=" + deletedPackage); 12001 boolean disabledSystem = false; 12002 boolean updatedSettings = false; 12003 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12004 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12005 != 0) { 12006 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12007 } 12008 String packageName = deletedPackage.packageName; 12009 if (packageName == null) { 12010 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12011 "Attempt to delete null packageName."); 12012 return; 12013 } 12014 PackageParser.Package oldPkg; 12015 PackageSetting oldPkgSetting; 12016 // reader 12017 synchronized (mPackages) { 12018 oldPkg = mPackages.get(packageName); 12019 oldPkgSetting = mSettings.mPackages.get(packageName); 12020 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12021 (oldPkgSetting == null)) { 12022 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12023 "Couldn't find package:" + packageName + " information"); 12024 return; 12025 } 12026 } 12027 12028 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12029 12030 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12031 res.removedInfo.removedPackage = packageName; 12032 // Remove existing system package 12033 removePackageLI(oldPkgSetting, true); 12034 // writer 12035 synchronized (mPackages) { 12036 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12037 if (!disabledSystem && deletedPackage != null) { 12038 // We didn't need to disable the .apk as a current system package, 12039 // which means we are replacing another update that is already 12040 // installed. We need to make sure to delete the older one's .apk. 12041 res.removedInfo.args = createInstallArgsForExisting(0, 12042 deletedPackage.applicationInfo.getCodePath(), 12043 deletedPackage.applicationInfo.getResourcePath(), 12044 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12045 } else { 12046 res.removedInfo.args = null; 12047 } 12048 } 12049 12050 // Successfully disabled the old package. Now proceed with re-installation 12051 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12052 12053 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12054 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12055 12056 PackageParser.Package newPackage = null; 12057 try { 12058 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12059 if (newPackage.mExtras != null) { 12060 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12061 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12062 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12063 12064 // is the update attempting to change shared user? that isn't going to work... 12065 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12066 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12067 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12068 + " to " + newPkgSetting.sharedUser); 12069 updatedSettings = true; 12070 } 12071 } 12072 12073 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12074 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12075 perUserInstalled, res, user); 12076 updatedSettings = true; 12077 } 12078 12079 } catch (PackageManagerException e) { 12080 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12081 } 12082 12083 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12084 // Re installation failed. Restore old information 12085 // Remove new pkg information 12086 if (newPackage != null) { 12087 removeInstalledPackageLI(newPackage, true); 12088 } 12089 // Add back the old system package 12090 try { 12091 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12092 } catch (PackageManagerException e) { 12093 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12094 } 12095 // Restore the old system information in Settings 12096 synchronized (mPackages) { 12097 if (disabledSystem) { 12098 mSettings.enableSystemPackageLPw(packageName); 12099 } 12100 if (updatedSettings) { 12101 mSettings.setInstallerPackageName(packageName, 12102 oldPkgSetting.installerPackageName); 12103 } 12104 mSettings.writeLPr(); 12105 } 12106 } 12107 } 12108 12109 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12110 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12111 UserHandle user) { 12112 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12113 12114 String pkgName = newPackage.packageName; 12115 synchronized (mPackages) { 12116 //write settings. the installStatus will be incomplete at this stage. 12117 //note that the new package setting would have already been 12118 //added to mPackages. It hasn't been persisted yet. 12119 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12120 mSettings.writeLPr(); 12121 } 12122 12123 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12124 synchronized (mPackages) { 12125 updatePermissionsLPw(newPackage.packageName, newPackage, 12126 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12127 ? UPDATE_PERMISSIONS_ALL : 0)); 12128 // For system-bundled packages, we assume that installing an upgraded version 12129 // of the package implies that the user actually wants to run that new code, 12130 // so we enable the package. 12131 PackageSetting ps = mSettings.mPackages.get(pkgName); 12132 if (ps != null) { 12133 if (isSystemApp(newPackage)) { 12134 // NB: implicit assumption that system package upgrades apply to all users 12135 if (DEBUG_INSTALL) { 12136 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12137 } 12138 if (res.origUsers != null) { 12139 for (int userHandle : res.origUsers) { 12140 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12141 userHandle, installerPackageName); 12142 } 12143 } 12144 // Also convey the prior install/uninstall state 12145 if (allUsers != null && perUserInstalled != null) { 12146 for (int i = 0; i < allUsers.length; i++) { 12147 if (DEBUG_INSTALL) { 12148 Slog.d(TAG, " user " + allUsers[i] 12149 + " => " + perUserInstalled[i]); 12150 } 12151 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12152 } 12153 // these install state changes will be persisted in the 12154 // upcoming call to mSettings.writeLPr(). 12155 } 12156 } 12157 // It's implied that when a user requests installation, they want the app to be 12158 // installed and enabled. 12159 int userId = user.getIdentifier(); 12160 if (userId != UserHandle.USER_ALL) { 12161 ps.setInstalled(true, userId); 12162 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12163 } 12164 } 12165 res.name = pkgName; 12166 res.uid = newPackage.applicationInfo.uid; 12167 res.pkg = newPackage; 12168 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12169 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12170 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12171 //to update install status 12172 mSettings.writeLPr(); 12173 } 12174 12175 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12176 } 12177 12178 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12179 try { 12180 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12181 installPackageLI(args, res); 12182 } finally { 12183 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12184 } 12185 } 12186 12187 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12188 final int installFlags = args.installFlags; 12189 final String installerPackageName = args.installerPackageName; 12190 final String volumeUuid = args.volumeUuid; 12191 final File tmpPackageFile = new File(args.getCodePath()); 12192 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12193 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12194 || (args.volumeUuid != null)); 12195 boolean replace = false; 12196 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12197 if (args.move != null) { 12198 // moving a complete application; perfom an initial scan on the new install location 12199 scanFlags |= SCAN_INITIAL; 12200 } 12201 // Result object to be returned 12202 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12203 12204 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12205 12206 // Retrieve PackageSettings and parse package 12207 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12208 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12209 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12210 PackageParser pp = new PackageParser(); 12211 pp.setSeparateProcesses(mSeparateProcesses); 12212 pp.setDisplayMetrics(mMetrics); 12213 12214 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12215 final PackageParser.Package pkg; 12216 try { 12217 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12218 } catch (PackageParserException e) { 12219 res.setError("Failed parse during installPackageLI", e); 12220 return; 12221 } finally { 12222 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12223 } 12224 12225 // Mark that we have an install time CPU ABI override. 12226 pkg.cpuAbiOverride = args.abiOverride; 12227 12228 String pkgName = res.name = pkg.packageName; 12229 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12230 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12231 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12232 return; 12233 } 12234 } 12235 12236 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12237 try { 12238 pp.collectCertificates(pkg, parseFlags); 12239 pp.collectManifestDigest(pkg); 12240 } catch (PackageParserException e) { 12241 res.setError("Failed collect during installPackageLI", e); 12242 return; 12243 } finally { 12244 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12245 } 12246 12247 /* If the installer passed in a manifest digest, compare it now. */ 12248 if (args.manifestDigest != null) { 12249 if (DEBUG_INSTALL) { 12250 final String parsedManifest = pkg.manifestDigest == null ? "null" 12251 : pkg.manifestDigest.toString(); 12252 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12253 + parsedManifest); 12254 } 12255 12256 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12257 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12258 return; 12259 } 12260 } else if (DEBUG_INSTALL) { 12261 final String parsedManifest = pkg.manifestDigest == null 12262 ? "null" : pkg.manifestDigest.toString(); 12263 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12264 } 12265 12266 // Get rid of all references to package scan path via parser. 12267 pp = null; 12268 String oldCodePath = null; 12269 boolean systemApp = false; 12270 synchronized (mPackages) { 12271 // Check if installing already existing package 12272 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12273 String oldName = mSettings.mRenamedPackages.get(pkgName); 12274 if (pkg.mOriginalPackages != null 12275 && pkg.mOriginalPackages.contains(oldName) 12276 && mPackages.containsKey(oldName)) { 12277 // This package is derived from an original package, 12278 // and this device has been updating from that original 12279 // name. We must continue using the original name, so 12280 // rename the new package here. 12281 pkg.setPackageName(oldName); 12282 pkgName = pkg.packageName; 12283 replace = true; 12284 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12285 + oldName + " pkgName=" + pkgName); 12286 } else if (mPackages.containsKey(pkgName)) { 12287 // This package, under its official name, already exists 12288 // on the device; we should replace it. 12289 replace = true; 12290 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12291 } 12292 12293 // Prevent apps opting out from runtime permissions 12294 if (replace) { 12295 PackageParser.Package oldPackage = mPackages.get(pkgName); 12296 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12297 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12298 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12299 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12300 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12301 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12302 + " doesn't support runtime permissions but the old" 12303 + " target SDK " + oldTargetSdk + " does."); 12304 return; 12305 } 12306 } 12307 } 12308 12309 PackageSetting ps = mSettings.mPackages.get(pkgName); 12310 if (ps != null) { 12311 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12312 12313 // Quick sanity check that we're signed correctly if updating; 12314 // we'll check this again later when scanning, but we want to 12315 // bail early here before tripping over redefined permissions. 12316 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12317 if (!checkUpgradeKeySetLP(ps, pkg)) { 12318 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12319 + pkg.packageName + " upgrade keys do not match the " 12320 + "previously installed version"); 12321 return; 12322 } 12323 } else { 12324 try { 12325 verifySignaturesLP(ps, pkg); 12326 } catch (PackageManagerException e) { 12327 res.setError(e.error, e.getMessage()); 12328 return; 12329 } 12330 } 12331 12332 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12333 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12334 systemApp = (ps.pkg.applicationInfo.flags & 12335 ApplicationInfo.FLAG_SYSTEM) != 0; 12336 } 12337 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12338 } 12339 12340 // Check whether the newly-scanned package wants to define an already-defined perm 12341 int N = pkg.permissions.size(); 12342 for (int i = N-1; i >= 0; i--) { 12343 PackageParser.Permission perm = pkg.permissions.get(i); 12344 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12345 if (bp != null) { 12346 // If the defining package is signed with our cert, it's okay. This 12347 // also includes the "updating the same package" case, of course. 12348 // "updating same package" could also involve key-rotation. 12349 final boolean sigsOk; 12350 if (bp.sourcePackage.equals(pkg.packageName) 12351 && (bp.packageSetting instanceof PackageSetting) 12352 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12353 scanFlags))) { 12354 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12355 } else { 12356 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12357 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12358 } 12359 if (!sigsOk) { 12360 // If the owning package is the system itself, we log but allow 12361 // install to proceed; we fail the install on all other permission 12362 // redefinitions. 12363 if (!bp.sourcePackage.equals("android")) { 12364 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12365 + pkg.packageName + " attempting to redeclare permission " 12366 + perm.info.name + " already owned by " + bp.sourcePackage); 12367 res.origPermission = perm.info.name; 12368 res.origPackage = bp.sourcePackage; 12369 return; 12370 } else { 12371 Slog.w(TAG, "Package " + pkg.packageName 12372 + " attempting to redeclare system permission " 12373 + perm.info.name + "; ignoring new declaration"); 12374 pkg.permissions.remove(i); 12375 } 12376 } 12377 } 12378 } 12379 12380 } 12381 12382 if (systemApp && onExternal) { 12383 // Disable updates to system apps on sdcard 12384 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12385 "Cannot install updates to system apps on sdcard"); 12386 return; 12387 } 12388 12389 if (args.move != null) { 12390 // We did an in-place move, so dex is ready to roll 12391 scanFlags |= SCAN_NO_DEX; 12392 scanFlags |= SCAN_MOVE; 12393 12394 synchronized (mPackages) { 12395 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12396 if (ps == null) { 12397 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12398 "Missing settings for moved package " + pkgName); 12399 } 12400 12401 // We moved the entire application as-is, so bring over the 12402 // previously derived ABI information. 12403 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12404 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12405 } 12406 12407 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12408 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12409 scanFlags |= SCAN_NO_DEX; 12410 12411 try { 12412 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12413 true /* extract libs */); 12414 } catch (PackageManagerException pme) { 12415 Slog.e(TAG, "Error deriving application ABI", pme); 12416 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12417 return; 12418 } 12419 12420 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12421 int result = mPackageDexOptimizer 12422 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12423 false /* defer */, false /* inclDependencies */); 12424 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12425 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12426 return; 12427 } 12428 } 12429 12430 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12431 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12432 return; 12433 } 12434 12435 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12436 12437 if (replace) { 12438 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12439 installerPackageName, volumeUuid, res); 12440 } else { 12441 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12442 args.user, installerPackageName, volumeUuid, res); 12443 } 12444 synchronized (mPackages) { 12445 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12446 if (ps != null) { 12447 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12448 } 12449 } 12450 } 12451 12452 private void startIntentFilterVerifications(int userId, boolean replacing, 12453 PackageParser.Package pkg) { 12454 if (mIntentFilterVerifierComponent == null) { 12455 Slog.w(TAG, "No IntentFilter verification will not be done as " 12456 + "there is no IntentFilterVerifier available!"); 12457 return; 12458 } 12459 12460 final int verifierUid = getPackageUid( 12461 mIntentFilterVerifierComponent.getPackageName(), 12462 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12463 12464 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12465 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12466 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12467 mHandler.sendMessage(msg); 12468 } 12469 12470 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12471 PackageParser.Package pkg) { 12472 int size = pkg.activities.size(); 12473 if (size == 0) { 12474 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12475 "No activity, so no need to verify any IntentFilter!"); 12476 return; 12477 } 12478 12479 final boolean hasDomainURLs = hasDomainURLs(pkg); 12480 if (!hasDomainURLs) { 12481 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12482 "No domain URLs, so no need to verify any IntentFilter!"); 12483 return; 12484 } 12485 12486 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12487 + " if any IntentFilter from the " + size 12488 + " Activities needs verification ..."); 12489 12490 int count = 0; 12491 final String packageName = pkg.packageName; 12492 12493 synchronized (mPackages) { 12494 // If this is a new install and we see that we've already run verification for this 12495 // package, we have nothing to do: it means the state was restored from backup. 12496 if (!replacing) { 12497 IntentFilterVerificationInfo ivi = 12498 mSettings.getIntentFilterVerificationLPr(packageName); 12499 if (ivi != null) { 12500 if (DEBUG_DOMAIN_VERIFICATION) { 12501 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12502 + ivi.getStatusString()); 12503 } 12504 return; 12505 } 12506 } 12507 12508 // If any filters need to be verified, then all need to be. 12509 boolean needToVerify = false; 12510 for (PackageParser.Activity a : pkg.activities) { 12511 for (ActivityIntentInfo filter : a.intents) { 12512 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12513 if (DEBUG_DOMAIN_VERIFICATION) { 12514 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12515 } 12516 needToVerify = true; 12517 break; 12518 } 12519 } 12520 } 12521 12522 if (needToVerify) { 12523 final int verificationId = mIntentFilterVerificationToken++; 12524 for (PackageParser.Activity a : pkg.activities) { 12525 for (ActivityIntentInfo filter : a.intents) { 12526 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12527 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12528 "Verification needed for IntentFilter:" + filter.toString()); 12529 mIntentFilterVerifier.addOneIntentFilterVerification( 12530 verifierUid, userId, verificationId, filter, packageName); 12531 count++; 12532 } 12533 } 12534 } 12535 } 12536 } 12537 12538 if (count > 0) { 12539 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12540 + " IntentFilter verification" + (count > 1 ? "s" : "") 12541 + " for userId:" + userId); 12542 mIntentFilterVerifier.startVerifications(userId); 12543 } else { 12544 if (DEBUG_DOMAIN_VERIFICATION) { 12545 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12546 } 12547 } 12548 } 12549 12550 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12551 final ComponentName cn = filter.activity.getComponentName(); 12552 final String packageName = cn.getPackageName(); 12553 12554 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12555 packageName); 12556 if (ivi == null) { 12557 return true; 12558 } 12559 int status = ivi.getStatus(); 12560 switch (status) { 12561 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12562 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12563 return true; 12564 12565 default: 12566 // Nothing to do 12567 return false; 12568 } 12569 } 12570 12571 private static boolean isMultiArch(PackageSetting ps) { 12572 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12573 } 12574 12575 private static boolean isMultiArch(ApplicationInfo info) { 12576 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12577 } 12578 12579 private static boolean isExternal(PackageParser.Package pkg) { 12580 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12581 } 12582 12583 private static boolean isExternal(PackageSetting ps) { 12584 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12585 } 12586 12587 private static boolean isExternal(ApplicationInfo info) { 12588 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12589 } 12590 12591 private static boolean isSystemApp(PackageParser.Package pkg) { 12592 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12593 } 12594 12595 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12596 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12597 } 12598 12599 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12600 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12601 } 12602 12603 private static boolean isSystemApp(PackageSetting ps) { 12604 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12605 } 12606 12607 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12608 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12609 } 12610 12611 private int packageFlagsToInstallFlags(PackageSetting ps) { 12612 int installFlags = 0; 12613 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12614 // This existing package was an external ASEC install when we have 12615 // the external flag without a UUID 12616 installFlags |= PackageManager.INSTALL_EXTERNAL; 12617 } 12618 if (ps.isForwardLocked()) { 12619 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12620 } 12621 return installFlags; 12622 } 12623 12624 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12625 if (isExternal(pkg)) { 12626 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12627 return mSettings.getExternalVersion(); 12628 } else { 12629 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12630 } 12631 } else { 12632 return mSettings.getInternalVersion(); 12633 } 12634 } 12635 12636 private void deleteTempPackageFiles() { 12637 final FilenameFilter filter = new FilenameFilter() { 12638 public boolean accept(File dir, String name) { 12639 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12640 } 12641 }; 12642 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12643 file.delete(); 12644 } 12645 } 12646 12647 @Override 12648 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12649 int flags) { 12650 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12651 flags); 12652 } 12653 12654 @Override 12655 public void deletePackage(final String packageName, 12656 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12657 mContext.enforceCallingOrSelfPermission( 12658 android.Manifest.permission.DELETE_PACKAGES, null); 12659 Preconditions.checkNotNull(packageName); 12660 Preconditions.checkNotNull(observer); 12661 final int uid = Binder.getCallingUid(); 12662 if (UserHandle.getUserId(uid) != userId) { 12663 mContext.enforceCallingPermission( 12664 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12665 "deletePackage for user " + userId); 12666 } 12667 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12668 try { 12669 observer.onPackageDeleted(packageName, 12670 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12671 } catch (RemoteException re) { 12672 } 12673 return; 12674 } 12675 12676 boolean uninstallBlocked = false; 12677 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12678 int[] users = sUserManager.getUserIds(); 12679 for (int i = 0; i < users.length; ++i) { 12680 if (getBlockUninstallForUser(packageName, users[i])) { 12681 uninstallBlocked = true; 12682 break; 12683 } 12684 } 12685 } else { 12686 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12687 } 12688 if (uninstallBlocked) { 12689 try { 12690 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12691 null); 12692 } catch (RemoteException re) { 12693 } 12694 return; 12695 } 12696 12697 if (DEBUG_REMOVE) { 12698 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12699 } 12700 // Queue up an async operation since the package deletion may take a little while. 12701 mHandler.post(new Runnable() { 12702 public void run() { 12703 mHandler.removeCallbacks(this); 12704 final int returnCode = deletePackageX(packageName, userId, flags); 12705 if (observer != null) { 12706 try { 12707 observer.onPackageDeleted(packageName, returnCode, null); 12708 } catch (RemoteException e) { 12709 Log.i(TAG, "Observer no longer exists."); 12710 } //end catch 12711 } //end if 12712 } //end run 12713 }); 12714 } 12715 12716 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12717 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12718 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12719 try { 12720 if (dpm != null) { 12721 if (dpm.isDeviceOwner(packageName)) { 12722 return true; 12723 } 12724 int[] users; 12725 if (userId == UserHandle.USER_ALL) { 12726 users = sUserManager.getUserIds(); 12727 } else { 12728 users = new int[]{userId}; 12729 } 12730 for (int i = 0; i < users.length; ++i) { 12731 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12732 return true; 12733 } 12734 } 12735 } 12736 } catch (RemoteException e) { 12737 } 12738 return false; 12739 } 12740 12741 /** 12742 * This method is an internal method that could be get invoked either 12743 * to delete an installed package or to clean up a failed installation. 12744 * After deleting an installed package, a broadcast is sent to notify any 12745 * listeners that the package has been installed. For cleaning up a failed 12746 * installation, the broadcast is not necessary since the package's 12747 * installation wouldn't have sent the initial broadcast either 12748 * The key steps in deleting a package are 12749 * deleting the package information in internal structures like mPackages, 12750 * deleting the packages base directories through installd 12751 * updating mSettings to reflect current status 12752 * persisting settings for later use 12753 * sending a broadcast if necessary 12754 */ 12755 private int deletePackageX(String packageName, int userId, int flags) { 12756 final PackageRemovedInfo info = new PackageRemovedInfo(); 12757 final boolean res; 12758 12759 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12760 ? UserHandle.ALL : new UserHandle(userId); 12761 12762 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12763 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12764 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12765 } 12766 12767 boolean removedForAllUsers = false; 12768 boolean systemUpdate = false; 12769 12770 // for the uninstall-updates case and restricted profiles, remember the per- 12771 // userhandle installed state 12772 int[] allUsers; 12773 boolean[] perUserInstalled; 12774 synchronized (mPackages) { 12775 PackageSetting ps = mSettings.mPackages.get(packageName); 12776 allUsers = sUserManager.getUserIds(); 12777 perUserInstalled = new boolean[allUsers.length]; 12778 for (int i = 0; i < allUsers.length; i++) { 12779 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12780 } 12781 } 12782 12783 synchronized (mInstallLock) { 12784 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12785 res = deletePackageLI(packageName, removeForUser, 12786 true, allUsers, perUserInstalled, 12787 flags | REMOVE_CHATTY, info, true); 12788 systemUpdate = info.isRemovedPackageSystemUpdate; 12789 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12790 removedForAllUsers = true; 12791 } 12792 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12793 + " removedForAllUsers=" + removedForAllUsers); 12794 } 12795 12796 if (res) { 12797 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12798 12799 // If the removed package was a system update, the old system package 12800 // was re-enabled; we need to broadcast this information 12801 if (systemUpdate) { 12802 Bundle extras = new Bundle(1); 12803 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12804 ? info.removedAppId : info.uid); 12805 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12806 12807 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12808 extras, null, null, null); 12809 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12810 extras, null, null, null); 12811 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12812 null, packageName, null, null); 12813 } 12814 } 12815 // Force a gc here. 12816 Runtime.getRuntime().gc(); 12817 // Delete the resources here after sending the broadcast to let 12818 // other processes clean up before deleting resources. 12819 if (info.args != null) { 12820 synchronized (mInstallLock) { 12821 info.args.doPostDeleteLI(true); 12822 } 12823 } 12824 12825 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12826 } 12827 12828 class PackageRemovedInfo { 12829 String removedPackage; 12830 int uid = -1; 12831 int removedAppId = -1; 12832 int[] removedUsers = null; 12833 boolean isRemovedPackageSystemUpdate = false; 12834 // Clean up resources deleted packages. 12835 InstallArgs args = null; 12836 12837 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12838 Bundle extras = new Bundle(1); 12839 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12840 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12841 if (replacing) { 12842 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12843 } 12844 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12845 if (removedPackage != null) { 12846 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12847 extras, null, null, removedUsers); 12848 if (fullRemove && !replacing) { 12849 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12850 extras, null, null, removedUsers); 12851 } 12852 } 12853 if (removedAppId >= 0) { 12854 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12855 removedUsers); 12856 } 12857 } 12858 } 12859 12860 /* 12861 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12862 * flag is not set, the data directory is removed as well. 12863 * make sure this flag is set for partially installed apps. If not its meaningless to 12864 * delete a partially installed application. 12865 */ 12866 private void removePackageDataLI(PackageSetting ps, 12867 int[] allUserHandles, boolean[] perUserInstalled, 12868 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12869 String packageName = ps.name; 12870 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12871 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12872 // Retrieve object to delete permissions for shared user later on 12873 final PackageSetting deletedPs; 12874 // reader 12875 synchronized (mPackages) { 12876 deletedPs = mSettings.mPackages.get(packageName); 12877 if (outInfo != null) { 12878 outInfo.removedPackage = packageName; 12879 outInfo.removedUsers = deletedPs != null 12880 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12881 : null; 12882 } 12883 } 12884 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12885 removeDataDirsLI(ps.volumeUuid, packageName); 12886 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12887 } 12888 // writer 12889 synchronized (mPackages) { 12890 if (deletedPs != null) { 12891 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12892 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12893 clearDefaultBrowserIfNeeded(packageName); 12894 if (outInfo != null) { 12895 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12896 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12897 } 12898 updatePermissionsLPw(deletedPs.name, null, 0); 12899 if (deletedPs.sharedUser != null) { 12900 // Remove permissions associated with package. Since runtime 12901 // permissions are per user we have to kill the removed package 12902 // or packages running under the shared user of the removed 12903 // package if revoking the permissions requested only by the removed 12904 // package is successful and this causes a change in gids. 12905 for (int userId : UserManagerService.getInstance().getUserIds()) { 12906 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12907 userId); 12908 if (userIdToKill == UserHandle.USER_ALL 12909 || userIdToKill >= UserHandle.USER_OWNER) { 12910 // If gids changed for this user, kill all affected packages. 12911 mHandler.post(new Runnable() { 12912 @Override 12913 public void run() { 12914 // This has to happen with no lock held. 12915 killApplication(deletedPs.name, deletedPs.appId, 12916 KILL_APP_REASON_GIDS_CHANGED); 12917 } 12918 }); 12919 break; 12920 } 12921 } 12922 } 12923 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12924 } 12925 // make sure to preserve per-user disabled state if this removal was just 12926 // a downgrade of a system app to the factory package 12927 if (allUserHandles != null && perUserInstalled != null) { 12928 if (DEBUG_REMOVE) { 12929 Slog.d(TAG, "Propagating install state across downgrade"); 12930 } 12931 for (int i = 0; i < allUserHandles.length; i++) { 12932 if (DEBUG_REMOVE) { 12933 Slog.d(TAG, " user " + allUserHandles[i] 12934 + " => " + perUserInstalled[i]); 12935 } 12936 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12937 } 12938 } 12939 } 12940 // can downgrade to reader 12941 if (writeSettings) { 12942 // Save settings now 12943 mSettings.writeLPr(); 12944 } 12945 } 12946 if (outInfo != null) { 12947 // A user ID was deleted here. Go through all users and remove it 12948 // from KeyStore. 12949 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12950 } 12951 } 12952 12953 static boolean locationIsPrivileged(File path) { 12954 try { 12955 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12956 .getCanonicalPath(); 12957 return path.getCanonicalPath().startsWith(privilegedAppDir); 12958 } catch (IOException e) { 12959 Slog.e(TAG, "Unable to access code path " + path); 12960 } 12961 return false; 12962 } 12963 12964 /* 12965 * Tries to delete system package. 12966 */ 12967 private boolean deleteSystemPackageLI(PackageSetting newPs, 12968 int[] allUserHandles, boolean[] perUserInstalled, 12969 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12970 final boolean applyUserRestrictions 12971 = (allUserHandles != null) && (perUserInstalled != null); 12972 PackageSetting disabledPs = null; 12973 // Confirm if the system package has been updated 12974 // An updated system app can be deleted. This will also have to restore 12975 // the system pkg from system partition 12976 // reader 12977 synchronized (mPackages) { 12978 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12979 } 12980 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12981 + " disabledPs=" + disabledPs); 12982 if (disabledPs == null) { 12983 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12984 return false; 12985 } else if (DEBUG_REMOVE) { 12986 Slog.d(TAG, "Deleting system pkg from data partition"); 12987 } 12988 if (DEBUG_REMOVE) { 12989 if (applyUserRestrictions) { 12990 Slog.d(TAG, "Remembering install states:"); 12991 for (int i = 0; i < allUserHandles.length; i++) { 12992 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12993 } 12994 } 12995 } 12996 // Delete the updated package 12997 outInfo.isRemovedPackageSystemUpdate = true; 12998 if (disabledPs.versionCode < newPs.versionCode) { 12999 // Delete data for downgrades 13000 flags &= ~PackageManager.DELETE_KEEP_DATA; 13001 } else { 13002 // Preserve data by setting flag 13003 flags |= PackageManager.DELETE_KEEP_DATA; 13004 } 13005 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13006 allUserHandles, perUserInstalled, outInfo, writeSettings); 13007 if (!ret) { 13008 return false; 13009 } 13010 // writer 13011 synchronized (mPackages) { 13012 // Reinstate the old system package 13013 mSettings.enableSystemPackageLPw(newPs.name); 13014 // Remove any native libraries from the upgraded package. 13015 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13016 } 13017 // Install the system package 13018 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13019 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13020 if (locationIsPrivileged(disabledPs.codePath)) { 13021 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13022 } 13023 13024 final PackageParser.Package newPkg; 13025 try { 13026 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13027 } catch (PackageManagerException e) { 13028 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13029 return false; 13030 } 13031 13032 // writer 13033 synchronized (mPackages) { 13034 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13035 13036 // Propagate the permissions state as we do not want to drop on the floor 13037 // runtime permissions. The update permissions method below will take 13038 // care of removing obsolete permissions and grant install permissions. 13039 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13040 updatePermissionsLPw(newPkg.packageName, newPkg, 13041 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13042 13043 if (applyUserRestrictions) { 13044 if (DEBUG_REMOVE) { 13045 Slog.d(TAG, "Propagating install state across reinstall"); 13046 } 13047 for (int i = 0; i < allUserHandles.length; i++) { 13048 if (DEBUG_REMOVE) { 13049 Slog.d(TAG, " user " + allUserHandles[i] 13050 + " => " + perUserInstalled[i]); 13051 } 13052 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13053 13054 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13055 } 13056 // Regardless of writeSettings we need to ensure that this restriction 13057 // state propagation is persisted 13058 mSettings.writeAllUsersPackageRestrictionsLPr(); 13059 } 13060 // can downgrade to reader here 13061 if (writeSettings) { 13062 mSettings.writeLPr(); 13063 } 13064 } 13065 return true; 13066 } 13067 13068 private boolean deleteInstalledPackageLI(PackageSetting ps, 13069 boolean deleteCodeAndResources, int flags, 13070 int[] allUserHandles, boolean[] perUserInstalled, 13071 PackageRemovedInfo outInfo, boolean writeSettings) { 13072 if (outInfo != null) { 13073 outInfo.uid = ps.appId; 13074 } 13075 13076 // Delete package data from internal structures and also remove data if flag is set 13077 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13078 13079 // Delete application code and resources 13080 if (deleteCodeAndResources && (outInfo != null)) { 13081 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13082 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13083 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13084 } 13085 return true; 13086 } 13087 13088 @Override 13089 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13090 int userId) { 13091 mContext.enforceCallingOrSelfPermission( 13092 android.Manifest.permission.DELETE_PACKAGES, null); 13093 synchronized (mPackages) { 13094 PackageSetting ps = mSettings.mPackages.get(packageName); 13095 if (ps == null) { 13096 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13097 return false; 13098 } 13099 if (!ps.getInstalled(userId)) { 13100 // Can't block uninstall for an app that is not installed or enabled. 13101 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13102 return false; 13103 } 13104 ps.setBlockUninstall(blockUninstall, userId); 13105 mSettings.writePackageRestrictionsLPr(userId); 13106 } 13107 return true; 13108 } 13109 13110 @Override 13111 public boolean getBlockUninstallForUser(String packageName, int userId) { 13112 synchronized (mPackages) { 13113 PackageSetting ps = mSettings.mPackages.get(packageName); 13114 if (ps == null) { 13115 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13116 return false; 13117 } 13118 return ps.getBlockUninstall(userId); 13119 } 13120 } 13121 13122 /* 13123 * This method handles package deletion in general 13124 */ 13125 private boolean deletePackageLI(String packageName, UserHandle user, 13126 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13127 int flags, PackageRemovedInfo outInfo, 13128 boolean writeSettings) { 13129 if (packageName == null) { 13130 Slog.w(TAG, "Attempt to delete null packageName."); 13131 return false; 13132 } 13133 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13134 PackageSetting ps; 13135 boolean dataOnly = false; 13136 int removeUser = -1; 13137 int appId = -1; 13138 synchronized (mPackages) { 13139 ps = mSettings.mPackages.get(packageName); 13140 if (ps == null) { 13141 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13142 return false; 13143 } 13144 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13145 && user.getIdentifier() != UserHandle.USER_ALL) { 13146 // The caller is asking that the package only be deleted for a single 13147 // user. To do this, we just mark its uninstalled state and delete 13148 // its data. If this is a system app, we only allow this to happen if 13149 // they have set the special DELETE_SYSTEM_APP which requests different 13150 // semantics than normal for uninstalling system apps. 13151 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13152 ps.setUserState(user.getIdentifier(), 13153 COMPONENT_ENABLED_STATE_DEFAULT, 13154 false, //installed 13155 true, //stopped 13156 true, //notLaunched 13157 false, //hidden 13158 null, null, null, 13159 false, // blockUninstall 13160 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 13161 if (!isSystemApp(ps)) { 13162 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13163 // Other user still have this package installed, so all 13164 // we need to do is clear this user's data and save that 13165 // it is uninstalled. 13166 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13167 removeUser = user.getIdentifier(); 13168 appId = ps.appId; 13169 scheduleWritePackageRestrictionsLocked(removeUser); 13170 } else { 13171 // We need to set it back to 'installed' so the uninstall 13172 // broadcasts will be sent correctly. 13173 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13174 ps.setInstalled(true, user.getIdentifier()); 13175 } 13176 } else { 13177 // This is a system app, so we assume that the 13178 // other users still have this package installed, so all 13179 // we need to do is clear this user's data and save that 13180 // it is uninstalled. 13181 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13182 removeUser = user.getIdentifier(); 13183 appId = ps.appId; 13184 scheduleWritePackageRestrictionsLocked(removeUser); 13185 } 13186 } 13187 } 13188 13189 if (removeUser >= 0) { 13190 // From above, we determined that we are deleting this only 13191 // for a single user. Continue the work here. 13192 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13193 if (outInfo != null) { 13194 outInfo.removedPackage = packageName; 13195 outInfo.removedAppId = appId; 13196 outInfo.removedUsers = new int[] {removeUser}; 13197 } 13198 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13199 removeKeystoreDataIfNeeded(removeUser, appId); 13200 schedulePackageCleaning(packageName, removeUser, false); 13201 synchronized (mPackages) { 13202 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13203 scheduleWritePackageRestrictionsLocked(removeUser); 13204 } 13205 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13206 } 13207 return true; 13208 } 13209 13210 if (dataOnly) { 13211 // Delete application data first 13212 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13213 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13214 return true; 13215 } 13216 13217 boolean ret = false; 13218 if (isSystemApp(ps)) { 13219 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13220 // When an updated system application is deleted we delete the existing resources as well and 13221 // fall back to existing code in system partition 13222 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13223 flags, outInfo, writeSettings); 13224 } else { 13225 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13226 // Kill application pre-emptively especially for apps on sd. 13227 killApplication(packageName, ps.appId, "uninstall pkg"); 13228 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13229 allUserHandles, perUserInstalled, 13230 outInfo, writeSettings); 13231 } 13232 13233 return ret; 13234 } 13235 13236 private final class ClearStorageConnection implements ServiceConnection { 13237 IMediaContainerService mContainerService; 13238 13239 @Override 13240 public void onServiceConnected(ComponentName name, IBinder service) { 13241 synchronized (this) { 13242 mContainerService = IMediaContainerService.Stub.asInterface(service); 13243 notifyAll(); 13244 } 13245 } 13246 13247 @Override 13248 public void onServiceDisconnected(ComponentName name) { 13249 } 13250 } 13251 13252 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13253 final boolean mounted; 13254 if (Environment.isExternalStorageEmulated()) { 13255 mounted = true; 13256 } else { 13257 final String status = Environment.getExternalStorageState(); 13258 13259 mounted = status.equals(Environment.MEDIA_MOUNTED) 13260 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13261 } 13262 13263 if (!mounted) { 13264 return; 13265 } 13266 13267 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13268 int[] users; 13269 if (userId == UserHandle.USER_ALL) { 13270 users = sUserManager.getUserIds(); 13271 } else { 13272 users = new int[] { userId }; 13273 } 13274 final ClearStorageConnection conn = new ClearStorageConnection(); 13275 if (mContext.bindServiceAsUser( 13276 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13277 try { 13278 for (int curUser : users) { 13279 long timeout = SystemClock.uptimeMillis() + 5000; 13280 synchronized (conn) { 13281 long now = SystemClock.uptimeMillis(); 13282 while (conn.mContainerService == null && now < timeout) { 13283 try { 13284 conn.wait(timeout - now); 13285 } catch (InterruptedException e) { 13286 } 13287 } 13288 } 13289 if (conn.mContainerService == null) { 13290 return; 13291 } 13292 13293 final UserEnvironment userEnv = new UserEnvironment(curUser); 13294 clearDirectory(conn.mContainerService, 13295 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13296 if (allData) { 13297 clearDirectory(conn.mContainerService, 13298 userEnv.buildExternalStorageAppDataDirs(packageName)); 13299 clearDirectory(conn.mContainerService, 13300 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13301 } 13302 } 13303 } finally { 13304 mContext.unbindService(conn); 13305 } 13306 } 13307 } 13308 13309 @Override 13310 public void clearApplicationUserData(final String packageName, 13311 final IPackageDataObserver observer, final int userId) { 13312 mContext.enforceCallingOrSelfPermission( 13313 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13314 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13315 // Queue up an async operation since the package deletion may take a little while. 13316 mHandler.post(new Runnable() { 13317 public void run() { 13318 mHandler.removeCallbacks(this); 13319 final boolean succeeded; 13320 synchronized (mInstallLock) { 13321 succeeded = clearApplicationUserDataLI(packageName, userId); 13322 } 13323 clearExternalStorageDataSync(packageName, userId, true); 13324 if (succeeded) { 13325 // invoke DeviceStorageMonitor's update method to clear any notifications 13326 DeviceStorageMonitorInternal 13327 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13328 if (dsm != null) { 13329 dsm.checkMemory(); 13330 } 13331 } 13332 if(observer != null) { 13333 try { 13334 observer.onRemoveCompleted(packageName, succeeded); 13335 } catch (RemoteException e) { 13336 Log.i(TAG, "Observer no longer exists."); 13337 } 13338 } //end if observer 13339 } //end run 13340 }); 13341 } 13342 13343 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13344 if (packageName == null) { 13345 Slog.w(TAG, "Attempt to delete null packageName."); 13346 return false; 13347 } 13348 13349 // Try finding details about the requested package 13350 PackageParser.Package pkg; 13351 synchronized (mPackages) { 13352 pkg = mPackages.get(packageName); 13353 if (pkg == null) { 13354 final PackageSetting ps = mSettings.mPackages.get(packageName); 13355 if (ps != null) { 13356 pkg = ps.pkg; 13357 } 13358 } 13359 13360 if (pkg == null) { 13361 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13362 return false; 13363 } 13364 13365 PackageSetting ps = (PackageSetting) pkg.mExtras; 13366 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13367 } 13368 13369 // Always delete data directories for package, even if we found no other 13370 // record of app. This helps users recover from UID mismatches without 13371 // resorting to a full data wipe. 13372 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13373 if (retCode < 0) { 13374 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13375 return false; 13376 } 13377 13378 final int appId = pkg.applicationInfo.uid; 13379 removeKeystoreDataIfNeeded(userId, appId); 13380 13381 // Create a native library symlink only if we have native libraries 13382 // and if the native libraries are 32 bit libraries. We do not provide 13383 // this symlink for 64 bit libraries. 13384 if (pkg.applicationInfo.primaryCpuAbi != null && 13385 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13386 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13387 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13388 nativeLibPath, userId) < 0) { 13389 Slog.w(TAG, "Failed linking native library dir"); 13390 return false; 13391 } 13392 } 13393 13394 return true; 13395 } 13396 13397 /** 13398 * Reverts user permission state changes (permissions and flags) in 13399 * all packages for a given user. 13400 * 13401 * @param userId The device user for which to do a reset. 13402 */ 13403 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13404 final int packageCount = mPackages.size(); 13405 for (int i = 0; i < packageCount; i++) { 13406 PackageParser.Package pkg = mPackages.valueAt(i); 13407 PackageSetting ps = (PackageSetting) pkg.mExtras; 13408 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13409 } 13410 } 13411 13412 /** 13413 * Reverts user permission state changes (permissions and flags). 13414 * 13415 * @param ps The package for which to reset. 13416 * @param userId The device user for which to do a reset. 13417 */ 13418 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13419 final PackageSetting ps, final int userId) { 13420 if (ps.pkg == null) { 13421 return; 13422 } 13423 13424 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13425 | FLAG_PERMISSION_USER_FIXED 13426 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13427 13428 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13429 | FLAG_PERMISSION_POLICY_FIXED; 13430 13431 boolean writeInstallPermissions = false; 13432 boolean writeRuntimePermissions = false; 13433 13434 final int permissionCount = ps.pkg.requestedPermissions.size(); 13435 for (int i = 0; i < permissionCount; i++) { 13436 String permission = ps.pkg.requestedPermissions.get(i); 13437 13438 BasePermission bp = mSettings.mPermissions.get(permission); 13439 if (bp == null) { 13440 continue; 13441 } 13442 13443 // If shared user we just reset the state to which only this app contributed. 13444 if (ps.sharedUser != null) { 13445 boolean used = false; 13446 final int packageCount = ps.sharedUser.packages.size(); 13447 for (int j = 0; j < packageCount; j++) { 13448 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13449 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13450 && pkg.pkg.requestedPermissions.contains(permission)) { 13451 used = true; 13452 break; 13453 } 13454 } 13455 if (used) { 13456 continue; 13457 } 13458 } 13459 13460 PermissionsState permissionsState = ps.getPermissionsState(); 13461 13462 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13463 13464 // Always clear the user settable flags. 13465 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13466 bp.name) != null; 13467 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13468 if (hasInstallState) { 13469 writeInstallPermissions = true; 13470 } else { 13471 writeRuntimePermissions = true; 13472 } 13473 } 13474 13475 // Below is only runtime permission handling. 13476 if (!bp.isRuntime()) { 13477 continue; 13478 } 13479 13480 // Never clobber system or policy. 13481 if ((oldFlags & policyOrSystemFlags) != 0) { 13482 continue; 13483 } 13484 13485 // If this permission was granted by default, make sure it is. 13486 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13487 if (permissionsState.grantRuntimePermission(bp, userId) 13488 != PERMISSION_OPERATION_FAILURE) { 13489 writeRuntimePermissions = true; 13490 } 13491 } else { 13492 // Otherwise, reset the permission. 13493 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13494 switch (revokeResult) { 13495 case PERMISSION_OPERATION_SUCCESS: { 13496 writeRuntimePermissions = true; 13497 } break; 13498 13499 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13500 writeRuntimePermissions = true; 13501 final int appId = ps.appId; 13502 mHandler.post(new Runnable() { 13503 @Override 13504 public void run() { 13505 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13506 } 13507 }); 13508 } break; 13509 } 13510 } 13511 } 13512 13513 // Synchronously write as we are taking permissions away. 13514 if (writeRuntimePermissions) { 13515 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13516 } 13517 13518 // Synchronously write as we are taking permissions away. 13519 if (writeInstallPermissions) { 13520 mSettings.writeLPr(); 13521 } 13522 } 13523 13524 /** 13525 * Remove entries from the keystore daemon. Will only remove it if the 13526 * {@code appId} is valid. 13527 */ 13528 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13529 if (appId < 0) { 13530 return; 13531 } 13532 13533 final KeyStore keyStore = KeyStore.getInstance(); 13534 if (keyStore != null) { 13535 if (userId == UserHandle.USER_ALL) { 13536 for (final int individual : sUserManager.getUserIds()) { 13537 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13538 } 13539 } else { 13540 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13541 } 13542 } else { 13543 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13544 } 13545 } 13546 13547 @Override 13548 public void deleteApplicationCacheFiles(final String packageName, 13549 final IPackageDataObserver observer) { 13550 mContext.enforceCallingOrSelfPermission( 13551 android.Manifest.permission.DELETE_CACHE_FILES, null); 13552 // Queue up an async operation since the package deletion may take a little while. 13553 final int userId = UserHandle.getCallingUserId(); 13554 mHandler.post(new Runnable() { 13555 public void run() { 13556 mHandler.removeCallbacks(this); 13557 final boolean succeded; 13558 synchronized (mInstallLock) { 13559 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13560 } 13561 clearExternalStorageDataSync(packageName, userId, false); 13562 if (observer != null) { 13563 try { 13564 observer.onRemoveCompleted(packageName, succeded); 13565 } catch (RemoteException e) { 13566 Log.i(TAG, "Observer no longer exists."); 13567 } 13568 } //end if observer 13569 } //end run 13570 }); 13571 } 13572 13573 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13574 if (packageName == null) { 13575 Slog.w(TAG, "Attempt to delete null packageName."); 13576 return false; 13577 } 13578 PackageParser.Package p; 13579 synchronized (mPackages) { 13580 p = mPackages.get(packageName); 13581 } 13582 if (p == null) { 13583 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13584 return false; 13585 } 13586 final ApplicationInfo applicationInfo = p.applicationInfo; 13587 if (applicationInfo == null) { 13588 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13589 return false; 13590 } 13591 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13592 if (retCode < 0) { 13593 Slog.w(TAG, "Couldn't remove cache files for package: " 13594 + packageName + " u" + userId); 13595 return false; 13596 } 13597 return true; 13598 } 13599 13600 @Override 13601 public void getPackageSizeInfo(final String packageName, int userHandle, 13602 final IPackageStatsObserver observer) { 13603 mContext.enforceCallingOrSelfPermission( 13604 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13605 if (packageName == null) { 13606 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13607 } 13608 13609 PackageStats stats = new PackageStats(packageName, userHandle); 13610 13611 /* 13612 * Queue up an async operation since the package measurement may take a 13613 * little while. 13614 */ 13615 Message msg = mHandler.obtainMessage(INIT_COPY); 13616 msg.obj = new MeasureParams(stats, observer); 13617 mHandler.sendMessage(msg); 13618 } 13619 13620 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13621 PackageStats pStats) { 13622 if (packageName == null) { 13623 Slog.w(TAG, "Attempt to get size of null packageName."); 13624 return false; 13625 } 13626 PackageParser.Package p; 13627 boolean dataOnly = false; 13628 String libDirRoot = null; 13629 String asecPath = null; 13630 PackageSetting ps = null; 13631 synchronized (mPackages) { 13632 p = mPackages.get(packageName); 13633 ps = mSettings.mPackages.get(packageName); 13634 if(p == null) { 13635 dataOnly = true; 13636 if((ps == null) || (ps.pkg == null)) { 13637 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13638 return false; 13639 } 13640 p = ps.pkg; 13641 } 13642 if (ps != null) { 13643 libDirRoot = ps.legacyNativeLibraryPathString; 13644 } 13645 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13646 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13647 if (secureContainerId != null) { 13648 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13649 } 13650 } 13651 } 13652 String publicSrcDir = null; 13653 if(!dataOnly) { 13654 final ApplicationInfo applicationInfo = p.applicationInfo; 13655 if (applicationInfo == null) { 13656 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13657 return false; 13658 } 13659 if (p.isForwardLocked()) { 13660 publicSrcDir = applicationInfo.getBaseResourcePath(); 13661 } 13662 } 13663 // TODO: extend to measure size of split APKs 13664 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13665 // not just the first level. 13666 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13667 // just the primary. 13668 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13669 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13670 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13671 if (res < 0) { 13672 return false; 13673 } 13674 13675 // Fix-up for forward-locked applications in ASEC containers. 13676 if (!isExternal(p)) { 13677 pStats.codeSize += pStats.externalCodeSize; 13678 pStats.externalCodeSize = 0L; 13679 } 13680 13681 return true; 13682 } 13683 13684 13685 @Override 13686 public void addPackageToPreferred(String packageName) { 13687 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13688 } 13689 13690 @Override 13691 public void removePackageFromPreferred(String packageName) { 13692 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13693 } 13694 13695 @Override 13696 public List<PackageInfo> getPreferredPackages(int flags) { 13697 return new ArrayList<PackageInfo>(); 13698 } 13699 13700 private int getUidTargetSdkVersionLockedLPr(int uid) { 13701 Object obj = mSettings.getUserIdLPr(uid); 13702 if (obj instanceof SharedUserSetting) { 13703 final SharedUserSetting sus = (SharedUserSetting) obj; 13704 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13705 final Iterator<PackageSetting> it = sus.packages.iterator(); 13706 while (it.hasNext()) { 13707 final PackageSetting ps = it.next(); 13708 if (ps.pkg != null) { 13709 int v = ps.pkg.applicationInfo.targetSdkVersion; 13710 if (v < vers) vers = v; 13711 } 13712 } 13713 return vers; 13714 } else if (obj instanceof PackageSetting) { 13715 final PackageSetting ps = (PackageSetting) obj; 13716 if (ps.pkg != null) { 13717 return ps.pkg.applicationInfo.targetSdkVersion; 13718 } 13719 } 13720 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13721 } 13722 13723 @Override 13724 public void addPreferredActivity(IntentFilter filter, int match, 13725 ComponentName[] set, ComponentName activity, int userId) { 13726 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13727 "Adding preferred"); 13728 } 13729 13730 private void addPreferredActivityInternal(IntentFilter filter, int match, 13731 ComponentName[] set, ComponentName activity, boolean always, int userId, 13732 String opname) { 13733 // writer 13734 int callingUid = Binder.getCallingUid(); 13735 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13736 if (filter.countActions() == 0) { 13737 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13738 return; 13739 } 13740 synchronized (mPackages) { 13741 if (mContext.checkCallingOrSelfPermission( 13742 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13743 != PackageManager.PERMISSION_GRANTED) { 13744 if (getUidTargetSdkVersionLockedLPr(callingUid) 13745 < Build.VERSION_CODES.FROYO) { 13746 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13747 + callingUid); 13748 return; 13749 } 13750 mContext.enforceCallingOrSelfPermission( 13751 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13752 } 13753 13754 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13755 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13756 + userId + ":"); 13757 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13758 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13759 scheduleWritePackageRestrictionsLocked(userId); 13760 } 13761 } 13762 13763 @Override 13764 public void replacePreferredActivity(IntentFilter filter, int match, 13765 ComponentName[] set, ComponentName activity, int userId) { 13766 if (filter.countActions() != 1) { 13767 throw new IllegalArgumentException( 13768 "replacePreferredActivity expects filter to have only 1 action."); 13769 } 13770 if (filter.countDataAuthorities() != 0 13771 || filter.countDataPaths() != 0 13772 || filter.countDataSchemes() > 1 13773 || filter.countDataTypes() != 0) { 13774 throw new IllegalArgumentException( 13775 "replacePreferredActivity expects filter to have no data authorities, " + 13776 "paths, or types; and at most one scheme."); 13777 } 13778 13779 final int callingUid = Binder.getCallingUid(); 13780 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13781 synchronized (mPackages) { 13782 if (mContext.checkCallingOrSelfPermission( 13783 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13784 != PackageManager.PERMISSION_GRANTED) { 13785 if (getUidTargetSdkVersionLockedLPr(callingUid) 13786 < Build.VERSION_CODES.FROYO) { 13787 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13788 + Binder.getCallingUid()); 13789 return; 13790 } 13791 mContext.enforceCallingOrSelfPermission( 13792 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13793 } 13794 13795 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13796 if (pir != null) { 13797 // Get all of the existing entries that exactly match this filter. 13798 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13799 if (existing != null && existing.size() == 1) { 13800 PreferredActivity cur = existing.get(0); 13801 if (DEBUG_PREFERRED) { 13802 Slog.i(TAG, "Checking replace of preferred:"); 13803 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13804 if (!cur.mPref.mAlways) { 13805 Slog.i(TAG, " -- CUR; not mAlways!"); 13806 } else { 13807 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13808 Slog.i(TAG, " -- CUR: mSet=" 13809 + Arrays.toString(cur.mPref.mSetComponents)); 13810 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13811 Slog.i(TAG, " -- NEW: mMatch=" 13812 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13813 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13814 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13815 } 13816 } 13817 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13818 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13819 && cur.mPref.sameSet(set)) { 13820 // Setting the preferred activity to what it happens to be already 13821 if (DEBUG_PREFERRED) { 13822 Slog.i(TAG, "Replacing with same preferred activity " 13823 + cur.mPref.mShortComponent + " for user " 13824 + userId + ":"); 13825 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13826 } 13827 return; 13828 } 13829 } 13830 13831 if (existing != null) { 13832 if (DEBUG_PREFERRED) { 13833 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13834 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13835 } 13836 for (int i = 0; i < existing.size(); i++) { 13837 PreferredActivity pa = existing.get(i); 13838 if (DEBUG_PREFERRED) { 13839 Slog.i(TAG, "Removing existing preferred activity " 13840 + pa.mPref.mComponent + ":"); 13841 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13842 } 13843 pir.removeFilter(pa); 13844 } 13845 } 13846 } 13847 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13848 "Replacing preferred"); 13849 } 13850 } 13851 13852 @Override 13853 public void clearPackagePreferredActivities(String packageName) { 13854 final int uid = Binder.getCallingUid(); 13855 // writer 13856 synchronized (mPackages) { 13857 PackageParser.Package pkg = mPackages.get(packageName); 13858 if (pkg == null || pkg.applicationInfo.uid != uid) { 13859 if (mContext.checkCallingOrSelfPermission( 13860 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13861 != PackageManager.PERMISSION_GRANTED) { 13862 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13863 < Build.VERSION_CODES.FROYO) { 13864 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13865 + Binder.getCallingUid()); 13866 return; 13867 } 13868 mContext.enforceCallingOrSelfPermission( 13869 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13870 } 13871 } 13872 13873 int user = UserHandle.getCallingUserId(); 13874 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13875 scheduleWritePackageRestrictionsLocked(user); 13876 } 13877 } 13878 } 13879 13880 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13881 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13882 ArrayList<PreferredActivity> removed = null; 13883 boolean changed = false; 13884 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13885 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13886 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13887 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13888 continue; 13889 } 13890 Iterator<PreferredActivity> it = pir.filterIterator(); 13891 while (it.hasNext()) { 13892 PreferredActivity pa = it.next(); 13893 // Mark entry for removal only if it matches the package name 13894 // and the entry is of type "always". 13895 if (packageName == null || 13896 (pa.mPref.mComponent.getPackageName().equals(packageName) 13897 && pa.mPref.mAlways)) { 13898 if (removed == null) { 13899 removed = new ArrayList<PreferredActivity>(); 13900 } 13901 removed.add(pa); 13902 } 13903 } 13904 if (removed != null) { 13905 for (int j=0; j<removed.size(); j++) { 13906 PreferredActivity pa = removed.get(j); 13907 pir.removeFilter(pa); 13908 } 13909 changed = true; 13910 } 13911 } 13912 return changed; 13913 } 13914 13915 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13916 private void clearIntentFilterVerificationsLPw(int userId) { 13917 final int packageCount = mPackages.size(); 13918 for (int i = 0; i < packageCount; i++) { 13919 PackageParser.Package pkg = mPackages.valueAt(i); 13920 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 13921 } 13922 } 13923 13924 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13925 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13926 if (userId == UserHandle.USER_ALL) { 13927 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13928 sUserManager.getUserIds())) { 13929 for (int oneUserId : sUserManager.getUserIds()) { 13930 scheduleWritePackageRestrictionsLocked(oneUserId); 13931 } 13932 } 13933 } else { 13934 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13935 scheduleWritePackageRestrictionsLocked(userId); 13936 } 13937 } 13938 } 13939 13940 void clearDefaultBrowserIfNeeded(String packageName) { 13941 for (int oneUserId : sUserManager.getUserIds()) { 13942 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13943 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13944 if (packageName.equals(defaultBrowserPackageName)) { 13945 setDefaultBrowserPackageName(null, oneUserId); 13946 } 13947 } 13948 } 13949 13950 @Override 13951 public void resetApplicationPreferences(int userId) { 13952 mContext.enforceCallingOrSelfPermission( 13953 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13954 // writer 13955 synchronized (mPackages) { 13956 final long identity = Binder.clearCallingIdentity(); 13957 try { 13958 clearPackagePreferredActivitiesLPw(null, userId); 13959 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13960 // TODO: We have to reset the default SMS and Phone. This requires 13961 // significant refactoring to keep all default apps in the package 13962 // manager (cleaner but more work) or have the services provide 13963 // callbacks to the package manager to request a default app reset. 13964 applyFactoryDefaultBrowserLPw(userId); 13965 clearIntentFilterVerificationsLPw(userId); 13966 primeDomainVerificationsLPw(userId); 13967 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 13968 scheduleWritePackageRestrictionsLocked(userId); 13969 } finally { 13970 Binder.restoreCallingIdentity(identity); 13971 } 13972 } 13973 } 13974 13975 @Override 13976 public int getPreferredActivities(List<IntentFilter> outFilters, 13977 List<ComponentName> outActivities, String packageName) { 13978 13979 int num = 0; 13980 final int userId = UserHandle.getCallingUserId(); 13981 // reader 13982 synchronized (mPackages) { 13983 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13984 if (pir != null) { 13985 final Iterator<PreferredActivity> it = pir.filterIterator(); 13986 while (it.hasNext()) { 13987 final PreferredActivity pa = it.next(); 13988 if (packageName == null 13989 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13990 && pa.mPref.mAlways)) { 13991 if (outFilters != null) { 13992 outFilters.add(new IntentFilter(pa)); 13993 } 13994 if (outActivities != null) { 13995 outActivities.add(pa.mPref.mComponent); 13996 } 13997 } 13998 } 13999 } 14000 } 14001 14002 return num; 14003 } 14004 14005 @Override 14006 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14007 int userId) { 14008 int callingUid = Binder.getCallingUid(); 14009 if (callingUid != Process.SYSTEM_UID) { 14010 throw new SecurityException( 14011 "addPersistentPreferredActivity can only be run by the system"); 14012 } 14013 if (filter.countActions() == 0) { 14014 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14015 return; 14016 } 14017 synchronized (mPackages) { 14018 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14019 " :"); 14020 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14021 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14022 new PersistentPreferredActivity(filter, activity)); 14023 scheduleWritePackageRestrictionsLocked(userId); 14024 } 14025 } 14026 14027 @Override 14028 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14029 int callingUid = Binder.getCallingUid(); 14030 if (callingUid != Process.SYSTEM_UID) { 14031 throw new SecurityException( 14032 "clearPackagePersistentPreferredActivities can only be run by the system"); 14033 } 14034 ArrayList<PersistentPreferredActivity> removed = null; 14035 boolean changed = false; 14036 synchronized (mPackages) { 14037 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14038 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14039 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14040 .valueAt(i); 14041 if (userId != thisUserId) { 14042 continue; 14043 } 14044 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14045 while (it.hasNext()) { 14046 PersistentPreferredActivity ppa = it.next(); 14047 // Mark entry for removal only if it matches the package name. 14048 if (ppa.mComponent.getPackageName().equals(packageName)) { 14049 if (removed == null) { 14050 removed = new ArrayList<PersistentPreferredActivity>(); 14051 } 14052 removed.add(ppa); 14053 } 14054 } 14055 if (removed != null) { 14056 for (int j=0; j<removed.size(); j++) { 14057 PersistentPreferredActivity ppa = removed.get(j); 14058 ppir.removeFilter(ppa); 14059 } 14060 changed = true; 14061 } 14062 } 14063 14064 if (changed) { 14065 scheduleWritePackageRestrictionsLocked(userId); 14066 } 14067 } 14068 } 14069 14070 /** 14071 * Common machinery for picking apart a restored XML blob and passing 14072 * it to a caller-supplied functor to be applied to the running system. 14073 */ 14074 private void restoreFromXml(XmlPullParser parser, int userId, 14075 String expectedStartTag, BlobXmlRestorer functor) 14076 throws IOException, XmlPullParserException { 14077 int type; 14078 while ((type = parser.next()) != XmlPullParser.START_TAG 14079 && type != XmlPullParser.END_DOCUMENT) { 14080 } 14081 if (type != XmlPullParser.START_TAG) { 14082 // oops didn't find a start tag?! 14083 if (DEBUG_BACKUP) { 14084 Slog.e(TAG, "Didn't find start tag during restore"); 14085 } 14086 return; 14087 } 14088 14089 // this is supposed to be TAG_PREFERRED_BACKUP 14090 if (!expectedStartTag.equals(parser.getName())) { 14091 if (DEBUG_BACKUP) { 14092 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14093 } 14094 return; 14095 } 14096 14097 // skip interfering stuff, then we're aligned with the backing implementation 14098 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14099 functor.apply(parser, userId); 14100 } 14101 14102 private interface BlobXmlRestorer { 14103 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14104 } 14105 14106 /** 14107 * Non-Binder method, support for the backup/restore mechanism: write the 14108 * full set of preferred activities in its canonical XML format. Returns the 14109 * XML output as a byte array, or null if there is none. 14110 */ 14111 @Override 14112 public byte[] getPreferredActivityBackup(int userId) { 14113 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14114 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14115 } 14116 14117 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14118 try { 14119 final XmlSerializer serializer = new FastXmlSerializer(); 14120 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14121 serializer.startDocument(null, true); 14122 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14123 14124 synchronized (mPackages) { 14125 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14126 } 14127 14128 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14129 serializer.endDocument(); 14130 serializer.flush(); 14131 } catch (Exception e) { 14132 if (DEBUG_BACKUP) { 14133 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14134 } 14135 return null; 14136 } 14137 14138 return dataStream.toByteArray(); 14139 } 14140 14141 @Override 14142 public void restorePreferredActivities(byte[] backup, int userId) { 14143 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14144 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14145 } 14146 14147 try { 14148 final XmlPullParser parser = Xml.newPullParser(); 14149 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14150 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14151 new BlobXmlRestorer() { 14152 @Override 14153 public void apply(XmlPullParser parser, int userId) 14154 throws XmlPullParserException, IOException { 14155 synchronized (mPackages) { 14156 mSettings.readPreferredActivitiesLPw(parser, userId); 14157 } 14158 } 14159 } ); 14160 } catch (Exception e) { 14161 if (DEBUG_BACKUP) { 14162 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14163 } 14164 } 14165 } 14166 14167 /** 14168 * Non-Binder method, support for the backup/restore mechanism: write the 14169 * default browser (etc) settings in its canonical XML format. Returns the default 14170 * browser XML representation as a byte array, or null if there is none. 14171 */ 14172 @Override 14173 public byte[] getDefaultAppsBackup(int userId) { 14174 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14175 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14176 } 14177 14178 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14179 try { 14180 final XmlSerializer serializer = new FastXmlSerializer(); 14181 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14182 serializer.startDocument(null, true); 14183 serializer.startTag(null, TAG_DEFAULT_APPS); 14184 14185 synchronized (mPackages) { 14186 mSettings.writeDefaultAppsLPr(serializer, userId); 14187 } 14188 14189 serializer.endTag(null, TAG_DEFAULT_APPS); 14190 serializer.endDocument(); 14191 serializer.flush(); 14192 } catch (Exception e) { 14193 if (DEBUG_BACKUP) { 14194 Slog.e(TAG, "Unable to write default apps for backup", e); 14195 } 14196 return null; 14197 } 14198 14199 return dataStream.toByteArray(); 14200 } 14201 14202 @Override 14203 public void restoreDefaultApps(byte[] backup, int userId) { 14204 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14205 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14206 } 14207 14208 try { 14209 final XmlPullParser parser = Xml.newPullParser(); 14210 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14211 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14212 new BlobXmlRestorer() { 14213 @Override 14214 public void apply(XmlPullParser parser, int userId) 14215 throws XmlPullParserException, IOException { 14216 synchronized (mPackages) { 14217 mSettings.readDefaultAppsLPw(parser, userId); 14218 } 14219 } 14220 } ); 14221 } catch (Exception e) { 14222 if (DEBUG_BACKUP) { 14223 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14224 } 14225 } 14226 } 14227 14228 @Override 14229 public byte[] getIntentFilterVerificationBackup(int userId) { 14230 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14231 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14232 } 14233 14234 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14235 try { 14236 final XmlSerializer serializer = new FastXmlSerializer(); 14237 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14238 serializer.startDocument(null, true); 14239 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14240 14241 synchronized (mPackages) { 14242 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14243 } 14244 14245 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14246 serializer.endDocument(); 14247 serializer.flush(); 14248 } catch (Exception e) { 14249 if (DEBUG_BACKUP) { 14250 Slog.e(TAG, "Unable to write default apps for backup", e); 14251 } 14252 return null; 14253 } 14254 14255 return dataStream.toByteArray(); 14256 } 14257 14258 @Override 14259 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14260 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14261 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14262 } 14263 14264 try { 14265 final XmlPullParser parser = Xml.newPullParser(); 14266 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14267 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14268 new BlobXmlRestorer() { 14269 @Override 14270 public void apply(XmlPullParser parser, int userId) 14271 throws XmlPullParserException, IOException { 14272 synchronized (mPackages) { 14273 mSettings.readAllDomainVerificationsLPr(parser, userId); 14274 mSettings.writeLPr(); 14275 } 14276 } 14277 } ); 14278 } catch (Exception e) { 14279 if (DEBUG_BACKUP) { 14280 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14281 } 14282 } 14283 } 14284 14285 @Override 14286 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14287 int sourceUserId, int targetUserId, int flags) { 14288 mContext.enforceCallingOrSelfPermission( 14289 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14290 int callingUid = Binder.getCallingUid(); 14291 enforceOwnerRights(ownerPackage, callingUid); 14292 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14293 if (intentFilter.countActions() == 0) { 14294 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14295 return; 14296 } 14297 synchronized (mPackages) { 14298 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14299 ownerPackage, targetUserId, flags); 14300 CrossProfileIntentResolver resolver = 14301 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14302 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14303 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14304 if (existing != null) { 14305 int size = existing.size(); 14306 for (int i = 0; i < size; i++) { 14307 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14308 return; 14309 } 14310 } 14311 } 14312 resolver.addFilter(newFilter); 14313 scheduleWritePackageRestrictionsLocked(sourceUserId); 14314 } 14315 } 14316 14317 @Override 14318 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14319 mContext.enforceCallingOrSelfPermission( 14320 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14321 int callingUid = Binder.getCallingUid(); 14322 enforceOwnerRights(ownerPackage, callingUid); 14323 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14324 synchronized (mPackages) { 14325 CrossProfileIntentResolver resolver = 14326 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14327 ArraySet<CrossProfileIntentFilter> set = 14328 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14329 for (CrossProfileIntentFilter filter : set) { 14330 if (filter.getOwnerPackage().equals(ownerPackage)) { 14331 resolver.removeFilter(filter); 14332 } 14333 } 14334 scheduleWritePackageRestrictionsLocked(sourceUserId); 14335 } 14336 } 14337 14338 // Enforcing that callingUid is owning pkg on userId 14339 private void enforceOwnerRights(String pkg, int callingUid) { 14340 // The system owns everything. 14341 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14342 return; 14343 } 14344 int callingUserId = UserHandle.getUserId(callingUid); 14345 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14346 if (pi == null) { 14347 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14348 + callingUserId); 14349 } 14350 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14351 throw new SecurityException("Calling uid " + callingUid 14352 + " does not own package " + pkg); 14353 } 14354 } 14355 14356 @Override 14357 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14358 Intent intent = new Intent(Intent.ACTION_MAIN); 14359 intent.addCategory(Intent.CATEGORY_HOME); 14360 14361 final int callingUserId = UserHandle.getCallingUserId(); 14362 List<ResolveInfo> list = queryIntentActivities(intent, null, 14363 PackageManager.GET_META_DATA, callingUserId); 14364 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14365 true, false, false, callingUserId); 14366 14367 allHomeCandidates.clear(); 14368 if (list != null) { 14369 for (ResolveInfo ri : list) { 14370 allHomeCandidates.add(ri); 14371 } 14372 } 14373 return (preferred == null || preferred.activityInfo == null) 14374 ? null 14375 : new ComponentName(preferred.activityInfo.packageName, 14376 preferred.activityInfo.name); 14377 } 14378 14379 @Override 14380 public void setApplicationEnabledSetting(String appPackageName, 14381 int newState, int flags, int userId, String callingPackage) { 14382 if (!sUserManager.exists(userId)) return; 14383 if (callingPackage == null) { 14384 callingPackage = Integer.toString(Binder.getCallingUid()); 14385 } 14386 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14387 } 14388 14389 @Override 14390 public void setComponentEnabledSetting(ComponentName componentName, 14391 int newState, int flags, int userId) { 14392 if (!sUserManager.exists(userId)) return; 14393 setEnabledSetting(componentName.getPackageName(), 14394 componentName.getClassName(), newState, flags, userId, null); 14395 } 14396 14397 private void setEnabledSetting(final String packageName, String className, int newState, 14398 final int flags, int userId, String callingPackage) { 14399 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14400 || newState == COMPONENT_ENABLED_STATE_ENABLED 14401 || newState == COMPONENT_ENABLED_STATE_DISABLED 14402 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14403 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14404 throw new IllegalArgumentException("Invalid new component state: " 14405 + newState); 14406 } 14407 PackageSetting pkgSetting; 14408 final int uid = Binder.getCallingUid(); 14409 final int permission = mContext.checkCallingOrSelfPermission( 14410 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14411 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14412 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14413 boolean sendNow = false; 14414 boolean isApp = (className == null); 14415 String componentName = isApp ? packageName : className; 14416 int packageUid = -1; 14417 ArrayList<String> components; 14418 14419 // writer 14420 synchronized (mPackages) { 14421 pkgSetting = mSettings.mPackages.get(packageName); 14422 if (pkgSetting == null) { 14423 if (className == null) { 14424 throw new IllegalArgumentException( 14425 "Unknown package: " + packageName); 14426 } 14427 throw new IllegalArgumentException( 14428 "Unknown component: " + packageName 14429 + "/" + className); 14430 } 14431 // Allow root and verify that userId is not being specified by a different user 14432 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14433 throw new SecurityException( 14434 "Permission Denial: attempt to change component state from pid=" 14435 + Binder.getCallingPid() 14436 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14437 } 14438 if (className == null) { 14439 // We're dealing with an application/package level state change 14440 if (pkgSetting.getEnabled(userId) == newState) { 14441 // Nothing to do 14442 return; 14443 } 14444 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14445 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14446 // Don't care about who enables an app. 14447 callingPackage = null; 14448 } 14449 pkgSetting.setEnabled(newState, userId, callingPackage); 14450 // pkgSetting.pkg.mSetEnabled = newState; 14451 } else { 14452 // We're dealing with a component level state change 14453 // First, verify that this is a valid class name. 14454 PackageParser.Package pkg = pkgSetting.pkg; 14455 if (pkg == null || !pkg.hasComponentClassName(className)) { 14456 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14457 throw new IllegalArgumentException("Component class " + className 14458 + " does not exist in " + packageName); 14459 } else { 14460 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14461 + className + " does not exist in " + packageName); 14462 } 14463 } 14464 switch (newState) { 14465 case COMPONENT_ENABLED_STATE_ENABLED: 14466 if (!pkgSetting.enableComponentLPw(className, userId)) { 14467 return; 14468 } 14469 break; 14470 case COMPONENT_ENABLED_STATE_DISABLED: 14471 if (!pkgSetting.disableComponentLPw(className, userId)) { 14472 return; 14473 } 14474 break; 14475 case COMPONENT_ENABLED_STATE_DEFAULT: 14476 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14477 return; 14478 } 14479 break; 14480 default: 14481 Slog.e(TAG, "Invalid new component state: " + newState); 14482 return; 14483 } 14484 } 14485 scheduleWritePackageRestrictionsLocked(userId); 14486 components = mPendingBroadcasts.get(userId, packageName); 14487 final boolean newPackage = components == null; 14488 if (newPackage) { 14489 components = new ArrayList<String>(); 14490 } 14491 if (!components.contains(componentName)) { 14492 components.add(componentName); 14493 } 14494 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14495 sendNow = true; 14496 // Purge entry from pending broadcast list if another one exists already 14497 // since we are sending one right away. 14498 mPendingBroadcasts.remove(userId, packageName); 14499 } else { 14500 if (newPackage) { 14501 mPendingBroadcasts.put(userId, packageName, components); 14502 } 14503 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14504 // Schedule a message 14505 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14506 } 14507 } 14508 } 14509 14510 long callingId = Binder.clearCallingIdentity(); 14511 try { 14512 if (sendNow) { 14513 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14514 sendPackageChangedBroadcast(packageName, 14515 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14516 } 14517 } finally { 14518 Binder.restoreCallingIdentity(callingId); 14519 } 14520 } 14521 14522 private void sendPackageChangedBroadcast(String packageName, 14523 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14524 if (DEBUG_INSTALL) 14525 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14526 + componentNames); 14527 Bundle extras = new Bundle(4); 14528 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14529 String nameList[] = new String[componentNames.size()]; 14530 componentNames.toArray(nameList); 14531 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14532 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14533 extras.putInt(Intent.EXTRA_UID, packageUid); 14534 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14535 new int[] {UserHandle.getUserId(packageUid)}); 14536 } 14537 14538 @Override 14539 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14540 if (!sUserManager.exists(userId)) return; 14541 final int uid = Binder.getCallingUid(); 14542 final int permission = mContext.checkCallingOrSelfPermission( 14543 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14544 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14545 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14546 // writer 14547 synchronized (mPackages) { 14548 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14549 allowedByPermission, uid, userId)) { 14550 scheduleWritePackageRestrictionsLocked(userId); 14551 } 14552 } 14553 } 14554 14555 @Override 14556 public String getInstallerPackageName(String packageName) { 14557 // reader 14558 synchronized (mPackages) { 14559 return mSettings.getInstallerPackageNameLPr(packageName); 14560 } 14561 } 14562 14563 @Override 14564 public int getApplicationEnabledSetting(String packageName, int userId) { 14565 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14566 int uid = Binder.getCallingUid(); 14567 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14568 // reader 14569 synchronized (mPackages) { 14570 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14571 } 14572 } 14573 14574 @Override 14575 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14576 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14577 int uid = Binder.getCallingUid(); 14578 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14579 // reader 14580 synchronized (mPackages) { 14581 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14582 } 14583 } 14584 14585 @Override 14586 public void enterSafeMode() { 14587 enforceSystemOrRoot("Only the system can request entering safe mode"); 14588 14589 if (!mSystemReady) { 14590 mSafeMode = true; 14591 } 14592 } 14593 14594 @Override 14595 public void systemReady() { 14596 mSystemReady = true; 14597 14598 // Read the compatibilty setting when the system is ready. 14599 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14600 mContext.getContentResolver(), 14601 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14602 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14603 if (DEBUG_SETTINGS) { 14604 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14605 } 14606 14607 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14608 14609 synchronized (mPackages) { 14610 // Verify that all of the preferred activity components actually 14611 // exist. It is possible for applications to be updated and at 14612 // that point remove a previously declared activity component that 14613 // had been set as a preferred activity. We try to clean this up 14614 // the next time we encounter that preferred activity, but it is 14615 // possible for the user flow to never be able to return to that 14616 // situation so here we do a sanity check to make sure we haven't 14617 // left any junk around. 14618 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14619 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14620 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14621 removed.clear(); 14622 for (PreferredActivity pa : pir.filterSet()) { 14623 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14624 removed.add(pa); 14625 } 14626 } 14627 if (removed.size() > 0) { 14628 for (int r=0; r<removed.size(); r++) { 14629 PreferredActivity pa = removed.get(r); 14630 Slog.w(TAG, "Removing dangling preferred activity: " 14631 + pa.mPref.mComponent); 14632 pir.removeFilter(pa); 14633 } 14634 mSettings.writePackageRestrictionsLPr( 14635 mSettings.mPreferredActivities.keyAt(i)); 14636 } 14637 } 14638 14639 for (int userId : UserManagerService.getInstance().getUserIds()) { 14640 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14641 grantPermissionsUserIds = ArrayUtils.appendInt( 14642 grantPermissionsUserIds, userId); 14643 } 14644 } 14645 } 14646 sUserManager.systemReady(); 14647 14648 // If we upgraded grant all default permissions before kicking off. 14649 for (int userId : grantPermissionsUserIds) { 14650 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14651 } 14652 14653 // Kick off any messages waiting for system ready 14654 if (mPostSystemReadyMessages != null) { 14655 for (Message msg : mPostSystemReadyMessages) { 14656 msg.sendToTarget(); 14657 } 14658 mPostSystemReadyMessages = null; 14659 } 14660 14661 // Watch for external volumes that come and go over time 14662 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14663 storage.registerListener(mStorageListener); 14664 14665 mInstallerService.systemReady(); 14666 mPackageDexOptimizer.systemReady(); 14667 14668 MountServiceInternal mountServiceInternal = LocalServices.getService( 14669 MountServiceInternal.class); 14670 mountServiceInternal.addExternalStoragePolicy( 14671 new MountServiceInternal.ExternalStorageMountPolicy() { 14672 @Override 14673 public int getMountMode(int uid, String packageName) { 14674 if (Process.isIsolated(uid)) { 14675 return Zygote.MOUNT_EXTERNAL_NONE; 14676 } 14677 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14678 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14679 } 14680 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14681 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14682 } 14683 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14684 return Zygote.MOUNT_EXTERNAL_READ; 14685 } 14686 return Zygote.MOUNT_EXTERNAL_WRITE; 14687 } 14688 14689 @Override 14690 public boolean hasExternalStorage(int uid, String packageName) { 14691 return true; 14692 } 14693 }); 14694 } 14695 14696 @Override 14697 public boolean isSafeMode() { 14698 return mSafeMode; 14699 } 14700 14701 @Override 14702 public boolean hasSystemUidErrors() { 14703 return mHasSystemUidErrors; 14704 } 14705 14706 static String arrayToString(int[] array) { 14707 StringBuffer buf = new StringBuffer(128); 14708 buf.append('['); 14709 if (array != null) { 14710 for (int i=0; i<array.length; i++) { 14711 if (i > 0) buf.append(", "); 14712 buf.append(array[i]); 14713 } 14714 } 14715 buf.append(']'); 14716 return buf.toString(); 14717 } 14718 14719 static class DumpState { 14720 public static final int DUMP_LIBS = 1 << 0; 14721 public static final int DUMP_FEATURES = 1 << 1; 14722 public static final int DUMP_RESOLVERS = 1 << 2; 14723 public static final int DUMP_PERMISSIONS = 1 << 3; 14724 public static final int DUMP_PACKAGES = 1 << 4; 14725 public static final int DUMP_SHARED_USERS = 1 << 5; 14726 public static final int DUMP_MESSAGES = 1 << 6; 14727 public static final int DUMP_PROVIDERS = 1 << 7; 14728 public static final int DUMP_VERIFIERS = 1 << 8; 14729 public static final int DUMP_PREFERRED = 1 << 9; 14730 public static final int DUMP_PREFERRED_XML = 1 << 10; 14731 public static final int DUMP_KEYSETS = 1 << 11; 14732 public static final int DUMP_VERSION = 1 << 12; 14733 public static final int DUMP_INSTALLS = 1 << 13; 14734 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14735 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14736 14737 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14738 14739 private int mTypes; 14740 14741 private int mOptions; 14742 14743 private boolean mTitlePrinted; 14744 14745 private SharedUserSetting mSharedUser; 14746 14747 public boolean isDumping(int type) { 14748 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14749 return true; 14750 } 14751 14752 return (mTypes & type) != 0; 14753 } 14754 14755 public void setDump(int type) { 14756 mTypes |= type; 14757 } 14758 14759 public boolean isOptionEnabled(int option) { 14760 return (mOptions & option) != 0; 14761 } 14762 14763 public void setOptionEnabled(int option) { 14764 mOptions |= option; 14765 } 14766 14767 public boolean onTitlePrinted() { 14768 final boolean printed = mTitlePrinted; 14769 mTitlePrinted = true; 14770 return printed; 14771 } 14772 14773 public boolean getTitlePrinted() { 14774 return mTitlePrinted; 14775 } 14776 14777 public void setTitlePrinted(boolean enabled) { 14778 mTitlePrinted = enabled; 14779 } 14780 14781 public SharedUserSetting getSharedUser() { 14782 return mSharedUser; 14783 } 14784 14785 public void setSharedUser(SharedUserSetting user) { 14786 mSharedUser = user; 14787 } 14788 } 14789 14790 @Override 14791 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14792 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14793 != PackageManager.PERMISSION_GRANTED) { 14794 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14795 + Binder.getCallingPid() 14796 + ", uid=" + Binder.getCallingUid() 14797 + " without permission " 14798 + android.Manifest.permission.DUMP); 14799 return; 14800 } 14801 14802 DumpState dumpState = new DumpState(); 14803 boolean fullPreferred = false; 14804 boolean checkin = false; 14805 14806 String packageName = null; 14807 ArraySet<String> permissionNames = null; 14808 14809 int opti = 0; 14810 while (opti < args.length) { 14811 String opt = args[opti]; 14812 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14813 break; 14814 } 14815 opti++; 14816 14817 if ("-a".equals(opt)) { 14818 // Right now we only know how to print all. 14819 } else if ("-h".equals(opt)) { 14820 pw.println("Package manager dump options:"); 14821 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14822 pw.println(" --checkin: dump for a checkin"); 14823 pw.println(" -f: print details of intent filters"); 14824 pw.println(" -h: print this help"); 14825 pw.println(" cmd may be one of:"); 14826 pw.println(" l[ibraries]: list known shared libraries"); 14827 pw.println(" f[ibraries]: list device features"); 14828 pw.println(" k[eysets]: print known keysets"); 14829 pw.println(" r[esolvers]: dump intent resolvers"); 14830 pw.println(" perm[issions]: dump permissions"); 14831 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14832 pw.println(" pref[erred]: print preferred package settings"); 14833 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14834 pw.println(" prov[iders]: dump content providers"); 14835 pw.println(" p[ackages]: dump installed packages"); 14836 pw.println(" s[hared-users]: dump shared user IDs"); 14837 pw.println(" m[essages]: print collected runtime messages"); 14838 pw.println(" v[erifiers]: print package verifier info"); 14839 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14840 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14841 pw.println(" version: print database version info"); 14842 pw.println(" write: write current settings now"); 14843 pw.println(" installs: details about install sessions"); 14844 pw.println(" <package.name>: info about given package"); 14845 return; 14846 } else if ("--checkin".equals(opt)) { 14847 checkin = true; 14848 } else if ("-f".equals(opt)) { 14849 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14850 } else { 14851 pw.println("Unknown argument: " + opt + "; use -h for help"); 14852 } 14853 } 14854 14855 // Is the caller requesting to dump a particular piece of data? 14856 if (opti < args.length) { 14857 String cmd = args[opti]; 14858 opti++; 14859 // Is this a package name? 14860 if ("android".equals(cmd) || cmd.contains(".")) { 14861 packageName = cmd; 14862 // When dumping a single package, we always dump all of its 14863 // filter information since the amount of data will be reasonable. 14864 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14865 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14866 dumpState.setDump(DumpState.DUMP_LIBS); 14867 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14868 dumpState.setDump(DumpState.DUMP_FEATURES); 14869 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14870 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14871 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14872 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14873 } else if ("permission".equals(cmd)) { 14874 if (opti >= args.length) { 14875 pw.println("Error: permission requires permission name"); 14876 return; 14877 } 14878 permissionNames = new ArraySet<>(); 14879 while (opti < args.length) { 14880 permissionNames.add(args[opti]); 14881 opti++; 14882 } 14883 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14884 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14885 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14886 dumpState.setDump(DumpState.DUMP_PREFERRED); 14887 } else if ("preferred-xml".equals(cmd)) { 14888 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14889 if (opti < args.length && "--full".equals(args[opti])) { 14890 fullPreferred = true; 14891 opti++; 14892 } 14893 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14894 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14895 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14896 dumpState.setDump(DumpState.DUMP_PACKAGES); 14897 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14898 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14899 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14900 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14901 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14902 dumpState.setDump(DumpState.DUMP_MESSAGES); 14903 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14904 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14905 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14906 || "intent-filter-verifiers".equals(cmd)) { 14907 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14908 } else if ("version".equals(cmd)) { 14909 dumpState.setDump(DumpState.DUMP_VERSION); 14910 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14911 dumpState.setDump(DumpState.DUMP_KEYSETS); 14912 } else if ("installs".equals(cmd)) { 14913 dumpState.setDump(DumpState.DUMP_INSTALLS); 14914 } else if ("write".equals(cmd)) { 14915 synchronized (mPackages) { 14916 mSettings.writeLPr(); 14917 pw.println("Settings written."); 14918 return; 14919 } 14920 } 14921 } 14922 14923 if (checkin) { 14924 pw.println("vers,1"); 14925 } 14926 14927 // reader 14928 synchronized (mPackages) { 14929 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14930 if (!checkin) { 14931 if (dumpState.onTitlePrinted()) 14932 pw.println(); 14933 pw.println("Database versions:"); 14934 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 14935 } 14936 } 14937 14938 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14939 if (!checkin) { 14940 if (dumpState.onTitlePrinted()) 14941 pw.println(); 14942 pw.println("Verifiers:"); 14943 pw.print(" Required: "); 14944 pw.print(mRequiredVerifierPackage); 14945 pw.print(" (uid="); 14946 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14947 pw.println(")"); 14948 } else if (mRequiredVerifierPackage != null) { 14949 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14950 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14951 } 14952 } 14953 14954 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14955 packageName == null) { 14956 if (mIntentFilterVerifierComponent != null) { 14957 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14958 if (!checkin) { 14959 if (dumpState.onTitlePrinted()) 14960 pw.println(); 14961 pw.println("Intent Filter Verifier:"); 14962 pw.print(" Using: "); 14963 pw.print(verifierPackageName); 14964 pw.print(" (uid="); 14965 pw.print(getPackageUid(verifierPackageName, 0)); 14966 pw.println(")"); 14967 } else if (verifierPackageName != null) { 14968 pw.print("ifv,"); pw.print(verifierPackageName); 14969 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14970 } 14971 } else { 14972 pw.println(); 14973 pw.println("No Intent Filter Verifier available!"); 14974 } 14975 } 14976 14977 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14978 boolean printedHeader = false; 14979 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14980 while (it.hasNext()) { 14981 String name = it.next(); 14982 SharedLibraryEntry ent = mSharedLibraries.get(name); 14983 if (!checkin) { 14984 if (!printedHeader) { 14985 if (dumpState.onTitlePrinted()) 14986 pw.println(); 14987 pw.println("Libraries:"); 14988 printedHeader = true; 14989 } 14990 pw.print(" "); 14991 } else { 14992 pw.print("lib,"); 14993 } 14994 pw.print(name); 14995 if (!checkin) { 14996 pw.print(" -> "); 14997 } 14998 if (ent.path != null) { 14999 if (!checkin) { 15000 pw.print("(jar) "); 15001 pw.print(ent.path); 15002 } else { 15003 pw.print(",jar,"); 15004 pw.print(ent.path); 15005 } 15006 } else { 15007 if (!checkin) { 15008 pw.print("(apk) "); 15009 pw.print(ent.apk); 15010 } else { 15011 pw.print(",apk,"); 15012 pw.print(ent.apk); 15013 } 15014 } 15015 pw.println(); 15016 } 15017 } 15018 15019 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15020 if (dumpState.onTitlePrinted()) 15021 pw.println(); 15022 if (!checkin) { 15023 pw.println("Features:"); 15024 } 15025 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15026 while (it.hasNext()) { 15027 String name = it.next(); 15028 if (!checkin) { 15029 pw.print(" "); 15030 } else { 15031 pw.print("feat,"); 15032 } 15033 pw.println(name); 15034 } 15035 } 15036 15037 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15038 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15039 : "Activity Resolver Table:", " ", packageName, 15040 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15041 dumpState.setTitlePrinted(true); 15042 } 15043 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15044 : "Receiver Resolver Table:", " ", packageName, 15045 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15046 dumpState.setTitlePrinted(true); 15047 } 15048 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15049 : "Service Resolver Table:", " ", packageName, 15050 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15051 dumpState.setTitlePrinted(true); 15052 } 15053 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15054 : "Provider Resolver Table:", " ", packageName, 15055 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15056 dumpState.setTitlePrinted(true); 15057 } 15058 } 15059 15060 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15061 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15062 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15063 int user = mSettings.mPreferredActivities.keyAt(i); 15064 if (pir.dump(pw, 15065 dumpState.getTitlePrinted() 15066 ? "\nPreferred Activities User " + user + ":" 15067 : "Preferred Activities User " + user + ":", " ", 15068 packageName, true, false)) { 15069 dumpState.setTitlePrinted(true); 15070 } 15071 } 15072 } 15073 15074 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15075 pw.flush(); 15076 FileOutputStream fout = new FileOutputStream(fd); 15077 BufferedOutputStream str = new BufferedOutputStream(fout); 15078 XmlSerializer serializer = new FastXmlSerializer(); 15079 try { 15080 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15081 serializer.startDocument(null, true); 15082 serializer.setFeature( 15083 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15084 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15085 serializer.endDocument(); 15086 serializer.flush(); 15087 } catch (IllegalArgumentException e) { 15088 pw.println("Failed writing: " + e); 15089 } catch (IllegalStateException e) { 15090 pw.println("Failed writing: " + e); 15091 } catch (IOException e) { 15092 pw.println("Failed writing: " + e); 15093 } 15094 } 15095 15096 if (!checkin 15097 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15098 && packageName == null) { 15099 pw.println(); 15100 int count = mSettings.mPackages.size(); 15101 if (count == 0) { 15102 pw.println("No applications!"); 15103 pw.println(); 15104 } else { 15105 final String prefix = " "; 15106 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15107 if (allPackageSettings.size() == 0) { 15108 pw.println("No domain preferred apps!"); 15109 pw.println(); 15110 } else { 15111 pw.println("App verification status:"); 15112 pw.println(); 15113 count = 0; 15114 for (PackageSetting ps : allPackageSettings) { 15115 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15116 if (ivi == null || ivi.getPackageName() == null) continue; 15117 pw.println(prefix + "Package: " + ivi.getPackageName()); 15118 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15119 pw.println(prefix + "Status: " + ivi.getStatusString()); 15120 pw.println(); 15121 count++; 15122 } 15123 if (count == 0) { 15124 pw.println(prefix + "No app verification established."); 15125 pw.println(); 15126 } 15127 for (int userId : sUserManager.getUserIds()) { 15128 pw.println("App linkages for user " + userId + ":"); 15129 pw.println(); 15130 count = 0; 15131 for (PackageSetting ps : allPackageSettings) { 15132 final long status = ps.getDomainVerificationStatusForUser(userId); 15133 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15134 continue; 15135 } 15136 pw.println(prefix + "Package: " + ps.name); 15137 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15138 String statusStr = IntentFilterVerificationInfo. 15139 getStatusStringFromValue(status); 15140 pw.println(prefix + "Status: " + statusStr); 15141 pw.println(); 15142 count++; 15143 } 15144 if (count == 0) { 15145 pw.println(prefix + "No configured app linkages."); 15146 pw.println(); 15147 } 15148 } 15149 } 15150 } 15151 } 15152 15153 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15154 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15155 if (packageName == null && permissionNames == null) { 15156 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15157 if (iperm == 0) { 15158 if (dumpState.onTitlePrinted()) 15159 pw.println(); 15160 pw.println("AppOp Permissions:"); 15161 } 15162 pw.print(" AppOp Permission "); 15163 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15164 pw.println(":"); 15165 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15166 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15167 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15168 } 15169 } 15170 } 15171 } 15172 15173 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15174 boolean printedSomething = false; 15175 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15176 if (packageName != null && !packageName.equals(p.info.packageName)) { 15177 continue; 15178 } 15179 if (!printedSomething) { 15180 if (dumpState.onTitlePrinted()) 15181 pw.println(); 15182 pw.println("Registered ContentProviders:"); 15183 printedSomething = true; 15184 } 15185 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15186 pw.print(" "); pw.println(p.toString()); 15187 } 15188 printedSomething = false; 15189 for (Map.Entry<String, PackageParser.Provider> entry : 15190 mProvidersByAuthority.entrySet()) { 15191 PackageParser.Provider p = entry.getValue(); 15192 if (packageName != null && !packageName.equals(p.info.packageName)) { 15193 continue; 15194 } 15195 if (!printedSomething) { 15196 if (dumpState.onTitlePrinted()) 15197 pw.println(); 15198 pw.println("ContentProvider Authorities:"); 15199 printedSomething = true; 15200 } 15201 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15202 pw.print(" "); pw.println(p.toString()); 15203 if (p.info != null && p.info.applicationInfo != null) { 15204 final String appInfo = p.info.applicationInfo.toString(); 15205 pw.print(" applicationInfo="); pw.println(appInfo); 15206 } 15207 } 15208 } 15209 15210 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15211 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15212 } 15213 15214 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15215 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15216 } 15217 15218 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15219 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15220 } 15221 15222 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15223 // XXX should handle packageName != null by dumping only install data that 15224 // the given package is involved with. 15225 if (dumpState.onTitlePrinted()) pw.println(); 15226 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15227 } 15228 15229 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15230 if (dumpState.onTitlePrinted()) pw.println(); 15231 mSettings.dumpReadMessagesLPr(pw, dumpState); 15232 15233 pw.println(); 15234 pw.println("Package warning messages:"); 15235 BufferedReader in = null; 15236 String line = null; 15237 try { 15238 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15239 while ((line = in.readLine()) != null) { 15240 if (line.contains("ignored: updated version")) continue; 15241 pw.println(line); 15242 } 15243 } catch (IOException ignored) { 15244 } finally { 15245 IoUtils.closeQuietly(in); 15246 } 15247 } 15248 15249 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15250 BufferedReader in = null; 15251 String line = null; 15252 try { 15253 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15254 while ((line = in.readLine()) != null) { 15255 if (line.contains("ignored: updated version")) continue; 15256 pw.print("msg,"); 15257 pw.println(line); 15258 } 15259 } catch (IOException ignored) { 15260 } finally { 15261 IoUtils.closeQuietly(in); 15262 } 15263 } 15264 } 15265 } 15266 15267 private String dumpDomainString(String packageName) { 15268 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15269 List<IntentFilter> filters = getAllIntentFilters(packageName); 15270 15271 ArraySet<String> result = new ArraySet<>(); 15272 if (iviList.size() > 0) { 15273 for (IntentFilterVerificationInfo ivi : iviList) { 15274 for (String host : ivi.getDomains()) { 15275 result.add(host); 15276 } 15277 } 15278 } 15279 if (filters != null && filters.size() > 0) { 15280 for (IntentFilter filter : filters) { 15281 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15282 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15283 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15284 result.addAll(filter.getHostsList()); 15285 } 15286 } 15287 } 15288 15289 StringBuilder sb = new StringBuilder(result.size() * 16); 15290 for (String domain : result) { 15291 if (sb.length() > 0) sb.append(" "); 15292 sb.append(domain); 15293 } 15294 return sb.toString(); 15295 } 15296 15297 // ------- apps on sdcard specific code ------- 15298 static final boolean DEBUG_SD_INSTALL = false; 15299 15300 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15301 15302 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15303 15304 private boolean mMediaMounted = false; 15305 15306 static String getEncryptKey() { 15307 try { 15308 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15309 SD_ENCRYPTION_KEYSTORE_NAME); 15310 if (sdEncKey == null) { 15311 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15312 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15313 if (sdEncKey == null) { 15314 Slog.e(TAG, "Failed to create encryption keys"); 15315 return null; 15316 } 15317 } 15318 return sdEncKey; 15319 } catch (NoSuchAlgorithmException nsae) { 15320 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15321 return null; 15322 } catch (IOException ioe) { 15323 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15324 return null; 15325 } 15326 } 15327 15328 /* 15329 * Update media status on PackageManager. 15330 */ 15331 @Override 15332 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15333 int callingUid = Binder.getCallingUid(); 15334 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15335 throw new SecurityException("Media status can only be updated by the system"); 15336 } 15337 // reader; this apparently protects mMediaMounted, but should probably 15338 // be a different lock in that case. 15339 synchronized (mPackages) { 15340 Log.i(TAG, "Updating external media status from " 15341 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15342 + (mediaStatus ? "mounted" : "unmounted")); 15343 if (DEBUG_SD_INSTALL) 15344 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15345 + ", mMediaMounted=" + mMediaMounted); 15346 if (mediaStatus == mMediaMounted) { 15347 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15348 : 0, -1); 15349 mHandler.sendMessage(msg); 15350 return; 15351 } 15352 mMediaMounted = mediaStatus; 15353 } 15354 // Queue up an async operation since the package installation may take a 15355 // little while. 15356 mHandler.post(new Runnable() { 15357 public void run() { 15358 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15359 } 15360 }); 15361 } 15362 15363 /** 15364 * Called by MountService when the initial ASECs to scan are available. 15365 * Should block until all the ASEC containers are finished being scanned. 15366 */ 15367 public void scanAvailableAsecs() { 15368 updateExternalMediaStatusInner(true, false, false); 15369 if (mShouldRestoreconData) { 15370 SELinuxMMAC.setRestoreconDone(); 15371 mShouldRestoreconData = false; 15372 } 15373 } 15374 15375 /* 15376 * Collect information of applications on external media, map them against 15377 * existing containers and update information based on current mount status. 15378 * Please note that we always have to report status if reportStatus has been 15379 * set to true especially when unloading packages. 15380 */ 15381 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15382 boolean externalStorage) { 15383 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15384 int[] uidArr = EmptyArray.INT; 15385 15386 final String[] list = PackageHelper.getSecureContainerList(); 15387 if (ArrayUtils.isEmpty(list)) { 15388 Log.i(TAG, "No secure containers found"); 15389 } else { 15390 // Process list of secure containers and categorize them 15391 // as active or stale based on their package internal state. 15392 15393 // reader 15394 synchronized (mPackages) { 15395 for (String cid : list) { 15396 // Leave stages untouched for now; installer service owns them 15397 if (PackageInstallerService.isStageName(cid)) continue; 15398 15399 if (DEBUG_SD_INSTALL) 15400 Log.i(TAG, "Processing container " + cid); 15401 String pkgName = getAsecPackageName(cid); 15402 if (pkgName == null) { 15403 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15404 continue; 15405 } 15406 if (DEBUG_SD_INSTALL) 15407 Log.i(TAG, "Looking for pkg : " + pkgName); 15408 15409 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15410 if (ps == null) { 15411 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15412 continue; 15413 } 15414 15415 /* 15416 * Skip packages that are not external if we're unmounting 15417 * external storage. 15418 */ 15419 if (externalStorage && !isMounted && !isExternal(ps)) { 15420 continue; 15421 } 15422 15423 final AsecInstallArgs args = new AsecInstallArgs(cid, 15424 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15425 // The package status is changed only if the code path 15426 // matches between settings and the container id. 15427 if (ps.codePathString != null 15428 && ps.codePathString.startsWith(args.getCodePath())) { 15429 if (DEBUG_SD_INSTALL) { 15430 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15431 + " at code path: " + ps.codePathString); 15432 } 15433 15434 // We do have a valid package installed on sdcard 15435 processCids.put(args, ps.codePathString); 15436 final int uid = ps.appId; 15437 if (uid != -1) { 15438 uidArr = ArrayUtils.appendInt(uidArr, uid); 15439 } 15440 } else { 15441 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15442 + ps.codePathString); 15443 } 15444 } 15445 } 15446 15447 Arrays.sort(uidArr); 15448 } 15449 15450 // Process packages with valid entries. 15451 if (isMounted) { 15452 if (DEBUG_SD_INSTALL) 15453 Log.i(TAG, "Loading packages"); 15454 loadMediaPackages(processCids, uidArr); 15455 startCleaningPackages(); 15456 mInstallerService.onSecureContainersAvailable(); 15457 } else { 15458 if (DEBUG_SD_INSTALL) 15459 Log.i(TAG, "Unloading packages"); 15460 unloadMediaPackages(processCids, uidArr, reportStatus); 15461 } 15462 } 15463 15464 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15465 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15466 final int size = infos.size(); 15467 final String[] packageNames = new String[size]; 15468 final int[] packageUids = new int[size]; 15469 for (int i = 0; i < size; i++) { 15470 final ApplicationInfo info = infos.get(i); 15471 packageNames[i] = info.packageName; 15472 packageUids[i] = info.uid; 15473 } 15474 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15475 finishedReceiver); 15476 } 15477 15478 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15479 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15480 sendResourcesChangedBroadcast(mediaStatus, replacing, 15481 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15482 } 15483 15484 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15485 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15486 int size = pkgList.length; 15487 if (size > 0) { 15488 // Send broadcasts here 15489 Bundle extras = new Bundle(); 15490 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15491 if (uidArr != null) { 15492 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15493 } 15494 if (replacing) { 15495 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15496 } 15497 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15498 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15499 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15500 } 15501 } 15502 15503 /* 15504 * Look at potentially valid container ids from processCids If package 15505 * information doesn't match the one on record or package scanning fails, 15506 * the cid is added to list of removeCids. We currently don't delete stale 15507 * containers. 15508 */ 15509 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15510 ArrayList<String> pkgList = new ArrayList<String>(); 15511 Set<AsecInstallArgs> keys = processCids.keySet(); 15512 15513 for (AsecInstallArgs args : keys) { 15514 String codePath = processCids.get(args); 15515 if (DEBUG_SD_INSTALL) 15516 Log.i(TAG, "Loading container : " + args.cid); 15517 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15518 try { 15519 // Make sure there are no container errors first. 15520 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15521 Slog.e(TAG, "Failed to mount cid : " + args.cid 15522 + " when installing from sdcard"); 15523 continue; 15524 } 15525 // Check code path here. 15526 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15527 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15528 + " does not match one in settings " + codePath); 15529 continue; 15530 } 15531 // Parse package 15532 int parseFlags = mDefParseFlags; 15533 if (args.isExternalAsec()) { 15534 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15535 } 15536 if (args.isFwdLocked()) { 15537 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15538 } 15539 15540 synchronized (mInstallLock) { 15541 PackageParser.Package pkg = null; 15542 try { 15543 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15544 } catch (PackageManagerException e) { 15545 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15546 } 15547 // Scan the package 15548 if (pkg != null) { 15549 /* 15550 * TODO why is the lock being held? doPostInstall is 15551 * called in other places without the lock. This needs 15552 * to be straightened out. 15553 */ 15554 // writer 15555 synchronized (mPackages) { 15556 retCode = PackageManager.INSTALL_SUCCEEDED; 15557 pkgList.add(pkg.packageName); 15558 // Post process args 15559 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15560 pkg.applicationInfo.uid); 15561 } 15562 } else { 15563 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15564 } 15565 } 15566 15567 } finally { 15568 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15569 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15570 } 15571 } 15572 } 15573 // writer 15574 synchronized (mPackages) { 15575 // If the platform SDK has changed since the last time we booted, 15576 // we need to re-grant app permission to catch any new ones that 15577 // appear. This is really a hack, and means that apps can in some 15578 // cases get permissions that the user didn't initially explicitly 15579 // allow... it would be nice to have some better way to handle 15580 // this situation. 15581 final VersionInfo ver = mSettings.getExternalVersion(); 15582 15583 int updateFlags = UPDATE_PERMISSIONS_ALL; 15584 if (ver.sdkVersion != mSdkVersion) { 15585 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15586 + mSdkVersion + "; regranting permissions for external"); 15587 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15588 } 15589 updatePermissionsLPw(null, null, updateFlags); 15590 15591 // Yay, everything is now upgraded 15592 ver.forceCurrent(); 15593 15594 // can downgrade to reader 15595 // Persist settings 15596 mSettings.writeLPr(); 15597 } 15598 // Send a broadcast to let everyone know we are done processing 15599 if (pkgList.size() > 0) { 15600 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15601 } 15602 } 15603 15604 /* 15605 * Utility method to unload a list of specified containers 15606 */ 15607 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15608 // Just unmount all valid containers. 15609 for (AsecInstallArgs arg : cidArgs) { 15610 synchronized (mInstallLock) { 15611 arg.doPostDeleteLI(false); 15612 } 15613 } 15614 } 15615 15616 /* 15617 * Unload packages mounted on external media. This involves deleting package 15618 * data from internal structures, sending broadcasts about diabled packages, 15619 * gc'ing to free up references, unmounting all secure containers 15620 * corresponding to packages on external media, and posting a 15621 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15622 * that we always have to post this message if status has been requested no 15623 * matter what. 15624 */ 15625 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15626 final boolean reportStatus) { 15627 if (DEBUG_SD_INSTALL) 15628 Log.i(TAG, "unloading media packages"); 15629 ArrayList<String> pkgList = new ArrayList<String>(); 15630 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15631 final Set<AsecInstallArgs> keys = processCids.keySet(); 15632 for (AsecInstallArgs args : keys) { 15633 String pkgName = args.getPackageName(); 15634 if (DEBUG_SD_INSTALL) 15635 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15636 // Delete package internally 15637 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15638 synchronized (mInstallLock) { 15639 boolean res = deletePackageLI(pkgName, null, false, null, null, 15640 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15641 if (res) { 15642 pkgList.add(pkgName); 15643 } else { 15644 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15645 failedList.add(args); 15646 } 15647 } 15648 } 15649 15650 // reader 15651 synchronized (mPackages) { 15652 // We didn't update the settings after removing each package; 15653 // write them now for all packages. 15654 mSettings.writeLPr(); 15655 } 15656 15657 // We have to absolutely send UPDATED_MEDIA_STATUS only 15658 // after confirming that all the receivers processed the ordered 15659 // broadcast when packages get disabled, force a gc to clean things up. 15660 // and unload all the containers. 15661 if (pkgList.size() > 0) { 15662 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15663 new IIntentReceiver.Stub() { 15664 public void performReceive(Intent intent, int resultCode, String data, 15665 Bundle extras, boolean ordered, boolean sticky, 15666 int sendingUser) throws RemoteException { 15667 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15668 reportStatus ? 1 : 0, 1, keys); 15669 mHandler.sendMessage(msg); 15670 } 15671 }); 15672 } else { 15673 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15674 keys); 15675 mHandler.sendMessage(msg); 15676 } 15677 } 15678 15679 private void loadPrivatePackages(VolumeInfo vol) { 15680 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15681 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15682 synchronized (mInstallLock) { 15683 synchronized (mPackages) { 15684 final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid); 15685 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15686 for (PackageSetting ps : packages) { 15687 final PackageParser.Package pkg; 15688 try { 15689 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15690 loaded.add(pkg.applicationInfo); 15691 } catch (PackageManagerException e) { 15692 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15693 } 15694 15695 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 15696 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 15697 } 15698 } 15699 15700 int updateFlags = UPDATE_PERMISSIONS_ALL; 15701 if (ver.sdkVersion != mSdkVersion) { 15702 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15703 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 15704 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15705 } 15706 updatePermissionsLPw(null, null, updateFlags); 15707 15708 // Yay, everything is now upgraded 15709 ver.forceCurrent(); 15710 15711 mSettings.writeLPr(); 15712 } 15713 } 15714 15715 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15716 sendResourcesChangedBroadcast(true, false, loaded, null); 15717 } 15718 15719 private void unloadPrivatePackages(VolumeInfo vol) { 15720 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15721 synchronized (mInstallLock) { 15722 synchronized (mPackages) { 15723 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15724 for (PackageSetting ps : packages) { 15725 if (ps.pkg == null) continue; 15726 15727 final ApplicationInfo info = ps.pkg.applicationInfo; 15728 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15729 if (deletePackageLI(ps.name, null, false, null, null, 15730 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15731 unloaded.add(info); 15732 } else { 15733 Slog.w(TAG, "Failed to unload " + ps.codePath); 15734 } 15735 } 15736 15737 mSettings.writeLPr(); 15738 } 15739 } 15740 15741 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15742 sendResourcesChangedBroadcast(false, false, unloaded, null); 15743 } 15744 15745 /** 15746 * Examine all users present on given mounted volume, and destroy data 15747 * belonging to users that are no longer valid, or whose user ID has been 15748 * recycled. 15749 */ 15750 private void reconcileUsers(String volumeUuid) { 15751 final File[] files = FileUtils 15752 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 15753 for (File file : files) { 15754 if (!file.isDirectory()) continue; 15755 15756 final int userId; 15757 final UserInfo info; 15758 try { 15759 userId = Integer.parseInt(file.getName()); 15760 info = sUserManager.getUserInfo(userId); 15761 } catch (NumberFormatException e) { 15762 Slog.w(TAG, "Invalid user directory " + file); 15763 continue; 15764 } 15765 15766 boolean destroyUser = false; 15767 if (info == null) { 15768 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15769 + " because no matching user was found"); 15770 destroyUser = true; 15771 } else { 15772 try { 15773 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15774 } catch (IOException e) { 15775 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15776 + " because we failed to enforce serial number: " + e); 15777 destroyUser = true; 15778 } 15779 } 15780 15781 if (destroyUser) { 15782 synchronized (mInstallLock) { 15783 mInstaller.removeUserDataDirs(volumeUuid, userId); 15784 } 15785 } 15786 } 15787 15788 final UserManager um = mContext.getSystemService(UserManager.class); 15789 for (UserInfo user : um.getUsers()) { 15790 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15791 if (userDir.exists()) continue; 15792 15793 try { 15794 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15795 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15796 } catch (IOException e) { 15797 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15798 } 15799 } 15800 } 15801 15802 /** 15803 * Examine all apps present on given mounted volume, and destroy apps that 15804 * aren't expected, either due to uninstallation or reinstallation on 15805 * another volume. 15806 */ 15807 private void reconcileApps(String volumeUuid) { 15808 final File[] files = FileUtils 15809 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 15810 for (File file : files) { 15811 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15812 && !PackageInstallerService.isStageName(file.getName()); 15813 if (!isPackage) { 15814 // Ignore entries which are not packages 15815 continue; 15816 } 15817 15818 boolean destroyApp = false; 15819 String packageName = null; 15820 try { 15821 final PackageLite pkg = PackageParser.parsePackageLite(file, 15822 PackageParser.PARSE_MUST_BE_APK); 15823 packageName = pkg.packageName; 15824 15825 synchronized (mPackages) { 15826 final PackageSetting ps = mSettings.mPackages.get(packageName); 15827 if (ps == null) { 15828 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15829 + volumeUuid + " because we found no install record"); 15830 destroyApp = true; 15831 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15832 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15833 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15834 destroyApp = true; 15835 } 15836 } 15837 15838 } catch (PackageParserException e) { 15839 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15840 destroyApp = true; 15841 } 15842 15843 if (destroyApp) { 15844 synchronized (mInstallLock) { 15845 if (packageName != null) { 15846 removeDataDirsLI(volumeUuid, packageName); 15847 } 15848 if (file.isDirectory()) { 15849 mInstaller.rmPackageDir(file.getAbsolutePath()); 15850 } else { 15851 file.delete(); 15852 } 15853 } 15854 } 15855 } 15856 } 15857 15858 private void unfreezePackage(String packageName) { 15859 synchronized (mPackages) { 15860 final PackageSetting ps = mSettings.mPackages.get(packageName); 15861 if (ps != null) { 15862 ps.frozen = false; 15863 } 15864 } 15865 } 15866 15867 @Override 15868 public int movePackage(final String packageName, final String volumeUuid) { 15869 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15870 15871 final int moveId = mNextMoveId.getAndIncrement(); 15872 try { 15873 movePackageInternal(packageName, volumeUuid, moveId); 15874 } catch (PackageManagerException e) { 15875 Slog.w(TAG, "Failed to move " + packageName, e); 15876 mMoveCallbacks.notifyStatusChanged(moveId, 15877 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15878 } 15879 return moveId; 15880 } 15881 15882 private void movePackageInternal(final String packageName, final String volumeUuid, 15883 final int moveId) throws PackageManagerException { 15884 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15885 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15886 final PackageManager pm = mContext.getPackageManager(); 15887 15888 final boolean currentAsec; 15889 final String currentVolumeUuid; 15890 final File codeFile; 15891 final String installerPackageName; 15892 final String packageAbiOverride; 15893 final int appId; 15894 final String seinfo; 15895 final String label; 15896 15897 // reader 15898 synchronized (mPackages) { 15899 final PackageParser.Package pkg = mPackages.get(packageName); 15900 final PackageSetting ps = mSettings.mPackages.get(packageName); 15901 if (pkg == null || ps == null) { 15902 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15903 } 15904 15905 if (pkg.applicationInfo.isSystemApp()) { 15906 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15907 "Cannot move system application"); 15908 } 15909 15910 if (pkg.applicationInfo.isExternalAsec()) { 15911 currentAsec = true; 15912 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 15913 } else if (pkg.applicationInfo.isForwardLocked()) { 15914 currentAsec = true; 15915 currentVolumeUuid = "forward_locked"; 15916 } else { 15917 currentAsec = false; 15918 currentVolumeUuid = ps.volumeUuid; 15919 15920 final File probe = new File(pkg.codePath); 15921 final File probeOat = new File(probe, "oat"); 15922 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15923 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15924 "Move only supported for modern cluster style installs"); 15925 } 15926 } 15927 15928 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 15929 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15930 "Package already moved to " + volumeUuid); 15931 } 15932 15933 if (ps.frozen) { 15934 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15935 "Failed to move already frozen package"); 15936 } 15937 ps.frozen = true; 15938 15939 codeFile = new File(pkg.codePath); 15940 installerPackageName = ps.installerPackageName; 15941 packageAbiOverride = ps.cpuAbiOverrideString; 15942 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15943 seinfo = pkg.applicationInfo.seinfo; 15944 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15945 } 15946 15947 // Now that we're guarded by frozen state, kill app during move 15948 final long token = Binder.clearCallingIdentity(); 15949 try { 15950 killApplication(packageName, appId, "move pkg"); 15951 } finally { 15952 Binder.restoreCallingIdentity(token); 15953 } 15954 15955 final Bundle extras = new Bundle(); 15956 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15957 extras.putString(Intent.EXTRA_TITLE, label); 15958 mMoveCallbacks.notifyCreated(moveId, extras); 15959 15960 int installFlags; 15961 final boolean moveCompleteApp; 15962 final File measurePath; 15963 15964 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15965 installFlags = INSTALL_INTERNAL; 15966 moveCompleteApp = !currentAsec; 15967 measurePath = Environment.getDataAppDirectory(volumeUuid); 15968 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15969 installFlags = INSTALL_EXTERNAL; 15970 moveCompleteApp = false; 15971 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15972 } else { 15973 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15974 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15975 || !volume.isMountedWritable()) { 15976 unfreezePackage(packageName); 15977 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15978 "Move location not mounted private volume"); 15979 } 15980 15981 Preconditions.checkState(!currentAsec); 15982 15983 installFlags = INSTALL_INTERNAL; 15984 moveCompleteApp = true; 15985 measurePath = Environment.getDataAppDirectory(volumeUuid); 15986 } 15987 15988 final PackageStats stats = new PackageStats(null, -1); 15989 synchronized (mInstaller) { 15990 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15991 unfreezePackage(packageName); 15992 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15993 "Failed to measure package size"); 15994 } 15995 } 15996 15997 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15998 + stats.dataSize); 15999 16000 final long startFreeBytes = measurePath.getFreeSpace(); 16001 final long sizeBytes; 16002 if (moveCompleteApp) { 16003 sizeBytes = stats.codeSize + stats.dataSize; 16004 } else { 16005 sizeBytes = stats.codeSize; 16006 } 16007 16008 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16009 unfreezePackage(packageName); 16010 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16011 "Not enough free space to move"); 16012 } 16013 16014 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16015 16016 final CountDownLatch installedLatch = new CountDownLatch(1); 16017 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16018 @Override 16019 public void onUserActionRequired(Intent intent) throws RemoteException { 16020 throw new IllegalStateException(); 16021 } 16022 16023 @Override 16024 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16025 Bundle extras) throws RemoteException { 16026 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16027 + PackageManager.installStatusToString(returnCode, msg)); 16028 16029 installedLatch.countDown(); 16030 16031 // Regardless of success or failure of the move operation, 16032 // always unfreeze the package 16033 unfreezePackage(packageName); 16034 16035 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16036 switch (status) { 16037 case PackageInstaller.STATUS_SUCCESS: 16038 mMoveCallbacks.notifyStatusChanged(moveId, 16039 PackageManager.MOVE_SUCCEEDED); 16040 break; 16041 case PackageInstaller.STATUS_FAILURE_STORAGE: 16042 mMoveCallbacks.notifyStatusChanged(moveId, 16043 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16044 break; 16045 default: 16046 mMoveCallbacks.notifyStatusChanged(moveId, 16047 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16048 break; 16049 } 16050 } 16051 }; 16052 16053 final MoveInfo move; 16054 if (moveCompleteApp) { 16055 // Kick off a thread to report progress estimates 16056 new Thread() { 16057 @Override 16058 public void run() { 16059 while (true) { 16060 try { 16061 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16062 break; 16063 } 16064 } catch (InterruptedException ignored) { 16065 } 16066 16067 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16068 final int progress = 10 + (int) MathUtils.constrain( 16069 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16070 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16071 } 16072 } 16073 }.start(); 16074 16075 final String dataAppName = codeFile.getName(); 16076 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16077 dataAppName, appId, seinfo); 16078 } else { 16079 move = null; 16080 } 16081 16082 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16083 16084 final Message msg = mHandler.obtainMessage(INIT_COPY); 16085 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16086 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 16087 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16088 mHandler.sendMessage(msg); 16089 } 16090 16091 @Override 16092 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16093 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16094 16095 final int realMoveId = mNextMoveId.getAndIncrement(); 16096 final Bundle extras = new Bundle(); 16097 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16098 mMoveCallbacks.notifyCreated(realMoveId, extras); 16099 16100 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16101 @Override 16102 public void onCreated(int moveId, Bundle extras) { 16103 // Ignored 16104 } 16105 16106 @Override 16107 public void onStatusChanged(int moveId, int status, long estMillis) { 16108 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16109 } 16110 }; 16111 16112 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16113 storage.setPrimaryStorageUuid(volumeUuid, callback); 16114 return realMoveId; 16115 } 16116 16117 @Override 16118 public int getMoveStatus(int moveId) { 16119 mContext.enforceCallingOrSelfPermission( 16120 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16121 return mMoveCallbacks.mLastStatus.get(moveId); 16122 } 16123 16124 @Override 16125 public void registerMoveCallback(IPackageMoveObserver callback) { 16126 mContext.enforceCallingOrSelfPermission( 16127 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16128 mMoveCallbacks.register(callback); 16129 } 16130 16131 @Override 16132 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16133 mContext.enforceCallingOrSelfPermission( 16134 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16135 mMoveCallbacks.unregister(callback); 16136 } 16137 16138 @Override 16139 public boolean setInstallLocation(int loc) { 16140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16141 null); 16142 if (getInstallLocation() == loc) { 16143 return true; 16144 } 16145 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16146 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16147 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16148 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16149 return true; 16150 } 16151 return false; 16152 } 16153 16154 @Override 16155 public int getInstallLocation() { 16156 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16157 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16158 PackageHelper.APP_INSTALL_AUTO); 16159 } 16160 16161 /** Called by UserManagerService */ 16162 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16163 mDirtyUsers.remove(userHandle); 16164 mSettings.removeUserLPw(userHandle); 16165 mPendingBroadcasts.remove(userHandle); 16166 if (mInstaller != null) { 16167 // Technically, we shouldn't be doing this with the package lock 16168 // held. However, this is very rare, and there is already so much 16169 // other disk I/O going on, that we'll let it slide for now. 16170 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16171 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16172 final String volumeUuid = vol.getFsUuid(); 16173 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16174 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16175 } 16176 } 16177 mUserNeedsBadging.delete(userHandle); 16178 removeUnusedPackagesLILPw(userManager, userHandle); 16179 } 16180 16181 /** 16182 * We're removing userHandle and would like to remove any downloaded packages 16183 * that are no longer in use by any other user. 16184 * @param userHandle the user being removed 16185 */ 16186 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16187 final boolean DEBUG_CLEAN_APKS = false; 16188 int [] users = userManager.getUserIdsLPr(); 16189 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16190 while (psit.hasNext()) { 16191 PackageSetting ps = psit.next(); 16192 if (ps.pkg == null) { 16193 continue; 16194 } 16195 final String packageName = ps.pkg.packageName; 16196 // Skip over if system app 16197 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16198 continue; 16199 } 16200 if (DEBUG_CLEAN_APKS) { 16201 Slog.i(TAG, "Checking package " + packageName); 16202 } 16203 boolean keep = false; 16204 for (int i = 0; i < users.length; i++) { 16205 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16206 keep = true; 16207 if (DEBUG_CLEAN_APKS) { 16208 Slog.i(TAG, " Keeping package " + packageName + " for user " 16209 + users[i]); 16210 } 16211 break; 16212 } 16213 } 16214 if (!keep) { 16215 if (DEBUG_CLEAN_APKS) { 16216 Slog.i(TAG, " Removing package " + packageName); 16217 } 16218 mHandler.post(new Runnable() { 16219 public void run() { 16220 deletePackageX(packageName, userHandle, 0); 16221 } //end run 16222 }); 16223 } 16224 } 16225 } 16226 16227 /** Called by UserManagerService */ 16228 void createNewUserLILPw(int userHandle) { 16229 if (mInstaller != null) { 16230 mInstaller.createUserConfig(userHandle); 16231 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16232 applyFactoryDefaultBrowserLPw(userHandle); 16233 primeDomainVerificationsLPw(userHandle); 16234 } 16235 } 16236 16237 void newUserCreated(final int userHandle) { 16238 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16239 } 16240 16241 @Override 16242 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16243 mContext.enforceCallingOrSelfPermission( 16244 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16245 "Only package verification agents can read the verifier device identity"); 16246 16247 synchronized (mPackages) { 16248 return mSettings.getVerifierDeviceIdentityLPw(); 16249 } 16250 } 16251 16252 @Override 16253 public void setPermissionEnforced(String permission, boolean enforced) { 16254 // TODO: Now that we no longer change GID for storage, this should to away. 16255 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16256 "setPermissionEnforced"); 16257 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16258 synchronized (mPackages) { 16259 if (mSettings.mReadExternalStorageEnforced == null 16260 || mSettings.mReadExternalStorageEnforced != enforced) { 16261 mSettings.mReadExternalStorageEnforced = enforced; 16262 mSettings.writeLPr(); 16263 } 16264 } 16265 // kill any non-foreground processes so we restart them and 16266 // grant/revoke the GID. 16267 final IActivityManager am = ActivityManagerNative.getDefault(); 16268 if (am != null) { 16269 final long token = Binder.clearCallingIdentity(); 16270 try { 16271 am.killProcessesBelowForeground("setPermissionEnforcement"); 16272 } catch (RemoteException e) { 16273 } finally { 16274 Binder.restoreCallingIdentity(token); 16275 } 16276 } 16277 } else { 16278 throw new IllegalArgumentException("No selective enforcement for " + permission); 16279 } 16280 } 16281 16282 @Override 16283 @Deprecated 16284 public boolean isPermissionEnforced(String permission) { 16285 return true; 16286 } 16287 16288 @Override 16289 public boolean isStorageLow() { 16290 final long token = Binder.clearCallingIdentity(); 16291 try { 16292 final DeviceStorageMonitorInternal 16293 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16294 if (dsm != null) { 16295 return dsm.isMemoryLow(); 16296 } else { 16297 return false; 16298 } 16299 } finally { 16300 Binder.restoreCallingIdentity(token); 16301 } 16302 } 16303 16304 @Override 16305 public IPackageInstaller getPackageInstaller() { 16306 return mInstallerService; 16307 } 16308 16309 private boolean userNeedsBadging(int userId) { 16310 int index = mUserNeedsBadging.indexOfKey(userId); 16311 if (index < 0) { 16312 final UserInfo userInfo; 16313 final long token = Binder.clearCallingIdentity(); 16314 try { 16315 userInfo = sUserManager.getUserInfo(userId); 16316 } finally { 16317 Binder.restoreCallingIdentity(token); 16318 } 16319 final boolean b; 16320 if (userInfo != null && userInfo.isManagedProfile()) { 16321 b = true; 16322 } else { 16323 b = false; 16324 } 16325 mUserNeedsBadging.put(userId, b); 16326 return b; 16327 } 16328 return mUserNeedsBadging.valueAt(index); 16329 } 16330 16331 @Override 16332 public KeySet getKeySetByAlias(String packageName, String alias) { 16333 if (packageName == null || alias == null) { 16334 return null; 16335 } 16336 synchronized(mPackages) { 16337 final PackageParser.Package pkg = mPackages.get(packageName); 16338 if (pkg == null) { 16339 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16340 throw new IllegalArgumentException("Unknown package: " + packageName); 16341 } 16342 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16343 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16344 } 16345 } 16346 16347 @Override 16348 public KeySet getSigningKeySet(String packageName) { 16349 if (packageName == null) { 16350 return null; 16351 } 16352 synchronized(mPackages) { 16353 final PackageParser.Package pkg = mPackages.get(packageName); 16354 if (pkg == null) { 16355 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16356 throw new IllegalArgumentException("Unknown package: " + packageName); 16357 } 16358 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16359 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16360 throw new SecurityException("May not access signing KeySet of other apps."); 16361 } 16362 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16363 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16364 } 16365 } 16366 16367 @Override 16368 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16369 if (packageName == null || ks == null) { 16370 return false; 16371 } 16372 synchronized(mPackages) { 16373 final PackageParser.Package pkg = mPackages.get(packageName); 16374 if (pkg == null) { 16375 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16376 throw new IllegalArgumentException("Unknown package: " + packageName); 16377 } 16378 IBinder ksh = ks.getToken(); 16379 if (ksh instanceof KeySetHandle) { 16380 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16381 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16382 } 16383 return false; 16384 } 16385 } 16386 16387 @Override 16388 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16389 if (packageName == null || ks == null) { 16390 return false; 16391 } 16392 synchronized(mPackages) { 16393 final PackageParser.Package pkg = mPackages.get(packageName); 16394 if (pkg == null) { 16395 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16396 throw new IllegalArgumentException("Unknown package: " + packageName); 16397 } 16398 IBinder ksh = ks.getToken(); 16399 if (ksh instanceof KeySetHandle) { 16400 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16401 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16402 } 16403 return false; 16404 } 16405 } 16406 16407 public void getUsageStatsIfNoPackageUsageInfo() { 16408 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16409 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16410 if (usm == null) { 16411 throw new IllegalStateException("UsageStatsManager must be initialized"); 16412 } 16413 long now = System.currentTimeMillis(); 16414 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16415 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16416 String packageName = entry.getKey(); 16417 PackageParser.Package pkg = mPackages.get(packageName); 16418 if (pkg == null) { 16419 continue; 16420 } 16421 UsageStats usage = entry.getValue(); 16422 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16423 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16424 } 16425 } 16426 } 16427 16428 /** 16429 * Check and throw if the given before/after packages would be considered a 16430 * downgrade. 16431 */ 16432 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16433 throws PackageManagerException { 16434 if (after.versionCode < before.mVersionCode) { 16435 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16436 "Update version code " + after.versionCode + " is older than current " 16437 + before.mVersionCode); 16438 } else if (after.versionCode == before.mVersionCode) { 16439 if (after.baseRevisionCode < before.baseRevisionCode) { 16440 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16441 "Update base revision code " + after.baseRevisionCode 16442 + " is older than current " + before.baseRevisionCode); 16443 } 16444 16445 if (!ArrayUtils.isEmpty(after.splitNames)) { 16446 for (int i = 0; i < after.splitNames.length; i++) { 16447 final String splitName = after.splitNames[i]; 16448 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16449 if (j != -1) { 16450 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16451 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16452 "Update split " + splitName + " revision code " 16453 + after.splitRevisionCodes[i] + " is older than current " 16454 + before.splitRevisionCodes[j]); 16455 } 16456 } 16457 } 16458 } 16459 } 16460 } 16461 16462 private static class MoveCallbacks extends Handler { 16463 private static final int MSG_CREATED = 1; 16464 private static final int MSG_STATUS_CHANGED = 2; 16465 16466 private final RemoteCallbackList<IPackageMoveObserver> 16467 mCallbacks = new RemoteCallbackList<>(); 16468 16469 private final SparseIntArray mLastStatus = new SparseIntArray(); 16470 16471 public MoveCallbacks(Looper looper) { 16472 super(looper); 16473 } 16474 16475 public void register(IPackageMoveObserver callback) { 16476 mCallbacks.register(callback); 16477 } 16478 16479 public void unregister(IPackageMoveObserver callback) { 16480 mCallbacks.unregister(callback); 16481 } 16482 16483 @Override 16484 public void handleMessage(Message msg) { 16485 final SomeArgs args = (SomeArgs) msg.obj; 16486 final int n = mCallbacks.beginBroadcast(); 16487 for (int i = 0; i < n; i++) { 16488 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16489 try { 16490 invokeCallback(callback, msg.what, args); 16491 } catch (RemoteException ignored) { 16492 } 16493 } 16494 mCallbacks.finishBroadcast(); 16495 args.recycle(); 16496 } 16497 16498 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16499 throws RemoteException { 16500 switch (what) { 16501 case MSG_CREATED: { 16502 callback.onCreated(args.argi1, (Bundle) args.arg2); 16503 break; 16504 } 16505 case MSG_STATUS_CHANGED: { 16506 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16507 break; 16508 } 16509 } 16510 } 16511 16512 private void notifyCreated(int moveId, Bundle extras) { 16513 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16514 16515 final SomeArgs args = SomeArgs.obtain(); 16516 args.argi1 = moveId; 16517 args.arg2 = extras; 16518 obtainMessage(MSG_CREATED, args).sendToTarget(); 16519 } 16520 16521 private void notifyStatusChanged(int moveId, int status) { 16522 notifyStatusChanged(moveId, status, -1); 16523 } 16524 16525 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16526 Slog.v(TAG, "Move " + moveId + " status " + status); 16527 16528 final SomeArgs args = SomeArgs.obtain(); 16529 args.argi1 = moveId; 16530 args.argi2 = status; 16531 args.arg3 = estMillis; 16532 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16533 16534 synchronized (mLastStatus) { 16535 mLastStatus.put(moveId, status); 16536 } 16537 } 16538 } 16539 16540 private final class OnPermissionChangeListeners extends Handler { 16541 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16542 16543 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16544 new RemoteCallbackList<>(); 16545 16546 public OnPermissionChangeListeners(Looper looper) { 16547 super(looper); 16548 } 16549 16550 @Override 16551 public void handleMessage(Message msg) { 16552 switch (msg.what) { 16553 case MSG_ON_PERMISSIONS_CHANGED: { 16554 final int uid = msg.arg1; 16555 handleOnPermissionsChanged(uid); 16556 } break; 16557 } 16558 } 16559 16560 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16561 mPermissionListeners.register(listener); 16562 16563 } 16564 16565 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16566 mPermissionListeners.unregister(listener); 16567 } 16568 16569 public void onPermissionsChanged(int uid) { 16570 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16571 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16572 } 16573 } 16574 16575 private void handleOnPermissionsChanged(int uid) { 16576 final int count = mPermissionListeners.beginBroadcast(); 16577 try { 16578 for (int i = 0; i < count; i++) { 16579 IOnPermissionsChangeListener callback = mPermissionListeners 16580 .getBroadcastItem(i); 16581 try { 16582 callback.onPermissionsChanged(uid); 16583 } catch (RemoteException e) { 16584 Log.e(TAG, "Permission listener is dead", e); 16585 } 16586 } 16587 } finally { 16588 mPermissionListeners.finishBroadcast(); 16589 } 16590 } 16591 } 16592 16593 private class PackageManagerInternalImpl extends PackageManagerInternal { 16594 @Override 16595 public void setLocationPackagesProvider(PackagesProvider provider) { 16596 synchronized (mPackages) { 16597 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16598 } 16599 } 16600 16601 @Override 16602 public void setImePackagesProvider(PackagesProvider provider) { 16603 synchronized (mPackages) { 16604 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16605 } 16606 } 16607 16608 @Override 16609 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16610 synchronized (mPackages) { 16611 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16612 } 16613 } 16614 16615 @Override 16616 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16617 synchronized (mPackages) { 16618 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16619 } 16620 } 16621 16622 @Override 16623 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16624 synchronized (mPackages) { 16625 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16626 } 16627 } 16628 16629 @Override 16630 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16631 synchronized (mPackages) { 16632 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16633 } 16634 } 16635 16636 @Override 16637 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16638 synchronized (mPackages) { 16639 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16640 } 16641 } 16642 16643 @Override 16644 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16645 synchronized (mPackages) { 16646 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16647 packageName, userId); 16648 } 16649 } 16650 16651 @Override 16652 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16653 synchronized (mPackages) { 16654 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16655 packageName, userId); 16656 } 16657 } 16658 @Override 16659 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 16660 synchronized (mPackages) { 16661 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 16662 packageName, userId); 16663 } 16664 } 16665 } 16666 16667 @Override 16668 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16669 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16670 synchronized (mPackages) { 16671 final long identity = Binder.clearCallingIdentity(); 16672 try { 16673 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16674 packageNames, userId); 16675 } finally { 16676 Binder.restoreCallingIdentity(identity); 16677 } 16678 } 16679 } 16680 16681 private static void enforceSystemOrPhoneCaller(String tag) { 16682 int callingUid = Binder.getCallingUid(); 16683 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16684 throw new SecurityException( 16685 "Cannot call " + tag + " from UID " + callingUid); 16686 } 16687 } 16688} 16689