PackageManagerService.java revision cb6fd80721253ffa9dcab5cf8c2f4e9b9cd17ccc
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.AppsQueryHelper; 109import android.content.pm.FeatureInfo; 110import android.content.pm.IOnPermissionsChangeListener; 111import android.content.pm.IPackageDataObserver; 112import android.content.pm.IPackageDeleteObserver; 113import android.content.pm.IPackageDeleteObserver2; 114import android.content.pm.IPackageInstallObserver2; 115import android.content.pm.IPackageInstaller; 116import android.content.pm.IPackageManager; 117import android.content.pm.IPackageMoveObserver; 118import android.content.pm.IPackageStatsObserver; 119import android.content.pm.InstrumentationInfo; 120import android.content.pm.IntentFilterVerificationInfo; 121import android.content.pm.KeySet; 122import android.content.pm.ManifestDigest; 123import android.content.pm.PackageCleanItem; 124import android.content.pm.PackageInfo; 125import android.content.pm.PackageInfoLite; 126import android.content.pm.PackageInstaller; 127import android.content.pm.PackageManager; 128import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 129import android.content.pm.PackageManagerInternal; 130import android.content.pm.PackageParser; 131import android.content.pm.PackageParser.ActivityIntentInfo; 132import android.content.pm.PackageParser.PackageLite; 133import android.content.pm.PackageParser.PackageParserException; 134import android.content.pm.PackageStats; 135import android.content.pm.PackageUserState; 136import android.content.pm.ParceledListSlice; 137import android.content.pm.PermissionGroupInfo; 138import android.content.pm.PermissionInfo; 139import android.content.pm.ProviderInfo; 140import android.content.pm.ResolveInfo; 141import android.content.pm.ServiceInfo; 142import android.content.pm.Signature; 143import android.content.pm.UserInfo; 144import android.content.pm.VerificationParams; 145import android.content.pm.VerifierDeviceIdentity; 146import android.content.pm.VerifierInfo; 147import android.content.res.Resources; 148import android.hardware.display.DisplayManager; 149import android.net.Uri; 150import android.os.Debug; 151import android.os.Binder; 152import android.os.Build; 153import android.os.Bundle; 154import android.os.Environment; 155import android.os.Environment.UserEnvironment; 156import android.os.FileUtils; 157import android.os.Handler; 158import android.os.IBinder; 159import android.os.Looper; 160import android.os.Message; 161import android.os.Parcel; 162import android.os.ParcelFileDescriptor; 163import android.os.Process; 164import android.os.RemoteCallbackList; 165import android.os.RemoteException; 166import android.os.ResultReceiver; 167import android.os.SELinux; 168import android.os.ServiceManager; 169import android.os.SystemClock; 170import android.os.SystemProperties; 171import android.os.Trace; 172import android.os.UserHandle; 173import android.os.UserManager; 174import android.os.storage.IMountService; 175import android.os.storage.MountServiceInternal; 176import android.os.storage.StorageEventListener; 177import android.os.storage.StorageManager; 178import android.os.storage.VolumeInfo; 179import android.os.storage.VolumeRecord; 180import android.security.KeyStore; 181import android.security.SystemKeyStore; 182import android.system.ErrnoException; 183import android.system.Os; 184import android.system.StructStat; 185import android.text.TextUtils; 186import android.text.format.DateUtils; 187import android.util.ArrayMap; 188import android.util.ArraySet; 189import android.util.AtomicFile; 190import android.util.DisplayMetrics; 191import android.util.EventLog; 192import android.util.ExceptionUtils; 193import android.util.Log; 194import android.util.LogPrinter; 195import android.util.MathUtils; 196import android.util.PrintStreamPrinter; 197import android.util.Slog; 198import android.util.SparseArray; 199import android.util.SparseBooleanArray; 200import android.util.SparseIntArray; 201import android.util.Xml; 202import android.view.Display; 203 204import dalvik.system.DexFile; 205import dalvik.system.VMRuntime; 206 207import libcore.io.IoUtils; 208import libcore.util.EmptyArray; 209 210import com.android.internal.R; 211import com.android.internal.annotations.GuardedBy; 212import com.android.internal.app.EphemeralResolveInfo; 213import com.android.internal.app.IMediaContainerService; 214import com.android.internal.app.ResolverActivity; 215import com.android.internal.content.NativeLibraryHelper; 216import com.android.internal.content.PackageHelper; 217import com.android.internal.os.IParcelFileDescriptorFactory; 218import com.android.internal.os.SomeArgs; 219import com.android.internal.os.Zygote; 220import com.android.internal.util.ArrayUtils; 221import com.android.internal.util.FastPrintWriter; 222import com.android.internal.util.FastXmlSerializer; 223import com.android.internal.util.IndentingPrintWriter; 224import com.android.internal.util.Preconditions; 225import com.android.server.EventLogTags; 226import com.android.server.FgThread; 227import com.android.server.IntentResolver; 228import com.android.server.LocalServices; 229import com.android.server.ServiceThread; 230import com.android.server.SystemConfig; 231import com.android.server.Watchdog; 232import com.android.server.pm.PermissionsState.PermissionState; 233import com.android.server.pm.Settings.DatabaseVersion; 234import com.android.server.pm.Settings.VersionInfo; 235import com.android.server.storage.DeviceStorageMonitorInternal; 236 237import org.xmlpull.v1.XmlPullParser; 238import org.xmlpull.v1.XmlPullParserException; 239import org.xmlpull.v1.XmlSerializer; 240 241import java.io.BufferedInputStream; 242import java.io.BufferedOutputStream; 243import java.io.BufferedReader; 244import java.io.ByteArrayInputStream; 245import java.io.ByteArrayOutputStream; 246import java.io.File; 247import java.io.FileDescriptor; 248import java.io.FileNotFoundException; 249import java.io.FileOutputStream; 250import java.io.FileReader; 251import java.io.FilenameFilter; 252import java.io.IOException; 253import java.io.InputStream; 254import java.io.PrintWriter; 255import java.nio.charset.StandardCharsets; 256import java.security.MessageDigest; 257import java.security.NoSuchAlgorithmException; 258import java.security.PublicKey; 259import java.security.cert.CertificateEncodingException; 260import java.security.cert.CertificateException; 261import java.text.SimpleDateFormat; 262import java.util.ArrayList; 263import java.util.Arrays; 264import java.util.Collection; 265import java.util.Collections; 266import java.util.Comparator; 267import java.util.Date; 268import java.util.Iterator; 269import java.util.List; 270import java.util.Map; 271import java.util.Objects; 272import java.util.Set; 273import java.util.concurrent.CountDownLatch; 274import java.util.concurrent.TimeUnit; 275import java.util.concurrent.atomic.AtomicBoolean; 276import java.util.concurrent.atomic.AtomicInteger; 277import java.util.concurrent.atomic.AtomicLong; 278 279/** 280 * Keep track of all those .apks everywhere. 281 * 282 * This is very central to the platform's security; please run the unit 283 * tests whenever making modifications here: 284 * 285runtest -c android.content.pm.PackageManagerTests frameworks-core 286 * 287 * {@hide} 288 */ 289public class PackageManagerService extends IPackageManager.Stub { 290 static final String TAG = "PackageManager"; 291 static final boolean DEBUG_SETTINGS = false; 292 static final boolean DEBUG_PREFERRED = false; 293 static final boolean DEBUG_UPGRADE = false; 294 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 295 private static final boolean DEBUG_BACKUP = false; 296 private static final boolean DEBUG_INSTALL = false; 297 private static final boolean DEBUG_REMOVE = false; 298 private static final boolean DEBUG_BROADCASTS = false; 299 private static final boolean DEBUG_SHOW_INFO = false; 300 private static final boolean DEBUG_PACKAGE_INFO = false; 301 private static final boolean DEBUG_INTENT_MATCHING = false; 302 private static final boolean DEBUG_PACKAGE_SCANNING = false; 303 private static final boolean DEBUG_VERIFY = false; 304 private static final boolean DEBUG_DEXOPT = false; 305 private static final boolean DEBUG_ABI_SELECTION = false; 306 private static final boolean DEBUG_EPHEMERAL = false; 307 308 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 309 310 private static final int RADIO_UID = Process.PHONE_UID; 311 private static final int LOG_UID = Process.LOG_UID; 312 private static final int NFC_UID = Process.NFC_UID; 313 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 314 private static final int SHELL_UID = Process.SHELL_UID; 315 316 // Cap the size of permission trees that 3rd party apps can define 317 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 318 319 // Suffix used during package installation when copying/moving 320 // package apks to install directory. 321 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 322 323 static final int SCAN_NO_DEX = 1<<1; 324 static final int SCAN_FORCE_DEX = 1<<2; 325 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 326 static final int SCAN_NEW_INSTALL = 1<<4; 327 static final int SCAN_NO_PATHS = 1<<5; 328 static final int SCAN_UPDATE_TIME = 1<<6; 329 static final int SCAN_DEFER_DEX = 1<<7; 330 static final int SCAN_BOOTING = 1<<8; 331 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 332 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 333 static final int SCAN_REPLACING = 1<<11; 334 static final int SCAN_REQUIRE_KNOWN = 1<<12; 335 static final int SCAN_MOVE = 1<<13; 336 static final int SCAN_INITIAL = 1<<14; 337 338 static final int REMOVE_CHATTY = 1<<16; 339 340 private static final int[] EMPTY_INT_ARRAY = new int[0]; 341 342 /** 343 * Timeout (in milliseconds) after which the watchdog should declare that 344 * our handler thread is wedged. The usual default for such things is one 345 * minute but we sometimes do very lengthy I/O operations on this thread, 346 * such as installing multi-gigabyte applications, so ours needs to be longer. 347 */ 348 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 349 350 /** 351 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 352 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 353 * settings entry if available, otherwise we use the hardcoded default. If it's been 354 * more than this long since the last fstrim, we force one during the boot sequence. 355 * 356 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 357 * one gets run at the next available charging+idle time. This final mandatory 358 * no-fstrim check kicks in only of the other scheduling criteria is never met. 359 */ 360 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 361 362 /** 363 * Whether verification is enabled by default. 364 */ 365 private static final boolean DEFAULT_VERIFY_ENABLE = true; 366 367 /** 368 * The default maximum time to wait for the verification agent to return in 369 * milliseconds. 370 */ 371 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 372 373 /** 374 * The default response for package verification timeout. 375 * 376 * This can be either PackageManager.VERIFICATION_ALLOW or 377 * PackageManager.VERIFICATION_REJECT. 378 */ 379 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 380 381 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 382 383 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 384 DEFAULT_CONTAINER_PACKAGE, 385 "com.android.defcontainer.DefaultContainerService"); 386 387 private static final String KILL_APP_REASON_GIDS_CHANGED = 388 "permission grant or revoke changed gids"; 389 390 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 391 "permissions revoked"; 392 393 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 394 395 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 396 397 /** Permission grant: not grant the permission. */ 398 private static final int GRANT_DENIED = 1; 399 400 /** Permission grant: grant the permission as an install permission. */ 401 private static final int GRANT_INSTALL = 2; 402 403 /** Permission grant: grant the permission as an install permission for a legacy app. */ 404 private static final int GRANT_INSTALL_LEGACY = 3; 405 406 /** Permission grant: grant the permission as a runtime one. */ 407 private static final int GRANT_RUNTIME = 4; 408 409 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 410 private static final int GRANT_UPGRADE = 5; 411 412 /** Canonical intent used to identify what counts as a "web browser" app */ 413 private static final Intent sBrowserIntent; 414 static { 415 sBrowserIntent = new Intent(); 416 sBrowserIntent.setAction(Intent.ACTION_VIEW); 417 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 418 sBrowserIntent.setData(Uri.parse("http:")); 419 } 420 421 final ServiceThread mHandlerThread; 422 423 final PackageHandler mHandler; 424 425 /** 426 * Messages for {@link #mHandler} that need to wait for system ready before 427 * being dispatched. 428 */ 429 private ArrayList<Message> mPostSystemReadyMessages; 430 431 final int mSdkVersion = Build.VERSION.SDK_INT; 432 433 final Context mContext; 434 final boolean mFactoryTest; 435 final boolean mOnlyCore; 436 final DisplayMetrics mMetrics; 437 final int mDefParseFlags; 438 final String[] mSeparateProcesses; 439 final boolean mIsUpgrade; 440 441 // This is where all application persistent data goes. 442 final File mAppDataDir; 443 444 // This is where all application persistent data goes for secondary users. 445 final File mUserAppDataDir; 446 447 /** The location for ASEC container files on internal storage. */ 448 final String mAsecInternalPath; 449 450 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 451 // LOCK HELD. Can be called with mInstallLock held. 452 @GuardedBy("mInstallLock") 453 final Installer mInstaller; 454 455 /** Directory where installed third-party apps stored */ 456 final File mAppInstallDir; 457 458 /** 459 * Directory to which applications installed internally have their 460 * 32 bit native libraries copied. 461 */ 462 private File mAppLib32InstallDir; 463 464 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 465 // apps. 466 final File mDrmAppPrivateInstallDir; 467 468 // ---------------------------------------------------------------- 469 470 // Lock for state used when installing and doing other long running 471 // operations. Methods that must be called with this lock held have 472 // the suffix "LI". 473 final Object mInstallLock = new Object(); 474 475 // ---------------------------------------------------------------- 476 477 // Keys are String (package name), values are Package. This also serves 478 // as the lock for the global state. Methods that must be called with 479 // this lock held have the prefix "LP". 480 @GuardedBy("mPackages") 481 final ArrayMap<String, PackageParser.Package> mPackages = 482 new ArrayMap<String, PackageParser.Package>(); 483 484 // Tracks available target package names -> overlay package paths. 485 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 486 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 487 488 /** 489 * Tracks new system packages [received in an OTA] that we expect to 490 * find updated user-installed versions. Keys are package name, values 491 * are package location. 492 */ 493 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 494 495 /** 496 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 497 */ 498 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 499 /** 500 * Whether or not system app permissions should be promoted from install to runtime. 501 */ 502 boolean mPromoteSystemApps; 503 504 final Settings mSettings; 505 boolean mRestoredSettings; 506 507 // System configuration read by SystemConfig. 508 final int[] mGlobalGids; 509 final SparseArray<ArraySet<String>> mSystemPermissions; 510 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 511 512 // If mac_permissions.xml was found for seinfo labeling. 513 boolean mFoundPolicyFile; 514 515 // If a recursive restorecon of /data/data/<pkg> is needed. 516 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 517 518 public static final class SharedLibraryEntry { 519 public final String path; 520 public final String apk; 521 522 SharedLibraryEntry(String _path, String _apk) { 523 path = _path; 524 apk = _apk; 525 } 526 } 527 528 // Currently known shared libraries. 529 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 530 new ArrayMap<String, SharedLibraryEntry>(); 531 532 // All available activities, for your resolving pleasure. 533 final ActivityIntentResolver mActivities = 534 new ActivityIntentResolver(); 535 536 // All available receivers, for your resolving pleasure. 537 final ActivityIntentResolver mReceivers = 538 new ActivityIntentResolver(); 539 540 // All available services, for your resolving pleasure. 541 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 542 543 // All available providers, for your resolving pleasure. 544 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 545 546 // Mapping from provider base names (first directory in content URI codePath) 547 // to the provider information. 548 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 549 new ArrayMap<String, PackageParser.Provider>(); 550 551 // Mapping from instrumentation class names to info about them. 552 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 553 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 554 555 // Mapping from permission names to info about them. 556 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 557 new ArrayMap<String, PackageParser.PermissionGroup>(); 558 559 // Packages whose data we have transfered into another package, thus 560 // should no longer exist. 561 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 562 563 // Broadcast actions that are only available to the system. 564 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 565 566 /** List of packages waiting for verification. */ 567 final SparseArray<PackageVerificationState> mPendingVerification 568 = new SparseArray<PackageVerificationState>(); 569 570 /** Set of packages associated with each app op permission. */ 571 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 572 573 final PackageInstallerService mInstallerService; 574 575 private final PackageDexOptimizer mPackageDexOptimizer; 576 577 private AtomicInteger mNextMoveId = new AtomicInteger(); 578 private final MoveCallbacks mMoveCallbacks; 579 580 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 581 582 // Cache of users who need badging. 583 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 584 585 /** Token for keys in mPendingVerification. */ 586 private int mPendingVerificationToken = 0; 587 588 volatile boolean mSystemReady; 589 volatile boolean mSafeMode; 590 volatile boolean mHasSystemUidErrors; 591 592 ApplicationInfo mAndroidApplication; 593 final ActivityInfo mResolveActivity = new ActivityInfo(); 594 final ResolveInfo mResolveInfo = new ResolveInfo(); 595 ComponentName mResolveComponentName; 596 PackageParser.Package mPlatformPackage; 597 ComponentName mCustomResolverComponentName; 598 599 boolean mResolverReplaced = false; 600 601 private final ComponentName mIntentFilterVerifierComponent; 602 private int mIntentFilterVerificationToken = 0; 603 604 /** Component that knows whether or not an ephemeral application exists */ 605 final ComponentName mEphemeralResolverComponent; 606 /** The service connection to the ephemeral resolver */ 607 final EphemeralResolverConnection mEphemeralResolverConnection; 608 609 /** Component used to install ephemeral applications */ 610 final ComponentName mEphemeralInstallerComponent; 611 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 612 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 613 614 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 615 = new SparseArray<IntentFilterVerificationState>(); 616 617 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 618 new DefaultPermissionGrantPolicy(this); 619 620 // List of packages names to keep cached, even if they are uninstalled for all users 621 private List<String> mKeepUninstalledPackages; 622 623 private static class IFVerificationParams { 624 PackageParser.Package pkg; 625 boolean replacing; 626 int userId; 627 int verifierUid; 628 629 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 630 int _userId, int _verifierUid) { 631 pkg = _pkg; 632 replacing = _replacing; 633 userId = _userId; 634 replacing = _replacing; 635 verifierUid = _verifierUid; 636 } 637 } 638 639 private interface IntentFilterVerifier<T extends IntentFilter> { 640 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 641 T filter, String packageName); 642 void startVerifications(int userId); 643 void receiveVerificationResponse(int verificationId); 644 } 645 646 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 647 private Context mContext; 648 private ComponentName mIntentFilterVerifierComponent; 649 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 650 651 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 652 mContext = context; 653 mIntentFilterVerifierComponent = verifierComponent; 654 } 655 656 private String getDefaultScheme() { 657 return IntentFilter.SCHEME_HTTPS; 658 } 659 660 @Override 661 public void startVerifications(int userId) { 662 // Launch verifications requests 663 int count = mCurrentIntentFilterVerifications.size(); 664 for (int n=0; n<count; n++) { 665 int verificationId = mCurrentIntentFilterVerifications.get(n); 666 final IntentFilterVerificationState ivs = 667 mIntentFilterVerificationStates.get(verificationId); 668 669 String packageName = ivs.getPackageName(); 670 671 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 672 final int filterCount = filters.size(); 673 ArraySet<String> domainsSet = new ArraySet<>(); 674 for (int m=0; m<filterCount; m++) { 675 PackageParser.ActivityIntentInfo filter = filters.get(m); 676 domainsSet.addAll(filter.getHostsList()); 677 } 678 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 679 synchronized (mPackages) { 680 if (mSettings.createIntentFilterVerificationIfNeededLPw( 681 packageName, domainsList) != null) { 682 scheduleWriteSettingsLocked(); 683 } 684 } 685 sendVerificationRequest(userId, verificationId, ivs); 686 } 687 mCurrentIntentFilterVerifications.clear(); 688 } 689 690 private void sendVerificationRequest(int userId, int verificationId, 691 IntentFilterVerificationState ivs) { 692 693 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 694 verificationIntent.putExtra( 695 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 696 verificationId); 697 verificationIntent.putExtra( 698 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 699 getDefaultScheme()); 700 verificationIntent.putExtra( 701 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 702 ivs.getHostsString()); 703 verificationIntent.putExtra( 704 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 705 ivs.getPackageName()); 706 verificationIntent.setComponent(mIntentFilterVerifierComponent); 707 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 708 709 UserHandle user = new UserHandle(userId); 710 mContext.sendBroadcastAsUser(verificationIntent, user); 711 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 712 "Sending IntentFilter verification broadcast"); 713 } 714 715 public void receiveVerificationResponse(int verificationId) { 716 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 717 718 final boolean verified = ivs.isVerified(); 719 720 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 721 final int count = filters.size(); 722 if (DEBUG_DOMAIN_VERIFICATION) { 723 Slog.i(TAG, "Received verification response " + verificationId 724 + " for " + count + " filters, verified=" + verified); 725 } 726 for (int n=0; n<count; n++) { 727 PackageParser.ActivityIntentInfo filter = filters.get(n); 728 filter.setVerified(verified); 729 730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 731 + " verified with result:" + verified + " and hosts:" 732 + ivs.getHostsString()); 733 } 734 735 mIntentFilterVerificationStates.remove(verificationId); 736 737 final String packageName = ivs.getPackageName(); 738 IntentFilterVerificationInfo ivi = null; 739 740 synchronized (mPackages) { 741 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 742 } 743 if (ivi == null) { 744 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 745 + verificationId + " packageName:" + packageName); 746 return; 747 } 748 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 749 "Updating IntentFilterVerificationInfo for package " + packageName 750 +" verificationId:" + verificationId); 751 752 synchronized (mPackages) { 753 if (verified) { 754 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 755 } else { 756 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 757 } 758 scheduleWriteSettingsLocked(); 759 760 final int userId = ivs.getUserId(); 761 if (userId != UserHandle.USER_ALL) { 762 final int userStatus = 763 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 764 765 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 766 boolean needUpdate = false; 767 768 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 769 // already been set by the User thru the Disambiguation dialog 770 switch (userStatus) { 771 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 772 if (verified) { 773 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 774 } else { 775 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 776 } 777 needUpdate = true; 778 break; 779 780 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 781 if (verified) { 782 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 783 needUpdate = true; 784 } 785 break; 786 787 default: 788 // Nothing to do 789 } 790 791 if (needUpdate) { 792 mSettings.updateIntentFilterVerificationStatusLPw( 793 packageName, updatedStatus, userId); 794 scheduleWritePackageRestrictionsLocked(userId); 795 } 796 } 797 } 798 } 799 800 @Override 801 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 802 ActivityIntentInfo filter, String packageName) { 803 if (!hasValidDomains(filter)) { 804 return false; 805 } 806 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 807 if (ivs == null) { 808 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 809 packageName); 810 } 811 if (DEBUG_DOMAIN_VERIFICATION) { 812 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 813 } 814 ivs.addFilter(filter); 815 return true; 816 } 817 818 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 819 int userId, int verificationId, String packageName) { 820 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 821 verifierUid, userId, packageName); 822 ivs.setPendingState(); 823 synchronized (mPackages) { 824 mIntentFilterVerificationStates.append(verificationId, ivs); 825 mCurrentIntentFilterVerifications.add(verificationId); 826 } 827 return ivs; 828 } 829 } 830 831 private static boolean hasValidDomains(ActivityIntentInfo filter) { 832 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 833 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 834 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 835 } 836 837 private IntentFilterVerifier mIntentFilterVerifier; 838 839 // Set of pending broadcasts for aggregating enable/disable of components. 840 static class PendingPackageBroadcasts { 841 // for each user id, a map of <package name -> components within that package> 842 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 843 844 public PendingPackageBroadcasts() { 845 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 846 } 847 848 public ArrayList<String> get(int userId, String packageName) { 849 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 850 return packages.get(packageName); 851 } 852 853 public void put(int userId, String packageName, ArrayList<String> components) { 854 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 855 packages.put(packageName, components); 856 } 857 858 public void remove(int userId, String packageName) { 859 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 860 if (packages != null) { 861 packages.remove(packageName); 862 } 863 } 864 865 public void remove(int userId) { 866 mUidMap.remove(userId); 867 } 868 869 public int userIdCount() { 870 return mUidMap.size(); 871 } 872 873 public int userIdAt(int n) { 874 return mUidMap.keyAt(n); 875 } 876 877 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 878 return mUidMap.get(userId); 879 } 880 881 public int size() { 882 // total number of pending broadcast entries across all userIds 883 int num = 0; 884 for (int i = 0; i< mUidMap.size(); i++) { 885 num += mUidMap.valueAt(i).size(); 886 } 887 return num; 888 } 889 890 public void clear() { 891 mUidMap.clear(); 892 } 893 894 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 895 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 896 if (map == null) { 897 map = new ArrayMap<String, ArrayList<String>>(); 898 mUidMap.put(userId, map); 899 } 900 return map; 901 } 902 } 903 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 904 905 // Service Connection to remote media container service to copy 906 // package uri's from external media onto secure containers 907 // or internal storage. 908 private IMediaContainerService mContainerService = null; 909 910 static final int SEND_PENDING_BROADCAST = 1; 911 static final int MCS_BOUND = 3; 912 static final int END_COPY = 4; 913 static final int INIT_COPY = 5; 914 static final int MCS_UNBIND = 6; 915 static final int START_CLEANING_PACKAGE = 7; 916 static final int FIND_INSTALL_LOC = 8; 917 static final int POST_INSTALL = 9; 918 static final int MCS_RECONNECT = 10; 919 static final int MCS_GIVE_UP = 11; 920 static final int UPDATED_MEDIA_STATUS = 12; 921 static final int WRITE_SETTINGS = 13; 922 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 923 static final int PACKAGE_VERIFIED = 15; 924 static final int CHECK_PENDING_VERIFICATION = 16; 925 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 926 static final int INTENT_FILTER_VERIFIED = 18; 927 928 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 929 930 // Delay time in millisecs 931 static final int BROADCAST_DELAY = 10 * 1000; 932 933 static UserManagerService sUserManager; 934 935 // Stores a list of users whose package restrictions file needs to be updated 936 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 937 938 final private DefaultContainerConnection mDefContainerConn = 939 new DefaultContainerConnection(); 940 class DefaultContainerConnection implements ServiceConnection { 941 public void onServiceConnected(ComponentName name, IBinder service) { 942 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 943 IMediaContainerService imcs = 944 IMediaContainerService.Stub.asInterface(service); 945 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 946 } 947 948 public void onServiceDisconnected(ComponentName name) { 949 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 950 } 951 } 952 953 // Recordkeeping of restore-after-install operations that are currently in flight 954 // between the Package Manager and the Backup Manager 955 class PostInstallData { 956 public InstallArgs args; 957 public PackageInstalledInfo res; 958 959 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 960 args = _a; 961 res = _r; 962 } 963 } 964 965 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 966 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 967 968 // XML tags for backup/restore of various bits of state 969 private static final String TAG_PREFERRED_BACKUP = "pa"; 970 private static final String TAG_DEFAULT_APPS = "da"; 971 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 972 973 final String mRequiredVerifierPackage; 974 final String mRequiredInstallerPackage; 975 976 private final PackageUsage mPackageUsage = new PackageUsage(); 977 978 private class PackageUsage { 979 private static final int WRITE_INTERVAL 980 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 981 982 private final Object mFileLock = new Object(); 983 private final AtomicLong mLastWritten = new AtomicLong(0); 984 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 985 986 private boolean mIsHistoricalPackageUsageAvailable = true; 987 988 boolean isHistoricalPackageUsageAvailable() { 989 return mIsHistoricalPackageUsageAvailable; 990 } 991 992 void write(boolean force) { 993 if (force) { 994 writeInternal(); 995 return; 996 } 997 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 998 && !DEBUG_DEXOPT) { 999 return; 1000 } 1001 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1002 new Thread("PackageUsage_DiskWriter") { 1003 @Override 1004 public void run() { 1005 try { 1006 writeInternal(); 1007 } finally { 1008 mBackgroundWriteRunning.set(false); 1009 } 1010 } 1011 }.start(); 1012 } 1013 } 1014 1015 private void writeInternal() { 1016 synchronized (mPackages) { 1017 synchronized (mFileLock) { 1018 AtomicFile file = getFile(); 1019 FileOutputStream f = null; 1020 try { 1021 f = file.startWrite(); 1022 BufferedOutputStream out = new BufferedOutputStream(f); 1023 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1024 StringBuilder sb = new StringBuilder(); 1025 for (PackageParser.Package pkg : mPackages.values()) { 1026 if (pkg.mLastPackageUsageTimeInMills == 0) { 1027 continue; 1028 } 1029 sb.setLength(0); 1030 sb.append(pkg.packageName); 1031 sb.append(' '); 1032 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1033 sb.append('\n'); 1034 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1035 } 1036 out.flush(); 1037 file.finishWrite(f); 1038 } catch (IOException e) { 1039 if (f != null) { 1040 file.failWrite(f); 1041 } 1042 Log.e(TAG, "Failed to write package usage times", e); 1043 } 1044 } 1045 } 1046 mLastWritten.set(SystemClock.elapsedRealtime()); 1047 } 1048 1049 void readLP() { 1050 synchronized (mFileLock) { 1051 AtomicFile file = getFile(); 1052 BufferedInputStream in = null; 1053 try { 1054 in = new BufferedInputStream(file.openRead()); 1055 StringBuffer sb = new StringBuffer(); 1056 while (true) { 1057 String packageName = readToken(in, sb, ' '); 1058 if (packageName == null) { 1059 break; 1060 } 1061 String timeInMillisString = readToken(in, sb, '\n'); 1062 if (timeInMillisString == null) { 1063 throw new IOException("Failed to find last usage time for package " 1064 + packageName); 1065 } 1066 PackageParser.Package pkg = mPackages.get(packageName); 1067 if (pkg == null) { 1068 continue; 1069 } 1070 long timeInMillis; 1071 try { 1072 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1073 } catch (NumberFormatException e) { 1074 throw new IOException("Failed to parse " + timeInMillisString 1075 + " as a long.", e); 1076 } 1077 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1078 } 1079 } catch (FileNotFoundException expected) { 1080 mIsHistoricalPackageUsageAvailable = false; 1081 } catch (IOException e) { 1082 Log.w(TAG, "Failed to read package usage times", e); 1083 } finally { 1084 IoUtils.closeQuietly(in); 1085 } 1086 } 1087 mLastWritten.set(SystemClock.elapsedRealtime()); 1088 } 1089 1090 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1091 throws IOException { 1092 sb.setLength(0); 1093 while (true) { 1094 int ch = in.read(); 1095 if (ch == -1) { 1096 if (sb.length() == 0) { 1097 return null; 1098 } 1099 throw new IOException("Unexpected EOF"); 1100 } 1101 if (ch == endOfToken) { 1102 return sb.toString(); 1103 } 1104 sb.append((char)ch); 1105 } 1106 } 1107 1108 private AtomicFile getFile() { 1109 File dataDir = Environment.getDataDirectory(); 1110 File systemDir = new File(dataDir, "system"); 1111 File fname = new File(systemDir, "package-usage.list"); 1112 return new AtomicFile(fname); 1113 } 1114 } 1115 1116 class PackageHandler extends Handler { 1117 private boolean mBound = false; 1118 final ArrayList<HandlerParams> mPendingInstalls = 1119 new ArrayList<HandlerParams>(); 1120 1121 private boolean connectToService() { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1123 " DefaultContainerService"); 1124 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1126 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1127 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1129 mBound = true; 1130 return true; 1131 } 1132 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1133 return false; 1134 } 1135 1136 private void disconnectService() { 1137 mContainerService = null; 1138 mBound = false; 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1140 mContext.unbindService(mDefContainerConn); 1141 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1142 } 1143 1144 PackageHandler(Looper looper) { 1145 super(looper); 1146 } 1147 1148 public void handleMessage(Message msg) { 1149 try { 1150 doHandleMessage(msg); 1151 } finally { 1152 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1153 } 1154 } 1155 1156 void doHandleMessage(Message msg) { 1157 switch (msg.what) { 1158 case INIT_COPY: { 1159 HandlerParams params = (HandlerParams) msg.obj; 1160 int idx = mPendingInstalls.size(); 1161 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1162 // If a bind was already initiated we dont really 1163 // need to do anything. The pending install 1164 // will be processed later on. 1165 if (!mBound) { 1166 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1167 System.identityHashCode(mHandler)); 1168 // If this is the only one pending we might 1169 // have to bind to the service again. 1170 if (!connectToService()) { 1171 Slog.e(TAG, "Failed to bind to media container service"); 1172 params.serviceError(); 1173 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1174 System.identityHashCode(mHandler)); 1175 if (params.traceMethod != null) { 1176 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1177 params.traceCookie); 1178 } 1179 return; 1180 } else { 1181 // Once we bind to the service, the first 1182 // pending request will be processed. 1183 mPendingInstalls.add(idx, params); 1184 } 1185 } else { 1186 mPendingInstalls.add(idx, params); 1187 // Already bound to the service. Just make 1188 // sure we trigger off processing the first request. 1189 if (idx == 0) { 1190 mHandler.sendEmptyMessage(MCS_BOUND); 1191 } 1192 } 1193 break; 1194 } 1195 case MCS_BOUND: { 1196 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1197 if (msg.obj != null) { 1198 mContainerService = (IMediaContainerService) msg.obj; 1199 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1200 System.identityHashCode(mHandler)); 1201 } 1202 if (mContainerService == null) { 1203 if (!mBound) { 1204 // Something seriously wrong since we are not bound and we are not 1205 // waiting for connection. Bail out. 1206 Slog.e(TAG, "Cannot bind to media container service"); 1207 for (HandlerParams params : mPendingInstalls) { 1208 // Indicate service bind error 1209 params.serviceError(); 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1211 System.identityHashCode(params)); 1212 if (params.traceMethod != null) { 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1214 params.traceMethod, params.traceCookie); 1215 } 1216 return; 1217 } 1218 mPendingInstalls.clear(); 1219 } else { 1220 Slog.w(TAG, "Waiting to connect to media container service"); 1221 } 1222 } else if (mPendingInstalls.size() > 0) { 1223 HandlerParams params = mPendingInstalls.get(0); 1224 if (params != null) { 1225 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1226 System.identityHashCode(params)); 1227 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1228 if (params.startCopy()) { 1229 // We are done... look for more work or to 1230 // go idle. 1231 if (DEBUG_SD_INSTALL) Log.i(TAG, 1232 "Checking for more work or unbind..."); 1233 // Delete pending install 1234 if (mPendingInstalls.size() > 0) { 1235 mPendingInstalls.remove(0); 1236 } 1237 if (mPendingInstalls.size() == 0) { 1238 if (mBound) { 1239 if (DEBUG_SD_INSTALL) Log.i(TAG, 1240 "Posting delayed MCS_UNBIND"); 1241 removeMessages(MCS_UNBIND); 1242 Message ubmsg = obtainMessage(MCS_UNBIND); 1243 // Unbind after a little delay, to avoid 1244 // continual thrashing. 1245 sendMessageDelayed(ubmsg, 10000); 1246 } 1247 } else { 1248 // There are more pending requests in queue. 1249 // Just post MCS_BOUND message to trigger processing 1250 // of next pending install. 1251 if (DEBUG_SD_INSTALL) Log.i(TAG, 1252 "Posting MCS_BOUND for next work"); 1253 mHandler.sendEmptyMessage(MCS_BOUND); 1254 } 1255 } 1256 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1257 } 1258 } else { 1259 // Should never happen ideally. 1260 Slog.w(TAG, "Empty queue"); 1261 } 1262 break; 1263 } 1264 case MCS_RECONNECT: { 1265 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1266 if (mPendingInstalls.size() > 0) { 1267 if (mBound) { 1268 disconnectService(); 1269 } 1270 if (!connectToService()) { 1271 Slog.e(TAG, "Failed to bind to media container service"); 1272 for (HandlerParams params : mPendingInstalls) { 1273 // Indicate service bind error 1274 params.serviceError(); 1275 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1276 System.identityHashCode(params)); 1277 } 1278 mPendingInstalls.clear(); 1279 } 1280 } 1281 break; 1282 } 1283 case MCS_UNBIND: { 1284 // If there is no actual work left, then time to unbind. 1285 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1286 1287 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1288 if (mBound) { 1289 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1290 1291 disconnectService(); 1292 } 1293 } else if (mPendingInstalls.size() > 0) { 1294 // There are more pending requests in queue. 1295 // Just post MCS_BOUND message to trigger processing 1296 // of next pending install. 1297 mHandler.sendEmptyMessage(MCS_BOUND); 1298 } 1299 1300 break; 1301 } 1302 case MCS_GIVE_UP: { 1303 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1304 HandlerParams params = mPendingInstalls.remove(0); 1305 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1306 System.identityHashCode(params)); 1307 break; 1308 } 1309 case SEND_PENDING_BROADCAST: { 1310 String packages[]; 1311 ArrayList<String> components[]; 1312 int size = 0; 1313 int uids[]; 1314 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1315 synchronized (mPackages) { 1316 if (mPendingBroadcasts == null) { 1317 return; 1318 } 1319 size = mPendingBroadcasts.size(); 1320 if (size <= 0) { 1321 // Nothing to be done. Just return 1322 return; 1323 } 1324 packages = new String[size]; 1325 components = new ArrayList[size]; 1326 uids = new int[size]; 1327 int i = 0; // filling out the above arrays 1328 1329 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1330 int packageUserId = mPendingBroadcasts.userIdAt(n); 1331 Iterator<Map.Entry<String, ArrayList<String>>> it 1332 = mPendingBroadcasts.packagesForUserId(packageUserId) 1333 .entrySet().iterator(); 1334 while (it.hasNext() && i < size) { 1335 Map.Entry<String, ArrayList<String>> ent = it.next(); 1336 packages[i] = ent.getKey(); 1337 components[i] = ent.getValue(); 1338 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1339 uids[i] = (ps != null) 1340 ? UserHandle.getUid(packageUserId, ps.appId) 1341 : -1; 1342 i++; 1343 } 1344 } 1345 size = i; 1346 mPendingBroadcasts.clear(); 1347 } 1348 // Send broadcasts 1349 for (int i = 0; i < size; i++) { 1350 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1351 } 1352 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1353 break; 1354 } 1355 case START_CLEANING_PACKAGE: { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1357 final String packageName = (String)msg.obj; 1358 final int userId = msg.arg1; 1359 final boolean andCode = msg.arg2 != 0; 1360 synchronized (mPackages) { 1361 if (userId == UserHandle.USER_ALL) { 1362 int[] users = sUserManager.getUserIds(); 1363 for (int user : users) { 1364 mSettings.addPackageToCleanLPw( 1365 new PackageCleanItem(user, packageName, andCode)); 1366 } 1367 } else { 1368 mSettings.addPackageToCleanLPw( 1369 new PackageCleanItem(userId, packageName, andCode)); 1370 } 1371 } 1372 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1373 startCleaningPackages(); 1374 } break; 1375 case POST_INSTALL: { 1376 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1377 PostInstallData data = mRunningInstalls.get(msg.arg1); 1378 mRunningInstalls.delete(msg.arg1); 1379 boolean deleteOld = false; 1380 1381 if (data != null) { 1382 InstallArgs args = data.args; 1383 PackageInstalledInfo res = data.res; 1384 1385 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1386 final String packageName = res.pkg.applicationInfo.packageName; 1387 res.removedInfo.sendBroadcast(false, true, false); 1388 Bundle extras = new Bundle(1); 1389 extras.putInt(Intent.EXTRA_UID, res.uid); 1390 1391 // Now that we successfully installed the package, grant runtime 1392 // permissions if requested before broadcasting the install. 1393 if ((args.installFlags 1394 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1395 && res.pkg.applicationInfo.targetSdkVersion 1396 >= Build.VERSION_CODES.M) { 1397 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1398 args.installGrantPermissions); 1399 } 1400 1401 // Determine the set of users who are adding this 1402 // package for the first time vs. those who are seeing 1403 // an update. 1404 int[] firstUsers; 1405 int[] updateUsers = new int[0]; 1406 if (res.origUsers == null || res.origUsers.length == 0) { 1407 firstUsers = res.newUsers; 1408 } else { 1409 firstUsers = new int[0]; 1410 for (int i=0; i<res.newUsers.length; i++) { 1411 int user = res.newUsers[i]; 1412 boolean isNew = true; 1413 for (int j=0; j<res.origUsers.length; j++) { 1414 if (res.origUsers[j] == user) { 1415 isNew = false; 1416 break; 1417 } 1418 } 1419 if (isNew) { 1420 int[] newFirst = new int[firstUsers.length+1]; 1421 System.arraycopy(firstUsers, 0, newFirst, 0, 1422 firstUsers.length); 1423 newFirst[firstUsers.length] = user; 1424 firstUsers = newFirst; 1425 } else { 1426 int[] newUpdate = new int[updateUsers.length+1]; 1427 System.arraycopy(updateUsers, 0, newUpdate, 0, 1428 updateUsers.length); 1429 newUpdate[updateUsers.length] = user; 1430 updateUsers = newUpdate; 1431 } 1432 } 1433 } 1434 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1435 packageName, extras, 0, null, null, firstUsers); 1436 final boolean update = res.removedInfo.removedPackage != null; 1437 if (update) { 1438 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1439 } 1440 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1441 packageName, extras, 0, null, null, updateUsers); 1442 if (update) { 1443 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1444 packageName, extras, 0, null, null, updateUsers); 1445 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1446 null, null, 0, packageName, null, updateUsers); 1447 1448 // treat asec-hosted packages like removable media on upgrade 1449 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1450 if (DEBUG_INSTALL) { 1451 Slog.i(TAG, "upgrading pkg " + res.pkg 1452 + " is ASEC-hosted -> AVAILABLE"); 1453 } 1454 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1455 ArrayList<String> pkgList = new ArrayList<String>(1); 1456 pkgList.add(packageName); 1457 sendResourcesChangedBroadcast(true, true, 1458 pkgList,uidArray, null); 1459 } 1460 } 1461 if (res.removedInfo.args != null) { 1462 // Remove the replaced package's older resources safely now 1463 deleteOld = true; 1464 } 1465 1466 // If this app is a browser and it's newly-installed for some 1467 // users, clear any default-browser state in those users 1468 if (firstUsers.length > 0) { 1469 // the app's nature doesn't depend on the user, so we can just 1470 // check its browser nature in any user and generalize. 1471 if (packageIsBrowser(packageName, firstUsers[0])) { 1472 synchronized (mPackages) { 1473 for (int userId : firstUsers) { 1474 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1475 } 1476 } 1477 } 1478 } 1479 // Log current value of "unknown sources" setting 1480 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1481 getUnknownSourcesSettings()); 1482 } 1483 // Force a gc to clear up things 1484 Runtime.getRuntime().gc(); 1485 // We delete after a gc for applications on sdcard. 1486 if (deleteOld) { 1487 synchronized (mInstallLock) { 1488 res.removedInfo.args.doPostDeleteLI(true); 1489 } 1490 } 1491 if (args.observer != null) { 1492 try { 1493 Bundle extras = extrasForInstallResult(res); 1494 args.observer.onPackageInstalled(res.name, res.returnCode, 1495 res.returnMsg, extras); 1496 } catch (RemoteException e) { 1497 Slog.i(TAG, "Observer no longer exists."); 1498 } 1499 } 1500 if (args.traceMethod != null) { 1501 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1502 args.traceCookie); 1503 } 1504 return; 1505 } else { 1506 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1507 } 1508 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1510 } break; 1511 case UPDATED_MEDIA_STATUS: { 1512 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1513 boolean reportStatus = msg.arg1 == 1; 1514 boolean doGc = msg.arg2 == 1; 1515 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1516 if (doGc) { 1517 // Force a gc to clear up stale containers. 1518 Runtime.getRuntime().gc(); 1519 } 1520 if (msg.obj != null) { 1521 @SuppressWarnings("unchecked") 1522 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1523 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1524 // Unload containers 1525 unloadAllContainers(args); 1526 } 1527 if (reportStatus) { 1528 try { 1529 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1530 PackageHelper.getMountService().finishMediaUpdate(); 1531 } catch (RemoteException e) { 1532 Log.e(TAG, "MountService not running?"); 1533 } 1534 } 1535 } break; 1536 case WRITE_SETTINGS: { 1537 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1538 synchronized (mPackages) { 1539 removeMessages(WRITE_SETTINGS); 1540 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1541 mSettings.writeLPr(); 1542 mDirtyUsers.clear(); 1543 } 1544 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1545 } break; 1546 case WRITE_PACKAGE_RESTRICTIONS: { 1547 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1548 synchronized (mPackages) { 1549 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1550 for (int userId : mDirtyUsers) { 1551 mSettings.writePackageRestrictionsLPr(userId); 1552 } 1553 mDirtyUsers.clear(); 1554 } 1555 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1556 } break; 1557 case CHECK_PENDING_VERIFICATION: { 1558 final int verificationId = msg.arg1; 1559 final PackageVerificationState state = mPendingVerification.get(verificationId); 1560 1561 if ((state != null) && !state.timeoutExtended()) { 1562 final InstallArgs args = state.getInstallArgs(); 1563 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1564 1565 Slog.i(TAG, "Verification timed out for " + originUri); 1566 mPendingVerification.remove(verificationId); 1567 1568 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1569 1570 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1571 Slog.i(TAG, "Continuing with installation of " + originUri); 1572 state.setVerifierResponse(Binder.getCallingUid(), 1573 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1574 broadcastPackageVerified(verificationId, originUri, 1575 PackageManager.VERIFICATION_ALLOW, 1576 state.getInstallArgs().getUser()); 1577 try { 1578 ret = args.copyApk(mContainerService, true); 1579 } catch (RemoteException e) { 1580 Slog.e(TAG, "Could not contact the ContainerService"); 1581 } 1582 } else { 1583 broadcastPackageVerified(verificationId, originUri, 1584 PackageManager.VERIFICATION_REJECT, 1585 state.getInstallArgs().getUser()); 1586 } 1587 1588 Trace.asyncTraceEnd( 1589 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1590 1591 processPendingInstall(args, ret); 1592 mHandler.sendEmptyMessage(MCS_UNBIND); 1593 } 1594 break; 1595 } 1596 case PACKAGE_VERIFIED: { 1597 final int verificationId = msg.arg1; 1598 1599 final PackageVerificationState state = mPendingVerification.get(verificationId); 1600 if (state == null) { 1601 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1602 break; 1603 } 1604 1605 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1606 1607 state.setVerifierResponse(response.callerUid, response.code); 1608 1609 if (state.isVerificationComplete()) { 1610 mPendingVerification.remove(verificationId); 1611 1612 final InstallArgs args = state.getInstallArgs(); 1613 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1614 1615 int ret; 1616 if (state.isInstallAllowed()) { 1617 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1618 broadcastPackageVerified(verificationId, originUri, 1619 response.code, state.getInstallArgs().getUser()); 1620 try { 1621 ret = args.copyApk(mContainerService, true); 1622 } catch (RemoteException e) { 1623 Slog.e(TAG, "Could not contact the ContainerService"); 1624 } 1625 } else { 1626 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1627 } 1628 1629 Trace.asyncTraceEnd( 1630 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1631 1632 processPendingInstall(args, ret); 1633 mHandler.sendEmptyMessage(MCS_UNBIND); 1634 } 1635 1636 break; 1637 } 1638 case START_INTENT_FILTER_VERIFICATIONS: { 1639 IFVerificationParams params = (IFVerificationParams) msg.obj; 1640 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1641 params.replacing, params.pkg); 1642 break; 1643 } 1644 case INTENT_FILTER_VERIFIED: { 1645 final int verificationId = msg.arg1; 1646 1647 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1648 verificationId); 1649 if (state == null) { 1650 Slog.w(TAG, "Invalid IntentFilter verification token " 1651 + verificationId + " received"); 1652 break; 1653 } 1654 1655 final int userId = state.getUserId(); 1656 1657 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1658 "Processing IntentFilter verification with token:" 1659 + verificationId + " and userId:" + userId); 1660 1661 final IntentFilterVerificationResponse response = 1662 (IntentFilterVerificationResponse) msg.obj; 1663 1664 state.setVerifierResponse(response.callerUid, response.code); 1665 1666 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1667 "IntentFilter verification with token:" + verificationId 1668 + " and userId:" + userId 1669 + " is settings verifier response with response code:" 1670 + response.code); 1671 1672 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1673 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1674 + response.getFailedDomainsString()); 1675 } 1676 1677 if (state.isVerificationComplete()) { 1678 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1679 } else { 1680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1681 "IntentFilter verification with token:" + verificationId 1682 + " was not said to be complete"); 1683 } 1684 1685 break; 1686 } 1687 } 1688 } 1689 } 1690 1691 private StorageEventListener mStorageListener = new StorageEventListener() { 1692 @Override 1693 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1694 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1695 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1696 final String volumeUuid = vol.getFsUuid(); 1697 1698 // Clean up any users or apps that were removed or recreated 1699 // while this volume was missing 1700 reconcileUsers(volumeUuid); 1701 reconcileApps(volumeUuid); 1702 1703 // Clean up any install sessions that expired or were 1704 // cancelled while this volume was missing 1705 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1706 1707 loadPrivatePackages(vol); 1708 1709 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1710 unloadPrivatePackages(vol); 1711 } 1712 } 1713 1714 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1715 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1716 updateExternalMediaStatus(true, false); 1717 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1718 updateExternalMediaStatus(false, false); 1719 } 1720 } 1721 } 1722 1723 @Override 1724 public void onVolumeForgotten(String fsUuid) { 1725 if (TextUtils.isEmpty(fsUuid)) { 1726 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1727 return; 1728 } 1729 1730 // Remove any apps installed on the forgotten volume 1731 synchronized (mPackages) { 1732 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1733 for (PackageSetting ps : packages) { 1734 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1735 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1736 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1737 } 1738 1739 mSettings.onVolumeForgotten(fsUuid); 1740 mSettings.writeLPr(); 1741 } 1742 } 1743 }; 1744 1745 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1746 String[] grantedPermissions) { 1747 if (userId >= UserHandle.USER_SYSTEM) { 1748 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1749 } else if (userId == UserHandle.USER_ALL) { 1750 final int[] userIds; 1751 synchronized (mPackages) { 1752 userIds = UserManagerService.getInstance().getUserIds(); 1753 } 1754 for (int someUserId : userIds) { 1755 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1756 } 1757 } 1758 1759 // We could have touched GID membership, so flush out packages.list 1760 synchronized (mPackages) { 1761 mSettings.writePackageListLPr(); 1762 } 1763 } 1764 1765 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1766 String[] grantedPermissions) { 1767 SettingBase sb = (SettingBase) pkg.mExtras; 1768 if (sb == null) { 1769 return; 1770 } 1771 1772 PermissionsState permissionsState = sb.getPermissionsState(); 1773 1774 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1775 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1776 1777 synchronized (mPackages) { 1778 for (String permission : pkg.requestedPermissions) { 1779 BasePermission bp = mSettings.mPermissions.get(permission); 1780 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1781 && (grantedPermissions == null 1782 || ArrayUtils.contains(grantedPermissions, permission))) { 1783 final int flags = permissionsState.getPermissionFlags(permission, userId); 1784 // Installer cannot change immutable permissions. 1785 if ((flags & immutableFlags) == 0) { 1786 grantRuntimePermission(pkg.packageName, permission, userId); 1787 } 1788 } 1789 } 1790 } 1791 } 1792 1793 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1794 Bundle extras = null; 1795 switch (res.returnCode) { 1796 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1797 extras = new Bundle(); 1798 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1799 res.origPermission); 1800 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1801 res.origPackage); 1802 break; 1803 } 1804 case PackageManager.INSTALL_SUCCEEDED: { 1805 extras = new Bundle(); 1806 extras.putBoolean(Intent.EXTRA_REPLACING, 1807 res.removedInfo != null && res.removedInfo.removedPackage != null); 1808 break; 1809 } 1810 } 1811 return extras; 1812 } 1813 1814 void scheduleWriteSettingsLocked() { 1815 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1816 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1817 } 1818 } 1819 1820 void scheduleWritePackageRestrictionsLocked(int userId) { 1821 if (!sUserManager.exists(userId)) return; 1822 mDirtyUsers.add(userId); 1823 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1824 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1825 } 1826 } 1827 1828 public static PackageManagerService main(Context context, Installer installer, 1829 boolean factoryTest, boolean onlyCore) { 1830 PackageManagerService m = new PackageManagerService(context, installer, 1831 factoryTest, onlyCore); 1832 m.enableSystemUserApps(); 1833 ServiceManager.addService("package", m); 1834 return m; 1835 } 1836 1837 private void enableSystemUserApps() { 1838 if (!UserManager.isSplitSystemUser()) { 1839 return; 1840 } 1841 // For system user, enable apps based on the following conditions: 1842 // - app is whitelisted or belong to one of these groups: 1843 // -- system app which has no launcher icons 1844 // -- system app which has INTERACT_ACROSS_USERS permission 1845 // -- system IME app 1846 // - app is not in the blacklist 1847 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1848 Set<String> enableApps = new ArraySet<>(); 1849 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1850 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1851 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1852 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1853 enableApps.addAll(wlApps); 1854 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1855 enableApps.removeAll(blApps); 1856 1857 List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true, 1858 UserHandle.SYSTEM); 1859 final int systemAppsSize = systemApps.size(); 1860 synchronized (mPackages) { 1861 for (int i = 0; i < systemAppsSize; i++) { 1862 String pName = systemApps.get(i); 1863 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1864 // Should not happen, but we shouldn't be failing if it does 1865 if (pkgSetting == null) { 1866 continue; 1867 } 1868 boolean installed = enableApps.contains(pName); 1869 pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM); 1870 } 1871 } 1872 } 1873 1874 static String[] splitString(String str, char sep) { 1875 int count = 1; 1876 int i = 0; 1877 while ((i=str.indexOf(sep, i)) >= 0) { 1878 count++; 1879 i++; 1880 } 1881 1882 String[] res = new String[count]; 1883 i=0; 1884 count = 0; 1885 int lastI=0; 1886 while ((i=str.indexOf(sep, i)) >= 0) { 1887 res[count] = str.substring(lastI, i); 1888 count++; 1889 i++; 1890 lastI = i; 1891 } 1892 res[count] = str.substring(lastI, str.length()); 1893 return res; 1894 } 1895 1896 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1897 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1898 Context.DISPLAY_SERVICE); 1899 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1900 } 1901 1902 public PackageManagerService(Context context, Installer installer, 1903 boolean factoryTest, boolean onlyCore) { 1904 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1905 SystemClock.uptimeMillis()); 1906 1907 if (mSdkVersion <= 0) { 1908 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1909 } 1910 1911 mContext = context; 1912 mFactoryTest = factoryTest; 1913 mOnlyCore = onlyCore; 1914 mMetrics = new DisplayMetrics(); 1915 mSettings = new Settings(mPackages); 1916 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1917 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1918 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1919 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1920 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1921 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1922 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1923 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1924 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1925 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1926 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1927 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1928 1929 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1930 if (separateProcesses != null && separateProcesses.length() > 0) { 1931 if ("*".equals(separateProcesses)) { 1932 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1933 mSeparateProcesses = null; 1934 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1935 } else { 1936 mDefParseFlags = 0; 1937 mSeparateProcesses = separateProcesses.split(","); 1938 Slog.w(TAG, "Running with debug.separate_processes: " 1939 + separateProcesses); 1940 } 1941 } else { 1942 mDefParseFlags = 0; 1943 mSeparateProcesses = null; 1944 } 1945 1946 mInstaller = installer; 1947 mPackageDexOptimizer = new PackageDexOptimizer(this); 1948 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1949 1950 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1951 FgThread.get().getLooper()); 1952 1953 getDefaultDisplayMetrics(context, mMetrics); 1954 1955 SystemConfig systemConfig = SystemConfig.getInstance(); 1956 mGlobalGids = systemConfig.getGlobalGids(); 1957 mSystemPermissions = systemConfig.getSystemPermissions(); 1958 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1959 1960 synchronized (mInstallLock) { 1961 // writer 1962 synchronized (mPackages) { 1963 mHandlerThread = new ServiceThread(TAG, 1964 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1965 mHandlerThread.start(); 1966 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1967 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1968 1969 File dataDir = Environment.getDataDirectory(); 1970 mAppDataDir = new File(dataDir, "data"); 1971 mAppInstallDir = new File(dataDir, "app"); 1972 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1973 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1974 mUserAppDataDir = new File(dataDir, "user"); 1975 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1976 1977 sUserManager = new UserManagerService(context, this, mPackages); 1978 1979 // Propagate permission configuration in to package manager. 1980 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1981 = systemConfig.getPermissions(); 1982 for (int i=0; i<permConfig.size(); i++) { 1983 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1984 BasePermission bp = mSettings.mPermissions.get(perm.name); 1985 if (bp == null) { 1986 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1987 mSettings.mPermissions.put(perm.name, bp); 1988 } 1989 if (perm.gids != null) { 1990 bp.setGids(perm.gids, perm.perUser); 1991 } 1992 } 1993 1994 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1995 for (int i=0; i<libConfig.size(); i++) { 1996 mSharedLibraries.put(libConfig.keyAt(i), 1997 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1998 } 1999 2000 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2001 2002 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2003 2004 String customResolverActivity = Resources.getSystem().getString( 2005 R.string.config_customResolverActivity); 2006 if (TextUtils.isEmpty(customResolverActivity)) { 2007 customResolverActivity = null; 2008 } else { 2009 mCustomResolverComponentName = ComponentName.unflattenFromString( 2010 customResolverActivity); 2011 } 2012 2013 long startTime = SystemClock.uptimeMillis(); 2014 2015 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2016 startTime); 2017 2018 // Set flag to monitor and not change apk file paths when 2019 // scanning install directories. 2020 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2021 2022 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2023 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2024 2025 if (bootClassPath == null) { 2026 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2027 } 2028 2029 if (systemServerClassPath == null) { 2030 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2031 } 2032 2033 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2034 final String[] dexCodeInstructionSets = 2035 getDexCodeInstructionSets( 2036 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2037 2038 /** 2039 * Ensure all external libraries have had dexopt run on them. 2040 */ 2041 if (mSharedLibraries.size() > 0) { 2042 // NOTE: For now, we're compiling these system "shared libraries" 2043 // (and framework jars) into all available architectures. It's possible 2044 // to compile them only when we come across an app that uses them (there's 2045 // already logic for that in scanPackageLI) but that adds some complexity. 2046 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2047 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2048 final String lib = libEntry.path; 2049 if (lib == null) { 2050 continue; 2051 } 2052 2053 try { 2054 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2055 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2056 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2057 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2058 } 2059 } catch (FileNotFoundException e) { 2060 Slog.w(TAG, "Library not found: " + lib); 2061 } catch (IOException e) { 2062 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2063 + e.getMessage()); 2064 } 2065 } 2066 } 2067 } 2068 2069 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2070 2071 final VersionInfo ver = mSettings.getInternalVersion(); 2072 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2073 // when upgrading from pre-M, promote system app permissions from install to runtime 2074 mPromoteSystemApps = 2075 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2076 2077 // save off the names of pre-existing system packages prior to scanning; we don't 2078 // want to automatically grant runtime permissions for new system apps 2079 if (mPromoteSystemApps) { 2080 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2081 while (pkgSettingIter.hasNext()) { 2082 PackageSetting ps = pkgSettingIter.next(); 2083 if (isSystemApp(ps)) { 2084 mExistingSystemPackages.add(ps.name); 2085 } 2086 } 2087 } 2088 2089 // Collect vendor overlay packages. 2090 // (Do this before scanning any apps.) 2091 // For security and version matching reason, only consider 2092 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2093 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2094 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2095 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2096 2097 // Find base frameworks (resource packages without code). 2098 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2099 | PackageParser.PARSE_IS_SYSTEM_DIR 2100 | PackageParser.PARSE_IS_PRIVILEGED, 2101 scanFlags | SCAN_NO_DEX, 0); 2102 2103 // Collected privileged system packages. 2104 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2105 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2106 | PackageParser.PARSE_IS_SYSTEM_DIR 2107 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2108 2109 // Collect ordinary system packages. 2110 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2111 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2112 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2113 2114 // Collect all vendor packages. 2115 File vendorAppDir = new File("/vendor/app"); 2116 try { 2117 vendorAppDir = vendorAppDir.getCanonicalFile(); 2118 } catch (IOException e) { 2119 // failed to look up canonical path, continue with original one 2120 } 2121 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2122 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2123 2124 // Collect all OEM packages. 2125 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2126 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2127 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2128 2129 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2130 mInstaller.moveFiles(); 2131 2132 // Prune any system packages that no longer exist. 2133 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2134 if (!mOnlyCore) { 2135 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2136 while (psit.hasNext()) { 2137 PackageSetting ps = psit.next(); 2138 2139 /* 2140 * If this is not a system app, it can't be a 2141 * disable system app. 2142 */ 2143 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2144 continue; 2145 } 2146 2147 /* 2148 * If the package is scanned, it's not erased. 2149 */ 2150 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2151 if (scannedPkg != null) { 2152 /* 2153 * If the system app is both scanned and in the 2154 * disabled packages list, then it must have been 2155 * added via OTA. Remove it from the currently 2156 * scanned package so the previously user-installed 2157 * application can be scanned. 2158 */ 2159 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2160 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2161 + ps.name + "; removing system app. Last known codePath=" 2162 + ps.codePathString + ", installStatus=" + ps.installStatus 2163 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2164 + scannedPkg.mVersionCode); 2165 removePackageLI(ps, true); 2166 mExpectingBetter.put(ps.name, ps.codePath); 2167 } 2168 2169 continue; 2170 } 2171 2172 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2173 psit.remove(); 2174 logCriticalInfo(Log.WARN, "System package " + ps.name 2175 + " no longer exists; wiping its data"); 2176 removeDataDirsLI(null, ps.name); 2177 } else { 2178 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2179 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2180 possiblyDeletedUpdatedSystemApps.add(ps.name); 2181 } 2182 } 2183 } 2184 } 2185 2186 //look for any incomplete package installations 2187 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2188 //clean up list 2189 for(int i = 0; i < deletePkgsList.size(); i++) { 2190 //clean up here 2191 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2192 } 2193 //delete tmp files 2194 deleteTempPackageFiles(); 2195 2196 // Remove any shared userIDs that have no associated packages 2197 mSettings.pruneSharedUsersLPw(); 2198 2199 if (!mOnlyCore) { 2200 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2201 SystemClock.uptimeMillis()); 2202 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2203 2204 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2205 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2206 2207 /** 2208 * Remove disable package settings for any updated system 2209 * apps that were removed via an OTA. If they're not a 2210 * previously-updated app, remove them completely. 2211 * Otherwise, just revoke their system-level permissions. 2212 */ 2213 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2214 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2215 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2216 2217 String msg; 2218 if (deletedPkg == null) { 2219 msg = "Updated system package " + deletedAppName 2220 + " no longer exists; wiping its data"; 2221 removeDataDirsLI(null, deletedAppName); 2222 } else { 2223 msg = "Updated system app + " + deletedAppName 2224 + " no longer present; removing system privileges for " 2225 + deletedAppName; 2226 2227 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2228 2229 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2230 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2231 } 2232 logCriticalInfo(Log.WARN, msg); 2233 } 2234 2235 /** 2236 * Make sure all system apps that we expected to appear on 2237 * the userdata partition actually showed up. If they never 2238 * appeared, crawl back and revive the system version. 2239 */ 2240 for (int i = 0; i < mExpectingBetter.size(); i++) { 2241 final String packageName = mExpectingBetter.keyAt(i); 2242 if (!mPackages.containsKey(packageName)) { 2243 final File scanFile = mExpectingBetter.valueAt(i); 2244 2245 logCriticalInfo(Log.WARN, "Expected better " + packageName 2246 + " but never showed up; reverting to system"); 2247 2248 final int reparseFlags; 2249 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2250 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2251 | PackageParser.PARSE_IS_SYSTEM_DIR 2252 | PackageParser.PARSE_IS_PRIVILEGED; 2253 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2254 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2255 | PackageParser.PARSE_IS_SYSTEM_DIR; 2256 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2257 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2258 | PackageParser.PARSE_IS_SYSTEM_DIR; 2259 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2260 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2261 | PackageParser.PARSE_IS_SYSTEM_DIR; 2262 } else { 2263 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2264 continue; 2265 } 2266 2267 mSettings.enableSystemPackageLPw(packageName); 2268 2269 try { 2270 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2271 } catch (PackageManagerException e) { 2272 Slog.e(TAG, "Failed to parse original system package: " 2273 + e.getMessage()); 2274 } 2275 } 2276 } 2277 } 2278 mExpectingBetter.clear(); 2279 2280 // Now that we know all of the shared libraries, update all clients to have 2281 // the correct library paths. 2282 updateAllSharedLibrariesLPw(); 2283 2284 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2285 // NOTE: We ignore potential failures here during a system scan (like 2286 // the rest of the commands above) because there's precious little we 2287 // can do about it. A settings error is reported, though. 2288 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2289 false /* boot complete */); 2290 } 2291 2292 // Now that we know all the packages we are keeping, 2293 // read and update their last usage times. 2294 mPackageUsage.readLP(); 2295 2296 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2297 SystemClock.uptimeMillis()); 2298 Slog.i(TAG, "Time to scan packages: " 2299 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2300 + " seconds"); 2301 2302 // If the platform SDK has changed since the last time we booted, 2303 // we need to re-grant app permission to catch any new ones that 2304 // appear. This is really a hack, and means that apps can in some 2305 // cases get permissions that the user didn't initially explicitly 2306 // allow... it would be nice to have some better way to handle 2307 // this situation. 2308 int updateFlags = UPDATE_PERMISSIONS_ALL; 2309 if (ver.sdkVersion != mSdkVersion) { 2310 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2311 + mSdkVersion + "; regranting permissions for internal storage"); 2312 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2313 } 2314 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2315 ver.sdkVersion = mSdkVersion; 2316 2317 // If this is the first boot or an update from pre-M, and it is a normal 2318 // boot, then we need to initialize the default preferred apps across 2319 // all defined users. 2320 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2321 for (UserInfo user : sUserManager.getUsers(true)) { 2322 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2323 applyFactoryDefaultBrowserLPw(user.id); 2324 primeDomainVerificationsLPw(user.id); 2325 } 2326 } 2327 2328 // If this is first boot after an OTA, and a normal boot, then 2329 // we need to clear code cache directories. 2330 if (mIsUpgrade && !onlyCore) { 2331 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2332 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2333 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2334 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2335 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2336 } 2337 } 2338 ver.fingerprint = Build.FINGERPRINT; 2339 } 2340 2341 checkDefaultBrowser(); 2342 2343 // clear only after permissions and other defaults have been updated 2344 mExistingSystemPackages.clear(); 2345 mPromoteSystemApps = false; 2346 2347 // All the changes are done during package scanning. 2348 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2349 2350 // can downgrade to reader 2351 mSettings.writeLPr(); 2352 2353 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2354 SystemClock.uptimeMillis()); 2355 2356 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2357 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2358 2359 mInstallerService = new PackageInstallerService(context, this); 2360 2361 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2362 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2363 mIntentFilterVerifierComponent); 2364 2365 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2366 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2367 // both the installer and resolver must be present to enable ephemeral 2368 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2369 if (DEBUG_EPHEMERAL) { 2370 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2371 + " installer:" + ephemeralInstallerComponent); 2372 } 2373 mEphemeralResolverComponent = ephemeralResolverComponent; 2374 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2375 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2376 mEphemeralResolverConnection = 2377 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2378 } else { 2379 if (DEBUG_EPHEMERAL) { 2380 final String missingComponent = 2381 (ephemeralResolverComponent == null) 2382 ? (ephemeralInstallerComponent == null) 2383 ? "resolver and installer" 2384 : "resolver" 2385 : "installer"; 2386 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2387 } 2388 mEphemeralResolverComponent = null; 2389 mEphemeralInstallerComponent = null; 2390 mEphemeralResolverConnection = null; 2391 } 2392 } // synchronized (mPackages) 2393 } // synchronized (mInstallLock) 2394 2395 // Now after opening every single application zip, make sure they 2396 // are all flushed. Not really needed, but keeps things nice and 2397 // tidy. 2398 Runtime.getRuntime().gc(); 2399 2400 // The initial scanning above does many calls into installd while 2401 // holding the mPackages lock, but we're mostly interested in yelling 2402 // once we have a booted system. 2403 mInstaller.setWarnIfHeld(mPackages); 2404 2405 // Expose private service for system components to use. 2406 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2407 } 2408 2409 @Override 2410 public boolean isFirstBoot() { 2411 return !mRestoredSettings; 2412 } 2413 2414 @Override 2415 public boolean isOnlyCoreApps() { 2416 return mOnlyCore; 2417 } 2418 2419 @Override 2420 public boolean isUpgrade() { 2421 return mIsUpgrade; 2422 } 2423 2424 private String getRequiredVerifierLPr() { 2425 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2426 // We only care about verifier that's installed under system user. 2427 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2428 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2429 2430 String requiredVerifier = null; 2431 2432 final int N = receivers.size(); 2433 for (int i = 0; i < N; i++) { 2434 final ResolveInfo info = receivers.get(i); 2435 2436 if (info.activityInfo == null) { 2437 continue; 2438 } 2439 2440 final String packageName = info.activityInfo.packageName; 2441 2442 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2443 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2444 continue; 2445 } 2446 2447 if (requiredVerifier != null) { 2448 throw new RuntimeException("There can be only one required verifier"); 2449 } 2450 2451 requiredVerifier = packageName; 2452 } 2453 2454 return requiredVerifier; 2455 } 2456 2457 private String getRequiredInstallerLPr() { 2458 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2459 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2460 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2461 2462 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2463 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2464 2465 String requiredInstaller = null; 2466 2467 final int N = installers.size(); 2468 for (int i = 0; i < N; i++) { 2469 final ResolveInfo info = installers.get(i); 2470 final String packageName = info.activityInfo.packageName; 2471 2472 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2473 continue; 2474 } 2475 2476 if (requiredInstaller != null) { 2477 throw new RuntimeException("There must be one required installer"); 2478 } 2479 2480 requiredInstaller = packageName; 2481 } 2482 2483 if (requiredInstaller == null) { 2484 throw new RuntimeException("There must be one required installer"); 2485 } 2486 2487 return requiredInstaller; 2488 } 2489 2490 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2491 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2492 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2493 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2494 2495 ComponentName verifierComponentName = null; 2496 2497 int priority = -1000; 2498 final int N = receivers.size(); 2499 for (int i = 0; i < N; i++) { 2500 final ResolveInfo info = receivers.get(i); 2501 2502 if (info.activityInfo == null) { 2503 continue; 2504 } 2505 2506 final String packageName = info.activityInfo.packageName; 2507 2508 final PackageSetting ps = mSettings.mPackages.get(packageName); 2509 if (ps == null) { 2510 continue; 2511 } 2512 2513 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2514 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2515 continue; 2516 } 2517 2518 // Select the IntentFilterVerifier with the highest priority 2519 if (priority < info.priority) { 2520 priority = info.priority; 2521 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2522 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2523 + verifierComponentName + " with priority: " + info.priority); 2524 } 2525 } 2526 2527 return verifierComponentName; 2528 } 2529 2530 private ComponentName getEphemeralResolverLPr() { 2531 final String[] packageArray = 2532 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2533 if (packageArray.length == 0) { 2534 if (DEBUG_EPHEMERAL) { 2535 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2536 } 2537 return null; 2538 } 2539 2540 Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2541 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, 2542 null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM); 2543 2544 final int N = resolvers.size(); 2545 if (N == 0) { 2546 if (DEBUG_EPHEMERAL) { 2547 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2548 } 2549 return null; 2550 } 2551 2552 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2553 for (int i = 0; i < N; i++) { 2554 final ResolveInfo info = resolvers.get(i); 2555 2556 if (info.serviceInfo == null) { 2557 continue; 2558 } 2559 2560 final String packageName = info.serviceInfo.packageName; 2561 if (!possiblePackages.contains(packageName)) { 2562 if (DEBUG_EPHEMERAL) { 2563 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2564 + " pkg: " + packageName + ", info:" + info); 2565 } 2566 continue; 2567 } 2568 2569 if (DEBUG_EPHEMERAL) { 2570 Slog.v(TAG, "Ephemeral resolver found;" 2571 + " pkg: " + packageName + ", info:" + info); 2572 } 2573 return new ComponentName(packageName, info.serviceInfo.name); 2574 } 2575 if (DEBUG_EPHEMERAL) { 2576 Slog.v(TAG, "Ephemeral resolver NOT found"); 2577 } 2578 return null; 2579 } 2580 2581 private ComponentName getEphemeralInstallerLPr() { 2582 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2583 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2584 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2585 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2586 PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/); 2587 2588 ComponentName ephemeralInstaller = null; 2589 2590 final int N = installers.size(); 2591 for (int i = 0; i < N; i++) { 2592 final ResolveInfo info = installers.get(i); 2593 final String packageName = info.activityInfo.packageName; 2594 2595 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2596 if (DEBUG_EPHEMERAL) { 2597 Slog.d(TAG, "Ephemeral installer is not system app;" 2598 + " pkg: " + packageName + ", info:" + info); 2599 } 2600 continue; 2601 } 2602 2603 if (ephemeralInstaller != null) { 2604 throw new RuntimeException("There must only be one ephemeral installer"); 2605 } 2606 2607 ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name); 2608 } 2609 2610 return ephemeralInstaller; 2611 } 2612 2613 private void primeDomainVerificationsLPw(int userId) { 2614 if (DEBUG_DOMAIN_VERIFICATION) { 2615 Slog.d(TAG, "Priming domain verifications in user " + userId); 2616 } 2617 2618 SystemConfig systemConfig = SystemConfig.getInstance(); 2619 ArraySet<String> packages = systemConfig.getLinkedApps(); 2620 ArraySet<String> domains = new ArraySet<String>(); 2621 2622 for (String packageName : packages) { 2623 PackageParser.Package pkg = mPackages.get(packageName); 2624 if (pkg != null) { 2625 if (!pkg.isSystemApp()) { 2626 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2627 continue; 2628 } 2629 2630 domains.clear(); 2631 for (PackageParser.Activity a : pkg.activities) { 2632 for (ActivityIntentInfo filter : a.intents) { 2633 if (hasValidDomains(filter)) { 2634 domains.addAll(filter.getHostsList()); 2635 } 2636 } 2637 } 2638 2639 if (domains.size() > 0) { 2640 if (DEBUG_DOMAIN_VERIFICATION) { 2641 Slog.v(TAG, " + " + packageName); 2642 } 2643 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2644 // state w.r.t. the formal app-linkage "no verification attempted" state; 2645 // and then 'always' in the per-user state actually used for intent resolution. 2646 final IntentFilterVerificationInfo ivi; 2647 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2648 new ArrayList<String>(domains)); 2649 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2650 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2651 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2652 } else { 2653 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2654 + "' does not handle web links"); 2655 } 2656 } else { 2657 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2658 } 2659 } 2660 2661 scheduleWritePackageRestrictionsLocked(userId); 2662 scheduleWriteSettingsLocked(); 2663 } 2664 2665 private void applyFactoryDefaultBrowserLPw(int userId) { 2666 // The default browser app's package name is stored in a string resource, 2667 // with a product-specific overlay used for vendor customization. 2668 String browserPkg = mContext.getResources().getString( 2669 com.android.internal.R.string.default_browser); 2670 if (!TextUtils.isEmpty(browserPkg)) { 2671 // non-empty string => required to be a known package 2672 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2673 if (ps == null) { 2674 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2675 browserPkg = null; 2676 } else { 2677 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2678 } 2679 } 2680 2681 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2682 // default. If there's more than one, just leave everything alone. 2683 if (browserPkg == null) { 2684 calculateDefaultBrowserLPw(userId); 2685 } 2686 } 2687 2688 private void calculateDefaultBrowserLPw(int userId) { 2689 List<String> allBrowsers = resolveAllBrowserApps(userId); 2690 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2691 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2692 } 2693 2694 private List<String> resolveAllBrowserApps(int userId) { 2695 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2696 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2697 PackageManager.MATCH_ALL, userId); 2698 2699 final int count = list.size(); 2700 List<String> result = new ArrayList<String>(count); 2701 for (int i=0; i<count; i++) { 2702 ResolveInfo info = list.get(i); 2703 if (info.activityInfo == null 2704 || !info.handleAllWebDataURI 2705 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2706 || result.contains(info.activityInfo.packageName)) { 2707 continue; 2708 } 2709 result.add(info.activityInfo.packageName); 2710 } 2711 2712 return result; 2713 } 2714 2715 private boolean packageIsBrowser(String packageName, int userId) { 2716 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2717 PackageManager.MATCH_ALL, userId); 2718 final int N = list.size(); 2719 for (int i = 0; i < N; i++) { 2720 ResolveInfo info = list.get(i); 2721 if (packageName.equals(info.activityInfo.packageName)) { 2722 return true; 2723 } 2724 } 2725 return false; 2726 } 2727 2728 private void checkDefaultBrowser() { 2729 final int myUserId = UserHandle.myUserId(); 2730 final String packageName = getDefaultBrowserPackageName(myUserId); 2731 if (packageName != null) { 2732 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2733 if (info == null) { 2734 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2735 synchronized (mPackages) { 2736 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2737 } 2738 } 2739 } 2740 } 2741 2742 @Override 2743 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2744 throws RemoteException { 2745 try { 2746 return super.onTransact(code, data, reply, flags); 2747 } catch (RuntimeException e) { 2748 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2749 Slog.wtf(TAG, "Package Manager Crash", e); 2750 } 2751 throw e; 2752 } 2753 } 2754 2755 void cleanupInstallFailedPackage(PackageSetting ps) { 2756 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2757 2758 removeDataDirsLI(ps.volumeUuid, ps.name); 2759 if (ps.codePath != null) { 2760 if (ps.codePath.isDirectory()) { 2761 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2762 } else { 2763 ps.codePath.delete(); 2764 } 2765 } 2766 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2767 if (ps.resourcePath.isDirectory()) { 2768 FileUtils.deleteContents(ps.resourcePath); 2769 } 2770 ps.resourcePath.delete(); 2771 } 2772 mSettings.removePackageLPw(ps.name); 2773 } 2774 2775 static int[] appendInts(int[] cur, int[] add) { 2776 if (add == null) return cur; 2777 if (cur == null) return add; 2778 final int N = add.length; 2779 for (int i=0; i<N; i++) { 2780 cur = appendInt(cur, add[i]); 2781 } 2782 return cur; 2783 } 2784 2785 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2786 if (!sUserManager.exists(userId)) return null; 2787 final PackageSetting ps = (PackageSetting) p.mExtras; 2788 if (ps == null) { 2789 return null; 2790 } 2791 2792 final PermissionsState permissionsState = ps.getPermissionsState(); 2793 2794 final int[] gids = permissionsState.computeGids(userId); 2795 final Set<String> permissions = permissionsState.getPermissions(userId); 2796 final PackageUserState state = ps.readUserState(userId); 2797 2798 return PackageParser.generatePackageInfo(p, gids, flags, 2799 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2800 } 2801 2802 @Override 2803 public boolean isPackageFrozen(String packageName) { 2804 synchronized (mPackages) { 2805 final PackageSetting ps = mSettings.mPackages.get(packageName); 2806 if (ps != null) { 2807 return ps.frozen; 2808 } 2809 } 2810 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2811 return true; 2812 } 2813 2814 @Override 2815 public boolean isPackageAvailable(String packageName, int userId) { 2816 if (!sUserManager.exists(userId)) return false; 2817 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2818 synchronized (mPackages) { 2819 PackageParser.Package p = mPackages.get(packageName); 2820 if (p != null) { 2821 final PackageSetting ps = (PackageSetting) p.mExtras; 2822 if (ps != null) { 2823 final PackageUserState state = ps.readUserState(userId); 2824 if (state != null) { 2825 return PackageParser.isAvailable(state); 2826 } 2827 } 2828 } 2829 } 2830 return false; 2831 } 2832 2833 @Override 2834 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2835 if (!sUserManager.exists(userId)) return null; 2836 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2837 // reader 2838 synchronized (mPackages) { 2839 PackageParser.Package p = mPackages.get(packageName); 2840 if (DEBUG_PACKAGE_INFO) 2841 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2842 if (p != null) { 2843 return generatePackageInfo(p, flags, userId); 2844 } 2845 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2846 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2847 } 2848 } 2849 return null; 2850 } 2851 2852 @Override 2853 public String[] currentToCanonicalPackageNames(String[] names) { 2854 String[] out = new String[names.length]; 2855 // reader 2856 synchronized (mPackages) { 2857 for (int i=names.length-1; i>=0; i--) { 2858 PackageSetting ps = mSettings.mPackages.get(names[i]); 2859 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2860 } 2861 } 2862 return out; 2863 } 2864 2865 @Override 2866 public String[] canonicalToCurrentPackageNames(String[] names) { 2867 String[] out = new String[names.length]; 2868 // reader 2869 synchronized (mPackages) { 2870 for (int i=names.length-1; i>=0; i--) { 2871 String cur = mSettings.mRenamedPackages.get(names[i]); 2872 out[i] = cur != null ? cur : names[i]; 2873 } 2874 } 2875 return out; 2876 } 2877 2878 @Override 2879 public int getPackageUid(String packageName, int userId) { 2880 return getPackageUidEtc(packageName, 0, userId); 2881 } 2882 2883 @Override 2884 public int getPackageUidEtc(String packageName, int flags, int userId) { 2885 if (!sUserManager.exists(userId)) return -1; 2886 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2887 2888 // reader 2889 synchronized (mPackages) { 2890 final PackageParser.Package p = mPackages.get(packageName); 2891 if (p != null) { 2892 return UserHandle.getUid(userId, p.applicationInfo.uid); 2893 } 2894 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2895 final PackageSetting ps = mSettings.mPackages.get(packageName); 2896 if (ps != null) { 2897 return UserHandle.getUid(userId, ps.appId); 2898 } 2899 } 2900 } 2901 2902 return -1; 2903 } 2904 2905 @Override 2906 public int[] getPackageGids(String packageName, int userId) { 2907 return getPackageGidsEtc(packageName, 0, userId); 2908 } 2909 2910 @Override 2911 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2912 if (!sUserManager.exists(userId)) { 2913 return null; 2914 } 2915 2916 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2917 "getPackageGids"); 2918 2919 // reader 2920 synchronized (mPackages) { 2921 final PackageParser.Package p = mPackages.get(packageName); 2922 if (p != null) { 2923 PackageSetting ps = (PackageSetting) p.mExtras; 2924 return ps.getPermissionsState().computeGids(userId); 2925 } 2926 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2927 final PackageSetting ps = mSettings.mPackages.get(packageName); 2928 if (ps != null) { 2929 return ps.getPermissionsState().computeGids(userId); 2930 } 2931 } 2932 } 2933 2934 return null; 2935 } 2936 2937 static PermissionInfo generatePermissionInfo( 2938 BasePermission bp, int flags) { 2939 if (bp.perm != null) { 2940 return PackageParser.generatePermissionInfo(bp.perm, flags); 2941 } 2942 PermissionInfo pi = new PermissionInfo(); 2943 pi.name = bp.name; 2944 pi.packageName = bp.sourcePackage; 2945 pi.nonLocalizedLabel = bp.name; 2946 pi.protectionLevel = bp.protectionLevel; 2947 return pi; 2948 } 2949 2950 @Override 2951 public PermissionInfo getPermissionInfo(String name, int flags) { 2952 // reader 2953 synchronized (mPackages) { 2954 final BasePermission p = mSettings.mPermissions.get(name); 2955 if (p != null) { 2956 return generatePermissionInfo(p, flags); 2957 } 2958 return null; 2959 } 2960 } 2961 2962 @Override 2963 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2964 // reader 2965 synchronized (mPackages) { 2966 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2967 for (BasePermission p : mSettings.mPermissions.values()) { 2968 if (group == null) { 2969 if (p.perm == null || p.perm.info.group == null) { 2970 out.add(generatePermissionInfo(p, flags)); 2971 } 2972 } else { 2973 if (p.perm != null && group.equals(p.perm.info.group)) { 2974 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2975 } 2976 } 2977 } 2978 2979 if (out.size() > 0) { 2980 return out; 2981 } 2982 return mPermissionGroups.containsKey(group) ? out : null; 2983 } 2984 } 2985 2986 @Override 2987 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2988 // reader 2989 synchronized (mPackages) { 2990 return PackageParser.generatePermissionGroupInfo( 2991 mPermissionGroups.get(name), flags); 2992 } 2993 } 2994 2995 @Override 2996 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2997 // reader 2998 synchronized (mPackages) { 2999 final int N = mPermissionGroups.size(); 3000 ArrayList<PermissionGroupInfo> out 3001 = new ArrayList<PermissionGroupInfo>(N); 3002 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3003 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3004 } 3005 return out; 3006 } 3007 } 3008 3009 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3010 int userId) { 3011 if (!sUserManager.exists(userId)) return null; 3012 PackageSetting ps = mSettings.mPackages.get(packageName); 3013 if (ps != null) { 3014 if (ps.pkg == null) { 3015 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3016 flags, userId); 3017 if (pInfo != null) { 3018 return pInfo.applicationInfo; 3019 } 3020 return null; 3021 } 3022 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3023 ps.readUserState(userId), userId); 3024 } 3025 return null; 3026 } 3027 3028 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3029 int userId) { 3030 if (!sUserManager.exists(userId)) return null; 3031 PackageSetting ps = mSettings.mPackages.get(packageName); 3032 if (ps != null) { 3033 PackageParser.Package pkg = ps.pkg; 3034 if (pkg == null) { 3035 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 3036 return null; 3037 } 3038 // Only data remains, so we aren't worried about code paths 3039 pkg = new PackageParser.Package(packageName); 3040 pkg.applicationInfo.packageName = packageName; 3041 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3042 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3043 pkg.applicationInfo.uid = ps.appId; 3044 pkg.applicationInfo.initForUser(userId); 3045 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3046 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3047 } 3048 return generatePackageInfo(pkg, flags, userId); 3049 } 3050 return null; 3051 } 3052 3053 @Override 3054 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3055 if (!sUserManager.exists(userId)) return null; 3056 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3057 // writer 3058 synchronized (mPackages) { 3059 PackageParser.Package p = mPackages.get(packageName); 3060 if (DEBUG_PACKAGE_INFO) Log.v( 3061 TAG, "getApplicationInfo " + packageName 3062 + ": " + p); 3063 if (p != null) { 3064 PackageSetting ps = mSettings.mPackages.get(packageName); 3065 if (ps == null) return null; 3066 // Note: isEnabledLP() does not apply here - always return info 3067 return PackageParser.generateApplicationInfo( 3068 p, flags, ps.readUserState(userId), userId); 3069 } 3070 if ("android".equals(packageName)||"system".equals(packageName)) { 3071 return mAndroidApplication; 3072 } 3073 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 3074 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3075 } 3076 } 3077 return null; 3078 } 3079 3080 @Override 3081 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3082 final IPackageDataObserver observer) { 3083 mContext.enforceCallingOrSelfPermission( 3084 android.Manifest.permission.CLEAR_APP_CACHE, null); 3085 // Queue up an async operation since clearing cache may take a little while. 3086 mHandler.post(new Runnable() { 3087 public void run() { 3088 mHandler.removeCallbacks(this); 3089 int retCode = -1; 3090 synchronized (mInstallLock) { 3091 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3092 if (retCode < 0) { 3093 Slog.w(TAG, "Couldn't clear application caches"); 3094 } 3095 } 3096 if (observer != null) { 3097 try { 3098 observer.onRemoveCompleted(null, (retCode >= 0)); 3099 } catch (RemoteException e) { 3100 Slog.w(TAG, "RemoveException when invoking call back"); 3101 } 3102 } 3103 } 3104 }); 3105 } 3106 3107 @Override 3108 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3109 final IntentSender pi) { 3110 mContext.enforceCallingOrSelfPermission( 3111 android.Manifest.permission.CLEAR_APP_CACHE, null); 3112 // Queue up an async operation since clearing cache may take a little while. 3113 mHandler.post(new Runnable() { 3114 public void run() { 3115 mHandler.removeCallbacks(this); 3116 int retCode = -1; 3117 synchronized (mInstallLock) { 3118 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3119 if (retCode < 0) { 3120 Slog.w(TAG, "Couldn't clear application caches"); 3121 } 3122 } 3123 if(pi != null) { 3124 try { 3125 // Callback via pending intent 3126 int code = (retCode >= 0) ? 1 : 0; 3127 pi.sendIntent(null, code, null, 3128 null, null); 3129 } catch (SendIntentException e1) { 3130 Slog.i(TAG, "Failed to send pending intent"); 3131 } 3132 } 3133 } 3134 }); 3135 } 3136 3137 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3138 synchronized (mInstallLock) { 3139 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3140 throw new IOException("Failed to free enough space"); 3141 } 3142 } 3143 } 3144 3145 /** 3146 * Augment the given flags depending on current user running state. This is 3147 * purposefully done before acquiring {@link #mPackages} lock. 3148 */ 3149 private int augmentFlagsForUser(int flags, int userId) { 3150 if (StorageManager.isFileBasedEncryptionEnabled()) { 3151 final IMountService mount = IMountService.Stub 3152 .asInterface(ServiceManager.getService("mount")); 3153 if (mount == null) { 3154 // We must be early in boot, so the best we can do is assume the 3155 // user is fully running. 3156 Slog.w(TAG, "Early during boot, assuming not encrypted"); 3157 return flags; 3158 } 3159 final long token = Binder.clearCallingIdentity(); 3160 try { 3161 if (!mount.isUserKeyUnlocked(userId)) { 3162 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY; 3163 } 3164 } catch (RemoteException e) { 3165 throw e.rethrowAsRuntimeException(); 3166 } finally { 3167 Binder.restoreCallingIdentity(token); 3168 } 3169 } 3170 return flags; 3171 } 3172 3173 @Override 3174 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3175 if (!sUserManager.exists(userId)) return null; 3176 flags = augmentFlagsForUser(flags, userId); 3177 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3178 synchronized (mPackages) { 3179 PackageParser.Activity a = mActivities.mActivities.get(component); 3180 3181 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3182 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3183 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3184 if (ps == null) return null; 3185 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3186 userId); 3187 } 3188 if (mResolveComponentName.equals(component)) { 3189 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3190 new PackageUserState(), userId); 3191 } 3192 } 3193 return null; 3194 } 3195 3196 @Override 3197 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3198 String resolvedType) { 3199 synchronized (mPackages) { 3200 if (component.equals(mResolveComponentName)) { 3201 // The resolver supports EVERYTHING! 3202 return true; 3203 } 3204 PackageParser.Activity a = mActivities.mActivities.get(component); 3205 if (a == null) { 3206 return false; 3207 } 3208 for (int i=0; i<a.intents.size(); i++) { 3209 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3210 intent.getData(), intent.getCategories(), TAG) >= 0) { 3211 return true; 3212 } 3213 } 3214 return false; 3215 } 3216 } 3217 3218 @Override 3219 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3220 if (!sUserManager.exists(userId)) return null; 3221 flags = augmentFlagsForUser(flags, userId); 3222 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3223 synchronized (mPackages) { 3224 PackageParser.Activity a = mReceivers.mActivities.get(component); 3225 if (DEBUG_PACKAGE_INFO) Log.v( 3226 TAG, "getReceiverInfo " + component + ": " + a); 3227 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3228 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3229 if (ps == null) return null; 3230 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3231 userId); 3232 } 3233 } 3234 return null; 3235 } 3236 3237 @Override 3238 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3239 if (!sUserManager.exists(userId)) return null; 3240 flags = augmentFlagsForUser(flags, userId); 3241 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3242 synchronized (mPackages) { 3243 PackageParser.Service s = mServices.mServices.get(component); 3244 if (DEBUG_PACKAGE_INFO) Log.v( 3245 TAG, "getServiceInfo " + component + ": " + s); 3246 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3247 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3248 if (ps == null) return null; 3249 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3250 userId); 3251 } 3252 } 3253 return null; 3254 } 3255 3256 @Override 3257 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3258 if (!sUserManager.exists(userId)) return null; 3259 flags = augmentFlagsForUser(flags, userId); 3260 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3261 synchronized (mPackages) { 3262 PackageParser.Provider p = mProviders.mProviders.get(component); 3263 if (DEBUG_PACKAGE_INFO) Log.v( 3264 TAG, "getProviderInfo " + component + ": " + p); 3265 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3266 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3267 if (ps == null) return null; 3268 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3269 userId); 3270 } 3271 } 3272 return null; 3273 } 3274 3275 @Override 3276 public String[] getSystemSharedLibraryNames() { 3277 Set<String> libSet; 3278 synchronized (mPackages) { 3279 libSet = mSharedLibraries.keySet(); 3280 int size = libSet.size(); 3281 if (size > 0) { 3282 String[] libs = new String[size]; 3283 libSet.toArray(libs); 3284 return libs; 3285 } 3286 } 3287 return null; 3288 } 3289 3290 /** 3291 * @hide 3292 */ 3293 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3294 synchronized (mPackages) { 3295 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3296 if (lib != null && lib.apk != null) { 3297 return mPackages.get(lib.apk); 3298 } 3299 } 3300 return null; 3301 } 3302 3303 @Override 3304 public FeatureInfo[] getSystemAvailableFeatures() { 3305 Collection<FeatureInfo> featSet; 3306 synchronized (mPackages) { 3307 featSet = mAvailableFeatures.values(); 3308 int size = featSet.size(); 3309 if (size > 0) { 3310 FeatureInfo[] features = new FeatureInfo[size+1]; 3311 featSet.toArray(features); 3312 FeatureInfo fi = new FeatureInfo(); 3313 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3314 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3315 features[size] = fi; 3316 return features; 3317 } 3318 } 3319 return null; 3320 } 3321 3322 @Override 3323 public boolean hasSystemFeature(String name) { 3324 synchronized (mPackages) { 3325 return mAvailableFeatures.containsKey(name); 3326 } 3327 } 3328 3329 private void checkValidCaller(int uid, int userId) { 3330 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3331 return; 3332 3333 throw new SecurityException("Caller uid=" + uid 3334 + " is not privileged to communicate with user=" + userId); 3335 } 3336 3337 @Override 3338 public int checkPermission(String permName, String pkgName, int userId) { 3339 if (!sUserManager.exists(userId)) { 3340 return PackageManager.PERMISSION_DENIED; 3341 } 3342 3343 synchronized (mPackages) { 3344 final PackageParser.Package p = mPackages.get(pkgName); 3345 if (p != null && p.mExtras != null) { 3346 final PackageSetting ps = (PackageSetting) p.mExtras; 3347 final PermissionsState permissionsState = ps.getPermissionsState(); 3348 if (permissionsState.hasPermission(permName, userId)) { 3349 return PackageManager.PERMISSION_GRANTED; 3350 } 3351 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3352 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3353 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3354 return PackageManager.PERMISSION_GRANTED; 3355 } 3356 } 3357 } 3358 3359 return PackageManager.PERMISSION_DENIED; 3360 } 3361 3362 @Override 3363 public int checkUidPermission(String permName, int uid) { 3364 final int userId = UserHandle.getUserId(uid); 3365 3366 if (!sUserManager.exists(userId)) { 3367 return PackageManager.PERMISSION_DENIED; 3368 } 3369 3370 synchronized (mPackages) { 3371 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3372 if (obj != null) { 3373 final SettingBase ps = (SettingBase) obj; 3374 final PermissionsState permissionsState = ps.getPermissionsState(); 3375 if (permissionsState.hasPermission(permName, userId)) { 3376 return PackageManager.PERMISSION_GRANTED; 3377 } 3378 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3379 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3380 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3381 return PackageManager.PERMISSION_GRANTED; 3382 } 3383 } else { 3384 ArraySet<String> perms = mSystemPermissions.get(uid); 3385 if (perms != null) { 3386 if (perms.contains(permName)) { 3387 return PackageManager.PERMISSION_GRANTED; 3388 } 3389 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3390 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3391 return PackageManager.PERMISSION_GRANTED; 3392 } 3393 } 3394 } 3395 } 3396 3397 return PackageManager.PERMISSION_DENIED; 3398 } 3399 3400 @Override 3401 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3402 if (UserHandle.getCallingUserId() != userId) { 3403 mContext.enforceCallingPermission( 3404 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3405 "isPermissionRevokedByPolicy for user " + userId); 3406 } 3407 3408 if (checkPermission(permission, packageName, userId) 3409 == PackageManager.PERMISSION_GRANTED) { 3410 return false; 3411 } 3412 3413 final long identity = Binder.clearCallingIdentity(); 3414 try { 3415 final int flags = getPermissionFlags(permission, packageName, userId); 3416 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3417 } finally { 3418 Binder.restoreCallingIdentity(identity); 3419 } 3420 } 3421 3422 @Override 3423 public String getPermissionControllerPackageName() { 3424 synchronized (mPackages) { 3425 return mRequiredInstallerPackage; 3426 } 3427 } 3428 3429 /** 3430 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3431 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3432 * @param checkShell TODO(yamasani): 3433 * @param message the message to log on security exception 3434 */ 3435 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3436 boolean checkShell, String message) { 3437 if (userId < 0) { 3438 throw new IllegalArgumentException("Invalid userId " + userId); 3439 } 3440 if (checkShell) { 3441 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3442 } 3443 if (userId == UserHandle.getUserId(callingUid)) return; 3444 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3445 if (requireFullPermission) { 3446 mContext.enforceCallingOrSelfPermission( 3447 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3448 } else { 3449 try { 3450 mContext.enforceCallingOrSelfPermission( 3451 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3452 } catch (SecurityException se) { 3453 mContext.enforceCallingOrSelfPermission( 3454 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3455 } 3456 } 3457 } 3458 } 3459 3460 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3461 if (callingUid == Process.SHELL_UID) { 3462 if (userHandle >= 0 3463 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3464 throw new SecurityException("Shell does not have permission to access user " 3465 + userHandle); 3466 } else if (userHandle < 0) { 3467 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3468 + Debug.getCallers(3)); 3469 } 3470 } 3471 } 3472 3473 private BasePermission findPermissionTreeLP(String permName) { 3474 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3475 if (permName.startsWith(bp.name) && 3476 permName.length() > bp.name.length() && 3477 permName.charAt(bp.name.length()) == '.') { 3478 return bp; 3479 } 3480 } 3481 return null; 3482 } 3483 3484 private BasePermission checkPermissionTreeLP(String permName) { 3485 if (permName != null) { 3486 BasePermission bp = findPermissionTreeLP(permName); 3487 if (bp != null) { 3488 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3489 return bp; 3490 } 3491 throw new SecurityException("Calling uid " 3492 + Binder.getCallingUid() 3493 + " is not allowed to add to permission tree " 3494 + bp.name + " owned by uid " + bp.uid); 3495 } 3496 } 3497 throw new SecurityException("No permission tree found for " + permName); 3498 } 3499 3500 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3501 if (s1 == null) { 3502 return s2 == null; 3503 } 3504 if (s2 == null) { 3505 return false; 3506 } 3507 if (s1.getClass() != s2.getClass()) { 3508 return false; 3509 } 3510 return s1.equals(s2); 3511 } 3512 3513 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3514 if (pi1.icon != pi2.icon) return false; 3515 if (pi1.logo != pi2.logo) return false; 3516 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3517 if (!compareStrings(pi1.name, pi2.name)) return false; 3518 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3519 // We'll take care of setting this one. 3520 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3521 // These are not currently stored in settings. 3522 //if (!compareStrings(pi1.group, pi2.group)) return false; 3523 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3524 //if (pi1.labelRes != pi2.labelRes) return false; 3525 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3526 return true; 3527 } 3528 3529 int permissionInfoFootprint(PermissionInfo info) { 3530 int size = info.name.length(); 3531 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3532 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3533 return size; 3534 } 3535 3536 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3537 int size = 0; 3538 for (BasePermission perm : mSettings.mPermissions.values()) { 3539 if (perm.uid == tree.uid) { 3540 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3541 } 3542 } 3543 return size; 3544 } 3545 3546 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3547 // We calculate the max size of permissions defined by this uid and throw 3548 // if that plus the size of 'info' would exceed our stated maximum. 3549 if (tree.uid != Process.SYSTEM_UID) { 3550 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3551 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3552 throw new SecurityException("Permission tree size cap exceeded"); 3553 } 3554 } 3555 } 3556 3557 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3558 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3559 throw new SecurityException("Label must be specified in permission"); 3560 } 3561 BasePermission tree = checkPermissionTreeLP(info.name); 3562 BasePermission bp = mSettings.mPermissions.get(info.name); 3563 boolean added = bp == null; 3564 boolean changed = true; 3565 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3566 if (added) { 3567 enforcePermissionCapLocked(info, tree); 3568 bp = new BasePermission(info.name, tree.sourcePackage, 3569 BasePermission.TYPE_DYNAMIC); 3570 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3571 throw new SecurityException( 3572 "Not allowed to modify non-dynamic permission " 3573 + info.name); 3574 } else { 3575 if (bp.protectionLevel == fixedLevel 3576 && bp.perm.owner.equals(tree.perm.owner) 3577 && bp.uid == tree.uid 3578 && comparePermissionInfos(bp.perm.info, info)) { 3579 changed = false; 3580 } 3581 } 3582 bp.protectionLevel = fixedLevel; 3583 info = new PermissionInfo(info); 3584 info.protectionLevel = fixedLevel; 3585 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3586 bp.perm.info.packageName = tree.perm.info.packageName; 3587 bp.uid = tree.uid; 3588 if (added) { 3589 mSettings.mPermissions.put(info.name, bp); 3590 } 3591 if (changed) { 3592 if (!async) { 3593 mSettings.writeLPr(); 3594 } else { 3595 scheduleWriteSettingsLocked(); 3596 } 3597 } 3598 return added; 3599 } 3600 3601 @Override 3602 public boolean addPermission(PermissionInfo info) { 3603 synchronized (mPackages) { 3604 return addPermissionLocked(info, false); 3605 } 3606 } 3607 3608 @Override 3609 public boolean addPermissionAsync(PermissionInfo info) { 3610 synchronized (mPackages) { 3611 return addPermissionLocked(info, true); 3612 } 3613 } 3614 3615 @Override 3616 public void removePermission(String name) { 3617 synchronized (mPackages) { 3618 checkPermissionTreeLP(name); 3619 BasePermission bp = mSettings.mPermissions.get(name); 3620 if (bp != null) { 3621 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3622 throw new SecurityException( 3623 "Not allowed to modify non-dynamic permission " 3624 + name); 3625 } 3626 mSettings.mPermissions.remove(name); 3627 mSettings.writeLPr(); 3628 } 3629 } 3630 } 3631 3632 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3633 BasePermission bp) { 3634 int index = pkg.requestedPermissions.indexOf(bp.name); 3635 if (index == -1) { 3636 throw new SecurityException("Package " + pkg.packageName 3637 + " has not requested permission " + bp.name); 3638 } 3639 if (!bp.isRuntime() && !bp.isDevelopment()) { 3640 throw new SecurityException("Permission " + bp.name 3641 + " is not a changeable permission type"); 3642 } 3643 } 3644 3645 @Override 3646 public void grantRuntimePermission(String packageName, String name, final int userId) { 3647 if (!sUserManager.exists(userId)) { 3648 Log.e(TAG, "No such user:" + userId); 3649 return; 3650 } 3651 3652 mContext.enforceCallingOrSelfPermission( 3653 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3654 "grantRuntimePermission"); 3655 3656 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3657 "grantRuntimePermission"); 3658 3659 final int uid; 3660 final SettingBase sb; 3661 3662 synchronized (mPackages) { 3663 final PackageParser.Package pkg = mPackages.get(packageName); 3664 if (pkg == null) { 3665 throw new IllegalArgumentException("Unknown package: " + packageName); 3666 } 3667 3668 final BasePermission bp = mSettings.mPermissions.get(name); 3669 if (bp == null) { 3670 throw new IllegalArgumentException("Unknown permission: " + name); 3671 } 3672 3673 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3674 3675 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3676 sb = (SettingBase) pkg.mExtras; 3677 if (sb == null) { 3678 throw new IllegalArgumentException("Unknown package: " + packageName); 3679 } 3680 3681 final PermissionsState permissionsState = sb.getPermissionsState(); 3682 3683 final int flags = permissionsState.getPermissionFlags(name, userId); 3684 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3685 throw new SecurityException("Cannot grant system fixed permission: " 3686 + name + " for package: " + packageName); 3687 } 3688 3689 if (bp.isDevelopment()) { 3690 // Development permissions must be handled specially, since they are not 3691 // normal runtime permissions. For now they apply to all users. 3692 if (permissionsState.grantInstallPermission(bp) != 3693 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3694 scheduleWriteSettingsLocked(); 3695 } 3696 return; 3697 } 3698 3699 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3700 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3701 return; 3702 } 3703 3704 final int result = permissionsState.grantRuntimePermission(bp, userId); 3705 switch (result) { 3706 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3707 return; 3708 } 3709 3710 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3711 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3712 mHandler.post(new Runnable() { 3713 @Override 3714 public void run() { 3715 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3716 } 3717 }); 3718 } 3719 break; 3720 } 3721 3722 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3723 3724 // Not critical if that is lost - app has to request again. 3725 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3726 } 3727 3728 // Only need to do this if user is initialized. Otherwise it's a new user 3729 // and there are no processes running as the user yet and there's no need 3730 // to make an expensive call to remount processes for the changed permissions. 3731 if (READ_EXTERNAL_STORAGE.equals(name) 3732 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3733 final long token = Binder.clearCallingIdentity(); 3734 try { 3735 if (sUserManager.isInitialized(userId)) { 3736 MountServiceInternal mountServiceInternal = LocalServices.getService( 3737 MountServiceInternal.class); 3738 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3739 } 3740 } finally { 3741 Binder.restoreCallingIdentity(token); 3742 } 3743 } 3744 } 3745 3746 @Override 3747 public void revokeRuntimePermission(String packageName, String name, int userId) { 3748 if (!sUserManager.exists(userId)) { 3749 Log.e(TAG, "No such user:" + userId); 3750 return; 3751 } 3752 3753 mContext.enforceCallingOrSelfPermission( 3754 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3755 "revokeRuntimePermission"); 3756 3757 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3758 "revokeRuntimePermission"); 3759 3760 final int appId; 3761 3762 synchronized (mPackages) { 3763 final PackageParser.Package pkg = mPackages.get(packageName); 3764 if (pkg == null) { 3765 throw new IllegalArgumentException("Unknown package: " + packageName); 3766 } 3767 3768 final BasePermission bp = mSettings.mPermissions.get(name); 3769 if (bp == null) { 3770 throw new IllegalArgumentException("Unknown permission: " + name); 3771 } 3772 3773 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3774 3775 SettingBase sb = (SettingBase) pkg.mExtras; 3776 if (sb == null) { 3777 throw new IllegalArgumentException("Unknown package: " + packageName); 3778 } 3779 3780 final PermissionsState permissionsState = sb.getPermissionsState(); 3781 3782 final int flags = permissionsState.getPermissionFlags(name, userId); 3783 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3784 throw new SecurityException("Cannot revoke system fixed permission: " 3785 + name + " for package: " + packageName); 3786 } 3787 3788 if (bp.isDevelopment()) { 3789 // Development permissions must be handled specially, since they are not 3790 // normal runtime permissions. For now they apply to all users. 3791 if (permissionsState.revokeInstallPermission(bp) != 3792 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3793 scheduleWriteSettingsLocked(); 3794 } 3795 return; 3796 } 3797 3798 if (permissionsState.revokeRuntimePermission(bp, userId) == 3799 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3800 return; 3801 } 3802 3803 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3804 3805 // Critical, after this call app should never have the permission. 3806 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3807 3808 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3809 } 3810 3811 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3812 } 3813 3814 @Override 3815 public void resetRuntimePermissions() { 3816 mContext.enforceCallingOrSelfPermission( 3817 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3818 "revokeRuntimePermission"); 3819 3820 int callingUid = Binder.getCallingUid(); 3821 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3822 mContext.enforceCallingOrSelfPermission( 3823 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3824 "resetRuntimePermissions"); 3825 } 3826 3827 synchronized (mPackages) { 3828 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3829 for (int userId : UserManagerService.getInstance().getUserIds()) { 3830 final int packageCount = mPackages.size(); 3831 for (int i = 0; i < packageCount; i++) { 3832 PackageParser.Package pkg = mPackages.valueAt(i); 3833 if (!(pkg.mExtras instanceof PackageSetting)) { 3834 continue; 3835 } 3836 PackageSetting ps = (PackageSetting) pkg.mExtras; 3837 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3838 } 3839 } 3840 } 3841 } 3842 3843 @Override 3844 public int getPermissionFlags(String name, String packageName, int userId) { 3845 if (!sUserManager.exists(userId)) { 3846 return 0; 3847 } 3848 3849 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3850 3851 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3852 "getPermissionFlags"); 3853 3854 synchronized (mPackages) { 3855 final PackageParser.Package pkg = mPackages.get(packageName); 3856 if (pkg == null) { 3857 throw new IllegalArgumentException("Unknown package: " + packageName); 3858 } 3859 3860 final BasePermission bp = mSettings.mPermissions.get(name); 3861 if (bp == null) { 3862 throw new IllegalArgumentException("Unknown permission: " + name); 3863 } 3864 3865 SettingBase sb = (SettingBase) pkg.mExtras; 3866 if (sb == null) { 3867 throw new IllegalArgumentException("Unknown package: " + packageName); 3868 } 3869 3870 PermissionsState permissionsState = sb.getPermissionsState(); 3871 return permissionsState.getPermissionFlags(name, userId); 3872 } 3873 } 3874 3875 @Override 3876 public void updatePermissionFlags(String name, String packageName, int flagMask, 3877 int flagValues, int userId) { 3878 if (!sUserManager.exists(userId)) { 3879 return; 3880 } 3881 3882 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3883 3884 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3885 "updatePermissionFlags"); 3886 3887 // Only the system can change these flags and nothing else. 3888 if (getCallingUid() != Process.SYSTEM_UID) { 3889 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3890 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3891 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3892 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3893 } 3894 3895 synchronized (mPackages) { 3896 final PackageParser.Package pkg = mPackages.get(packageName); 3897 if (pkg == null) { 3898 throw new IllegalArgumentException("Unknown package: " + packageName); 3899 } 3900 3901 final BasePermission bp = mSettings.mPermissions.get(name); 3902 if (bp == null) { 3903 throw new IllegalArgumentException("Unknown permission: " + name); 3904 } 3905 3906 SettingBase sb = (SettingBase) pkg.mExtras; 3907 if (sb == null) { 3908 throw new IllegalArgumentException("Unknown package: " + packageName); 3909 } 3910 3911 PermissionsState permissionsState = sb.getPermissionsState(); 3912 3913 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3914 3915 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3916 // Install and runtime permissions are stored in different places, 3917 // so figure out what permission changed and persist the change. 3918 if (permissionsState.getInstallPermissionState(name) != null) { 3919 scheduleWriteSettingsLocked(); 3920 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3921 || hadState) { 3922 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3923 } 3924 } 3925 } 3926 } 3927 3928 /** 3929 * Update the permission flags for all packages and runtime permissions of a user in order 3930 * to allow device or profile owner to remove POLICY_FIXED. 3931 */ 3932 @Override 3933 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3934 if (!sUserManager.exists(userId)) { 3935 return; 3936 } 3937 3938 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3939 3940 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3941 "updatePermissionFlagsForAllApps"); 3942 3943 // Only the system can change system fixed flags. 3944 if (getCallingUid() != Process.SYSTEM_UID) { 3945 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3946 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3947 } 3948 3949 synchronized (mPackages) { 3950 boolean changed = false; 3951 final int packageCount = mPackages.size(); 3952 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3953 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3954 SettingBase sb = (SettingBase) pkg.mExtras; 3955 if (sb == null) { 3956 continue; 3957 } 3958 PermissionsState permissionsState = sb.getPermissionsState(); 3959 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3960 userId, flagMask, flagValues); 3961 } 3962 if (changed) { 3963 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3964 } 3965 } 3966 } 3967 3968 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3969 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3970 != PackageManager.PERMISSION_GRANTED 3971 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3972 != PackageManager.PERMISSION_GRANTED) { 3973 throw new SecurityException(message + " requires " 3974 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3975 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3976 } 3977 } 3978 3979 @Override 3980 public boolean shouldShowRequestPermissionRationale(String permissionName, 3981 String packageName, int userId) { 3982 if (UserHandle.getCallingUserId() != userId) { 3983 mContext.enforceCallingPermission( 3984 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3985 "canShowRequestPermissionRationale for user " + userId); 3986 } 3987 3988 final int uid = getPackageUid(packageName, userId); 3989 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3990 return false; 3991 } 3992 3993 if (checkPermission(permissionName, packageName, userId) 3994 == PackageManager.PERMISSION_GRANTED) { 3995 return false; 3996 } 3997 3998 final int flags; 3999 4000 final long identity = Binder.clearCallingIdentity(); 4001 try { 4002 flags = getPermissionFlags(permissionName, 4003 packageName, userId); 4004 } finally { 4005 Binder.restoreCallingIdentity(identity); 4006 } 4007 4008 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4009 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4010 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4011 4012 if ((flags & fixedFlags) != 0) { 4013 return false; 4014 } 4015 4016 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4017 } 4018 4019 @Override 4020 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4021 mContext.enforceCallingOrSelfPermission( 4022 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4023 "addOnPermissionsChangeListener"); 4024 4025 synchronized (mPackages) { 4026 mOnPermissionChangeListeners.addListenerLocked(listener); 4027 } 4028 } 4029 4030 @Override 4031 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4032 synchronized (mPackages) { 4033 mOnPermissionChangeListeners.removeListenerLocked(listener); 4034 } 4035 } 4036 4037 @Override 4038 public boolean isProtectedBroadcast(String actionName) { 4039 synchronized (mPackages) { 4040 return mProtectedBroadcasts.contains(actionName); 4041 } 4042 } 4043 4044 @Override 4045 public int checkSignatures(String pkg1, String pkg2) { 4046 synchronized (mPackages) { 4047 final PackageParser.Package p1 = mPackages.get(pkg1); 4048 final PackageParser.Package p2 = mPackages.get(pkg2); 4049 if (p1 == null || p1.mExtras == null 4050 || p2 == null || p2.mExtras == null) { 4051 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4052 } 4053 return compareSignatures(p1.mSignatures, p2.mSignatures); 4054 } 4055 } 4056 4057 @Override 4058 public int checkUidSignatures(int uid1, int uid2) { 4059 // Map to base uids. 4060 uid1 = UserHandle.getAppId(uid1); 4061 uid2 = UserHandle.getAppId(uid2); 4062 // reader 4063 synchronized (mPackages) { 4064 Signature[] s1; 4065 Signature[] s2; 4066 Object obj = mSettings.getUserIdLPr(uid1); 4067 if (obj != null) { 4068 if (obj instanceof SharedUserSetting) { 4069 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4070 } else if (obj instanceof PackageSetting) { 4071 s1 = ((PackageSetting)obj).signatures.mSignatures; 4072 } else { 4073 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4074 } 4075 } else { 4076 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4077 } 4078 obj = mSettings.getUserIdLPr(uid2); 4079 if (obj != null) { 4080 if (obj instanceof SharedUserSetting) { 4081 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4082 } else if (obj instanceof PackageSetting) { 4083 s2 = ((PackageSetting)obj).signatures.mSignatures; 4084 } else { 4085 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4086 } 4087 } else { 4088 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4089 } 4090 return compareSignatures(s1, s2); 4091 } 4092 } 4093 4094 private void killUid(int appId, int userId, String reason) { 4095 final long identity = Binder.clearCallingIdentity(); 4096 try { 4097 IActivityManager am = ActivityManagerNative.getDefault(); 4098 if (am != null) { 4099 try { 4100 am.killUid(appId, userId, reason); 4101 } catch (RemoteException e) { 4102 /* ignore - same process */ 4103 } 4104 } 4105 } finally { 4106 Binder.restoreCallingIdentity(identity); 4107 } 4108 } 4109 4110 /** 4111 * Compares two sets of signatures. Returns: 4112 * <br /> 4113 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4114 * <br /> 4115 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4116 * <br /> 4117 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4118 * <br /> 4119 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4120 * <br /> 4121 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4122 */ 4123 static int compareSignatures(Signature[] s1, Signature[] s2) { 4124 if (s1 == null) { 4125 return s2 == null 4126 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4127 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4128 } 4129 4130 if (s2 == null) { 4131 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4132 } 4133 4134 if (s1.length != s2.length) { 4135 return PackageManager.SIGNATURE_NO_MATCH; 4136 } 4137 4138 // Since both signature sets are of size 1, we can compare without HashSets. 4139 if (s1.length == 1) { 4140 return s1[0].equals(s2[0]) ? 4141 PackageManager.SIGNATURE_MATCH : 4142 PackageManager.SIGNATURE_NO_MATCH; 4143 } 4144 4145 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4146 for (Signature sig : s1) { 4147 set1.add(sig); 4148 } 4149 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4150 for (Signature sig : s2) { 4151 set2.add(sig); 4152 } 4153 // Make sure s2 contains all signatures in s1. 4154 if (set1.equals(set2)) { 4155 return PackageManager.SIGNATURE_MATCH; 4156 } 4157 return PackageManager.SIGNATURE_NO_MATCH; 4158 } 4159 4160 /** 4161 * If the database version for this type of package (internal storage or 4162 * external storage) is less than the version where package signatures 4163 * were updated, return true. 4164 */ 4165 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4166 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4167 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4168 } 4169 4170 /** 4171 * Used for backward compatibility to make sure any packages with 4172 * certificate chains get upgraded to the new style. {@code existingSigs} 4173 * will be in the old format (since they were stored on disk from before the 4174 * system upgrade) and {@code scannedSigs} will be in the newer format. 4175 */ 4176 private int compareSignaturesCompat(PackageSignatures existingSigs, 4177 PackageParser.Package scannedPkg) { 4178 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4179 return PackageManager.SIGNATURE_NO_MATCH; 4180 } 4181 4182 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4183 for (Signature sig : existingSigs.mSignatures) { 4184 existingSet.add(sig); 4185 } 4186 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4187 for (Signature sig : scannedPkg.mSignatures) { 4188 try { 4189 Signature[] chainSignatures = sig.getChainSignatures(); 4190 for (Signature chainSig : chainSignatures) { 4191 scannedCompatSet.add(chainSig); 4192 } 4193 } catch (CertificateEncodingException e) { 4194 scannedCompatSet.add(sig); 4195 } 4196 } 4197 /* 4198 * Make sure the expanded scanned set contains all signatures in the 4199 * existing one. 4200 */ 4201 if (scannedCompatSet.equals(existingSet)) { 4202 // Migrate the old signatures to the new scheme. 4203 existingSigs.assignSignatures(scannedPkg.mSignatures); 4204 // The new KeySets will be re-added later in the scanning process. 4205 synchronized (mPackages) { 4206 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4207 } 4208 return PackageManager.SIGNATURE_MATCH; 4209 } 4210 return PackageManager.SIGNATURE_NO_MATCH; 4211 } 4212 4213 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4214 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4215 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4216 } 4217 4218 private int compareSignaturesRecover(PackageSignatures existingSigs, 4219 PackageParser.Package scannedPkg) { 4220 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4221 return PackageManager.SIGNATURE_NO_MATCH; 4222 } 4223 4224 String msg = null; 4225 try { 4226 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4227 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4228 + scannedPkg.packageName); 4229 return PackageManager.SIGNATURE_MATCH; 4230 } 4231 } catch (CertificateException e) { 4232 msg = e.getMessage(); 4233 } 4234 4235 logCriticalInfo(Log.INFO, 4236 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4237 return PackageManager.SIGNATURE_NO_MATCH; 4238 } 4239 4240 @Override 4241 public String[] getPackagesForUid(int uid) { 4242 uid = UserHandle.getAppId(uid); 4243 // reader 4244 synchronized (mPackages) { 4245 Object obj = mSettings.getUserIdLPr(uid); 4246 if (obj instanceof SharedUserSetting) { 4247 final SharedUserSetting sus = (SharedUserSetting) obj; 4248 final int N = sus.packages.size(); 4249 final String[] res = new String[N]; 4250 final Iterator<PackageSetting> it = sus.packages.iterator(); 4251 int i = 0; 4252 while (it.hasNext()) { 4253 res[i++] = it.next().name; 4254 } 4255 return res; 4256 } else if (obj instanceof PackageSetting) { 4257 final PackageSetting ps = (PackageSetting) obj; 4258 return new String[] { ps.name }; 4259 } 4260 } 4261 return null; 4262 } 4263 4264 @Override 4265 public String getNameForUid(int uid) { 4266 // reader 4267 synchronized (mPackages) { 4268 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4269 if (obj instanceof SharedUserSetting) { 4270 final SharedUserSetting sus = (SharedUserSetting) obj; 4271 return sus.name + ":" + sus.userId; 4272 } else if (obj instanceof PackageSetting) { 4273 final PackageSetting ps = (PackageSetting) obj; 4274 return ps.name; 4275 } 4276 } 4277 return null; 4278 } 4279 4280 @Override 4281 public int getUidForSharedUser(String sharedUserName) { 4282 if(sharedUserName == null) { 4283 return -1; 4284 } 4285 // reader 4286 synchronized (mPackages) { 4287 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4288 if (suid == null) { 4289 return -1; 4290 } 4291 return suid.userId; 4292 } 4293 } 4294 4295 @Override 4296 public int getFlagsForUid(int uid) { 4297 synchronized (mPackages) { 4298 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4299 if (obj instanceof SharedUserSetting) { 4300 final SharedUserSetting sus = (SharedUserSetting) obj; 4301 return sus.pkgFlags; 4302 } else if (obj instanceof PackageSetting) { 4303 final PackageSetting ps = (PackageSetting) obj; 4304 return ps.pkgFlags; 4305 } 4306 } 4307 return 0; 4308 } 4309 4310 @Override 4311 public int getPrivateFlagsForUid(int uid) { 4312 synchronized (mPackages) { 4313 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4314 if (obj instanceof SharedUserSetting) { 4315 final SharedUserSetting sus = (SharedUserSetting) obj; 4316 return sus.pkgPrivateFlags; 4317 } else if (obj instanceof PackageSetting) { 4318 final PackageSetting ps = (PackageSetting) obj; 4319 return ps.pkgPrivateFlags; 4320 } 4321 } 4322 return 0; 4323 } 4324 4325 @Override 4326 public boolean isUidPrivileged(int uid) { 4327 uid = UserHandle.getAppId(uid); 4328 // reader 4329 synchronized (mPackages) { 4330 Object obj = mSettings.getUserIdLPr(uid); 4331 if (obj instanceof SharedUserSetting) { 4332 final SharedUserSetting sus = (SharedUserSetting) obj; 4333 final Iterator<PackageSetting> it = sus.packages.iterator(); 4334 while (it.hasNext()) { 4335 if (it.next().isPrivileged()) { 4336 return true; 4337 } 4338 } 4339 } else if (obj instanceof PackageSetting) { 4340 final PackageSetting ps = (PackageSetting) obj; 4341 return ps.isPrivileged(); 4342 } 4343 } 4344 return false; 4345 } 4346 4347 @Override 4348 public String[] getAppOpPermissionPackages(String permissionName) { 4349 synchronized (mPackages) { 4350 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4351 if (pkgs == null) { 4352 return null; 4353 } 4354 return pkgs.toArray(new String[pkgs.size()]); 4355 } 4356 } 4357 4358 @Override 4359 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4360 int flags, int userId) { 4361 if (!sUserManager.exists(userId)) return null; 4362 flags = augmentFlagsForUser(flags, userId); 4363 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4364 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4365 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4366 } 4367 4368 @Override 4369 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4370 IntentFilter filter, int match, ComponentName activity) { 4371 final int userId = UserHandle.getCallingUserId(); 4372 if (DEBUG_PREFERRED) { 4373 Log.v(TAG, "setLastChosenActivity intent=" + intent 4374 + " resolvedType=" + resolvedType 4375 + " flags=" + flags 4376 + " filter=" + filter 4377 + " match=" + match 4378 + " activity=" + activity); 4379 filter.dump(new PrintStreamPrinter(System.out), " "); 4380 } 4381 intent.setComponent(null); 4382 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4383 // Find any earlier preferred or last chosen entries and nuke them 4384 findPreferredActivity(intent, resolvedType, 4385 flags, query, 0, false, true, false, userId); 4386 // Add the new activity as the last chosen for this filter 4387 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4388 "Setting last chosen"); 4389 } 4390 4391 @Override 4392 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4393 final int userId = UserHandle.getCallingUserId(); 4394 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4395 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4396 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4397 false, false, false, userId); 4398 } 4399 4400 private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) { 4401 MessageDigest digest = null; 4402 try { 4403 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4404 } catch (NoSuchAlgorithmException e) { 4405 // If we can't create a digest, ignore ephemeral apps. 4406 return false; 4407 } 4408 4409 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4410 final byte[] digestBytes = digest.digest(hostBytes); 4411 int shaPrefix = 4412 digestBytes[0] << 24 4413 | digestBytes[1] << 16 4414 | digestBytes[2] << 8 4415 | digestBytes[3] << 0; 4416 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4417 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4418 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4419 // No hash prefix match; there are no ephemeral apps for this domain. 4420 return false; 4421 } 4422 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4423 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4424 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4425 continue; 4426 } 4427 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4428 // No filters; this should never happen. 4429 if (filters.isEmpty()) { 4430 continue; 4431 } 4432 // We have a domain match; resolve the filters to see if anything matches. 4433 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4434 for (int j = filters.size() - 1; j >= 0; --j) { 4435 ephemeralResolver.addFilter(filters.get(j)); 4436 } 4437 List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent( 4438 intent, resolvedType, false /*defaultOnly*/, userId); 4439 return !ephemeralResolveList.isEmpty(); 4440 } 4441 // Hash or filter mis-match; no ephemeral apps for this domain. 4442 return false; 4443 } 4444 4445 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4446 int flags, List<ResolveInfo> query, int userId) { 4447 final boolean isWebUri = hasWebURI(intent); 4448 // Check whether or not an ephemeral app exists to handle the URI. 4449 if (isWebUri && mEphemeralResolverConnection != null) { 4450 // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution. 4451 boolean hasAlwaysHandler = false; 4452 synchronized (mPackages) { 4453 final int count = query.size(); 4454 for (int n=0; n<count; n++) { 4455 ResolveInfo info = query.get(n); 4456 String packageName = info.activityInfo.packageName; 4457 PackageSetting ps = mSettings.mPackages.get(packageName); 4458 if (ps != null) { 4459 // Try to get the status from User settings first 4460 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4461 int status = (int) (packedStatus >> 32); 4462 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4463 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4464 hasAlwaysHandler = true; 4465 break; 4466 } 4467 } 4468 } 4469 } 4470 4471 // Only consider installing an ephemeral app if there isn't already a verified handler. 4472 // We've determined that there's an ephemeral app available for the URI, ignore any 4473 // ResolveInfo's and just return the ephemeral installer 4474 if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) { 4475 if (DEBUG_EPHEMERAL) { 4476 Slog.v(TAG, "Resolving to the ephemeral installer"); 4477 } 4478 // ditch the result and return a ResolveInfo to launch the ephemeral installer 4479 ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo); 4480 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4481 // make a deep copy of the applicationInfo 4482 ri.activityInfo.applicationInfo = new ApplicationInfo( 4483 ri.activityInfo.applicationInfo); 4484 if (userId != 0) { 4485 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4486 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4487 } 4488 return ri; 4489 } 4490 } 4491 if (query != null) { 4492 final int N = query.size(); 4493 if (N == 1) { 4494 return query.get(0); 4495 } else if (N > 1) { 4496 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4497 // If there is more than one activity with the same priority, 4498 // then let the user decide between them. 4499 ResolveInfo r0 = query.get(0); 4500 ResolveInfo r1 = query.get(1); 4501 if (DEBUG_INTENT_MATCHING || debug) { 4502 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4503 + r1.activityInfo.name + "=" + r1.priority); 4504 } 4505 // If the first activity has a higher priority, or a different 4506 // default, then it is always desireable to pick it. 4507 if (r0.priority != r1.priority 4508 || r0.preferredOrder != r1.preferredOrder 4509 || r0.isDefault != r1.isDefault) { 4510 return query.get(0); 4511 } 4512 // If we have saved a preference for a preferred activity for 4513 // this Intent, use that. 4514 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4515 flags, query, r0.priority, true, false, debug, userId); 4516 if (ri != null) { 4517 return ri; 4518 } 4519 ri = new ResolveInfo(mResolveInfo); 4520 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4521 ri.activityInfo.applicationInfo = new ApplicationInfo( 4522 ri.activityInfo.applicationInfo); 4523 if (userId != 0) { 4524 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4525 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4526 } 4527 // Make sure that the resolver is displayable in car mode 4528 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4529 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4530 return ri; 4531 } 4532 } 4533 return null; 4534 } 4535 4536 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4537 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4538 final int N = query.size(); 4539 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4540 .get(userId); 4541 // Get the list of persistent preferred activities that handle the intent 4542 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4543 List<PersistentPreferredActivity> pprefs = ppir != null 4544 ? ppir.queryIntent(intent, resolvedType, 4545 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4546 : null; 4547 if (pprefs != null && pprefs.size() > 0) { 4548 final int M = pprefs.size(); 4549 for (int i=0; i<M; i++) { 4550 final PersistentPreferredActivity ppa = pprefs.get(i); 4551 if (DEBUG_PREFERRED || debug) { 4552 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4553 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4554 + "\n component=" + ppa.mComponent); 4555 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4556 } 4557 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4558 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4559 if (DEBUG_PREFERRED || debug) { 4560 Slog.v(TAG, "Found persistent preferred activity:"); 4561 if (ai != null) { 4562 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4563 } else { 4564 Slog.v(TAG, " null"); 4565 } 4566 } 4567 if (ai == null) { 4568 // This previously registered persistent preferred activity 4569 // component is no longer known. Ignore it and do NOT remove it. 4570 continue; 4571 } 4572 for (int j=0; j<N; j++) { 4573 final ResolveInfo ri = query.get(j); 4574 if (!ri.activityInfo.applicationInfo.packageName 4575 .equals(ai.applicationInfo.packageName)) { 4576 continue; 4577 } 4578 if (!ri.activityInfo.name.equals(ai.name)) { 4579 continue; 4580 } 4581 // Found a persistent preference that can handle the intent. 4582 if (DEBUG_PREFERRED || debug) { 4583 Slog.v(TAG, "Returning persistent preferred activity: " + 4584 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4585 } 4586 return ri; 4587 } 4588 } 4589 } 4590 return null; 4591 } 4592 4593 // TODO: handle preferred activities missing while user has amnesia 4594 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4595 List<ResolveInfo> query, int priority, boolean always, 4596 boolean removeMatches, boolean debug, int userId) { 4597 if (!sUserManager.exists(userId)) return null; 4598 flags = augmentFlagsForUser(flags, userId); 4599 // writer 4600 synchronized (mPackages) { 4601 if (intent.getSelector() != null) { 4602 intent = intent.getSelector(); 4603 } 4604 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4605 4606 // Try to find a matching persistent preferred activity. 4607 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4608 debug, userId); 4609 4610 // If a persistent preferred activity matched, use it. 4611 if (pri != null) { 4612 return pri; 4613 } 4614 4615 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4616 // Get the list of preferred activities that handle the intent 4617 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4618 List<PreferredActivity> prefs = pir != null 4619 ? pir.queryIntent(intent, resolvedType, 4620 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4621 : null; 4622 if (prefs != null && prefs.size() > 0) { 4623 boolean changed = false; 4624 try { 4625 // First figure out how good the original match set is. 4626 // We will only allow preferred activities that came 4627 // from the same match quality. 4628 int match = 0; 4629 4630 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4631 4632 final int N = query.size(); 4633 for (int j=0; j<N; j++) { 4634 final ResolveInfo ri = query.get(j); 4635 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4636 + ": 0x" + Integer.toHexString(match)); 4637 if (ri.match > match) { 4638 match = ri.match; 4639 } 4640 } 4641 4642 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4643 + Integer.toHexString(match)); 4644 4645 match &= IntentFilter.MATCH_CATEGORY_MASK; 4646 final int M = prefs.size(); 4647 for (int i=0; i<M; i++) { 4648 final PreferredActivity pa = prefs.get(i); 4649 if (DEBUG_PREFERRED || debug) { 4650 Slog.v(TAG, "Checking PreferredActivity ds=" 4651 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4652 + "\n component=" + pa.mPref.mComponent); 4653 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4654 } 4655 if (pa.mPref.mMatch != match) { 4656 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4657 + Integer.toHexString(pa.mPref.mMatch)); 4658 continue; 4659 } 4660 // If it's not an "always" type preferred activity and that's what we're 4661 // looking for, skip it. 4662 if (always && !pa.mPref.mAlways) { 4663 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4664 continue; 4665 } 4666 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4667 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4668 if (DEBUG_PREFERRED || debug) { 4669 Slog.v(TAG, "Found preferred activity:"); 4670 if (ai != null) { 4671 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4672 } else { 4673 Slog.v(TAG, " null"); 4674 } 4675 } 4676 if (ai == null) { 4677 // This previously registered preferred activity 4678 // component is no longer known. Most likely an update 4679 // to the app was installed and in the new version this 4680 // component no longer exists. Clean it up by removing 4681 // it from the preferred activities list, and skip it. 4682 Slog.w(TAG, "Removing dangling preferred activity: " 4683 + pa.mPref.mComponent); 4684 pir.removeFilter(pa); 4685 changed = true; 4686 continue; 4687 } 4688 for (int j=0; j<N; j++) { 4689 final ResolveInfo ri = query.get(j); 4690 if (!ri.activityInfo.applicationInfo.packageName 4691 .equals(ai.applicationInfo.packageName)) { 4692 continue; 4693 } 4694 if (!ri.activityInfo.name.equals(ai.name)) { 4695 continue; 4696 } 4697 4698 if (removeMatches) { 4699 pir.removeFilter(pa); 4700 changed = true; 4701 if (DEBUG_PREFERRED) { 4702 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4703 } 4704 break; 4705 } 4706 4707 // Okay we found a previously set preferred or last chosen app. 4708 // If the result set is different from when this 4709 // was created, we need to clear it and re-ask the 4710 // user their preference, if we're looking for an "always" type entry. 4711 if (always && !pa.mPref.sameSet(query)) { 4712 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4713 + intent + " type " + resolvedType); 4714 if (DEBUG_PREFERRED) { 4715 Slog.v(TAG, "Removing preferred activity since set changed " 4716 + pa.mPref.mComponent); 4717 } 4718 pir.removeFilter(pa); 4719 // Re-add the filter as a "last chosen" entry (!always) 4720 PreferredActivity lastChosen = new PreferredActivity( 4721 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4722 pir.addFilter(lastChosen); 4723 changed = true; 4724 return null; 4725 } 4726 4727 // Yay! Either the set matched or we're looking for the last chosen 4728 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4729 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4730 return ri; 4731 } 4732 } 4733 } finally { 4734 if (changed) { 4735 if (DEBUG_PREFERRED) { 4736 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4737 } 4738 scheduleWritePackageRestrictionsLocked(userId); 4739 } 4740 } 4741 } 4742 } 4743 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4744 return null; 4745 } 4746 4747 /* 4748 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4749 */ 4750 @Override 4751 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4752 int targetUserId) { 4753 mContext.enforceCallingOrSelfPermission( 4754 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4755 List<CrossProfileIntentFilter> matches = 4756 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4757 if (matches != null) { 4758 int size = matches.size(); 4759 for (int i = 0; i < size; i++) { 4760 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4761 } 4762 } 4763 if (hasWebURI(intent)) { 4764 // cross-profile app linking works only towards the parent. 4765 final UserInfo parent = getProfileParent(sourceUserId); 4766 synchronized(mPackages) { 4767 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4768 intent, resolvedType, 0, sourceUserId, parent.id); 4769 return xpDomainInfo != null; 4770 } 4771 } 4772 return false; 4773 } 4774 4775 private UserInfo getProfileParent(int userId) { 4776 final long identity = Binder.clearCallingIdentity(); 4777 try { 4778 return sUserManager.getProfileParent(userId); 4779 } finally { 4780 Binder.restoreCallingIdentity(identity); 4781 } 4782 } 4783 4784 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4785 String resolvedType, int userId) { 4786 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4787 if (resolver != null) { 4788 return resolver.queryIntent(intent, resolvedType, false, userId); 4789 } 4790 return null; 4791 } 4792 4793 @Override 4794 public List<ResolveInfo> queryIntentActivities(Intent intent, 4795 String resolvedType, int flags, int userId) { 4796 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4797 flags = augmentFlagsForUser(flags, userId); 4798 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4799 ComponentName comp = intent.getComponent(); 4800 if (comp == null) { 4801 if (intent.getSelector() != null) { 4802 intent = intent.getSelector(); 4803 comp = intent.getComponent(); 4804 } 4805 } 4806 4807 if (comp != null) { 4808 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4809 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4810 if (ai != null) { 4811 final ResolveInfo ri = new ResolveInfo(); 4812 ri.activityInfo = ai; 4813 list.add(ri); 4814 } 4815 return list; 4816 } 4817 4818 // reader 4819 synchronized (mPackages) { 4820 final String pkgName = intent.getPackage(); 4821 if (pkgName == null) { 4822 List<CrossProfileIntentFilter> matchingFilters = 4823 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4824 // Check for results that need to skip the current profile. 4825 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4826 resolvedType, flags, userId); 4827 if (xpResolveInfo != null) { 4828 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4829 result.add(xpResolveInfo); 4830 return filterIfNotSystemUser(result, userId); 4831 } 4832 4833 // Check for results in the current profile. 4834 List<ResolveInfo> result = mActivities.queryIntent( 4835 intent, resolvedType, flags, userId); 4836 4837 // Check for cross profile results. 4838 xpResolveInfo = queryCrossProfileIntents( 4839 matchingFilters, intent, resolvedType, flags, userId); 4840 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4841 result.add(xpResolveInfo); 4842 Collections.sort(result, mResolvePrioritySorter); 4843 } 4844 result = filterIfNotSystemUser(result, userId); 4845 if (hasWebURI(intent)) { 4846 CrossProfileDomainInfo xpDomainInfo = null; 4847 final UserInfo parent = getProfileParent(userId); 4848 if (parent != null) { 4849 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4850 flags, userId, parent.id); 4851 } 4852 if (xpDomainInfo != null) { 4853 if (xpResolveInfo != null) { 4854 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4855 // in the result. 4856 result.remove(xpResolveInfo); 4857 } 4858 if (result.size() == 0) { 4859 result.add(xpDomainInfo.resolveInfo); 4860 return result; 4861 } 4862 } else if (result.size() <= 1) { 4863 return result; 4864 } 4865 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4866 xpDomainInfo, userId); 4867 Collections.sort(result, mResolvePrioritySorter); 4868 } 4869 return result; 4870 } 4871 final PackageParser.Package pkg = mPackages.get(pkgName); 4872 if (pkg != null) { 4873 return filterIfNotSystemUser( 4874 mActivities.queryIntentForPackage( 4875 intent, resolvedType, flags, pkg.activities, userId), 4876 userId); 4877 } 4878 return new ArrayList<ResolveInfo>(); 4879 } 4880 } 4881 4882 private static class CrossProfileDomainInfo { 4883 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4884 ResolveInfo resolveInfo; 4885 /* Best domain verification status of the activities found in the other profile */ 4886 int bestDomainVerificationStatus; 4887 } 4888 4889 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4890 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4891 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4892 sourceUserId)) { 4893 return null; 4894 } 4895 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4896 resolvedType, flags, parentUserId); 4897 4898 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4899 return null; 4900 } 4901 CrossProfileDomainInfo result = null; 4902 int size = resultTargetUser.size(); 4903 for (int i = 0; i < size; i++) { 4904 ResolveInfo riTargetUser = resultTargetUser.get(i); 4905 // Intent filter verification is only for filters that specify a host. So don't return 4906 // those that handle all web uris. 4907 if (riTargetUser.handleAllWebDataURI) { 4908 continue; 4909 } 4910 String packageName = riTargetUser.activityInfo.packageName; 4911 PackageSetting ps = mSettings.mPackages.get(packageName); 4912 if (ps == null) { 4913 continue; 4914 } 4915 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4916 int status = (int)(verificationState >> 32); 4917 if (result == null) { 4918 result = new CrossProfileDomainInfo(); 4919 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4920 sourceUserId, parentUserId); 4921 result.bestDomainVerificationStatus = status; 4922 } else { 4923 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4924 result.bestDomainVerificationStatus); 4925 } 4926 } 4927 // Don't consider matches with status NEVER across profiles. 4928 if (result != null && result.bestDomainVerificationStatus 4929 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4930 return null; 4931 } 4932 return result; 4933 } 4934 4935 /** 4936 * Verification statuses are ordered from the worse to the best, except for 4937 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4938 */ 4939 private int bestDomainVerificationStatus(int status1, int status2) { 4940 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4941 return status2; 4942 } 4943 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4944 return status1; 4945 } 4946 return (int) MathUtils.max(status1, status2); 4947 } 4948 4949 private boolean isUserEnabled(int userId) { 4950 long callingId = Binder.clearCallingIdentity(); 4951 try { 4952 UserInfo userInfo = sUserManager.getUserInfo(userId); 4953 return userInfo != null && userInfo.isEnabled(); 4954 } finally { 4955 Binder.restoreCallingIdentity(callingId); 4956 } 4957 } 4958 4959 /** 4960 * Filter out activities with systemUserOnly flag set, when current user is not System. 4961 * 4962 * @return filtered list 4963 */ 4964 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4965 if (userId == UserHandle.USER_SYSTEM) { 4966 return resolveInfos; 4967 } 4968 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4969 ResolveInfo info = resolveInfos.get(i); 4970 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4971 resolveInfos.remove(i); 4972 } 4973 } 4974 return resolveInfos; 4975 } 4976 4977 private static boolean hasWebURI(Intent intent) { 4978 if (intent.getData() == null) { 4979 return false; 4980 } 4981 final String scheme = intent.getScheme(); 4982 if (TextUtils.isEmpty(scheme)) { 4983 return false; 4984 } 4985 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4986 } 4987 4988 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4989 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4990 int userId) { 4991 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4992 4993 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4994 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4995 candidates.size()); 4996 } 4997 4998 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4999 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5000 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5001 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5002 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5003 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5004 5005 synchronized (mPackages) { 5006 final int count = candidates.size(); 5007 // First, try to use linked apps. Partition the candidates into four lists: 5008 // one for the final results, one for the "do not use ever", one for "undefined status" 5009 // and finally one for "browser app type". 5010 for (int n=0; n<count; n++) { 5011 ResolveInfo info = candidates.get(n); 5012 String packageName = info.activityInfo.packageName; 5013 PackageSetting ps = mSettings.mPackages.get(packageName); 5014 if (ps != null) { 5015 // Add to the special match all list (Browser use case) 5016 if (info.handleAllWebDataURI) { 5017 matchAllList.add(info); 5018 continue; 5019 } 5020 // Try to get the status from User settings first 5021 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5022 int status = (int)(packedStatus >> 32); 5023 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5024 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5025 if (DEBUG_DOMAIN_VERIFICATION) { 5026 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5027 + " : linkgen=" + linkGeneration); 5028 } 5029 // Use link-enabled generation as preferredOrder, i.e. 5030 // prefer newly-enabled over earlier-enabled. 5031 info.preferredOrder = linkGeneration; 5032 alwaysList.add(info); 5033 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5034 if (DEBUG_DOMAIN_VERIFICATION) { 5035 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5036 } 5037 neverList.add(info); 5038 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5039 if (DEBUG_DOMAIN_VERIFICATION) { 5040 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5041 } 5042 alwaysAskList.add(info); 5043 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5044 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5045 if (DEBUG_DOMAIN_VERIFICATION) { 5046 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5047 } 5048 undefinedList.add(info); 5049 } 5050 } 5051 } 5052 5053 // We'll want to include browser possibilities in a few cases 5054 boolean includeBrowser = false; 5055 5056 // First try to add the "always" resolution(s) for the current user, if any 5057 if (alwaysList.size() > 0) { 5058 result.addAll(alwaysList); 5059 } else { 5060 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5061 result.addAll(undefinedList); 5062 // Maybe add one for the other profile. 5063 if (xpDomainInfo != null && ( 5064 xpDomainInfo.bestDomainVerificationStatus 5065 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5066 result.add(xpDomainInfo.resolveInfo); 5067 } 5068 includeBrowser = true; 5069 } 5070 5071 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5072 // If there were 'always' entries their preferred order has been set, so we also 5073 // back that off to make the alternatives equivalent 5074 if (alwaysAskList.size() > 0) { 5075 for (ResolveInfo i : result) { 5076 i.preferredOrder = 0; 5077 } 5078 result.addAll(alwaysAskList); 5079 includeBrowser = true; 5080 } 5081 5082 if (includeBrowser) { 5083 // Also add browsers (all of them or only the default one) 5084 if (DEBUG_DOMAIN_VERIFICATION) { 5085 Slog.v(TAG, " ...including browsers in candidate set"); 5086 } 5087 if ((matchFlags & MATCH_ALL) != 0) { 5088 result.addAll(matchAllList); 5089 } else { 5090 // Browser/generic handling case. If there's a default browser, go straight 5091 // to that (but only if there is no other higher-priority match). 5092 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5093 int maxMatchPrio = 0; 5094 ResolveInfo defaultBrowserMatch = null; 5095 final int numCandidates = matchAllList.size(); 5096 for (int n = 0; n < numCandidates; n++) { 5097 ResolveInfo info = matchAllList.get(n); 5098 // track the highest overall match priority... 5099 if (info.priority > maxMatchPrio) { 5100 maxMatchPrio = info.priority; 5101 } 5102 // ...and the highest-priority default browser match 5103 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5104 if (defaultBrowserMatch == null 5105 || (defaultBrowserMatch.priority < info.priority)) { 5106 if (debug) { 5107 Slog.v(TAG, "Considering default browser match " + info); 5108 } 5109 defaultBrowserMatch = info; 5110 } 5111 } 5112 } 5113 if (defaultBrowserMatch != null 5114 && defaultBrowserMatch.priority >= maxMatchPrio 5115 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5116 { 5117 if (debug) { 5118 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5119 } 5120 result.add(defaultBrowserMatch); 5121 } else { 5122 result.addAll(matchAllList); 5123 } 5124 } 5125 5126 // If there is nothing selected, add all candidates and remove the ones that the user 5127 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5128 if (result.size() == 0) { 5129 result.addAll(candidates); 5130 result.removeAll(neverList); 5131 } 5132 } 5133 } 5134 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5135 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5136 result.size()); 5137 for (ResolveInfo info : result) { 5138 Slog.v(TAG, " + " + info.activityInfo); 5139 } 5140 } 5141 return result; 5142 } 5143 5144 // Returns a packed value as a long: 5145 // 5146 // high 'int'-sized word: link status: undefined/ask/never/always. 5147 // low 'int'-sized word: relative priority among 'always' results. 5148 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5149 long result = ps.getDomainVerificationStatusForUser(userId); 5150 // if none available, get the master status 5151 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5152 if (ps.getIntentFilterVerificationInfo() != null) { 5153 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5154 } 5155 } 5156 return result; 5157 } 5158 5159 private ResolveInfo querySkipCurrentProfileIntents( 5160 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5161 int flags, int sourceUserId) { 5162 if (matchingFilters != null) { 5163 int size = matchingFilters.size(); 5164 for (int i = 0; i < size; i ++) { 5165 CrossProfileIntentFilter filter = matchingFilters.get(i); 5166 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5167 // Checking if there are activities in the target user that can handle the 5168 // intent. 5169 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5170 resolvedType, flags, sourceUserId); 5171 if (resolveInfo != null) { 5172 return resolveInfo; 5173 } 5174 } 5175 } 5176 } 5177 return null; 5178 } 5179 5180 // Return matching ResolveInfo if any for skip current profile intent filters. 5181 private ResolveInfo queryCrossProfileIntents( 5182 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5183 int flags, int sourceUserId) { 5184 if (matchingFilters != null) { 5185 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5186 // match the same intent. For performance reasons, it is better not to 5187 // run queryIntent twice for the same userId 5188 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5189 int size = matchingFilters.size(); 5190 for (int i = 0; i < size; i++) { 5191 CrossProfileIntentFilter filter = matchingFilters.get(i); 5192 int targetUserId = filter.getTargetUserId(); 5193 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 5194 && !alreadyTriedUserIds.get(targetUserId)) { 5195 // Checking if there are activities in the target user that can handle the 5196 // intent. 5197 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5198 resolvedType, flags, sourceUserId); 5199 if (resolveInfo != null) return resolveInfo; 5200 alreadyTriedUserIds.put(targetUserId, true); 5201 } 5202 } 5203 } 5204 return null; 5205 } 5206 5207 /** 5208 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5209 * will forward the intent to the filter's target user. 5210 * Otherwise, returns null. 5211 */ 5212 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5213 String resolvedType, int flags, int sourceUserId) { 5214 int targetUserId = filter.getTargetUserId(); 5215 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5216 resolvedType, flags, targetUserId); 5217 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5218 && isUserEnabled(targetUserId)) { 5219 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5220 } 5221 return null; 5222 } 5223 5224 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5225 int sourceUserId, int targetUserId) { 5226 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5227 long ident = Binder.clearCallingIdentity(); 5228 boolean targetIsProfile; 5229 try { 5230 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5231 } finally { 5232 Binder.restoreCallingIdentity(ident); 5233 } 5234 String className; 5235 if (targetIsProfile) { 5236 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5237 } else { 5238 className = FORWARD_INTENT_TO_PARENT; 5239 } 5240 ComponentName forwardingActivityComponentName = new ComponentName( 5241 mAndroidApplication.packageName, className); 5242 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5243 sourceUserId); 5244 if (!targetIsProfile) { 5245 forwardingActivityInfo.showUserIcon = targetUserId; 5246 forwardingResolveInfo.noResourceId = true; 5247 } 5248 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5249 forwardingResolveInfo.priority = 0; 5250 forwardingResolveInfo.preferredOrder = 0; 5251 forwardingResolveInfo.match = 0; 5252 forwardingResolveInfo.isDefault = true; 5253 forwardingResolveInfo.filter = filter; 5254 forwardingResolveInfo.targetUserId = targetUserId; 5255 return forwardingResolveInfo; 5256 } 5257 5258 @Override 5259 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5260 Intent[] specifics, String[] specificTypes, Intent intent, 5261 String resolvedType, int flags, int userId) { 5262 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5263 flags = augmentFlagsForUser(flags, userId); 5264 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5265 false, "query intent activity options"); 5266 final String resultsAction = intent.getAction(); 5267 5268 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5269 | PackageManager.GET_RESOLVED_FILTER, userId); 5270 5271 if (DEBUG_INTENT_MATCHING) { 5272 Log.v(TAG, "Query " + intent + ": " + results); 5273 } 5274 5275 int specificsPos = 0; 5276 int N; 5277 5278 // todo: note that the algorithm used here is O(N^2). This 5279 // isn't a problem in our current environment, but if we start running 5280 // into situations where we have more than 5 or 10 matches then this 5281 // should probably be changed to something smarter... 5282 5283 // First we go through and resolve each of the specific items 5284 // that were supplied, taking care of removing any corresponding 5285 // duplicate items in the generic resolve list. 5286 if (specifics != null) { 5287 for (int i=0; i<specifics.length; i++) { 5288 final Intent sintent = specifics[i]; 5289 if (sintent == null) { 5290 continue; 5291 } 5292 5293 if (DEBUG_INTENT_MATCHING) { 5294 Log.v(TAG, "Specific #" + i + ": " + sintent); 5295 } 5296 5297 String action = sintent.getAction(); 5298 if (resultsAction != null && resultsAction.equals(action)) { 5299 // If this action was explicitly requested, then don't 5300 // remove things that have it. 5301 action = null; 5302 } 5303 5304 ResolveInfo ri = null; 5305 ActivityInfo ai = null; 5306 5307 ComponentName comp = sintent.getComponent(); 5308 if (comp == null) { 5309 ri = resolveIntent( 5310 sintent, 5311 specificTypes != null ? specificTypes[i] : null, 5312 flags, userId); 5313 if (ri == null) { 5314 continue; 5315 } 5316 if (ri == mResolveInfo) { 5317 // ACK! Must do something better with this. 5318 } 5319 ai = ri.activityInfo; 5320 comp = new ComponentName(ai.applicationInfo.packageName, 5321 ai.name); 5322 } else { 5323 ai = getActivityInfo(comp, flags, userId); 5324 if (ai == null) { 5325 continue; 5326 } 5327 } 5328 5329 // Look for any generic query activities that are duplicates 5330 // of this specific one, and remove them from the results. 5331 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5332 N = results.size(); 5333 int j; 5334 for (j=specificsPos; j<N; j++) { 5335 ResolveInfo sri = results.get(j); 5336 if ((sri.activityInfo.name.equals(comp.getClassName()) 5337 && sri.activityInfo.applicationInfo.packageName.equals( 5338 comp.getPackageName())) 5339 || (action != null && sri.filter.matchAction(action))) { 5340 results.remove(j); 5341 if (DEBUG_INTENT_MATCHING) Log.v( 5342 TAG, "Removing duplicate item from " + j 5343 + " due to specific " + specificsPos); 5344 if (ri == null) { 5345 ri = sri; 5346 } 5347 j--; 5348 N--; 5349 } 5350 } 5351 5352 // Add this specific item to its proper place. 5353 if (ri == null) { 5354 ri = new ResolveInfo(); 5355 ri.activityInfo = ai; 5356 } 5357 results.add(specificsPos, ri); 5358 ri.specificIndex = i; 5359 specificsPos++; 5360 } 5361 } 5362 5363 // Now we go through the remaining generic results and remove any 5364 // duplicate actions that are found here. 5365 N = results.size(); 5366 for (int i=specificsPos; i<N-1; i++) { 5367 final ResolveInfo rii = results.get(i); 5368 if (rii.filter == null) { 5369 continue; 5370 } 5371 5372 // Iterate over all of the actions of this result's intent 5373 // filter... typically this should be just one. 5374 final Iterator<String> it = rii.filter.actionsIterator(); 5375 if (it == null) { 5376 continue; 5377 } 5378 while (it.hasNext()) { 5379 final String action = it.next(); 5380 if (resultsAction != null && resultsAction.equals(action)) { 5381 // If this action was explicitly requested, then don't 5382 // remove things that have it. 5383 continue; 5384 } 5385 for (int j=i+1; j<N; j++) { 5386 final ResolveInfo rij = results.get(j); 5387 if (rij.filter != null && rij.filter.hasAction(action)) { 5388 results.remove(j); 5389 if (DEBUG_INTENT_MATCHING) Log.v( 5390 TAG, "Removing duplicate item from " + j 5391 + " due to action " + action + " at " + i); 5392 j--; 5393 N--; 5394 } 5395 } 5396 } 5397 5398 // If the caller didn't request filter information, drop it now 5399 // so we don't have to marshall/unmarshall it. 5400 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5401 rii.filter = null; 5402 } 5403 } 5404 5405 // Filter out the caller activity if so requested. 5406 if (caller != null) { 5407 N = results.size(); 5408 for (int i=0; i<N; i++) { 5409 ActivityInfo ainfo = results.get(i).activityInfo; 5410 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5411 && caller.getClassName().equals(ainfo.name)) { 5412 results.remove(i); 5413 break; 5414 } 5415 } 5416 } 5417 5418 // If the caller didn't request filter information, 5419 // drop them now so we don't have to 5420 // marshall/unmarshall it. 5421 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5422 N = results.size(); 5423 for (int i=0; i<N; i++) { 5424 results.get(i).filter = null; 5425 } 5426 } 5427 5428 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5429 return results; 5430 } 5431 5432 @Override 5433 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5434 int userId) { 5435 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5436 flags = augmentFlagsForUser(flags, userId); 5437 ComponentName comp = intent.getComponent(); 5438 if (comp == null) { 5439 if (intent.getSelector() != null) { 5440 intent = intent.getSelector(); 5441 comp = intent.getComponent(); 5442 } 5443 } 5444 if (comp != null) { 5445 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5446 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5447 if (ai != null) { 5448 ResolveInfo ri = new ResolveInfo(); 5449 ri.activityInfo = ai; 5450 list.add(ri); 5451 } 5452 return list; 5453 } 5454 5455 // reader 5456 synchronized (mPackages) { 5457 String pkgName = intent.getPackage(); 5458 if (pkgName == null) { 5459 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5460 } 5461 final PackageParser.Package pkg = mPackages.get(pkgName); 5462 if (pkg != null) { 5463 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5464 userId); 5465 } 5466 return null; 5467 } 5468 } 5469 5470 @Override 5471 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5472 if (!sUserManager.exists(userId)) return null; 5473 flags = augmentFlagsForUser(flags, userId); 5474 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5475 if (query != null) { 5476 if (query.size() >= 1) { 5477 // If there is more than one service with the same priority, 5478 // just arbitrarily pick the first one. 5479 return query.get(0); 5480 } 5481 } 5482 return null; 5483 } 5484 5485 @Override 5486 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5487 int userId) { 5488 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5489 flags = augmentFlagsForUser(flags, userId); 5490 ComponentName comp = intent.getComponent(); 5491 if (comp == null) { 5492 if (intent.getSelector() != null) { 5493 intent = intent.getSelector(); 5494 comp = intent.getComponent(); 5495 } 5496 } 5497 if (comp != null) { 5498 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5499 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5500 if (si != null) { 5501 final ResolveInfo ri = new ResolveInfo(); 5502 ri.serviceInfo = si; 5503 list.add(ri); 5504 } 5505 return list; 5506 } 5507 5508 // reader 5509 synchronized (mPackages) { 5510 String pkgName = intent.getPackage(); 5511 if (pkgName == null) { 5512 return mServices.queryIntent(intent, resolvedType, flags, userId); 5513 } 5514 final PackageParser.Package pkg = mPackages.get(pkgName); 5515 if (pkg != null) { 5516 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5517 userId); 5518 } 5519 return null; 5520 } 5521 } 5522 5523 @Override 5524 public List<ResolveInfo> queryIntentContentProviders( 5525 Intent intent, String resolvedType, int flags, int userId) { 5526 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5527 flags = augmentFlagsForUser(flags, userId); 5528 ComponentName comp = intent.getComponent(); 5529 if (comp == null) { 5530 if (intent.getSelector() != null) { 5531 intent = intent.getSelector(); 5532 comp = intent.getComponent(); 5533 } 5534 } 5535 if (comp != null) { 5536 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5537 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5538 if (pi != null) { 5539 final ResolveInfo ri = new ResolveInfo(); 5540 ri.providerInfo = pi; 5541 list.add(ri); 5542 } 5543 return list; 5544 } 5545 5546 // reader 5547 synchronized (mPackages) { 5548 String pkgName = intent.getPackage(); 5549 if (pkgName == null) { 5550 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5551 } 5552 final PackageParser.Package pkg = mPackages.get(pkgName); 5553 if (pkg != null) { 5554 return mProviders.queryIntentForPackage( 5555 intent, resolvedType, flags, pkg.providers, userId); 5556 } 5557 return null; 5558 } 5559 } 5560 5561 @Override 5562 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5563 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5564 5565 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5566 5567 // writer 5568 synchronized (mPackages) { 5569 ArrayList<PackageInfo> list; 5570 if (listUninstalled) { 5571 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5572 for (PackageSetting ps : mSettings.mPackages.values()) { 5573 PackageInfo pi; 5574 if (ps.pkg != null) { 5575 pi = generatePackageInfo(ps.pkg, flags, userId); 5576 } else { 5577 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5578 } 5579 if (pi != null) { 5580 list.add(pi); 5581 } 5582 } 5583 } else { 5584 list = new ArrayList<PackageInfo>(mPackages.size()); 5585 for (PackageParser.Package p : mPackages.values()) { 5586 PackageInfo pi = generatePackageInfo(p, flags, userId); 5587 if (pi != null) { 5588 list.add(pi); 5589 } 5590 } 5591 } 5592 5593 return new ParceledListSlice<PackageInfo>(list); 5594 } 5595 } 5596 5597 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5598 String[] permissions, boolean[] tmp, int flags, int userId) { 5599 int numMatch = 0; 5600 final PermissionsState permissionsState = ps.getPermissionsState(); 5601 for (int i=0; i<permissions.length; i++) { 5602 final String permission = permissions[i]; 5603 if (permissionsState.hasPermission(permission, userId)) { 5604 tmp[i] = true; 5605 numMatch++; 5606 } else { 5607 tmp[i] = false; 5608 } 5609 } 5610 if (numMatch == 0) { 5611 return; 5612 } 5613 PackageInfo pi; 5614 if (ps.pkg != null) { 5615 pi = generatePackageInfo(ps.pkg, flags, userId); 5616 } else { 5617 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5618 } 5619 // The above might return null in cases of uninstalled apps or install-state 5620 // skew across users/profiles. 5621 if (pi != null) { 5622 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5623 if (numMatch == permissions.length) { 5624 pi.requestedPermissions = permissions; 5625 } else { 5626 pi.requestedPermissions = new String[numMatch]; 5627 numMatch = 0; 5628 for (int i=0; i<permissions.length; i++) { 5629 if (tmp[i]) { 5630 pi.requestedPermissions[numMatch] = permissions[i]; 5631 numMatch++; 5632 } 5633 } 5634 } 5635 } 5636 list.add(pi); 5637 } 5638 } 5639 5640 @Override 5641 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5642 String[] permissions, int flags, int userId) { 5643 if (!sUserManager.exists(userId)) return null; 5644 flags = augmentFlagsForUser(flags, userId); 5645 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5646 5647 // writer 5648 synchronized (mPackages) { 5649 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5650 boolean[] tmpBools = new boolean[permissions.length]; 5651 if (listUninstalled) { 5652 for (PackageSetting ps : mSettings.mPackages.values()) { 5653 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5654 } 5655 } else { 5656 for (PackageParser.Package pkg : mPackages.values()) { 5657 PackageSetting ps = (PackageSetting)pkg.mExtras; 5658 if (ps != null) { 5659 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5660 userId); 5661 } 5662 } 5663 } 5664 5665 return new ParceledListSlice<PackageInfo>(list); 5666 } 5667 } 5668 5669 @Override 5670 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5671 if (!sUserManager.exists(userId)) return null; 5672 flags = augmentFlagsForUser(flags, userId); 5673 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5674 5675 // writer 5676 synchronized (mPackages) { 5677 ArrayList<ApplicationInfo> list; 5678 if (listUninstalled) { 5679 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5680 for (PackageSetting ps : mSettings.mPackages.values()) { 5681 ApplicationInfo ai; 5682 if (ps.pkg != null) { 5683 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5684 ps.readUserState(userId), userId); 5685 } else { 5686 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5687 } 5688 if (ai != null) { 5689 list.add(ai); 5690 } 5691 } 5692 } else { 5693 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5694 for (PackageParser.Package p : mPackages.values()) { 5695 if (p.mExtras != null) { 5696 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5697 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5698 if (ai != null) { 5699 list.add(ai); 5700 } 5701 } 5702 } 5703 } 5704 5705 return new ParceledListSlice<ApplicationInfo>(list); 5706 } 5707 } 5708 5709 public List<ApplicationInfo> getPersistentApplications(int flags) { 5710 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5711 5712 // reader 5713 synchronized (mPackages) { 5714 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5715 final int userId = UserHandle.getCallingUserId(); 5716 while (i.hasNext()) { 5717 final PackageParser.Package p = i.next(); 5718 if (p.applicationInfo != null 5719 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5720 && (!mSafeMode || isSystemApp(p))) { 5721 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5722 if (ps != null) { 5723 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5724 ps.readUserState(userId), userId); 5725 if (ai != null) { 5726 finalList.add(ai); 5727 } 5728 } 5729 } 5730 } 5731 } 5732 5733 return finalList; 5734 } 5735 5736 @Override 5737 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5738 if (!sUserManager.exists(userId)) return null; 5739 flags = augmentFlagsForUser(flags, userId); 5740 // reader 5741 synchronized (mPackages) { 5742 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5743 PackageSetting ps = provider != null 5744 ? mSettings.mPackages.get(provider.owner.packageName) 5745 : null; 5746 return ps != null 5747 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5748 && (!mSafeMode || (provider.info.applicationInfo.flags 5749 &ApplicationInfo.FLAG_SYSTEM) != 0) 5750 ? PackageParser.generateProviderInfo(provider, flags, 5751 ps.readUserState(userId), userId) 5752 : null; 5753 } 5754 } 5755 5756 /** 5757 * @deprecated 5758 */ 5759 @Deprecated 5760 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5761 // reader 5762 synchronized (mPackages) { 5763 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5764 .entrySet().iterator(); 5765 final int userId = UserHandle.getCallingUserId(); 5766 while (i.hasNext()) { 5767 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5768 PackageParser.Provider p = entry.getValue(); 5769 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5770 5771 if (ps != null && p.syncable 5772 && (!mSafeMode || (p.info.applicationInfo.flags 5773 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5774 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5775 ps.readUserState(userId), userId); 5776 if (info != null) { 5777 outNames.add(entry.getKey()); 5778 outInfo.add(info); 5779 } 5780 } 5781 } 5782 } 5783 } 5784 5785 @Override 5786 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5787 int uid, int flags) { 5788 final int userId = processName != null ? UserHandle.getUserId(uid) 5789 : UserHandle.getCallingUserId(); 5790 if (!sUserManager.exists(userId)) return null; 5791 flags = augmentFlagsForUser(flags, userId); 5792 5793 ArrayList<ProviderInfo> finalList = null; 5794 // reader 5795 synchronized (mPackages) { 5796 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5797 while (i.hasNext()) { 5798 final PackageParser.Provider p = i.next(); 5799 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5800 if (ps != null && p.info.authority != null 5801 && (processName == null 5802 || (p.info.processName.equals(processName) 5803 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5804 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5805 && (!mSafeMode 5806 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5807 if (finalList == null) { 5808 finalList = new ArrayList<ProviderInfo>(3); 5809 } 5810 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5811 ps.readUserState(userId), userId); 5812 if (info != null) { 5813 finalList.add(info); 5814 } 5815 } 5816 } 5817 } 5818 5819 if (finalList != null) { 5820 Collections.sort(finalList, mProviderInitOrderSorter); 5821 return new ParceledListSlice<ProviderInfo>(finalList); 5822 } 5823 5824 return null; 5825 } 5826 5827 @Override 5828 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5829 int flags) { 5830 // reader 5831 synchronized (mPackages) { 5832 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5833 return PackageParser.generateInstrumentationInfo(i, flags); 5834 } 5835 } 5836 5837 @Override 5838 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5839 int flags) { 5840 ArrayList<InstrumentationInfo> finalList = 5841 new ArrayList<InstrumentationInfo>(); 5842 5843 // reader 5844 synchronized (mPackages) { 5845 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5846 while (i.hasNext()) { 5847 final PackageParser.Instrumentation p = i.next(); 5848 if (targetPackage == null 5849 || targetPackage.equals(p.info.targetPackage)) { 5850 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5851 flags); 5852 if (ii != null) { 5853 finalList.add(ii); 5854 } 5855 } 5856 } 5857 } 5858 5859 return finalList; 5860 } 5861 5862 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5863 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5864 if (overlays == null) { 5865 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5866 return; 5867 } 5868 for (PackageParser.Package opkg : overlays.values()) { 5869 // Not much to do if idmap fails: we already logged the error 5870 // and we certainly don't want to abort installation of pkg simply 5871 // because an overlay didn't fit properly. For these reasons, 5872 // ignore the return value of createIdmapForPackagePairLI. 5873 createIdmapForPackagePairLI(pkg, opkg); 5874 } 5875 } 5876 5877 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5878 PackageParser.Package opkg) { 5879 if (!opkg.mTrustedOverlay) { 5880 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5881 opkg.baseCodePath + ": overlay not trusted"); 5882 return false; 5883 } 5884 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5885 if (overlaySet == null) { 5886 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5887 opkg.baseCodePath + " but target package has no known overlays"); 5888 return false; 5889 } 5890 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5891 // TODO: generate idmap for split APKs 5892 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5893 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5894 + opkg.baseCodePath); 5895 return false; 5896 } 5897 PackageParser.Package[] overlayArray = 5898 overlaySet.values().toArray(new PackageParser.Package[0]); 5899 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5900 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5901 return p1.mOverlayPriority - p2.mOverlayPriority; 5902 } 5903 }; 5904 Arrays.sort(overlayArray, cmp); 5905 5906 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5907 int i = 0; 5908 for (PackageParser.Package p : overlayArray) { 5909 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5910 } 5911 return true; 5912 } 5913 5914 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5915 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5916 try { 5917 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5918 } finally { 5919 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5920 } 5921 } 5922 5923 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5924 final File[] files = dir.listFiles(); 5925 if (ArrayUtils.isEmpty(files)) { 5926 Log.d(TAG, "No files in app dir " + dir); 5927 return; 5928 } 5929 5930 if (DEBUG_PACKAGE_SCANNING) { 5931 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5932 + " flags=0x" + Integer.toHexString(parseFlags)); 5933 } 5934 5935 for (File file : files) { 5936 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5937 && !PackageInstallerService.isStageName(file.getName()); 5938 if (!isPackage) { 5939 // Ignore entries which are not packages 5940 continue; 5941 } 5942 try { 5943 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5944 scanFlags, currentTime, null); 5945 } catch (PackageManagerException e) { 5946 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5947 5948 // Delete invalid userdata apps 5949 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5950 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5951 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5952 if (file.isDirectory()) { 5953 mInstaller.rmPackageDir(file.getAbsolutePath()); 5954 } else { 5955 file.delete(); 5956 } 5957 } 5958 } 5959 } 5960 } 5961 5962 private static File getSettingsProblemFile() { 5963 File dataDir = Environment.getDataDirectory(); 5964 File systemDir = new File(dataDir, "system"); 5965 File fname = new File(systemDir, "uiderrors.txt"); 5966 return fname; 5967 } 5968 5969 static void reportSettingsProblem(int priority, String msg) { 5970 logCriticalInfo(priority, msg); 5971 } 5972 5973 static void logCriticalInfo(int priority, String msg) { 5974 Slog.println(priority, TAG, msg); 5975 EventLogTags.writePmCriticalInfo(msg); 5976 try { 5977 File fname = getSettingsProblemFile(); 5978 FileOutputStream out = new FileOutputStream(fname, true); 5979 PrintWriter pw = new FastPrintWriter(out); 5980 SimpleDateFormat formatter = new SimpleDateFormat(); 5981 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5982 pw.println(dateString + ": " + msg); 5983 pw.close(); 5984 FileUtils.setPermissions( 5985 fname.toString(), 5986 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5987 -1, -1); 5988 } catch (java.io.IOException e) { 5989 } 5990 } 5991 5992 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5993 PackageParser.Package pkg, File srcFile, int parseFlags) 5994 throws PackageManagerException { 5995 if (ps != null 5996 && ps.codePath.equals(srcFile) 5997 && ps.timeStamp == srcFile.lastModified() 5998 && !isCompatSignatureUpdateNeeded(pkg) 5999 && !isRecoverSignatureUpdateNeeded(pkg)) { 6000 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6001 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6002 ArraySet<PublicKey> signingKs; 6003 synchronized (mPackages) { 6004 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6005 } 6006 if (ps.signatures.mSignatures != null 6007 && ps.signatures.mSignatures.length != 0 6008 && signingKs != null) { 6009 // Optimization: reuse the existing cached certificates 6010 // if the package appears to be unchanged. 6011 pkg.mSignatures = ps.signatures.mSignatures; 6012 pkg.mSigningKeys = signingKs; 6013 return; 6014 } 6015 6016 Slog.w(TAG, "PackageSetting for " + ps.name 6017 + " is missing signatures. Collecting certs again to recover them."); 6018 } else { 6019 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6020 } 6021 6022 try { 6023 pp.collectCertificates(pkg, parseFlags); 6024 pp.collectManifestDigest(pkg); 6025 } catch (PackageParserException e) { 6026 throw PackageManagerException.from(e); 6027 } 6028 } 6029 6030 /** 6031 * Traces a package scan. 6032 * @see #scanPackageLI(File, int, int, long, UserHandle) 6033 */ 6034 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6035 long currentTime, UserHandle user) throws PackageManagerException { 6036 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6037 try { 6038 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6039 } finally { 6040 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6041 } 6042 } 6043 6044 /** 6045 * Scans a package and returns the newly parsed package. 6046 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6047 */ 6048 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6049 long currentTime, UserHandle user) throws PackageManagerException { 6050 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6051 parseFlags |= mDefParseFlags; 6052 PackageParser pp = new PackageParser(); 6053 pp.setSeparateProcesses(mSeparateProcesses); 6054 pp.setOnlyCoreApps(mOnlyCore); 6055 pp.setDisplayMetrics(mMetrics); 6056 6057 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6058 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6059 } 6060 6061 final PackageParser.Package pkg; 6062 try { 6063 pkg = pp.parsePackage(scanFile, parseFlags); 6064 } catch (PackageParserException e) { 6065 throw PackageManagerException.from(e); 6066 } 6067 6068 PackageSetting ps = null; 6069 PackageSetting updatedPkg; 6070 // reader 6071 synchronized (mPackages) { 6072 // Look to see if we already know about this package. 6073 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6074 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6075 // This package has been renamed to its original name. Let's 6076 // use that. 6077 ps = mSettings.peekPackageLPr(oldName); 6078 } 6079 // If there was no original package, see one for the real package name. 6080 if (ps == null) { 6081 ps = mSettings.peekPackageLPr(pkg.packageName); 6082 } 6083 // Check to see if this package could be hiding/updating a system 6084 // package. Must look for it either under the original or real 6085 // package name depending on our state. 6086 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6087 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6088 } 6089 boolean updatedPkgBetter = false; 6090 // First check if this is a system package that may involve an update 6091 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6092 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6093 // it needs to drop FLAG_PRIVILEGED. 6094 if (locationIsPrivileged(scanFile)) { 6095 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6096 } else { 6097 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6098 } 6099 6100 if (ps != null && !ps.codePath.equals(scanFile)) { 6101 // The path has changed from what was last scanned... check the 6102 // version of the new path against what we have stored to determine 6103 // what to do. 6104 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6105 if (pkg.mVersionCode <= ps.versionCode) { 6106 // The system package has been updated and the code path does not match 6107 // Ignore entry. Skip it. 6108 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6109 + " ignored: updated version " + ps.versionCode 6110 + " better than this " + pkg.mVersionCode); 6111 if (!updatedPkg.codePath.equals(scanFile)) { 6112 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 6113 + ps.name + " changing from " + updatedPkg.codePathString 6114 + " to " + scanFile); 6115 updatedPkg.codePath = scanFile; 6116 updatedPkg.codePathString = scanFile.toString(); 6117 updatedPkg.resourcePath = scanFile; 6118 updatedPkg.resourcePathString = scanFile.toString(); 6119 } 6120 updatedPkg.pkg = pkg; 6121 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6122 "Package " + ps.name + " at " + scanFile 6123 + " ignored: updated version " + ps.versionCode 6124 + " better than this " + pkg.mVersionCode); 6125 } else { 6126 // The current app on the system partition is better than 6127 // what we have updated to on the data partition; switch 6128 // back to the system partition version. 6129 // At this point, its safely assumed that package installation for 6130 // apps in system partition will go through. If not there won't be a working 6131 // version of the app 6132 // writer 6133 synchronized (mPackages) { 6134 // Just remove the loaded entries from package lists. 6135 mPackages.remove(ps.name); 6136 } 6137 6138 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6139 + " reverting from " + ps.codePathString 6140 + ": new version " + pkg.mVersionCode 6141 + " better than installed " + ps.versionCode); 6142 6143 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6144 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6145 synchronized (mInstallLock) { 6146 args.cleanUpResourcesLI(); 6147 } 6148 synchronized (mPackages) { 6149 mSettings.enableSystemPackageLPw(ps.name); 6150 } 6151 updatedPkgBetter = true; 6152 } 6153 } 6154 } 6155 6156 if (updatedPkg != null) { 6157 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6158 // initially 6159 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6160 6161 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6162 // flag set initially 6163 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6164 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6165 } 6166 } 6167 6168 // Verify certificates against what was last scanned 6169 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6170 6171 /* 6172 * A new system app appeared, but we already had a non-system one of the 6173 * same name installed earlier. 6174 */ 6175 boolean shouldHideSystemApp = false; 6176 if (updatedPkg == null && ps != null 6177 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6178 /* 6179 * Check to make sure the signatures match first. If they don't, 6180 * wipe the installed application and its data. 6181 */ 6182 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6183 != PackageManager.SIGNATURE_MATCH) { 6184 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6185 + " signatures don't match existing userdata copy; removing"); 6186 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6187 ps = null; 6188 } else { 6189 /* 6190 * If the newly-added system app is an older version than the 6191 * already installed version, hide it. It will be scanned later 6192 * and re-added like an update. 6193 */ 6194 if (pkg.mVersionCode <= ps.versionCode) { 6195 shouldHideSystemApp = true; 6196 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6197 + " but new version " + pkg.mVersionCode + " better than installed " 6198 + ps.versionCode + "; hiding system"); 6199 } else { 6200 /* 6201 * The newly found system app is a newer version that the 6202 * one previously installed. Simply remove the 6203 * already-installed application and replace it with our own 6204 * while keeping the application data. 6205 */ 6206 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6207 + " reverting from " + ps.codePathString + ": new version " 6208 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6209 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6210 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6211 synchronized (mInstallLock) { 6212 args.cleanUpResourcesLI(); 6213 } 6214 } 6215 } 6216 } 6217 6218 // The apk is forward locked (not public) if its code and resources 6219 // are kept in different files. (except for app in either system or 6220 // vendor path). 6221 // TODO grab this value from PackageSettings 6222 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6223 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6224 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6225 } 6226 } 6227 6228 // TODO: extend to support forward-locked splits 6229 String resourcePath = null; 6230 String baseResourcePath = null; 6231 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6232 if (ps != null && ps.resourcePathString != null) { 6233 resourcePath = ps.resourcePathString; 6234 baseResourcePath = ps.resourcePathString; 6235 } else { 6236 // Should not happen at all. Just log an error. 6237 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6238 } 6239 } else { 6240 resourcePath = pkg.codePath; 6241 baseResourcePath = pkg.baseCodePath; 6242 } 6243 6244 // Set application objects path explicitly. 6245 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6246 pkg.applicationInfo.setCodePath(pkg.codePath); 6247 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6248 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6249 pkg.applicationInfo.setResourcePath(resourcePath); 6250 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6251 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6252 6253 // Note that we invoke the following method only if we are about to unpack an application 6254 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6255 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6256 6257 /* 6258 * If the system app should be overridden by a previously installed 6259 * data, hide the system app now and let the /data/app scan pick it up 6260 * again. 6261 */ 6262 if (shouldHideSystemApp) { 6263 synchronized (mPackages) { 6264 mSettings.disableSystemPackageLPw(pkg.packageName); 6265 } 6266 } 6267 6268 return scannedPkg; 6269 } 6270 6271 private static String fixProcessName(String defProcessName, 6272 String processName, int uid) { 6273 if (processName == null) { 6274 return defProcessName; 6275 } 6276 return processName; 6277 } 6278 6279 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6280 throws PackageManagerException { 6281 if (pkgSetting.signatures.mSignatures != null) { 6282 // Already existing package. Make sure signatures match 6283 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6284 == PackageManager.SIGNATURE_MATCH; 6285 if (!match) { 6286 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6287 == PackageManager.SIGNATURE_MATCH; 6288 } 6289 if (!match) { 6290 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6291 == PackageManager.SIGNATURE_MATCH; 6292 } 6293 if (!match) { 6294 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6295 + pkg.packageName + " signatures do not match the " 6296 + "previously installed version; ignoring!"); 6297 } 6298 } 6299 6300 // Check for shared user signatures 6301 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6302 // Already existing package. Make sure signatures match 6303 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6304 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6305 if (!match) { 6306 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6307 == PackageManager.SIGNATURE_MATCH; 6308 } 6309 if (!match) { 6310 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6311 == PackageManager.SIGNATURE_MATCH; 6312 } 6313 if (!match) { 6314 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6315 "Package " + pkg.packageName 6316 + " has no signatures that match those in shared user " 6317 + pkgSetting.sharedUser.name + "; ignoring!"); 6318 } 6319 } 6320 } 6321 6322 /** 6323 * Enforces that only the system UID or root's UID can call a method exposed 6324 * via Binder. 6325 * 6326 * @param message used as message if SecurityException is thrown 6327 * @throws SecurityException if the caller is not system or root 6328 */ 6329 private static final void enforceSystemOrRoot(String message) { 6330 final int uid = Binder.getCallingUid(); 6331 if (uid != Process.SYSTEM_UID && uid != 0) { 6332 throw new SecurityException(message); 6333 } 6334 } 6335 6336 @Override 6337 public void performFstrimIfNeeded() { 6338 enforceSystemOrRoot("Only the system can request fstrim"); 6339 6340 // Before everything else, see whether we need to fstrim. 6341 try { 6342 IMountService ms = PackageHelper.getMountService(); 6343 if (ms != null) { 6344 final boolean isUpgrade = isUpgrade(); 6345 boolean doTrim = isUpgrade; 6346 if (doTrim) { 6347 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6348 } else { 6349 final long interval = android.provider.Settings.Global.getLong( 6350 mContext.getContentResolver(), 6351 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6352 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6353 if (interval > 0) { 6354 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6355 if (timeSinceLast > interval) { 6356 doTrim = true; 6357 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6358 + "; running immediately"); 6359 } 6360 } 6361 } 6362 if (doTrim) { 6363 if (!isFirstBoot()) { 6364 try { 6365 ActivityManagerNative.getDefault().showBootMessage( 6366 mContext.getResources().getString( 6367 R.string.android_upgrading_fstrim), true); 6368 } catch (RemoteException e) { 6369 } 6370 } 6371 ms.runMaintenance(); 6372 } 6373 } else { 6374 Slog.e(TAG, "Mount service unavailable!"); 6375 } 6376 } catch (RemoteException e) { 6377 // Can't happen; MountService is local 6378 } 6379 } 6380 6381 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6382 List<ResolveInfo> ris = null; 6383 try { 6384 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6385 intent, null, 0, userId); 6386 } catch (RemoteException e) { 6387 } 6388 ArraySet<String> pkgNames = new ArraySet<String>(); 6389 if (ris != null) { 6390 for (ResolveInfo ri : ris) { 6391 pkgNames.add(ri.activityInfo.packageName); 6392 } 6393 } 6394 return pkgNames; 6395 } 6396 6397 @Override 6398 public void notifyPackageUse(String packageName) { 6399 synchronized (mPackages) { 6400 PackageParser.Package p = mPackages.get(packageName); 6401 if (p == null) { 6402 return; 6403 } 6404 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6405 } 6406 } 6407 6408 @Override 6409 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6410 return performDexOptTraced(packageName, instructionSet); 6411 } 6412 6413 public boolean performDexOpt(String packageName, String instructionSet) { 6414 return performDexOptTraced(packageName, instructionSet); 6415 } 6416 6417 private boolean performDexOptTraced(String packageName, String instructionSet) { 6418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6419 try { 6420 return performDexOptInternal(packageName, instructionSet); 6421 } finally { 6422 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6423 } 6424 } 6425 6426 private boolean performDexOptInternal(String packageName, String instructionSet) { 6427 PackageParser.Package p; 6428 final String targetInstructionSet; 6429 synchronized (mPackages) { 6430 p = mPackages.get(packageName); 6431 if (p == null) { 6432 return false; 6433 } 6434 mPackageUsage.write(false); 6435 6436 targetInstructionSet = instructionSet != null ? instructionSet : 6437 getPrimaryInstructionSet(p.applicationInfo); 6438 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6439 return false; 6440 } 6441 } 6442 long callingId = Binder.clearCallingIdentity(); 6443 try { 6444 synchronized (mInstallLock) { 6445 final String[] instructionSets = new String[] { targetInstructionSet }; 6446 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6447 true /* inclDependencies */); 6448 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6449 } 6450 } finally { 6451 Binder.restoreCallingIdentity(callingId); 6452 } 6453 } 6454 6455 public ArraySet<String> getPackagesThatNeedDexOpt() { 6456 ArraySet<String> pkgs = null; 6457 synchronized (mPackages) { 6458 for (PackageParser.Package p : mPackages.values()) { 6459 if (DEBUG_DEXOPT) { 6460 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6461 } 6462 if (!p.mDexOptPerformed.isEmpty()) { 6463 continue; 6464 } 6465 if (pkgs == null) { 6466 pkgs = new ArraySet<String>(); 6467 } 6468 pkgs.add(p.packageName); 6469 } 6470 } 6471 return pkgs; 6472 } 6473 6474 public void shutdown() { 6475 mPackageUsage.write(true); 6476 } 6477 6478 @Override 6479 public void forceDexOpt(String packageName) { 6480 enforceSystemOrRoot("forceDexOpt"); 6481 6482 PackageParser.Package pkg; 6483 synchronized (mPackages) { 6484 pkg = mPackages.get(packageName); 6485 if (pkg == null) { 6486 throw new IllegalArgumentException("Missing package: " + packageName); 6487 } 6488 } 6489 6490 synchronized (mInstallLock) { 6491 final String[] instructionSets = new String[] { 6492 getPrimaryInstructionSet(pkg.applicationInfo) }; 6493 6494 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6495 6496 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6497 true /* inclDependencies */); 6498 6499 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6500 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6501 throw new IllegalStateException("Failed to dexopt: " + res); 6502 } 6503 } 6504 } 6505 6506 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6507 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6508 Slog.w(TAG, "Unable to update from " + oldPkg.name 6509 + " to " + newPkg.packageName 6510 + ": old package not in system partition"); 6511 return false; 6512 } else if (mPackages.get(oldPkg.name) != null) { 6513 Slog.w(TAG, "Unable to update from " + oldPkg.name 6514 + " to " + newPkg.packageName 6515 + ": old package still exists"); 6516 return false; 6517 } 6518 return true; 6519 } 6520 6521 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6522 throws PackageManagerException { 6523 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6524 if (res != 0) { 6525 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6526 "Failed to install " + packageName + ": " + res); 6527 } 6528 6529 final int[] users = sUserManager.getUserIds(); 6530 for (int user : users) { 6531 if (user != 0) { 6532 res = mInstaller.createUserData(volumeUuid, packageName, 6533 UserHandle.getUid(user, uid), user, seinfo); 6534 if (res != 0) { 6535 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6536 "Failed to createUserData " + packageName + ": " + res); 6537 } 6538 } 6539 } 6540 } 6541 6542 private int removeDataDirsLI(String volumeUuid, String packageName) { 6543 int[] users = sUserManager.getUserIds(); 6544 int res = 0; 6545 for (int user : users) { 6546 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6547 if (resInner < 0) { 6548 res = resInner; 6549 } 6550 } 6551 6552 return res; 6553 } 6554 6555 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6556 int[] users = sUserManager.getUserIds(); 6557 int res = 0; 6558 for (int user : users) { 6559 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6560 if (resInner < 0) { 6561 res = resInner; 6562 } 6563 } 6564 return res; 6565 } 6566 6567 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6568 PackageParser.Package changingLib) { 6569 if (file.path != null) { 6570 usesLibraryFiles.add(file.path); 6571 return; 6572 } 6573 PackageParser.Package p = mPackages.get(file.apk); 6574 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6575 // If we are doing this while in the middle of updating a library apk, 6576 // then we need to make sure to use that new apk for determining the 6577 // dependencies here. (We haven't yet finished committing the new apk 6578 // to the package manager state.) 6579 if (p == null || p.packageName.equals(changingLib.packageName)) { 6580 p = changingLib; 6581 } 6582 } 6583 if (p != null) { 6584 usesLibraryFiles.addAll(p.getAllCodePaths()); 6585 } 6586 } 6587 6588 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6589 PackageParser.Package changingLib) throws PackageManagerException { 6590 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6591 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6592 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6593 for (int i=0; i<N; i++) { 6594 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6595 if (file == null) { 6596 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6597 "Package " + pkg.packageName + " requires unavailable shared library " 6598 + pkg.usesLibraries.get(i) + "; failing!"); 6599 } 6600 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6601 } 6602 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6603 for (int i=0; i<N; i++) { 6604 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6605 if (file == null) { 6606 Slog.w(TAG, "Package " + pkg.packageName 6607 + " desires unavailable shared library " 6608 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6609 } else { 6610 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6611 } 6612 } 6613 N = usesLibraryFiles.size(); 6614 if (N > 0) { 6615 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6616 } else { 6617 pkg.usesLibraryFiles = null; 6618 } 6619 } 6620 } 6621 6622 private static boolean hasString(List<String> list, List<String> which) { 6623 if (list == null) { 6624 return false; 6625 } 6626 for (int i=list.size()-1; i>=0; i--) { 6627 for (int j=which.size()-1; j>=0; j--) { 6628 if (which.get(j).equals(list.get(i))) { 6629 return true; 6630 } 6631 } 6632 } 6633 return false; 6634 } 6635 6636 private void updateAllSharedLibrariesLPw() { 6637 for (PackageParser.Package pkg : mPackages.values()) { 6638 try { 6639 updateSharedLibrariesLPw(pkg, null); 6640 } catch (PackageManagerException e) { 6641 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6642 } 6643 } 6644 } 6645 6646 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6647 PackageParser.Package changingPkg) { 6648 ArrayList<PackageParser.Package> res = null; 6649 for (PackageParser.Package pkg : mPackages.values()) { 6650 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6651 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6652 if (res == null) { 6653 res = new ArrayList<PackageParser.Package>(); 6654 } 6655 res.add(pkg); 6656 try { 6657 updateSharedLibrariesLPw(pkg, changingPkg); 6658 } catch (PackageManagerException e) { 6659 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6660 } 6661 } 6662 } 6663 return res; 6664 } 6665 6666 /** 6667 * Derive the value of the {@code cpuAbiOverride} based on the provided 6668 * value and an optional stored value from the package settings. 6669 */ 6670 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6671 String cpuAbiOverride = null; 6672 6673 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6674 cpuAbiOverride = null; 6675 } else if (abiOverride != null) { 6676 cpuAbiOverride = abiOverride; 6677 } else if (settings != null) { 6678 cpuAbiOverride = settings.cpuAbiOverrideString; 6679 } 6680 6681 return cpuAbiOverride; 6682 } 6683 6684 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6685 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6686 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6687 try { 6688 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6689 } finally { 6690 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6691 } 6692 } 6693 6694 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6695 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6696 boolean success = false; 6697 try { 6698 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6699 currentTime, user); 6700 success = true; 6701 return res; 6702 } finally { 6703 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6704 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6705 } 6706 } 6707 } 6708 6709 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6710 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6711 final File scanFile = new File(pkg.codePath); 6712 if (pkg.applicationInfo.getCodePath() == null || 6713 pkg.applicationInfo.getResourcePath() == null) { 6714 // Bail out. The resource and code paths haven't been set. 6715 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6716 "Code and resource paths haven't been set correctly"); 6717 } 6718 6719 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6720 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6721 } else { 6722 // Only allow system apps to be flagged as core apps. 6723 pkg.coreApp = false; 6724 } 6725 6726 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6727 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6728 } 6729 6730 if (mCustomResolverComponentName != null && 6731 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6732 setUpCustomResolverActivity(pkg); 6733 } 6734 6735 if (pkg.packageName.equals("android")) { 6736 synchronized (mPackages) { 6737 if (mAndroidApplication != null) { 6738 Slog.w(TAG, "*************************************************"); 6739 Slog.w(TAG, "Core android package being redefined. Skipping."); 6740 Slog.w(TAG, " file=" + scanFile); 6741 Slog.w(TAG, "*************************************************"); 6742 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6743 "Core android package being redefined. Skipping."); 6744 } 6745 6746 // Set up information for our fall-back user intent resolution activity. 6747 mPlatformPackage = pkg; 6748 pkg.mVersionCode = mSdkVersion; 6749 mAndroidApplication = pkg.applicationInfo; 6750 6751 if (!mResolverReplaced) { 6752 mResolveActivity.applicationInfo = mAndroidApplication; 6753 mResolveActivity.name = ResolverActivity.class.getName(); 6754 mResolveActivity.packageName = mAndroidApplication.packageName; 6755 mResolveActivity.processName = "system:ui"; 6756 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6757 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6758 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6759 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6760 mResolveActivity.exported = true; 6761 mResolveActivity.enabled = true; 6762 mResolveInfo.activityInfo = mResolveActivity; 6763 mResolveInfo.priority = 0; 6764 mResolveInfo.preferredOrder = 0; 6765 mResolveInfo.match = 0; 6766 mResolveComponentName = new ComponentName( 6767 mAndroidApplication.packageName, mResolveActivity.name); 6768 } 6769 } 6770 } 6771 6772 if (DEBUG_PACKAGE_SCANNING) { 6773 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6774 Log.d(TAG, "Scanning package " + pkg.packageName); 6775 } 6776 6777 if (mPackages.containsKey(pkg.packageName) 6778 || mSharedLibraries.containsKey(pkg.packageName)) { 6779 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6780 "Application package " + pkg.packageName 6781 + " already installed. Skipping duplicate."); 6782 } 6783 6784 // If we're only installing presumed-existing packages, require that the 6785 // scanned APK is both already known and at the path previously established 6786 // for it. Previously unknown packages we pick up normally, but if we have an 6787 // a priori expectation about this package's install presence, enforce it. 6788 // With a singular exception for new system packages. When an OTA contains 6789 // a new system package, we allow the codepath to change from a system location 6790 // to the user-installed location. If we don't allow this change, any newer, 6791 // user-installed version of the application will be ignored. 6792 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6793 if (mExpectingBetter.containsKey(pkg.packageName)) { 6794 logCriticalInfo(Log.WARN, 6795 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6796 } else { 6797 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6798 if (known != null) { 6799 if (DEBUG_PACKAGE_SCANNING) { 6800 Log.d(TAG, "Examining " + pkg.codePath 6801 + " and requiring known paths " + known.codePathString 6802 + " & " + known.resourcePathString); 6803 } 6804 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6805 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6806 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6807 "Application package " + pkg.packageName 6808 + " found at " + pkg.applicationInfo.getCodePath() 6809 + " but expected at " + known.codePathString + "; ignoring."); 6810 } 6811 } 6812 } 6813 } 6814 6815 // Initialize package source and resource directories 6816 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6817 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6818 6819 SharedUserSetting suid = null; 6820 PackageSetting pkgSetting = null; 6821 6822 if (!isSystemApp(pkg)) { 6823 // Only system apps can use these features. 6824 pkg.mOriginalPackages = null; 6825 pkg.mRealPackage = null; 6826 pkg.mAdoptPermissions = null; 6827 } 6828 6829 // writer 6830 synchronized (mPackages) { 6831 if (pkg.mSharedUserId != null) { 6832 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6833 if (suid == null) { 6834 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6835 "Creating application package " + pkg.packageName 6836 + " for shared user failed"); 6837 } 6838 if (DEBUG_PACKAGE_SCANNING) { 6839 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6840 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6841 + "): packages=" + suid.packages); 6842 } 6843 } 6844 6845 // Check if we are renaming from an original package name. 6846 PackageSetting origPackage = null; 6847 String realName = null; 6848 if (pkg.mOriginalPackages != null) { 6849 // This package may need to be renamed to a previously 6850 // installed name. Let's check on that... 6851 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6852 if (pkg.mOriginalPackages.contains(renamed)) { 6853 // This package had originally been installed as the 6854 // original name, and we have already taken care of 6855 // transitioning to the new one. Just update the new 6856 // one to continue using the old name. 6857 realName = pkg.mRealPackage; 6858 if (!pkg.packageName.equals(renamed)) { 6859 // Callers into this function may have already taken 6860 // care of renaming the package; only do it here if 6861 // it is not already done. 6862 pkg.setPackageName(renamed); 6863 } 6864 6865 } else { 6866 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6867 if ((origPackage = mSettings.peekPackageLPr( 6868 pkg.mOriginalPackages.get(i))) != null) { 6869 // We do have the package already installed under its 6870 // original name... should we use it? 6871 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6872 // New package is not compatible with original. 6873 origPackage = null; 6874 continue; 6875 } else if (origPackage.sharedUser != null) { 6876 // Make sure uid is compatible between packages. 6877 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6878 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6879 + " to " + pkg.packageName + ": old uid " 6880 + origPackage.sharedUser.name 6881 + " differs from " + pkg.mSharedUserId); 6882 origPackage = null; 6883 continue; 6884 } 6885 } else { 6886 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6887 + pkg.packageName + " to old name " + origPackage.name); 6888 } 6889 break; 6890 } 6891 } 6892 } 6893 } 6894 6895 if (mTransferedPackages.contains(pkg.packageName)) { 6896 Slog.w(TAG, "Package " + pkg.packageName 6897 + " was transferred to another, but its .apk remains"); 6898 } 6899 6900 // Just create the setting, don't add it yet. For already existing packages 6901 // the PkgSetting exists already and doesn't have to be created. 6902 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6903 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6904 pkg.applicationInfo.primaryCpuAbi, 6905 pkg.applicationInfo.secondaryCpuAbi, 6906 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6907 user, false); 6908 if (pkgSetting == null) { 6909 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6910 "Creating application package " + pkg.packageName + " failed"); 6911 } 6912 6913 if (pkgSetting.origPackage != null) { 6914 // If we are first transitioning from an original package, 6915 // fix up the new package's name now. We need to do this after 6916 // looking up the package under its new name, so getPackageLP 6917 // can take care of fiddling things correctly. 6918 pkg.setPackageName(origPackage.name); 6919 6920 // File a report about this. 6921 String msg = "New package " + pkgSetting.realName 6922 + " renamed to replace old package " + pkgSetting.name; 6923 reportSettingsProblem(Log.WARN, msg); 6924 6925 // Make a note of it. 6926 mTransferedPackages.add(origPackage.name); 6927 6928 // No longer need to retain this. 6929 pkgSetting.origPackage = null; 6930 } 6931 6932 if (realName != null) { 6933 // Make a note of it. 6934 mTransferedPackages.add(pkg.packageName); 6935 } 6936 6937 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6938 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6939 } 6940 6941 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6942 // Check all shared libraries and map to their actual file path. 6943 // We only do this here for apps not on a system dir, because those 6944 // are the only ones that can fail an install due to this. We 6945 // will take care of the system apps by updating all of their 6946 // library paths after the scan is done. 6947 updateSharedLibrariesLPw(pkg, null); 6948 } 6949 6950 if (mFoundPolicyFile) { 6951 SELinuxMMAC.assignSeinfoValue(pkg); 6952 } 6953 6954 pkg.applicationInfo.uid = pkgSetting.appId; 6955 pkg.mExtras = pkgSetting; 6956 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6957 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6958 // We just determined the app is signed correctly, so bring 6959 // over the latest parsed certs. 6960 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6961 } else { 6962 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6963 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6964 "Package " + pkg.packageName + " upgrade keys do not match the " 6965 + "previously installed version"); 6966 } else { 6967 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6968 String msg = "System package " + pkg.packageName 6969 + " signature changed; retaining data."; 6970 reportSettingsProblem(Log.WARN, msg); 6971 } 6972 } 6973 } else { 6974 try { 6975 verifySignaturesLP(pkgSetting, pkg); 6976 // We just determined the app is signed correctly, so bring 6977 // over the latest parsed certs. 6978 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6979 } catch (PackageManagerException e) { 6980 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6981 throw e; 6982 } 6983 // The signature has changed, but this package is in the system 6984 // image... let's recover! 6985 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6986 // However... if this package is part of a shared user, but it 6987 // doesn't match the signature of the shared user, let's fail. 6988 // What this means is that you can't change the signatures 6989 // associated with an overall shared user, which doesn't seem all 6990 // that unreasonable. 6991 if (pkgSetting.sharedUser != null) { 6992 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6993 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6994 throw new PackageManagerException( 6995 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6996 "Signature mismatch for shared user : " 6997 + pkgSetting.sharedUser); 6998 } 6999 } 7000 // File a report about this. 7001 String msg = "System package " + pkg.packageName 7002 + " signature changed; retaining data."; 7003 reportSettingsProblem(Log.WARN, msg); 7004 } 7005 } 7006 // Verify that this new package doesn't have any content providers 7007 // that conflict with existing packages. Only do this if the 7008 // package isn't already installed, since we don't want to break 7009 // things that are installed. 7010 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7011 final int N = pkg.providers.size(); 7012 int i; 7013 for (i=0; i<N; i++) { 7014 PackageParser.Provider p = pkg.providers.get(i); 7015 if (p.info.authority != null) { 7016 String names[] = p.info.authority.split(";"); 7017 for (int j = 0; j < names.length; j++) { 7018 if (mProvidersByAuthority.containsKey(names[j])) { 7019 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7020 final String otherPackageName = 7021 ((other != null && other.getComponentName() != null) ? 7022 other.getComponentName().getPackageName() : "?"); 7023 throw new PackageManagerException( 7024 INSTALL_FAILED_CONFLICTING_PROVIDER, 7025 "Can't install because provider name " + names[j] 7026 + " (in package " + pkg.applicationInfo.packageName 7027 + ") is already used by " + otherPackageName); 7028 } 7029 } 7030 } 7031 } 7032 } 7033 7034 if (pkg.mAdoptPermissions != null) { 7035 // This package wants to adopt ownership of permissions from 7036 // another package. 7037 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7038 final String origName = pkg.mAdoptPermissions.get(i); 7039 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7040 if (orig != null) { 7041 if (verifyPackageUpdateLPr(orig, pkg)) { 7042 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7043 + pkg.packageName); 7044 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7045 } 7046 } 7047 } 7048 } 7049 } 7050 7051 final String pkgName = pkg.packageName; 7052 7053 final long scanFileTime = scanFile.lastModified(); 7054 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7055 pkg.applicationInfo.processName = fixProcessName( 7056 pkg.applicationInfo.packageName, 7057 pkg.applicationInfo.processName, 7058 pkg.applicationInfo.uid); 7059 7060 if (pkg != mPlatformPackage) { 7061 // This is a normal package, need to make its data directory. 7062 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7063 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7064 7065 boolean uidError = false; 7066 if (dataPath.exists()) { 7067 int currentUid = 0; 7068 try { 7069 StructStat stat = Os.stat(dataPath.getPath()); 7070 currentUid = stat.st_uid; 7071 } catch (ErrnoException e) { 7072 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7073 } 7074 7075 // If we have mismatched owners for the data path, we have a problem. 7076 if (currentUid != pkg.applicationInfo.uid) { 7077 boolean recovered = false; 7078 if (currentUid == 0) { 7079 // The directory somehow became owned by root. Wow. 7080 // This is probably because the system was stopped while 7081 // installd was in the middle of messing with its libs 7082 // directory. Ask installd to fix that. 7083 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7084 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7085 if (ret >= 0) { 7086 recovered = true; 7087 String msg = "Package " + pkg.packageName 7088 + " unexpectedly changed to uid 0; recovered to " + 7089 + pkg.applicationInfo.uid; 7090 reportSettingsProblem(Log.WARN, msg); 7091 } 7092 } 7093 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7094 || (scanFlags&SCAN_BOOTING) != 0)) { 7095 // If this is a system app, we can at least delete its 7096 // current data so the application will still work. 7097 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7098 if (ret >= 0) { 7099 // TODO: Kill the processes first 7100 // Old data gone! 7101 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7102 ? "System package " : "Third party package "; 7103 String msg = prefix + pkg.packageName 7104 + " has changed from uid: " 7105 + currentUid + " to " 7106 + pkg.applicationInfo.uid + "; old data erased"; 7107 reportSettingsProblem(Log.WARN, msg); 7108 recovered = true; 7109 } 7110 if (!recovered) { 7111 mHasSystemUidErrors = true; 7112 } 7113 } else if (!recovered) { 7114 // If we allow this install to proceed, we will be broken. 7115 // Abort, abort! 7116 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7117 "scanPackageLI"); 7118 } 7119 if (!recovered) { 7120 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7121 + pkg.applicationInfo.uid + "/fs_" 7122 + currentUid; 7123 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7124 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7125 String msg = "Package " + pkg.packageName 7126 + " has mismatched uid: " 7127 + currentUid + " on disk, " 7128 + pkg.applicationInfo.uid + " in settings"; 7129 // writer 7130 synchronized (mPackages) { 7131 mSettings.mReadMessages.append(msg); 7132 mSettings.mReadMessages.append('\n'); 7133 uidError = true; 7134 if (!pkgSetting.uidError) { 7135 reportSettingsProblem(Log.ERROR, msg); 7136 } 7137 } 7138 } 7139 } 7140 7141 // Ensure that directories are prepared 7142 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7143 pkg.applicationInfo.seinfo); 7144 7145 if (mShouldRestoreconData) { 7146 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7147 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7148 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7149 } 7150 } else { 7151 if (DEBUG_PACKAGE_SCANNING) { 7152 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7153 Log.v(TAG, "Want this data dir: " + dataPath); 7154 } 7155 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7156 pkg.applicationInfo.seinfo); 7157 } 7158 7159 // Get all of our default paths setup 7160 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7161 7162 pkgSetting.uidError = uidError; 7163 } 7164 7165 final String path = scanFile.getPath(); 7166 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7167 7168 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7169 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7170 7171 // Some system apps still use directory structure for native libraries 7172 // in which case we might end up not detecting abi solely based on apk 7173 // structure. Try to detect abi based on directory structure. 7174 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7175 pkg.applicationInfo.primaryCpuAbi == null) { 7176 setBundledAppAbisAndRoots(pkg, pkgSetting); 7177 setNativeLibraryPaths(pkg); 7178 } 7179 7180 } else { 7181 if ((scanFlags & SCAN_MOVE) != 0) { 7182 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7183 // but we already have this packages package info in the PackageSetting. We just 7184 // use that and derive the native library path based on the new codepath. 7185 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7186 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7187 } 7188 7189 // Set native library paths again. For moves, the path will be updated based on the 7190 // ABIs we've determined above. For non-moves, the path will be updated based on the 7191 // ABIs we determined during compilation, but the path will depend on the final 7192 // package path (after the rename away from the stage path). 7193 setNativeLibraryPaths(pkg); 7194 } 7195 7196 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7197 final int[] userIds = sUserManager.getUserIds(); 7198 synchronized (mInstallLock) { 7199 // Make sure all user data directories are ready to roll; we're okay 7200 // if they already exist 7201 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7202 for (int userId : userIds) { 7203 if (userId != UserHandle.USER_SYSTEM) { 7204 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7205 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7206 pkg.applicationInfo.seinfo); 7207 } 7208 } 7209 } 7210 7211 // Create a native library symlink only if we have native libraries 7212 // and if the native libraries are 32 bit libraries. We do not provide 7213 // this symlink for 64 bit libraries. 7214 if (pkg.applicationInfo.primaryCpuAbi != null && 7215 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7217 try { 7218 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7219 for (int userId : userIds) { 7220 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7221 nativeLibPath, userId) < 0) { 7222 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7223 "Failed linking native library dir (user=" + userId + ")"); 7224 } 7225 } 7226 } finally { 7227 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7228 } 7229 } 7230 } 7231 7232 // This is a special case for the "system" package, where the ABI is 7233 // dictated by the zygote configuration (and init.rc). We should keep track 7234 // of this ABI so that we can deal with "normal" applications that run under 7235 // the same UID correctly. 7236 if (mPlatformPackage == pkg) { 7237 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7238 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7239 } 7240 7241 // If there's a mismatch between the abi-override in the package setting 7242 // and the abiOverride specified for the install. Warn about this because we 7243 // would've already compiled the app without taking the package setting into 7244 // account. 7245 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7246 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7247 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7248 " for package: " + pkg.packageName); 7249 } 7250 } 7251 7252 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7253 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7254 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7255 7256 // Copy the derived override back to the parsed package, so that we can 7257 // update the package settings accordingly. 7258 pkg.cpuAbiOverride = cpuAbiOverride; 7259 7260 if (DEBUG_ABI_SELECTION) { 7261 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7262 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7263 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7264 } 7265 7266 // Push the derived path down into PackageSettings so we know what to 7267 // clean up at uninstall time. 7268 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7269 7270 if (DEBUG_ABI_SELECTION) { 7271 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7272 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7273 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7274 } 7275 7276 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7277 // We don't do this here during boot because we can do it all 7278 // at once after scanning all existing packages. 7279 // 7280 // We also do this *before* we perform dexopt on this package, so that 7281 // we can avoid redundant dexopts, and also to make sure we've got the 7282 // code and package path correct. 7283 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7284 pkg, true /* boot complete */); 7285 } 7286 7287 if (mFactoryTest && pkg.requestedPermissions.contains( 7288 android.Manifest.permission.FACTORY_TEST)) { 7289 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7290 } 7291 7292 ArrayList<PackageParser.Package> clientLibPkgs = null; 7293 7294 // writer 7295 synchronized (mPackages) { 7296 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7297 // Only system apps can add new shared libraries. 7298 if (pkg.libraryNames != null) { 7299 for (int i=0; i<pkg.libraryNames.size(); i++) { 7300 String name = pkg.libraryNames.get(i); 7301 boolean allowed = false; 7302 if (pkg.isUpdatedSystemApp()) { 7303 // New library entries can only be added through the 7304 // system image. This is important to get rid of a lot 7305 // of nasty edge cases: for example if we allowed a non- 7306 // system update of the app to add a library, then uninstalling 7307 // the update would make the library go away, and assumptions 7308 // we made such as through app install filtering would now 7309 // have allowed apps on the device which aren't compatible 7310 // with it. Better to just have the restriction here, be 7311 // conservative, and create many fewer cases that can negatively 7312 // impact the user experience. 7313 final PackageSetting sysPs = mSettings 7314 .getDisabledSystemPkgLPr(pkg.packageName); 7315 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7316 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7317 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7318 allowed = true; 7319 break; 7320 } 7321 } 7322 } 7323 } else { 7324 allowed = true; 7325 } 7326 if (allowed) { 7327 if (!mSharedLibraries.containsKey(name)) { 7328 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7329 } else if (!name.equals(pkg.packageName)) { 7330 Slog.w(TAG, "Package " + pkg.packageName + " library " 7331 + name + " already exists; skipping"); 7332 } 7333 } else { 7334 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7335 + name + " that is not declared on system image; skipping"); 7336 } 7337 } 7338 if ((scanFlags & SCAN_BOOTING) == 0) { 7339 // If we are not booting, we need to update any applications 7340 // that are clients of our shared library. If we are booting, 7341 // this will all be done once the scan is complete. 7342 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7343 } 7344 } 7345 } 7346 } 7347 7348 // Request the ActivityManager to kill the process(only for existing packages) 7349 // so that we do not end up in a confused state while the user is still using the older 7350 // version of the application while the new one gets installed. 7351 if ((scanFlags & SCAN_REPLACING) != 0) { 7352 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7353 7354 killApplication(pkg.applicationInfo.packageName, 7355 pkg.applicationInfo.uid, "replace pkg"); 7356 7357 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7358 } 7359 7360 // Also need to kill any apps that are dependent on the library. 7361 if (clientLibPkgs != null) { 7362 for (int i=0; i<clientLibPkgs.size(); i++) { 7363 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7364 killApplication(clientPkg.applicationInfo.packageName, 7365 clientPkg.applicationInfo.uid, "update lib"); 7366 } 7367 } 7368 7369 // Make sure we're not adding any bogus keyset info 7370 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7371 ksms.assertScannedPackageValid(pkg); 7372 7373 // writer 7374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7375 7376 boolean createIdmapFailed = false; 7377 synchronized (mPackages) { 7378 // We don't expect installation to fail beyond this point 7379 7380 // Add the new setting to mSettings 7381 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7382 // Add the new setting to mPackages 7383 mPackages.put(pkg.applicationInfo.packageName, pkg); 7384 // Make sure we don't accidentally delete its data. 7385 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7386 while (iter.hasNext()) { 7387 PackageCleanItem item = iter.next(); 7388 if (pkgName.equals(item.packageName)) { 7389 iter.remove(); 7390 } 7391 } 7392 7393 // Take care of first install / last update times. 7394 if (currentTime != 0) { 7395 if (pkgSetting.firstInstallTime == 0) { 7396 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7397 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7398 pkgSetting.lastUpdateTime = currentTime; 7399 } 7400 } else if (pkgSetting.firstInstallTime == 0) { 7401 // We need *something*. Take time time stamp of the file. 7402 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7403 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7404 if (scanFileTime != pkgSetting.timeStamp) { 7405 // A package on the system image has changed; consider this 7406 // to be an update. 7407 pkgSetting.lastUpdateTime = scanFileTime; 7408 } 7409 } 7410 7411 // Add the package's KeySets to the global KeySetManagerService 7412 ksms.addScannedPackageLPw(pkg); 7413 7414 int N = pkg.providers.size(); 7415 StringBuilder r = null; 7416 int i; 7417 for (i=0; i<N; i++) { 7418 PackageParser.Provider p = pkg.providers.get(i); 7419 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7420 p.info.processName, pkg.applicationInfo.uid); 7421 mProviders.addProvider(p); 7422 p.syncable = p.info.isSyncable; 7423 if (p.info.authority != null) { 7424 String names[] = p.info.authority.split(";"); 7425 p.info.authority = null; 7426 for (int j = 0; j < names.length; j++) { 7427 if (j == 1 && p.syncable) { 7428 // We only want the first authority for a provider to possibly be 7429 // syncable, so if we already added this provider using a different 7430 // authority clear the syncable flag. We copy the provider before 7431 // changing it because the mProviders object contains a reference 7432 // to a provider that we don't want to change. 7433 // Only do this for the second authority since the resulting provider 7434 // object can be the same for all future authorities for this provider. 7435 p = new PackageParser.Provider(p); 7436 p.syncable = false; 7437 } 7438 if (!mProvidersByAuthority.containsKey(names[j])) { 7439 mProvidersByAuthority.put(names[j], p); 7440 if (p.info.authority == null) { 7441 p.info.authority = names[j]; 7442 } else { 7443 p.info.authority = p.info.authority + ";" + names[j]; 7444 } 7445 if (DEBUG_PACKAGE_SCANNING) { 7446 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7447 Log.d(TAG, "Registered content provider: " + names[j] 7448 + ", className = " + p.info.name + ", isSyncable = " 7449 + p.info.isSyncable); 7450 } 7451 } else { 7452 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7453 Slog.w(TAG, "Skipping provider name " + names[j] + 7454 " (in package " + pkg.applicationInfo.packageName + 7455 "): name already used by " 7456 + ((other != null && other.getComponentName() != null) 7457 ? other.getComponentName().getPackageName() : "?")); 7458 } 7459 } 7460 } 7461 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7462 if (r == null) { 7463 r = new StringBuilder(256); 7464 } else { 7465 r.append(' '); 7466 } 7467 r.append(p.info.name); 7468 } 7469 } 7470 if (r != null) { 7471 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7472 } 7473 7474 N = pkg.services.size(); 7475 r = null; 7476 for (i=0; i<N; i++) { 7477 PackageParser.Service s = pkg.services.get(i); 7478 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7479 s.info.processName, pkg.applicationInfo.uid); 7480 mServices.addService(s); 7481 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7482 if (r == null) { 7483 r = new StringBuilder(256); 7484 } else { 7485 r.append(' '); 7486 } 7487 r.append(s.info.name); 7488 } 7489 } 7490 if (r != null) { 7491 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7492 } 7493 7494 N = pkg.receivers.size(); 7495 r = null; 7496 for (i=0; i<N; i++) { 7497 PackageParser.Activity a = pkg.receivers.get(i); 7498 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7499 a.info.processName, pkg.applicationInfo.uid); 7500 mReceivers.addActivity(a, "receiver"); 7501 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7502 if (r == null) { 7503 r = new StringBuilder(256); 7504 } else { 7505 r.append(' '); 7506 } 7507 r.append(a.info.name); 7508 } 7509 } 7510 if (r != null) { 7511 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7512 } 7513 7514 N = pkg.activities.size(); 7515 r = null; 7516 for (i=0; i<N; i++) { 7517 PackageParser.Activity a = pkg.activities.get(i); 7518 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7519 a.info.processName, pkg.applicationInfo.uid); 7520 mActivities.addActivity(a, "activity"); 7521 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7522 if (r == null) { 7523 r = new StringBuilder(256); 7524 } else { 7525 r.append(' '); 7526 } 7527 r.append(a.info.name); 7528 } 7529 } 7530 if (r != null) { 7531 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7532 } 7533 7534 N = pkg.permissionGroups.size(); 7535 r = null; 7536 for (i=0; i<N; i++) { 7537 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7538 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7539 if (cur == null) { 7540 mPermissionGroups.put(pg.info.name, pg); 7541 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7542 if (r == null) { 7543 r = new StringBuilder(256); 7544 } else { 7545 r.append(' '); 7546 } 7547 r.append(pg.info.name); 7548 } 7549 } else { 7550 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7551 + pg.info.packageName + " ignored: original from " 7552 + cur.info.packageName); 7553 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7554 if (r == null) { 7555 r = new StringBuilder(256); 7556 } else { 7557 r.append(' '); 7558 } 7559 r.append("DUP:"); 7560 r.append(pg.info.name); 7561 } 7562 } 7563 } 7564 if (r != null) { 7565 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7566 } 7567 7568 N = pkg.permissions.size(); 7569 r = null; 7570 for (i=0; i<N; i++) { 7571 PackageParser.Permission p = pkg.permissions.get(i); 7572 7573 // Assume by default that we did not install this permission into the system. 7574 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7575 7576 // Now that permission groups have a special meaning, we ignore permission 7577 // groups for legacy apps to prevent unexpected behavior. In particular, 7578 // permissions for one app being granted to someone just becuase they happen 7579 // to be in a group defined by another app (before this had no implications). 7580 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7581 p.group = mPermissionGroups.get(p.info.group); 7582 // Warn for a permission in an unknown group. 7583 if (p.info.group != null && p.group == null) { 7584 Slog.w(TAG, "Permission " + p.info.name + " from package " 7585 + p.info.packageName + " in an unknown group " + p.info.group); 7586 } 7587 } 7588 7589 ArrayMap<String, BasePermission> permissionMap = 7590 p.tree ? mSettings.mPermissionTrees 7591 : mSettings.mPermissions; 7592 BasePermission bp = permissionMap.get(p.info.name); 7593 7594 // Allow system apps to redefine non-system permissions 7595 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7596 final boolean currentOwnerIsSystem = (bp.perm != null 7597 && isSystemApp(bp.perm.owner)); 7598 if (isSystemApp(p.owner)) { 7599 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7600 // It's a built-in permission and no owner, take ownership now 7601 bp.packageSetting = pkgSetting; 7602 bp.perm = p; 7603 bp.uid = pkg.applicationInfo.uid; 7604 bp.sourcePackage = p.info.packageName; 7605 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7606 } else if (!currentOwnerIsSystem) { 7607 String msg = "New decl " + p.owner + " of permission " 7608 + p.info.name + " is system; overriding " + bp.sourcePackage; 7609 reportSettingsProblem(Log.WARN, msg); 7610 bp = null; 7611 } 7612 } 7613 } 7614 7615 if (bp == null) { 7616 bp = new BasePermission(p.info.name, p.info.packageName, 7617 BasePermission.TYPE_NORMAL); 7618 permissionMap.put(p.info.name, bp); 7619 } 7620 7621 if (bp.perm == null) { 7622 if (bp.sourcePackage == null 7623 || bp.sourcePackage.equals(p.info.packageName)) { 7624 BasePermission tree = findPermissionTreeLP(p.info.name); 7625 if (tree == null 7626 || tree.sourcePackage.equals(p.info.packageName)) { 7627 bp.packageSetting = pkgSetting; 7628 bp.perm = p; 7629 bp.uid = pkg.applicationInfo.uid; 7630 bp.sourcePackage = p.info.packageName; 7631 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7632 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7633 if (r == null) { 7634 r = new StringBuilder(256); 7635 } else { 7636 r.append(' '); 7637 } 7638 r.append(p.info.name); 7639 } 7640 } else { 7641 Slog.w(TAG, "Permission " + p.info.name + " from package " 7642 + p.info.packageName + " ignored: base tree " 7643 + tree.name + " is from package " 7644 + tree.sourcePackage); 7645 } 7646 } else { 7647 Slog.w(TAG, "Permission " + p.info.name + " from package " 7648 + p.info.packageName + " ignored: original from " 7649 + bp.sourcePackage); 7650 } 7651 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7652 if (r == null) { 7653 r = new StringBuilder(256); 7654 } else { 7655 r.append(' '); 7656 } 7657 r.append("DUP:"); 7658 r.append(p.info.name); 7659 } 7660 if (bp.perm == p) { 7661 bp.protectionLevel = p.info.protectionLevel; 7662 } 7663 } 7664 7665 if (r != null) { 7666 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7667 } 7668 7669 N = pkg.instrumentation.size(); 7670 r = null; 7671 for (i=0; i<N; i++) { 7672 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7673 a.info.packageName = pkg.applicationInfo.packageName; 7674 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7675 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7676 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7677 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7678 a.info.dataDir = pkg.applicationInfo.dataDir; 7679 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7680 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7681 7682 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7683 // need other information about the application, like the ABI and what not ? 7684 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7685 mInstrumentation.put(a.getComponentName(), a); 7686 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7687 if (r == null) { 7688 r = new StringBuilder(256); 7689 } else { 7690 r.append(' '); 7691 } 7692 r.append(a.info.name); 7693 } 7694 } 7695 if (r != null) { 7696 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7697 } 7698 7699 if (pkg.protectedBroadcasts != null) { 7700 N = pkg.protectedBroadcasts.size(); 7701 for (i=0; i<N; i++) { 7702 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7703 } 7704 } 7705 7706 pkgSetting.setTimeStamp(scanFileTime); 7707 7708 // Create idmap files for pairs of (packages, overlay packages). 7709 // Note: "android", ie framework-res.apk, is handled by native layers. 7710 if (pkg.mOverlayTarget != null) { 7711 // This is an overlay package. 7712 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7713 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7714 mOverlays.put(pkg.mOverlayTarget, 7715 new ArrayMap<String, PackageParser.Package>()); 7716 } 7717 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7718 map.put(pkg.packageName, pkg); 7719 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7720 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7721 createIdmapFailed = true; 7722 } 7723 } 7724 } else if (mOverlays.containsKey(pkg.packageName) && 7725 !pkg.packageName.equals("android")) { 7726 // This is a regular package, with one or more known overlay packages. 7727 createIdmapsForPackageLI(pkg); 7728 } 7729 } 7730 7731 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7732 7733 if (createIdmapFailed) { 7734 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7735 "scanPackageLI failed to createIdmap"); 7736 } 7737 return pkg; 7738 } 7739 7740 /** 7741 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7742 * is derived purely on the basis of the contents of {@code scanFile} and 7743 * {@code cpuAbiOverride}. 7744 * 7745 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7746 */ 7747 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7748 String cpuAbiOverride, boolean extractLibs) 7749 throws PackageManagerException { 7750 // TODO: We can probably be smarter about this stuff. For installed apps, 7751 // we can calculate this information at install time once and for all. For 7752 // system apps, we can probably assume that this information doesn't change 7753 // after the first boot scan. As things stand, we do lots of unnecessary work. 7754 7755 // Give ourselves some initial paths; we'll come back for another 7756 // pass once we've determined ABI below. 7757 setNativeLibraryPaths(pkg); 7758 7759 // We would never need to extract libs for forward-locked and external packages, 7760 // since the container service will do it for us. We shouldn't attempt to 7761 // extract libs from system app when it was not updated. 7762 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7763 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7764 extractLibs = false; 7765 } 7766 7767 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7768 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7769 7770 NativeLibraryHelper.Handle handle = null; 7771 try { 7772 handle = NativeLibraryHelper.Handle.create(pkg); 7773 // TODO(multiArch): This can be null for apps that didn't go through the 7774 // usual installation process. We can calculate it again, like we 7775 // do during install time. 7776 // 7777 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7778 // unnecessary. 7779 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7780 7781 // Null out the abis so that they can be recalculated. 7782 pkg.applicationInfo.primaryCpuAbi = null; 7783 pkg.applicationInfo.secondaryCpuAbi = null; 7784 if (isMultiArch(pkg.applicationInfo)) { 7785 // Warn if we've set an abiOverride for multi-lib packages.. 7786 // By definition, we need to copy both 32 and 64 bit libraries for 7787 // such packages. 7788 if (pkg.cpuAbiOverride != null 7789 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7790 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7791 } 7792 7793 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7794 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7795 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7796 if (extractLibs) { 7797 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7798 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7799 useIsaSpecificSubdirs); 7800 } else { 7801 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7802 } 7803 } 7804 7805 maybeThrowExceptionForMultiArchCopy( 7806 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7807 7808 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7809 if (extractLibs) { 7810 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7811 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7812 useIsaSpecificSubdirs); 7813 } else { 7814 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7815 } 7816 } 7817 7818 maybeThrowExceptionForMultiArchCopy( 7819 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7820 7821 if (abi64 >= 0) { 7822 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7823 } 7824 7825 if (abi32 >= 0) { 7826 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7827 if (abi64 >= 0) { 7828 pkg.applicationInfo.secondaryCpuAbi = abi; 7829 } else { 7830 pkg.applicationInfo.primaryCpuAbi = abi; 7831 } 7832 } 7833 } else { 7834 String[] abiList = (cpuAbiOverride != null) ? 7835 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7836 7837 // Enable gross and lame hacks for apps that are built with old 7838 // SDK tools. We must scan their APKs for renderscript bitcode and 7839 // not launch them if it's present. Don't bother checking on devices 7840 // that don't have 64 bit support. 7841 boolean needsRenderScriptOverride = false; 7842 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7843 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7844 abiList = Build.SUPPORTED_32_BIT_ABIS; 7845 needsRenderScriptOverride = true; 7846 } 7847 7848 final int copyRet; 7849 if (extractLibs) { 7850 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7851 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7852 } else { 7853 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7854 } 7855 7856 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7857 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7858 "Error unpackaging native libs for app, errorCode=" + copyRet); 7859 } 7860 7861 if (copyRet >= 0) { 7862 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7863 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7864 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7865 } else if (needsRenderScriptOverride) { 7866 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7867 } 7868 } 7869 } catch (IOException ioe) { 7870 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7871 } finally { 7872 IoUtils.closeQuietly(handle); 7873 } 7874 7875 // Now that we've calculated the ABIs and determined if it's an internal app, 7876 // we will go ahead and populate the nativeLibraryPath. 7877 setNativeLibraryPaths(pkg); 7878 } 7879 7880 /** 7881 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7882 * i.e, so that all packages can be run inside a single process if required. 7883 * 7884 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7885 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7886 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7887 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7888 * updating a package that belongs to a shared user. 7889 * 7890 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7891 * adds unnecessary complexity. 7892 */ 7893 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7894 PackageParser.Package scannedPackage, boolean bootComplete) { 7895 String requiredInstructionSet = null; 7896 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7897 requiredInstructionSet = VMRuntime.getInstructionSet( 7898 scannedPackage.applicationInfo.primaryCpuAbi); 7899 } 7900 7901 PackageSetting requirer = null; 7902 for (PackageSetting ps : packagesForUser) { 7903 // If packagesForUser contains scannedPackage, we skip it. This will happen 7904 // when scannedPackage is an update of an existing package. Without this check, 7905 // we will never be able to change the ABI of any package belonging to a shared 7906 // user, even if it's compatible with other packages. 7907 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7908 if (ps.primaryCpuAbiString == null) { 7909 continue; 7910 } 7911 7912 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7913 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7914 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7915 // this but there's not much we can do. 7916 String errorMessage = "Instruction set mismatch, " 7917 + ((requirer == null) ? "[caller]" : requirer) 7918 + " requires " + requiredInstructionSet + " whereas " + ps 7919 + " requires " + instructionSet; 7920 Slog.w(TAG, errorMessage); 7921 } 7922 7923 if (requiredInstructionSet == null) { 7924 requiredInstructionSet = instructionSet; 7925 requirer = ps; 7926 } 7927 } 7928 } 7929 7930 if (requiredInstructionSet != null) { 7931 String adjustedAbi; 7932 if (requirer != null) { 7933 // requirer != null implies that either scannedPackage was null or that scannedPackage 7934 // did not require an ABI, in which case we have to adjust scannedPackage to match 7935 // the ABI of the set (which is the same as requirer's ABI) 7936 adjustedAbi = requirer.primaryCpuAbiString; 7937 if (scannedPackage != null) { 7938 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7939 } 7940 } else { 7941 // requirer == null implies that we're updating all ABIs in the set to 7942 // match scannedPackage. 7943 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7944 } 7945 7946 for (PackageSetting ps : packagesForUser) { 7947 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7948 if (ps.primaryCpuAbiString != null) { 7949 continue; 7950 } 7951 7952 ps.primaryCpuAbiString = adjustedAbi; 7953 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7954 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7955 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7956 mInstaller.rmdex(ps.codePathString, 7957 getDexCodeInstructionSet(getPreferredInstructionSet())); 7958 } 7959 } 7960 } 7961 } 7962 } 7963 7964 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7965 synchronized (mPackages) { 7966 mResolverReplaced = true; 7967 // Set up information for custom user intent resolution activity. 7968 mResolveActivity.applicationInfo = pkg.applicationInfo; 7969 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7970 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7971 mResolveActivity.processName = pkg.applicationInfo.packageName; 7972 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7973 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7974 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7975 mResolveActivity.theme = 0; 7976 mResolveActivity.exported = true; 7977 mResolveActivity.enabled = true; 7978 mResolveInfo.activityInfo = mResolveActivity; 7979 mResolveInfo.priority = 0; 7980 mResolveInfo.preferredOrder = 0; 7981 mResolveInfo.match = 0; 7982 mResolveComponentName = mCustomResolverComponentName; 7983 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7984 mResolveComponentName); 7985 } 7986 } 7987 7988 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 7989 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 7990 7991 // Set up information for ephemeral installer activity 7992 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 7993 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 7994 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 7995 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 7996 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7997 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7998 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7999 mEphemeralInstallerActivity.theme = 0; 8000 mEphemeralInstallerActivity.exported = true; 8001 mEphemeralInstallerActivity.enabled = true; 8002 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8003 mEphemeralInstallerInfo.priority = 0; 8004 mEphemeralInstallerInfo.preferredOrder = 0; 8005 mEphemeralInstallerInfo.match = 0; 8006 8007 if (DEBUG_EPHEMERAL) { 8008 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8009 } 8010 } 8011 8012 private static String calculateBundledApkRoot(final String codePathString) { 8013 final File codePath = new File(codePathString); 8014 final File codeRoot; 8015 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8016 codeRoot = Environment.getRootDirectory(); 8017 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8018 codeRoot = Environment.getOemDirectory(); 8019 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8020 codeRoot = Environment.getVendorDirectory(); 8021 } else { 8022 // Unrecognized code path; take its top real segment as the apk root: 8023 // e.g. /something/app/blah.apk => /something 8024 try { 8025 File f = codePath.getCanonicalFile(); 8026 File parent = f.getParentFile(); // non-null because codePath is a file 8027 File tmp; 8028 while ((tmp = parent.getParentFile()) != null) { 8029 f = parent; 8030 parent = tmp; 8031 } 8032 codeRoot = f; 8033 Slog.w(TAG, "Unrecognized code path " 8034 + codePath + " - using " + codeRoot); 8035 } catch (IOException e) { 8036 // Can't canonicalize the code path -- shenanigans? 8037 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8038 return Environment.getRootDirectory().getPath(); 8039 } 8040 } 8041 return codeRoot.getPath(); 8042 } 8043 8044 /** 8045 * Derive and set the location of native libraries for the given package, 8046 * which varies depending on where and how the package was installed. 8047 */ 8048 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8049 final ApplicationInfo info = pkg.applicationInfo; 8050 final String codePath = pkg.codePath; 8051 final File codeFile = new File(codePath); 8052 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8053 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8054 8055 info.nativeLibraryRootDir = null; 8056 info.nativeLibraryRootRequiresIsa = false; 8057 info.nativeLibraryDir = null; 8058 info.secondaryNativeLibraryDir = null; 8059 8060 if (isApkFile(codeFile)) { 8061 // Monolithic install 8062 if (bundledApp) { 8063 // If "/system/lib64/apkname" exists, assume that is the per-package 8064 // native library directory to use; otherwise use "/system/lib/apkname". 8065 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8066 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8067 getPrimaryInstructionSet(info)); 8068 8069 // This is a bundled system app so choose the path based on the ABI. 8070 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8071 // is just the default path. 8072 final String apkName = deriveCodePathName(codePath); 8073 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8074 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8075 apkName).getAbsolutePath(); 8076 8077 if (info.secondaryCpuAbi != null) { 8078 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8079 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8080 secondaryLibDir, apkName).getAbsolutePath(); 8081 } 8082 } else if (asecApp) { 8083 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8084 .getAbsolutePath(); 8085 } else { 8086 final String apkName = deriveCodePathName(codePath); 8087 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8088 .getAbsolutePath(); 8089 } 8090 8091 info.nativeLibraryRootRequiresIsa = false; 8092 info.nativeLibraryDir = info.nativeLibraryRootDir; 8093 } else { 8094 // Cluster install 8095 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8096 info.nativeLibraryRootRequiresIsa = true; 8097 8098 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8099 getPrimaryInstructionSet(info)).getAbsolutePath(); 8100 8101 if (info.secondaryCpuAbi != null) { 8102 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8103 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8104 } 8105 } 8106 } 8107 8108 /** 8109 * Calculate the abis and roots for a bundled app. These can uniquely 8110 * be determined from the contents of the system partition, i.e whether 8111 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8112 * of this information, and instead assume that the system was built 8113 * sensibly. 8114 */ 8115 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8116 PackageSetting pkgSetting) { 8117 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8118 8119 // If "/system/lib64/apkname" exists, assume that is the per-package 8120 // native library directory to use; otherwise use "/system/lib/apkname". 8121 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8122 setBundledAppAbi(pkg, apkRoot, apkName); 8123 // pkgSetting might be null during rescan following uninstall of updates 8124 // to a bundled app, so accommodate that possibility. The settings in 8125 // that case will be established later from the parsed package. 8126 // 8127 // If the settings aren't null, sync them up with what we've just derived. 8128 // note that apkRoot isn't stored in the package settings. 8129 if (pkgSetting != null) { 8130 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8131 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8132 } 8133 } 8134 8135 /** 8136 * Deduces the ABI of a bundled app and sets the relevant fields on the 8137 * parsed pkg object. 8138 * 8139 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8140 * under which system libraries are installed. 8141 * @param apkName the name of the installed package. 8142 */ 8143 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8144 final File codeFile = new File(pkg.codePath); 8145 8146 final boolean has64BitLibs; 8147 final boolean has32BitLibs; 8148 if (isApkFile(codeFile)) { 8149 // Monolithic install 8150 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8151 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8152 } else { 8153 // Cluster install 8154 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8155 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8156 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8157 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8158 has64BitLibs = (new File(rootDir, isa)).exists(); 8159 } else { 8160 has64BitLibs = false; 8161 } 8162 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8163 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8164 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8165 has32BitLibs = (new File(rootDir, isa)).exists(); 8166 } else { 8167 has32BitLibs = false; 8168 } 8169 } 8170 8171 if (has64BitLibs && !has32BitLibs) { 8172 // The package has 64 bit libs, but not 32 bit libs. Its primary 8173 // ABI should be 64 bit. We can safely assume here that the bundled 8174 // native libraries correspond to the most preferred ABI in the list. 8175 8176 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8177 pkg.applicationInfo.secondaryCpuAbi = null; 8178 } else if (has32BitLibs && !has64BitLibs) { 8179 // The package has 32 bit libs but not 64 bit libs. Its primary 8180 // ABI should be 32 bit. 8181 8182 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8183 pkg.applicationInfo.secondaryCpuAbi = null; 8184 } else if (has32BitLibs && has64BitLibs) { 8185 // The application has both 64 and 32 bit bundled libraries. We check 8186 // here that the app declares multiArch support, and warn if it doesn't. 8187 // 8188 // We will be lenient here and record both ABIs. The primary will be the 8189 // ABI that's higher on the list, i.e, a device that's configured to prefer 8190 // 64 bit apps will see a 64 bit primary ABI, 8191 8192 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8193 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8194 } 8195 8196 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8197 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8198 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8199 } else { 8200 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8201 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8202 } 8203 } else { 8204 pkg.applicationInfo.primaryCpuAbi = null; 8205 pkg.applicationInfo.secondaryCpuAbi = null; 8206 } 8207 } 8208 8209 private void killApplication(String pkgName, int appId, String reason) { 8210 // Request the ActivityManager to kill the process(only for existing packages) 8211 // so that we do not end up in a confused state while the user is still using the older 8212 // version of the application while the new one gets installed. 8213 IActivityManager am = ActivityManagerNative.getDefault(); 8214 if (am != null) { 8215 try { 8216 am.killApplicationWithAppId(pkgName, appId, reason); 8217 } catch (RemoteException e) { 8218 } 8219 } 8220 } 8221 8222 void removePackageLI(PackageSetting ps, boolean chatty) { 8223 if (DEBUG_INSTALL) { 8224 if (chatty) 8225 Log.d(TAG, "Removing package " + ps.name); 8226 } 8227 8228 // writer 8229 synchronized (mPackages) { 8230 mPackages.remove(ps.name); 8231 final PackageParser.Package pkg = ps.pkg; 8232 if (pkg != null) { 8233 cleanPackageDataStructuresLILPw(pkg, chatty); 8234 } 8235 } 8236 } 8237 8238 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8239 if (DEBUG_INSTALL) { 8240 if (chatty) 8241 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8242 } 8243 8244 // writer 8245 synchronized (mPackages) { 8246 mPackages.remove(pkg.applicationInfo.packageName); 8247 cleanPackageDataStructuresLILPw(pkg, chatty); 8248 } 8249 } 8250 8251 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8252 int N = pkg.providers.size(); 8253 StringBuilder r = null; 8254 int i; 8255 for (i=0; i<N; i++) { 8256 PackageParser.Provider p = pkg.providers.get(i); 8257 mProviders.removeProvider(p); 8258 if (p.info.authority == null) { 8259 8260 /* There was another ContentProvider with this authority when 8261 * this app was installed so this authority is null, 8262 * Ignore it as we don't have to unregister the provider. 8263 */ 8264 continue; 8265 } 8266 String names[] = p.info.authority.split(";"); 8267 for (int j = 0; j < names.length; j++) { 8268 if (mProvidersByAuthority.get(names[j]) == p) { 8269 mProvidersByAuthority.remove(names[j]); 8270 if (DEBUG_REMOVE) { 8271 if (chatty) 8272 Log.d(TAG, "Unregistered content provider: " + names[j] 8273 + ", className = " + p.info.name + ", isSyncable = " 8274 + p.info.isSyncable); 8275 } 8276 } 8277 } 8278 if (DEBUG_REMOVE && chatty) { 8279 if (r == null) { 8280 r = new StringBuilder(256); 8281 } else { 8282 r.append(' '); 8283 } 8284 r.append(p.info.name); 8285 } 8286 } 8287 if (r != null) { 8288 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8289 } 8290 8291 N = pkg.services.size(); 8292 r = null; 8293 for (i=0; i<N; i++) { 8294 PackageParser.Service s = pkg.services.get(i); 8295 mServices.removeService(s); 8296 if (chatty) { 8297 if (r == null) { 8298 r = new StringBuilder(256); 8299 } else { 8300 r.append(' '); 8301 } 8302 r.append(s.info.name); 8303 } 8304 } 8305 if (r != null) { 8306 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8307 } 8308 8309 N = pkg.receivers.size(); 8310 r = null; 8311 for (i=0; i<N; i++) { 8312 PackageParser.Activity a = pkg.receivers.get(i); 8313 mReceivers.removeActivity(a, "receiver"); 8314 if (DEBUG_REMOVE && chatty) { 8315 if (r == null) { 8316 r = new StringBuilder(256); 8317 } else { 8318 r.append(' '); 8319 } 8320 r.append(a.info.name); 8321 } 8322 } 8323 if (r != null) { 8324 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8325 } 8326 8327 N = pkg.activities.size(); 8328 r = null; 8329 for (i=0; i<N; i++) { 8330 PackageParser.Activity a = pkg.activities.get(i); 8331 mActivities.removeActivity(a, "activity"); 8332 if (DEBUG_REMOVE && chatty) { 8333 if (r == null) { 8334 r = new StringBuilder(256); 8335 } else { 8336 r.append(' '); 8337 } 8338 r.append(a.info.name); 8339 } 8340 } 8341 if (r != null) { 8342 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8343 } 8344 8345 N = pkg.permissions.size(); 8346 r = null; 8347 for (i=0; i<N; i++) { 8348 PackageParser.Permission p = pkg.permissions.get(i); 8349 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8350 if (bp == null) { 8351 bp = mSettings.mPermissionTrees.get(p.info.name); 8352 } 8353 if (bp != null && bp.perm == p) { 8354 bp.perm = null; 8355 if (DEBUG_REMOVE && chatty) { 8356 if (r == null) { 8357 r = new StringBuilder(256); 8358 } else { 8359 r.append(' '); 8360 } 8361 r.append(p.info.name); 8362 } 8363 } 8364 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8365 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8366 if (appOpPerms != null) { 8367 appOpPerms.remove(pkg.packageName); 8368 } 8369 } 8370 } 8371 if (r != null) { 8372 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8373 } 8374 8375 N = pkg.requestedPermissions.size(); 8376 r = null; 8377 for (i=0; i<N; i++) { 8378 String perm = pkg.requestedPermissions.get(i); 8379 BasePermission bp = mSettings.mPermissions.get(perm); 8380 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8381 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8382 if (appOpPerms != null) { 8383 appOpPerms.remove(pkg.packageName); 8384 if (appOpPerms.isEmpty()) { 8385 mAppOpPermissionPackages.remove(perm); 8386 } 8387 } 8388 } 8389 } 8390 if (r != null) { 8391 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8392 } 8393 8394 N = pkg.instrumentation.size(); 8395 r = null; 8396 for (i=0; i<N; i++) { 8397 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8398 mInstrumentation.remove(a.getComponentName()); 8399 if (DEBUG_REMOVE && chatty) { 8400 if (r == null) { 8401 r = new StringBuilder(256); 8402 } else { 8403 r.append(' '); 8404 } 8405 r.append(a.info.name); 8406 } 8407 } 8408 if (r != null) { 8409 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8410 } 8411 8412 r = null; 8413 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8414 // Only system apps can hold shared libraries. 8415 if (pkg.libraryNames != null) { 8416 for (i=0; i<pkg.libraryNames.size(); i++) { 8417 String name = pkg.libraryNames.get(i); 8418 SharedLibraryEntry cur = mSharedLibraries.get(name); 8419 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8420 mSharedLibraries.remove(name); 8421 if (DEBUG_REMOVE && chatty) { 8422 if (r == null) { 8423 r = new StringBuilder(256); 8424 } else { 8425 r.append(' '); 8426 } 8427 r.append(name); 8428 } 8429 } 8430 } 8431 } 8432 } 8433 if (r != null) { 8434 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8435 } 8436 } 8437 8438 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8439 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8440 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8441 return true; 8442 } 8443 } 8444 return false; 8445 } 8446 8447 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8448 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8449 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8450 8451 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8452 int flags) { 8453 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8454 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8455 } 8456 8457 private void updatePermissionsLPw(String changingPkg, 8458 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8459 // Make sure there are no dangling permission trees. 8460 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8461 while (it.hasNext()) { 8462 final BasePermission bp = it.next(); 8463 if (bp.packageSetting == null) { 8464 // We may not yet have parsed the package, so just see if 8465 // we still know about its settings. 8466 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8467 } 8468 if (bp.packageSetting == null) { 8469 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8470 + " from package " + bp.sourcePackage); 8471 it.remove(); 8472 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8473 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8474 Slog.i(TAG, "Removing old permission tree: " + bp.name 8475 + " from package " + bp.sourcePackage); 8476 flags |= UPDATE_PERMISSIONS_ALL; 8477 it.remove(); 8478 } 8479 } 8480 } 8481 8482 // Make sure all dynamic permissions have been assigned to a package, 8483 // and make sure there are no dangling permissions. 8484 it = mSettings.mPermissions.values().iterator(); 8485 while (it.hasNext()) { 8486 final BasePermission bp = it.next(); 8487 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8488 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8489 + bp.name + " pkg=" + bp.sourcePackage 8490 + " info=" + bp.pendingInfo); 8491 if (bp.packageSetting == null && bp.pendingInfo != null) { 8492 final BasePermission tree = findPermissionTreeLP(bp.name); 8493 if (tree != null && tree.perm != null) { 8494 bp.packageSetting = tree.packageSetting; 8495 bp.perm = new PackageParser.Permission(tree.perm.owner, 8496 new PermissionInfo(bp.pendingInfo)); 8497 bp.perm.info.packageName = tree.perm.info.packageName; 8498 bp.perm.info.name = bp.name; 8499 bp.uid = tree.uid; 8500 } 8501 } 8502 } 8503 if (bp.packageSetting == null) { 8504 // We may not yet have parsed the package, so just see if 8505 // we still know about its settings. 8506 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8507 } 8508 if (bp.packageSetting == null) { 8509 Slog.w(TAG, "Removing dangling permission: " + bp.name 8510 + " from package " + bp.sourcePackage); 8511 it.remove(); 8512 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8513 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8514 Slog.i(TAG, "Removing old permission: " + bp.name 8515 + " from package " + bp.sourcePackage); 8516 flags |= UPDATE_PERMISSIONS_ALL; 8517 it.remove(); 8518 } 8519 } 8520 } 8521 8522 // Now update the permissions for all packages, in particular 8523 // replace the granted permissions of the system packages. 8524 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8525 for (PackageParser.Package pkg : mPackages.values()) { 8526 if (pkg != pkgInfo) { 8527 // Only replace for packages on requested volume 8528 final String volumeUuid = getVolumeUuidForPackage(pkg); 8529 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8530 && Objects.equals(replaceVolumeUuid, volumeUuid); 8531 grantPermissionsLPw(pkg, replace, changingPkg); 8532 } 8533 } 8534 } 8535 8536 if (pkgInfo != null) { 8537 // Only replace for packages on requested volume 8538 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8539 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8540 && Objects.equals(replaceVolumeUuid, volumeUuid); 8541 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8542 } 8543 } 8544 8545 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8546 String packageOfInterest) { 8547 // IMPORTANT: There are two types of permissions: install and runtime. 8548 // Install time permissions are granted when the app is installed to 8549 // all device users and users added in the future. Runtime permissions 8550 // are granted at runtime explicitly to specific users. Normal and signature 8551 // protected permissions are install time permissions. Dangerous permissions 8552 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8553 // otherwise they are runtime permissions. This function does not manage 8554 // runtime permissions except for the case an app targeting Lollipop MR1 8555 // being upgraded to target a newer SDK, in which case dangerous permissions 8556 // are transformed from install time to runtime ones. 8557 8558 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8559 if (ps == null) { 8560 return; 8561 } 8562 8563 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8564 8565 PermissionsState permissionsState = ps.getPermissionsState(); 8566 PermissionsState origPermissions = permissionsState; 8567 8568 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8569 8570 boolean runtimePermissionsRevoked = false; 8571 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8572 8573 boolean changedInstallPermission = false; 8574 8575 if (replace) { 8576 ps.installPermissionsFixed = false; 8577 if (!ps.isSharedUser()) { 8578 origPermissions = new PermissionsState(permissionsState); 8579 permissionsState.reset(); 8580 } else { 8581 // We need to know only about runtime permission changes since the 8582 // calling code always writes the install permissions state but 8583 // the runtime ones are written only if changed. The only cases of 8584 // changed runtime permissions here are promotion of an install to 8585 // runtime and revocation of a runtime from a shared user. 8586 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8587 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8588 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8589 runtimePermissionsRevoked = true; 8590 } 8591 } 8592 } 8593 8594 permissionsState.setGlobalGids(mGlobalGids); 8595 8596 final int N = pkg.requestedPermissions.size(); 8597 for (int i=0; i<N; i++) { 8598 final String name = pkg.requestedPermissions.get(i); 8599 final BasePermission bp = mSettings.mPermissions.get(name); 8600 8601 if (DEBUG_INSTALL) { 8602 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8603 } 8604 8605 if (bp == null || bp.packageSetting == null) { 8606 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8607 Slog.w(TAG, "Unknown permission " + name 8608 + " in package " + pkg.packageName); 8609 } 8610 continue; 8611 } 8612 8613 final String perm = bp.name; 8614 boolean allowedSig = false; 8615 int grant = GRANT_DENIED; 8616 8617 // Keep track of app op permissions. 8618 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8619 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8620 if (pkgs == null) { 8621 pkgs = new ArraySet<>(); 8622 mAppOpPermissionPackages.put(bp.name, pkgs); 8623 } 8624 pkgs.add(pkg.packageName); 8625 } 8626 8627 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8628 switch (level) { 8629 case PermissionInfo.PROTECTION_NORMAL: { 8630 // For all apps normal permissions are install time ones. 8631 grant = GRANT_INSTALL; 8632 } break; 8633 8634 case PermissionInfo.PROTECTION_DANGEROUS: { 8635 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8636 // For legacy apps dangerous permissions are install time ones. 8637 grant = GRANT_INSTALL_LEGACY; 8638 } else if (origPermissions.hasInstallPermission(bp.name)) { 8639 // For legacy apps that became modern, install becomes runtime. 8640 grant = GRANT_UPGRADE; 8641 } else if (mPromoteSystemApps 8642 && isSystemApp(ps) 8643 && mExistingSystemPackages.contains(ps.name)) { 8644 // For legacy system apps, install becomes runtime. 8645 // We cannot check hasInstallPermission() for system apps since those 8646 // permissions were granted implicitly and not persisted pre-M. 8647 grant = GRANT_UPGRADE; 8648 } else { 8649 // For modern apps keep runtime permissions unchanged. 8650 grant = GRANT_RUNTIME; 8651 } 8652 } break; 8653 8654 case PermissionInfo.PROTECTION_SIGNATURE: { 8655 // For all apps signature permissions are install time ones. 8656 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8657 if (allowedSig) { 8658 grant = GRANT_INSTALL; 8659 } 8660 } break; 8661 } 8662 8663 if (DEBUG_INSTALL) { 8664 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8665 } 8666 8667 if (grant != GRANT_DENIED) { 8668 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8669 // If this is an existing, non-system package, then 8670 // we can't add any new permissions to it. 8671 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8672 // Except... if this is a permission that was added 8673 // to the platform (note: need to only do this when 8674 // updating the platform). 8675 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8676 grant = GRANT_DENIED; 8677 } 8678 } 8679 } 8680 8681 switch (grant) { 8682 case GRANT_INSTALL: { 8683 // Revoke this as runtime permission to handle the case of 8684 // a runtime permission being downgraded to an install one. 8685 for (int userId : UserManagerService.getInstance().getUserIds()) { 8686 if (origPermissions.getRuntimePermissionState( 8687 bp.name, userId) != null) { 8688 // Revoke the runtime permission and clear the flags. 8689 origPermissions.revokeRuntimePermission(bp, userId); 8690 origPermissions.updatePermissionFlags(bp, userId, 8691 PackageManager.MASK_PERMISSION_FLAGS, 0); 8692 // If we revoked a permission permission, we have to write. 8693 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8694 changedRuntimePermissionUserIds, userId); 8695 } 8696 } 8697 // Grant an install permission. 8698 if (permissionsState.grantInstallPermission(bp) != 8699 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8700 changedInstallPermission = true; 8701 } 8702 } break; 8703 8704 case GRANT_INSTALL_LEGACY: { 8705 // Grant an install permission. 8706 if (permissionsState.grantInstallPermission(bp) != 8707 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8708 changedInstallPermission = true; 8709 } 8710 } break; 8711 8712 case GRANT_RUNTIME: { 8713 // Grant previously granted runtime permissions. 8714 for (int userId : UserManagerService.getInstance().getUserIds()) { 8715 PermissionState permissionState = origPermissions 8716 .getRuntimePermissionState(bp.name, userId); 8717 final int flags = permissionState != null 8718 ? permissionState.getFlags() : 0; 8719 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8720 if (permissionsState.grantRuntimePermission(bp, userId) == 8721 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8722 // If we cannot put the permission as it was, we have to write. 8723 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8724 changedRuntimePermissionUserIds, userId); 8725 } 8726 } 8727 // Propagate the permission flags. 8728 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8729 } 8730 } break; 8731 8732 case GRANT_UPGRADE: { 8733 // Grant runtime permissions for a previously held install permission. 8734 PermissionState permissionState = origPermissions 8735 .getInstallPermissionState(bp.name); 8736 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8737 8738 if (origPermissions.revokeInstallPermission(bp) 8739 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8740 // We will be transferring the permission flags, so clear them. 8741 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8742 PackageManager.MASK_PERMISSION_FLAGS, 0); 8743 changedInstallPermission = true; 8744 } 8745 8746 // If the permission is not to be promoted to runtime we ignore it and 8747 // also its other flags as they are not applicable to install permissions. 8748 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8749 for (int userId : currentUserIds) { 8750 if (permissionsState.grantRuntimePermission(bp, userId) != 8751 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8752 // Transfer the permission flags. 8753 permissionsState.updatePermissionFlags(bp, userId, 8754 flags, flags); 8755 // If we granted the permission, we have to write. 8756 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8757 changedRuntimePermissionUserIds, userId); 8758 } 8759 } 8760 } 8761 } break; 8762 8763 default: { 8764 if (packageOfInterest == null 8765 || packageOfInterest.equals(pkg.packageName)) { 8766 Slog.w(TAG, "Not granting permission " + perm 8767 + " to package " + pkg.packageName 8768 + " because it was previously installed without"); 8769 } 8770 } break; 8771 } 8772 } else { 8773 if (permissionsState.revokeInstallPermission(bp) != 8774 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8775 // Also drop the permission flags. 8776 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8777 PackageManager.MASK_PERMISSION_FLAGS, 0); 8778 changedInstallPermission = true; 8779 Slog.i(TAG, "Un-granting permission " + perm 8780 + " from package " + pkg.packageName 8781 + " (protectionLevel=" + bp.protectionLevel 8782 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8783 + ")"); 8784 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8785 // Don't print warning for app op permissions, since it is fine for them 8786 // not to be granted, there is a UI for the user to decide. 8787 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8788 Slog.w(TAG, "Not granting permission " + perm 8789 + " to package " + pkg.packageName 8790 + " (protectionLevel=" + bp.protectionLevel 8791 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8792 + ")"); 8793 } 8794 } 8795 } 8796 } 8797 8798 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8799 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8800 // This is the first that we have heard about this package, so the 8801 // permissions we have now selected are fixed until explicitly 8802 // changed. 8803 ps.installPermissionsFixed = true; 8804 } 8805 8806 // Persist the runtime permissions state for users with changes. If permissions 8807 // were revoked because no app in the shared user declares them we have to 8808 // write synchronously to avoid losing runtime permissions state. 8809 for (int userId : changedRuntimePermissionUserIds) { 8810 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8811 } 8812 8813 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8814 } 8815 8816 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8817 boolean allowed = false; 8818 final int NP = PackageParser.NEW_PERMISSIONS.length; 8819 for (int ip=0; ip<NP; ip++) { 8820 final PackageParser.NewPermissionInfo npi 8821 = PackageParser.NEW_PERMISSIONS[ip]; 8822 if (npi.name.equals(perm) 8823 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8824 allowed = true; 8825 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8826 + pkg.packageName); 8827 break; 8828 } 8829 } 8830 return allowed; 8831 } 8832 8833 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8834 BasePermission bp, PermissionsState origPermissions) { 8835 boolean allowed; 8836 allowed = (compareSignatures( 8837 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8838 == PackageManager.SIGNATURE_MATCH) 8839 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8840 == PackageManager.SIGNATURE_MATCH); 8841 if (!allowed && (bp.protectionLevel 8842 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8843 if (isSystemApp(pkg)) { 8844 // For updated system applications, a system permission 8845 // is granted only if it had been defined by the original application. 8846 if (pkg.isUpdatedSystemApp()) { 8847 final PackageSetting sysPs = mSettings 8848 .getDisabledSystemPkgLPr(pkg.packageName); 8849 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8850 // If the original was granted this permission, we take 8851 // that grant decision as read and propagate it to the 8852 // update. 8853 if (sysPs.isPrivileged()) { 8854 allowed = true; 8855 } 8856 } else { 8857 // The system apk may have been updated with an older 8858 // version of the one on the data partition, but which 8859 // granted a new system permission that it didn't have 8860 // before. In this case we do want to allow the app to 8861 // now get the new permission if the ancestral apk is 8862 // privileged to get it. 8863 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8864 for (int j=0; 8865 j<sysPs.pkg.requestedPermissions.size(); j++) { 8866 if (perm.equals( 8867 sysPs.pkg.requestedPermissions.get(j))) { 8868 allowed = true; 8869 break; 8870 } 8871 } 8872 } 8873 } 8874 } else { 8875 allowed = isPrivilegedApp(pkg); 8876 } 8877 } 8878 } 8879 if (!allowed) { 8880 if (!allowed && (bp.protectionLevel 8881 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8882 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8883 // If this was a previously normal/dangerous permission that got moved 8884 // to a system permission as part of the runtime permission redesign, then 8885 // we still want to blindly grant it to old apps. 8886 allowed = true; 8887 } 8888 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8889 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8890 // If this permission is to be granted to the system installer and 8891 // this app is an installer, then it gets the permission. 8892 allowed = true; 8893 } 8894 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8895 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8896 // If this permission is to be granted to the system verifier and 8897 // this app is a verifier, then it gets the permission. 8898 allowed = true; 8899 } 8900 if (!allowed && (bp.protectionLevel 8901 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8902 && isSystemApp(pkg)) { 8903 // Any pre-installed system app is allowed to get this permission. 8904 allowed = true; 8905 } 8906 if (!allowed && (bp.protectionLevel 8907 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8908 // For development permissions, a development permission 8909 // is granted only if it was already granted. 8910 allowed = origPermissions.hasInstallPermission(perm); 8911 } 8912 } 8913 return allowed; 8914 } 8915 8916 final class ActivityIntentResolver 8917 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8918 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8919 boolean defaultOnly, int userId) { 8920 if (!sUserManager.exists(userId)) return null; 8921 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8922 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8923 } 8924 8925 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8926 int userId) { 8927 if (!sUserManager.exists(userId)) return null; 8928 mFlags = flags; 8929 return super.queryIntent(intent, resolvedType, 8930 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8931 } 8932 8933 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8934 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8935 if (!sUserManager.exists(userId)) return null; 8936 if (packageActivities == null) { 8937 return null; 8938 } 8939 mFlags = flags; 8940 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8941 final int N = packageActivities.size(); 8942 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8943 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8944 8945 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8946 for (int i = 0; i < N; ++i) { 8947 intentFilters = packageActivities.get(i).intents; 8948 if (intentFilters != null && intentFilters.size() > 0) { 8949 PackageParser.ActivityIntentInfo[] array = 8950 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8951 intentFilters.toArray(array); 8952 listCut.add(array); 8953 } 8954 } 8955 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8956 } 8957 8958 public final void addActivity(PackageParser.Activity a, String type) { 8959 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8960 mActivities.put(a.getComponentName(), a); 8961 if (DEBUG_SHOW_INFO) 8962 Log.v( 8963 TAG, " " + type + " " + 8964 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8965 if (DEBUG_SHOW_INFO) 8966 Log.v(TAG, " Class=" + a.info.name); 8967 final int NI = a.intents.size(); 8968 for (int j=0; j<NI; j++) { 8969 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8970 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8971 intent.setPriority(0); 8972 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8973 + a.className + " with priority > 0, forcing to 0"); 8974 } 8975 if (DEBUG_SHOW_INFO) { 8976 Log.v(TAG, " IntentFilter:"); 8977 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8978 } 8979 if (!intent.debugCheck()) { 8980 Log.w(TAG, "==> For Activity " + a.info.name); 8981 } 8982 addFilter(intent); 8983 } 8984 } 8985 8986 public final void removeActivity(PackageParser.Activity a, String type) { 8987 mActivities.remove(a.getComponentName()); 8988 if (DEBUG_SHOW_INFO) { 8989 Log.v(TAG, " " + type + " " 8990 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8991 : a.info.name) + ":"); 8992 Log.v(TAG, " Class=" + a.info.name); 8993 } 8994 final int NI = a.intents.size(); 8995 for (int j=0; j<NI; j++) { 8996 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8997 if (DEBUG_SHOW_INFO) { 8998 Log.v(TAG, " IntentFilter:"); 8999 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9000 } 9001 removeFilter(intent); 9002 } 9003 } 9004 9005 @Override 9006 protected boolean allowFilterResult( 9007 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9008 ActivityInfo filterAi = filter.activity.info; 9009 for (int i=dest.size()-1; i>=0; i--) { 9010 ActivityInfo destAi = dest.get(i).activityInfo; 9011 if (destAi.name == filterAi.name 9012 && destAi.packageName == filterAi.packageName) { 9013 return false; 9014 } 9015 } 9016 return true; 9017 } 9018 9019 @Override 9020 protected ActivityIntentInfo[] newArray(int size) { 9021 return new ActivityIntentInfo[size]; 9022 } 9023 9024 @Override 9025 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9026 if (!sUserManager.exists(userId)) return true; 9027 PackageParser.Package p = filter.activity.owner; 9028 if (p != null) { 9029 PackageSetting ps = (PackageSetting)p.mExtras; 9030 if (ps != null) { 9031 // System apps are never considered stopped for purposes of 9032 // filtering, because there may be no way for the user to 9033 // actually re-launch them. 9034 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9035 && ps.getStopped(userId); 9036 } 9037 } 9038 return false; 9039 } 9040 9041 @Override 9042 protected boolean isPackageForFilter(String packageName, 9043 PackageParser.ActivityIntentInfo info) { 9044 return packageName.equals(info.activity.owner.packageName); 9045 } 9046 9047 @Override 9048 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9049 int match, int userId) { 9050 if (!sUserManager.exists(userId)) return null; 9051 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 9052 return null; 9053 } 9054 final PackageParser.Activity activity = info.activity; 9055 if (mSafeMode && (activity.info.applicationInfo.flags 9056 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9057 return null; 9058 } 9059 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9060 if (ps == null) { 9061 return null; 9062 } 9063 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9064 ps.readUserState(userId), userId); 9065 if (ai == null) { 9066 return null; 9067 } 9068 final ResolveInfo res = new ResolveInfo(); 9069 res.activityInfo = ai; 9070 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9071 res.filter = info; 9072 } 9073 if (info != null) { 9074 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9075 } 9076 res.priority = info.getPriority(); 9077 res.preferredOrder = activity.owner.mPreferredOrder; 9078 //System.out.println("Result: " + res.activityInfo.className + 9079 // " = " + res.priority); 9080 res.match = match; 9081 res.isDefault = info.hasDefault; 9082 res.labelRes = info.labelRes; 9083 res.nonLocalizedLabel = info.nonLocalizedLabel; 9084 if (userNeedsBadging(userId)) { 9085 res.noResourceId = true; 9086 } else { 9087 res.icon = info.icon; 9088 } 9089 res.iconResourceId = info.icon; 9090 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9091 return res; 9092 } 9093 9094 @Override 9095 protected void sortResults(List<ResolveInfo> results) { 9096 Collections.sort(results, mResolvePrioritySorter); 9097 } 9098 9099 @Override 9100 protected void dumpFilter(PrintWriter out, String prefix, 9101 PackageParser.ActivityIntentInfo filter) { 9102 out.print(prefix); out.print( 9103 Integer.toHexString(System.identityHashCode(filter.activity))); 9104 out.print(' '); 9105 filter.activity.printComponentShortName(out); 9106 out.print(" filter "); 9107 out.println(Integer.toHexString(System.identityHashCode(filter))); 9108 } 9109 9110 @Override 9111 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9112 return filter.activity; 9113 } 9114 9115 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9116 PackageParser.Activity activity = (PackageParser.Activity)label; 9117 out.print(prefix); out.print( 9118 Integer.toHexString(System.identityHashCode(activity))); 9119 out.print(' '); 9120 activity.printComponentShortName(out); 9121 if (count > 1) { 9122 out.print(" ("); out.print(count); out.print(" filters)"); 9123 } 9124 out.println(); 9125 } 9126 9127// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9128// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9129// final List<ResolveInfo> retList = Lists.newArrayList(); 9130// while (i.hasNext()) { 9131// final ResolveInfo resolveInfo = i.next(); 9132// if (isEnabledLP(resolveInfo.activityInfo)) { 9133// retList.add(resolveInfo); 9134// } 9135// } 9136// return retList; 9137// } 9138 9139 // Keys are String (activity class name), values are Activity. 9140 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9141 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9142 private int mFlags; 9143 } 9144 9145 private final class ServiceIntentResolver 9146 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9147 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9148 boolean defaultOnly, int userId) { 9149 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9150 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9151 } 9152 9153 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9154 int userId) { 9155 if (!sUserManager.exists(userId)) return null; 9156 mFlags = flags; 9157 return super.queryIntent(intent, resolvedType, 9158 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9159 } 9160 9161 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9162 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9163 if (!sUserManager.exists(userId)) return null; 9164 if (packageServices == null) { 9165 return null; 9166 } 9167 mFlags = flags; 9168 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9169 final int N = packageServices.size(); 9170 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9171 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9172 9173 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9174 for (int i = 0; i < N; ++i) { 9175 intentFilters = packageServices.get(i).intents; 9176 if (intentFilters != null && intentFilters.size() > 0) { 9177 PackageParser.ServiceIntentInfo[] array = 9178 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9179 intentFilters.toArray(array); 9180 listCut.add(array); 9181 } 9182 } 9183 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9184 } 9185 9186 public final void addService(PackageParser.Service s) { 9187 mServices.put(s.getComponentName(), s); 9188 if (DEBUG_SHOW_INFO) { 9189 Log.v(TAG, " " 9190 + (s.info.nonLocalizedLabel != null 9191 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9192 Log.v(TAG, " Class=" + s.info.name); 9193 } 9194 final int NI = s.intents.size(); 9195 int j; 9196 for (j=0; j<NI; j++) { 9197 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9198 if (DEBUG_SHOW_INFO) { 9199 Log.v(TAG, " IntentFilter:"); 9200 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9201 } 9202 if (!intent.debugCheck()) { 9203 Log.w(TAG, "==> For Service " + s.info.name); 9204 } 9205 addFilter(intent); 9206 } 9207 } 9208 9209 public final void removeService(PackageParser.Service s) { 9210 mServices.remove(s.getComponentName()); 9211 if (DEBUG_SHOW_INFO) { 9212 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9213 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9214 Log.v(TAG, " Class=" + s.info.name); 9215 } 9216 final int NI = s.intents.size(); 9217 int j; 9218 for (j=0; j<NI; j++) { 9219 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9220 if (DEBUG_SHOW_INFO) { 9221 Log.v(TAG, " IntentFilter:"); 9222 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9223 } 9224 removeFilter(intent); 9225 } 9226 } 9227 9228 @Override 9229 protected boolean allowFilterResult( 9230 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9231 ServiceInfo filterSi = filter.service.info; 9232 for (int i=dest.size()-1; i>=0; i--) { 9233 ServiceInfo destAi = dest.get(i).serviceInfo; 9234 if (destAi.name == filterSi.name 9235 && destAi.packageName == filterSi.packageName) { 9236 return false; 9237 } 9238 } 9239 return true; 9240 } 9241 9242 @Override 9243 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9244 return new PackageParser.ServiceIntentInfo[size]; 9245 } 9246 9247 @Override 9248 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9249 if (!sUserManager.exists(userId)) return true; 9250 PackageParser.Package p = filter.service.owner; 9251 if (p != null) { 9252 PackageSetting ps = (PackageSetting)p.mExtras; 9253 if (ps != null) { 9254 // System apps are never considered stopped for purposes of 9255 // filtering, because there may be no way for the user to 9256 // actually re-launch them. 9257 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9258 && ps.getStopped(userId); 9259 } 9260 } 9261 return false; 9262 } 9263 9264 @Override 9265 protected boolean isPackageForFilter(String packageName, 9266 PackageParser.ServiceIntentInfo info) { 9267 return packageName.equals(info.service.owner.packageName); 9268 } 9269 9270 @Override 9271 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9272 int match, int userId) { 9273 if (!sUserManager.exists(userId)) return null; 9274 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9275 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9276 return null; 9277 } 9278 final PackageParser.Service service = info.service; 9279 if (mSafeMode && (service.info.applicationInfo.flags 9280 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9281 return null; 9282 } 9283 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9284 if (ps == null) { 9285 return null; 9286 } 9287 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9288 ps.readUserState(userId), userId); 9289 if (si == null) { 9290 return null; 9291 } 9292 final ResolveInfo res = new ResolveInfo(); 9293 res.serviceInfo = si; 9294 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9295 res.filter = filter; 9296 } 9297 res.priority = info.getPriority(); 9298 res.preferredOrder = service.owner.mPreferredOrder; 9299 res.match = match; 9300 res.isDefault = info.hasDefault; 9301 res.labelRes = info.labelRes; 9302 res.nonLocalizedLabel = info.nonLocalizedLabel; 9303 res.icon = info.icon; 9304 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9305 return res; 9306 } 9307 9308 @Override 9309 protected void sortResults(List<ResolveInfo> results) { 9310 Collections.sort(results, mResolvePrioritySorter); 9311 } 9312 9313 @Override 9314 protected void dumpFilter(PrintWriter out, String prefix, 9315 PackageParser.ServiceIntentInfo filter) { 9316 out.print(prefix); out.print( 9317 Integer.toHexString(System.identityHashCode(filter.service))); 9318 out.print(' '); 9319 filter.service.printComponentShortName(out); 9320 out.print(" filter "); 9321 out.println(Integer.toHexString(System.identityHashCode(filter))); 9322 } 9323 9324 @Override 9325 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9326 return filter.service; 9327 } 9328 9329 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9330 PackageParser.Service service = (PackageParser.Service)label; 9331 out.print(prefix); out.print( 9332 Integer.toHexString(System.identityHashCode(service))); 9333 out.print(' '); 9334 service.printComponentShortName(out); 9335 if (count > 1) { 9336 out.print(" ("); out.print(count); out.print(" filters)"); 9337 } 9338 out.println(); 9339 } 9340 9341// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9342// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9343// final List<ResolveInfo> retList = Lists.newArrayList(); 9344// while (i.hasNext()) { 9345// final ResolveInfo resolveInfo = (ResolveInfo) i; 9346// if (isEnabledLP(resolveInfo.serviceInfo)) { 9347// retList.add(resolveInfo); 9348// } 9349// } 9350// return retList; 9351// } 9352 9353 // Keys are String (activity class name), values are Activity. 9354 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9355 = new ArrayMap<ComponentName, PackageParser.Service>(); 9356 private int mFlags; 9357 }; 9358 9359 private final class ProviderIntentResolver 9360 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9361 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9362 boolean defaultOnly, int userId) { 9363 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9364 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9365 } 9366 9367 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9368 int userId) { 9369 if (!sUserManager.exists(userId)) 9370 return null; 9371 mFlags = flags; 9372 return super.queryIntent(intent, resolvedType, 9373 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9374 } 9375 9376 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9377 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9378 if (!sUserManager.exists(userId)) 9379 return null; 9380 if (packageProviders == null) { 9381 return null; 9382 } 9383 mFlags = flags; 9384 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9385 final int N = packageProviders.size(); 9386 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9387 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9388 9389 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9390 for (int i = 0; i < N; ++i) { 9391 intentFilters = packageProviders.get(i).intents; 9392 if (intentFilters != null && intentFilters.size() > 0) { 9393 PackageParser.ProviderIntentInfo[] array = 9394 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9395 intentFilters.toArray(array); 9396 listCut.add(array); 9397 } 9398 } 9399 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9400 } 9401 9402 public final void addProvider(PackageParser.Provider p) { 9403 if (mProviders.containsKey(p.getComponentName())) { 9404 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9405 return; 9406 } 9407 9408 mProviders.put(p.getComponentName(), p); 9409 if (DEBUG_SHOW_INFO) { 9410 Log.v(TAG, " " 9411 + (p.info.nonLocalizedLabel != null 9412 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9413 Log.v(TAG, " Class=" + p.info.name); 9414 } 9415 final int NI = p.intents.size(); 9416 int j; 9417 for (j = 0; j < NI; j++) { 9418 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9419 if (DEBUG_SHOW_INFO) { 9420 Log.v(TAG, " IntentFilter:"); 9421 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9422 } 9423 if (!intent.debugCheck()) { 9424 Log.w(TAG, "==> For Provider " + p.info.name); 9425 } 9426 addFilter(intent); 9427 } 9428 } 9429 9430 public final void removeProvider(PackageParser.Provider p) { 9431 mProviders.remove(p.getComponentName()); 9432 if (DEBUG_SHOW_INFO) { 9433 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9434 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9435 Log.v(TAG, " Class=" + p.info.name); 9436 } 9437 final int NI = p.intents.size(); 9438 int j; 9439 for (j = 0; j < NI; j++) { 9440 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9441 if (DEBUG_SHOW_INFO) { 9442 Log.v(TAG, " IntentFilter:"); 9443 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9444 } 9445 removeFilter(intent); 9446 } 9447 } 9448 9449 @Override 9450 protected boolean allowFilterResult( 9451 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9452 ProviderInfo filterPi = filter.provider.info; 9453 for (int i = dest.size() - 1; i >= 0; i--) { 9454 ProviderInfo destPi = dest.get(i).providerInfo; 9455 if (destPi.name == filterPi.name 9456 && destPi.packageName == filterPi.packageName) { 9457 return false; 9458 } 9459 } 9460 return true; 9461 } 9462 9463 @Override 9464 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9465 return new PackageParser.ProviderIntentInfo[size]; 9466 } 9467 9468 @Override 9469 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9470 if (!sUserManager.exists(userId)) 9471 return true; 9472 PackageParser.Package p = filter.provider.owner; 9473 if (p != null) { 9474 PackageSetting ps = (PackageSetting) p.mExtras; 9475 if (ps != null) { 9476 // System apps are never considered stopped for purposes of 9477 // filtering, because there may be no way for the user to 9478 // actually re-launch them. 9479 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9480 && ps.getStopped(userId); 9481 } 9482 } 9483 return false; 9484 } 9485 9486 @Override 9487 protected boolean isPackageForFilter(String packageName, 9488 PackageParser.ProviderIntentInfo info) { 9489 return packageName.equals(info.provider.owner.packageName); 9490 } 9491 9492 @Override 9493 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9494 int match, int userId) { 9495 if (!sUserManager.exists(userId)) 9496 return null; 9497 final PackageParser.ProviderIntentInfo info = filter; 9498 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9499 return null; 9500 } 9501 final PackageParser.Provider provider = info.provider; 9502 if (mSafeMode && (provider.info.applicationInfo.flags 9503 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9504 return null; 9505 } 9506 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9507 if (ps == null) { 9508 return null; 9509 } 9510 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9511 ps.readUserState(userId), userId); 9512 if (pi == null) { 9513 return null; 9514 } 9515 final ResolveInfo res = new ResolveInfo(); 9516 res.providerInfo = pi; 9517 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9518 res.filter = filter; 9519 } 9520 res.priority = info.getPriority(); 9521 res.preferredOrder = provider.owner.mPreferredOrder; 9522 res.match = match; 9523 res.isDefault = info.hasDefault; 9524 res.labelRes = info.labelRes; 9525 res.nonLocalizedLabel = info.nonLocalizedLabel; 9526 res.icon = info.icon; 9527 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9528 return res; 9529 } 9530 9531 @Override 9532 protected void sortResults(List<ResolveInfo> results) { 9533 Collections.sort(results, mResolvePrioritySorter); 9534 } 9535 9536 @Override 9537 protected void dumpFilter(PrintWriter out, String prefix, 9538 PackageParser.ProviderIntentInfo filter) { 9539 out.print(prefix); 9540 out.print( 9541 Integer.toHexString(System.identityHashCode(filter.provider))); 9542 out.print(' '); 9543 filter.provider.printComponentShortName(out); 9544 out.print(" filter "); 9545 out.println(Integer.toHexString(System.identityHashCode(filter))); 9546 } 9547 9548 @Override 9549 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9550 return filter.provider; 9551 } 9552 9553 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9554 PackageParser.Provider provider = (PackageParser.Provider)label; 9555 out.print(prefix); out.print( 9556 Integer.toHexString(System.identityHashCode(provider))); 9557 out.print(' '); 9558 provider.printComponentShortName(out); 9559 if (count > 1) { 9560 out.print(" ("); out.print(count); out.print(" filters)"); 9561 } 9562 out.println(); 9563 } 9564 9565 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9566 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9567 private int mFlags; 9568 } 9569 9570 private static final class EphemeralIntentResolver 9571 extends IntentResolver<IntentFilter, ResolveInfo> { 9572 @Override 9573 protected IntentFilter[] newArray(int size) { 9574 return new IntentFilter[size]; 9575 } 9576 9577 @Override 9578 protected boolean isPackageForFilter(String packageName, IntentFilter info) { 9579 return true; 9580 } 9581 9582 @Override 9583 protected ResolveInfo newResult(IntentFilter info, int match, int userId) { 9584 if (!sUserManager.exists(userId)) return null; 9585 final ResolveInfo res = new ResolveInfo(); 9586 res.filter = info; 9587 return res; 9588 } 9589 } 9590 9591 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9592 new Comparator<ResolveInfo>() { 9593 public int compare(ResolveInfo r1, ResolveInfo r2) { 9594 int v1 = r1.priority; 9595 int v2 = r2.priority; 9596 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9597 if (v1 != v2) { 9598 return (v1 > v2) ? -1 : 1; 9599 } 9600 v1 = r1.preferredOrder; 9601 v2 = r2.preferredOrder; 9602 if (v1 != v2) { 9603 return (v1 > v2) ? -1 : 1; 9604 } 9605 if (r1.isDefault != r2.isDefault) { 9606 return r1.isDefault ? -1 : 1; 9607 } 9608 v1 = r1.match; 9609 v2 = r2.match; 9610 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9611 if (v1 != v2) { 9612 return (v1 > v2) ? -1 : 1; 9613 } 9614 if (r1.system != r2.system) { 9615 return r1.system ? -1 : 1; 9616 } 9617 return 0; 9618 } 9619 }; 9620 9621 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9622 new Comparator<ProviderInfo>() { 9623 public int compare(ProviderInfo p1, ProviderInfo p2) { 9624 final int v1 = p1.initOrder; 9625 final int v2 = p2.initOrder; 9626 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9627 } 9628 }; 9629 9630 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9631 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9632 final int[] userIds) { 9633 mHandler.post(new Runnable() { 9634 @Override 9635 public void run() { 9636 try { 9637 final IActivityManager am = ActivityManagerNative.getDefault(); 9638 if (am == null) return; 9639 final int[] resolvedUserIds; 9640 if (userIds == null) { 9641 resolvedUserIds = am.getRunningUserIds(); 9642 } else { 9643 resolvedUserIds = userIds; 9644 } 9645 for (int id : resolvedUserIds) { 9646 final Intent intent = new Intent(action, 9647 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9648 if (extras != null) { 9649 intent.putExtras(extras); 9650 } 9651 if (targetPkg != null) { 9652 intent.setPackage(targetPkg); 9653 } 9654 // Modify the UID when posting to other users 9655 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9656 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9657 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9658 intent.putExtra(Intent.EXTRA_UID, uid); 9659 } 9660 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9661 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9662 if (DEBUG_BROADCASTS) { 9663 RuntimeException here = new RuntimeException("here"); 9664 here.fillInStackTrace(); 9665 Slog.d(TAG, "Sending to user " + id + ": " 9666 + intent.toShortString(false, true, false, false) 9667 + " " + intent.getExtras(), here); 9668 } 9669 am.broadcastIntent(null, intent, null, finishedReceiver, 9670 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9671 null, finishedReceiver != null, false, id); 9672 } 9673 } catch (RemoteException ex) { 9674 } 9675 } 9676 }); 9677 } 9678 9679 /** 9680 * Check if the external storage media is available. This is true if there 9681 * is a mounted external storage medium or if the external storage is 9682 * emulated. 9683 */ 9684 private boolean isExternalMediaAvailable() { 9685 return mMediaMounted || Environment.isExternalStorageEmulated(); 9686 } 9687 9688 @Override 9689 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9690 // writer 9691 synchronized (mPackages) { 9692 if (!isExternalMediaAvailable()) { 9693 // If the external storage is no longer mounted at this point, 9694 // the caller may not have been able to delete all of this 9695 // packages files and can not delete any more. Bail. 9696 return null; 9697 } 9698 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9699 if (lastPackage != null) { 9700 pkgs.remove(lastPackage); 9701 } 9702 if (pkgs.size() > 0) { 9703 return pkgs.get(0); 9704 } 9705 } 9706 return null; 9707 } 9708 9709 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9710 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9711 userId, andCode ? 1 : 0, packageName); 9712 if (mSystemReady) { 9713 msg.sendToTarget(); 9714 } else { 9715 if (mPostSystemReadyMessages == null) { 9716 mPostSystemReadyMessages = new ArrayList<>(); 9717 } 9718 mPostSystemReadyMessages.add(msg); 9719 } 9720 } 9721 9722 void startCleaningPackages() { 9723 // reader 9724 synchronized (mPackages) { 9725 if (!isExternalMediaAvailable()) { 9726 return; 9727 } 9728 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9729 return; 9730 } 9731 } 9732 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9733 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9734 IActivityManager am = ActivityManagerNative.getDefault(); 9735 if (am != null) { 9736 try { 9737 am.startService(null, intent, null, mContext.getOpPackageName(), 9738 UserHandle.USER_SYSTEM); 9739 } catch (RemoteException e) { 9740 } 9741 } 9742 } 9743 9744 @Override 9745 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9746 int installFlags, String installerPackageName, VerificationParams verificationParams, 9747 String packageAbiOverride) { 9748 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9749 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9750 } 9751 9752 @Override 9753 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9754 int installFlags, String installerPackageName, VerificationParams verificationParams, 9755 String packageAbiOverride, int userId) { 9756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9757 9758 final int callingUid = Binder.getCallingUid(); 9759 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9760 9761 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9762 try { 9763 if (observer != null) { 9764 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9765 } 9766 } catch (RemoteException re) { 9767 } 9768 return; 9769 } 9770 9771 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9772 installFlags |= PackageManager.INSTALL_FROM_ADB; 9773 9774 } else { 9775 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9776 // about installerPackageName. 9777 9778 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9779 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9780 } 9781 9782 UserHandle user; 9783 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9784 user = UserHandle.ALL; 9785 } else { 9786 user = new UserHandle(userId); 9787 } 9788 9789 // Only system components can circumvent runtime permissions when installing. 9790 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9791 && mContext.checkCallingOrSelfPermission(Manifest.permission 9792 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9793 throw new SecurityException("You need the " 9794 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9795 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9796 } 9797 9798 verificationParams.setInstallerUid(callingUid); 9799 9800 final File originFile = new File(originPath); 9801 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9802 9803 final Message msg = mHandler.obtainMessage(INIT_COPY); 9804 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9805 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9806 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9807 msg.obj = params; 9808 9809 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9810 System.identityHashCode(msg.obj)); 9811 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9812 System.identityHashCode(msg.obj)); 9813 9814 mHandler.sendMessage(msg); 9815 } 9816 9817 void installStage(String packageName, File stagedDir, String stagedCid, 9818 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9819 String installerPackageName, int installerUid, UserHandle user) { 9820 final VerificationParams verifParams = new VerificationParams( 9821 null, sessionParams.originatingUri, sessionParams.referrerUri, 9822 sessionParams.originatingUid, null); 9823 verifParams.setInstallerUid(installerUid); 9824 9825 final OriginInfo origin; 9826 if (stagedDir != null) { 9827 origin = OriginInfo.fromStagedFile(stagedDir); 9828 } else { 9829 origin = OriginInfo.fromStagedContainer(stagedCid); 9830 } 9831 9832 final Message msg = mHandler.obtainMessage(INIT_COPY); 9833 final InstallParams params = new InstallParams(origin, null, observer, 9834 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9835 verifParams, user, sessionParams.abiOverride, 9836 sessionParams.grantedRuntimePermissions); 9837 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9838 msg.obj = params; 9839 9840 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9841 System.identityHashCode(msg.obj)); 9842 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9843 System.identityHashCode(msg.obj)); 9844 9845 mHandler.sendMessage(msg); 9846 } 9847 9848 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9849 Bundle extras = new Bundle(1); 9850 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9851 9852 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9853 packageName, extras, 0, null, null, new int[] {userId}); 9854 try { 9855 IActivityManager am = ActivityManagerNative.getDefault(); 9856 final boolean isSystem = 9857 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9858 if (isSystem && am.isUserRunning(userId, 0)) { 9859 // The just-installed/enabled app is bundled on the system, so presumed 9860 // to be able to run automatically without needing an explicit launch. 9861 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9862 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9863 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9864 .setPackage(packageName); 9865 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9866 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9867 } 9868 } catch (RemoteException e) { 9869 // shouldn't happen 9870 Slog.w(TAG, "Unable to bootstrap installed package", e); 9871 } 9872 } 9873 9874 @Override 9875 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9876 int userId) { 9877 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9878 PackageSetting pkgSetting; 9879 final int uid = Binder.getCallingUid(); 9880 enforceCrossUserPermission(uid, userId, true, true, 9881 "setApplicationHiddenSetting for user " + userId); 9882 9883 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9884 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9885 return false; 9886 } 9887 9888 long callingId = Binder.clearCallingIdentity(); 9889 try { 9890 boolean sendAdded = false; 9891 boolean sendRemoved = false; 9892 // writer 9893 synchronized (mPackages) { 9894 pkgSetting = mSettings.mPackages.get(packageName); 9895 if (pkgSetting == null) { 9896 return false; 9897 } 9898 if (pkgSetting.getHidden(userId) != hidden) { 9899 pkgSetting.setHidden(hidden, userId); 9900 mSettings.writePackageRestrictionsLPr(userId); 9901 if (hidden) { 9902 sendRemoved = true; 9903 } else { 9904 sendAdded = true; 9905 } 9906 } 9907 } 9908 if (sendAdded) { 9909 sendPackageAddedForUser(packageName, pkgSetting, userId); 9910 return true; 9911 } 9912 if (sendRemoved) { 9913 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9914 "hiding pkg"); 9915 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9916 return true; 9917 } 9918 } finally { 9919 Binder.restoreCallingIdentity(callingId); 9920 } 9921 return false; 9922 } 9923 9924 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9925 int userId) { 9926 final PackageRemovedInfo info = new PackageRemovedInfo(); 9927 info.removedPackage = packageName; 9928 info.removedUsers = new int[] {userId}; 9929 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9930 info.sendBroadcast(false, false, false); 9931 } 9932 9933 /** 9934 * Returns true if application is not found or there was an error. Otherwise it returns 9935 * the hidden state of the package for the given user. 9936 */ 9937 @Override 9938 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9939 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9940 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9941 false, "getApplicationHidden for user " + userId); 9942 PackageSetting pkgSetting; 9943 long callingId = Binder.clearCallingIdentity(); 9944 try { 9945 // writer 9946 synchronized (mPackages) { 9947 pkgSetting = mSettings.mPackages.get(packageName); 9948 if (pkgSetting == null) { 9949 return true; 9950 } 9951 return pkgSetting.getHidden(userId); 9952 } 9953 } finally { 9954 Binder.restoreCallingIdentity(callingId); 9955 } 9956 } 9957 9958 /** 9959 * @hide 9960 */ 9961 @Override 9962 public int installExistingPackageAsUser(String packageName, int userId) { 9963 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9964 null); 9965 PackageSetting pkgSetting; 9966 final int uid = Binder.getCallingUid(); 9967 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9968 + userId); 9969 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9970 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9971 } 9972 9973 long callingId = Binder.clearCallingIdentity(); 9974 try { 9975 boolean sendAdded = false; 9976 9977 // writer 9978 synchronized (mPackages) { 9979 pkgSetting = mSettings.mPackages.get(packageName); 9980 if (pkgSetting == null) { 9981 return PackageManager.INSTALL_FAILED_INVALID_URI; 9982 } 9983 if (!pkgSetting.getInstalled(userId)) { 9984 pkgSetting.setInstalled(true, userId); 9985 pkgSetting.setHidden(false, userId); 9986 mSettings.writePackageRestrictionsLPr(userId); 9987 sendAdded = true; 9988 } 9989 } 9990 9991 if (sendAdded) { 9992 sendPackageAddedForUser(packageName, pkgSetting, userId); 9993 } 9994 } finally { 9995 Binder.restoreCallingIdentity(callingId); 9996 } 9997 9998 return PackageManager.INSTALL_SUCCEEDED; 9999 } 10000 10001 boolean isUserRestricted(int userId, String restrictionKey) { 10002 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10003 if (restrictions.getBoolean(restrictionKey, false)) { 10004 Log.w(TAG, "User is restricted: " + restrictionKey); 10005 return true; 10006 } 10007 return false; 10008 } 10009 10010 @Override 10011 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10012 mContext.enforceCallingOrSelfPermission( 10013 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10014 "Only package verification agents can verify applications"); 10015 10016 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10017 final PackageVerificationResponse response = new PackageVerificationResponse( 10018 verificationCode, Binder.getCallingUid()); 10019 msg.arg1 = id; 10020 msg.obj = response; 10021 mHandler.sendMessage(msg); 10022 } 10023 10024 @Override 10025 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10026 long millisecondsToDelay) { 10027 mContext.enforceCallingOrSelfPermission( 10028 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10029 "Only package verification agents can extend verification timeouts"); 10030 10031 final PackageVerificationState state = mPendingVerification.get(id); 10032 final PackageVerificationResponse response = new PackageVerificationResponse( 10033 verificationCodeAtTimeout, Binder.getCallingUid()); 10034 10035 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10036 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10037 } 10038 if (millisecondsToDelay < 0) { 10039 millisecondsToDelay = 0; 10040 } 10041 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10042 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10043 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10044 } 10045 10046 if ((state != null) && !state.timeoutExtended()) { 10047 state.extendTimeout(); 10048 10049 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10050 msg.arg1 = id; 10051 msg.obj = response; 10052 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10053 } 10054 } 10055 10056 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10057 int verificationCode, UserHandle user) { 10058 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10059 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10060 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10061 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10062 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10063 10064 mContext.sendBroadcastAsUser(intent, user, 10065 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10066 } 10067 10068 private ComponentName matchComponentForVerifier(String packageName, 10069 List<ResolveInfo> receivers) { 10070 ActivityInfo targetReceiver = null; 10071 10072 final int NR = receivers.size(); 10073 for (int i = 0; i < NR; i++) { 10074 final ResolveInfo info = receivers.get(i); 10075 if (info.activityInfo == null) { 10076 continue; 10077 } 10078 10079 if (packageName.equals(info.activityInfo.packageName)) { 10080 targetReceiver = info.activityInfo; 10081 break; 10082 } 10083 } 10084 10085 if (targetReceiver == null) { 10086 return null; 10087 } 10088 10089 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10090 } 10091 10092 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10093 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10094 if (pkgInfo.verifiers.length == 0) { 10095 return null; 10096 } 10097 10098 final int N = pkgInfo.verifiers.length; 10099 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10100 for (int i = 0; i < N; i++) { 10101 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10102 10103 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10104 receivers); 10105 if (comp == null) { 10106 continue; 10107 } 10108 10109 final int verifierUid = getUidForVerifier(verifierInfo); 10110 if (verifierUid == -1) { 10111 continue; 10112 } 10113 10114 if (DEBUG_VERIFY) { 10115 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10116 + " with the correct signature"); 10117 } 10118 sufficientVerifiers.add(comp); 10119 verificationState.addSufficientVerifier(verifierUid); 10120 } 10121 10122 return sufficientVerifiers; 10123 } 10124 10125 private int getUidForVerifier(VerifierInfo verifierInfo) { 10126 synchronized (mPackages) { 10127 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10128 if (pkg == null) { 10129 return -1; 10130 } else if (pkg.mSignatures.length != 1) { 10131 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10132 + " has more than one signature; ignoring"); 10133 return -1; 10134 } 10135 10136 /* 10137 * If the public key of the package's signature does not match 10138 * our expected public key, then this is a different package and 10139 * we should skip. 10140 */ 10141 10142 final byte[] expectedPublicKey; 10143 try { 10144 final Signature verifierSig = pkg.mSignatures[0]; 10145 final PublicKey publicKey = verifierSig.getPublicKey(); 10146 expectedPublicKey = publicKey.getEncoded(); 10147 } catch (CertificateException e) { 10148 return -1; 10149 } 10150 10151 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10152 10153 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10154 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10155 + " does not have the expected public key; ignoring"); 10156 return -1; 10157 } 10158 10159 return pkg.applicationInfo.uid; 10160 } 10161 } 10162 10163 @Override 10164 public void finishPackageInstall(int token) { 10165 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10166 10167 if (DEBUG_INSTALL) { 10168 Slog.v(TAG, "BM finishing package install for " + token); 10169 } 10170 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10171 10172 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10173 mHandler.sendMessage(msg); 10174 } 10175 10176 /** 10177 * Get the verification agent timeout. 10178 * 10179 * @return verification timeout in milliseconds 10180 */ 10181 private long getVerificationTimeout() { 10182 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10183 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10184 DEFAULT_VERIFICATION_TIMEOUT); 10185 } 10186 10187 /** 10188 * Get the default verification agent response code. 10189 * 10190 * @return default verification response code 10191 */ 10192 private int getDefaultVerificationResponse() { 10193 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10194 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10195 DEFAULT_VERIFICATION_RESPONSE); 10196 } 10197 10198 /** 10199 * Check whether or not package verification has been enabled. 10200 * 10201 * @return true if verification should be performed 10202 */ 10203 private boolean isVerificationEnabled(int userId, int installFlags) { 10204 if (!DEFAULT_VERIFY_ENABLE) { 10205 return false; 10206 } 10207 // TODO: fix b/25118622; don't bypass verification 10208 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10209 return false; 10210 } 10211 10212 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10213 10214 // Check if installing from ADB 10215 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10216 // Do not run verification in a test harness environment 10217 if (ActivityManager.isRunningInTestHarness()) { 10218 return false; 10219 } 10220 if (ensureVerifyAppsEnabled) { 10221 return true; 10222 } 10223 // Check if the developer does not want package verification for ADB installs 10224 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10225 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10226 return false; 10227 } 10228 } 10229 10230 if (ensureVerifyAppsEnabled) { 10231 return true; 10232 } 10233 10234 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10235 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10236 } 10237 10238 @Override 10239 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10240 throws RemoteException { 10241 mContext.enforceCallingOrSelfPermission( 10242 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10243 "Only intentfilter verification agents can verify applications"); 10244 10245 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10246 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10247 Binder.getCallingUid(), verificationCode, failedDomains); 10248 msg.arg1 = id; 10249 msg.obj = response; 10250 mHandler.sendMessage(msg); 10251 } 10252 10253 @Override 10254 public int getIntentVerificationStatus(String packageName, int userId) { 10255 synchronized (mPackages) { 10256 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10257 } 10258 } 10259 10260 @Override 10261 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10262 mContext.enforceCallingOrSelfPermission( 10263 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10264 10265 boolean result = false; 10266 synchronized (mPackages) { 10267 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10268 } 10269 if (result) { 10270 scheduleWritePackageRestrictionsLocked(userId); 10271 } 10272 return result; 10273 } 10274 10275 @Override 10276 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10277 synchronized (mPackages) { 10278 return mSettings.getIntentFilterVerificationsLPr(packageName); 10279 } 10280 } 10281 10282 @Override 10283 public List<IntentFilter> getAllIntentFilters(String packageName) { 10284 if (TextUtils.isEmpty(packageName)) { 10285 return Collections.<IntentFilter>emptyList(); 10286 } 10287 synchronized (mPackages) { 10288 PackageParser.Package pkg = mPackages.get(packageName); 10289 if (pkg == null || pkg.activities == null) { 10290 return Collections.<IntentFilter>emptyList(); 10291 } 10292 final int count = pkg.activities.size(); 10293 ArrayList<IntentFilter> result = new ArrayList<>(); 10294 for (int n=0; n<count; n++) { 10295 PackageParser.Activity activity = pkg.activities.get(n); 10296 if (activity.intents != null || activity.intents.size() > 0) { 10297 result.addAll(activity.intents); 10298 } 10299 } 10300 return result; 10301 } 10302 } 10303 10304 @Override 10305 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10306 mContext.enforceCallingOrSelfPermission( 10307 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10308 10309 synchronized (mPackages) { 10310 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10311 if (packageName != null) { 10312 result |= updateIntentVerificationStatus(packageName, 10313 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10314 userId); 10315 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10316 packageName, userId); 10317 } 10318 return result; 10319 } 10320 } 10321 10322 @Override 10323 public String getDefaultBrowserPackageName(int userId) { 10324 synchronized (mPackages) { 10325 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10326 } 10327 } 10328 10329 /** 10330 * Get the "allow unknown sources" setting. 10331 * 10332 * @return the current "allow unknown sources" setting 10333 */ 10334 private int getUnknownSourcesSettings() { 10335 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10336 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10337 -1); 10338 } 10339 10340 @Override 10341 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10342 final int uid = Binder.getCallingUid(); 10343 // writer 10344 synchronized (mPackages) { 10345 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10346 if (targetPackageSetting == null) { 10347 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10348 } 10349 10350 PackageSetting installerPackageSetting; 10351 if (installerPackageName != null) { 10352 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10353 if (installerPackageSetting == null) { 10354 throw new IllegalArgumentException("Unknown installer package: " 10355 + installerPackageName); 10356 } 10357 } else { 10358 installerPackageSetting = null; 10359 } 10360 10361 Signature[] callerSignature; 10362 Object obj = mSettings.getUserIdLPr(uid); 10363 if (obj != null) { 10364 if (obj instanceof SharedUserSetting) { 10365 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10366 } else if (obj instanceof PackageSetting) { 10367 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10368 } else { 10369 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10370 } 10371 } else { 10372 throw new SecurityException("Unknown calling uid " + uid); 10373 } 10374 10375 // Verify: can't set installerPackageName to a package that is 10376 // not signed with the same cert as the caller. 10377 if (installerPackageSetting != null) { 10378 if (compareSignatures(callerSignature, 10379 installerPackageSetting.signatures.mSignatures) 10380 != PackageManager.SIGNATURE_MATCH) { 10381 throw new SecurityException( 10382 "Caller does not have same cert as new installer package " 10383 + installerPackageName); 10384 } 10385 } 10386 10387 // Verify: if target already has an installer package, it must 10388 // be signed with the same cert as the caller. 10389 if (targetPackageSetting.installerPackageName != null) { 10390 PackageSetting setting = mSettings.mPackages.get( 10391 targetPackageSetting.installerPackageName); 10392 // If the currently set package isn't valid, then it's always 10393 // okay to change it. 10394 if (setting != null) { 10395 if (compareSignatures(callerSignature, 10396 setting.signatures.mSignatures) 10397 != PackageManager.SIGNATURE_MATCH) { 10398 throw new SecurityException( 10399 "Caller does not have same cert as old installer package " 10400 + targetPackageSetting.installerPackageName); 10401 } 10402 } 10403 } 10404 10405 // Okay! 10406 targetPackageSetting.installerPackageName = installerPackageName; 10407 scheduleWriteSettingsLocked(); 10408 } 10409 } 10410 10411 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10412 // Queue up an async operation since the package installation may take a little while. 10413 mHandler.post(new Runnable() { 10414 public void run() { 10415 mHandler.removeCallbacks(this); 10416 // Result object to be returned 10417 PackageInstalledInfo res = new PackageInstalledInfo(); 10418 res.returnCode = currentStatus; 10419 res.uid = -1; 10420 res.pkg = null; 10421 res.removedInfo = new PackageRemovedInfo(); 10422 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10423 args.doPreInstall(res.returnCode); 10424 synchronized (mInstallLock) { 10425 installPackageTracedLI(args, res); 10426 } 10427 args.doPostInstall(res.returnCode, res.uid); 10428 } 10429 10430 // A restore should be performed at this point if (a) the install 10431 // succeeded, (b) the operation is not an update, and (c) the new 10432 // package has not opted out of backup participation. 10433 final boolean update = res.removedInfo.removedPackage != null; 10434 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10435 boolean doRestore = !update 10436 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10437 10438 // Set up the post-install work request bookkeeping. This will be used 10439 // and cleaned up by the post-install event handling regardless of whether 10440 // there's a restore pass performed. Token values are >= 1. 10441 int token; 10442 if (mNextInstallToken < 0) mNextInstallToken = 1; 10443 token = mNextInstallToken++; 10444 10445 PostInstallData data = new PostInstallData(args, res); 10446 mRunningInstalls.put(token, data); 10447 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10448 10449 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10450 // Pass responsibility to the Backup Manager. It will perform a 10451 // restore if appropriate, then pass responsibility back to the 10452 // Package Manager to run the post-install observer callbacks 10453 // and broadcasts. 10454 IBackupManager bm = IBackupManager.Stub.asInterface( 10455 ServiceManager.getService(Context.BACKUP_SERVICE)); 10456 if (bm != null) { 10457 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10458 + " to BM for possible restore"); 10459 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10460 try { 10461 // TODO: http://b/22388012 10462 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10463 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10464 } else { 10465 doRestore = false; 10466 } 10467 } catch (RemoteException e) { 10468 // can't happen; the backup manager is local 10469 } catch (Exception e) { 10470 Slog.e(TAG, "Exception trying to enqueue restore", e); 10471 doRestore = false; 10472 } 10473 } else { 10474 Slog.e(TAG, "Backup Manager not found!"); 10475 doRestore = false; 10476 } 10477 } 10478 10479 if (!doRestore) { 10480 // No restore possible, or the Backup Manager was mysteriously not 10481 // available -- just fire the post-install work request directly. 10482 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10483 10484 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10485 10486 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10487 mHandler.sendMessage(msg); 10488 } 10489 } 10490 }); 10491 } 10492 10493 private abstract class HandlerParams { 10494 private static final int MAX_RETRIES = 4; 10495 10496 /** 10497 * Number of times startCopy() has been attempted and had a non-fatal 10498 * error. 10499 */ 10500 private int mRetries = 0; 10501 10502 /** User handle for the user requesting the information or installation. */ 10503 private final UserHandle mUser; 10504 String traceMethod; 10505 int traceCookie; 10506 10507 HandlerParams(UserHandle user) { 10508 mUser = user; 10509 } 10510 10511 UserHandle getUser() { 10512 return mUser; 10513 } 10514 10515 HandlerParams setTraceMethod(String traceMethod) { 10516 this.traceMethod = traceMethod; 10517 return this; 10518 } 10519 10520 HandlerParams setTraceCookie(int traceCookie) { 10521 this.traceCookie = traceCookie; 10522 return this; 10523 } 10524 10525 final boolean startCopy() { 10526 boolean res; 10527 try { 10528 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10529 10530 if (++mRetries > MAX_RETRIES) { 10531 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10532 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10533 handleServiceError(); 10534 return false; 10535 } else { 10536 handleStartCopy(); 10537 res = true; 10538 } 10539 } catch (RemoteException e) { 10540 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10541 mHandler.sendEmptyMessage(MCS_RECONNECT); 10542 res = false; 10543 } 10544 handleReturnCode(); 10545 return res; 10546 } 10547 10548 final void serviceError() { 10549 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10550 handleServiceError(); 10551 handleReturnCode(); 10552 } 10553 10554 abstract void handleStartCopy() throws RemoteException; 10555 abstract void handleServiceError(); 10556 abstract void handleReturnCode(); 10557 } 10558 10559 class MeasureParams extends HandlerParams { 10560 private final PackageStats mStats; 10561 private boolean mSuccess; 10562 10563 private final IPackageStatsObserver mObserver; 10564 10565 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10566 super(new UserHandle(stats.userHandle)); 10567 mObserver = observer; 10568 mStats = stats; 10569 } 10570 10571 @Override 10572 public String toString() { 10573 return "MeasureParams{" 10574 + Integer.toHexString(System.identityHashCode(this)) 10575 + " " + mStats.packageName + "}"; 10576 } 10577 10578 @Override 10579 void handleStartCopy() throws RemoteException { 10580 synchronized (mInstallLock) { 10581 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10582 } 10583 10584 if (mSuccess) { 10585 final boolean mounted; 10586 if (Environment.isExternalStorageEmulated()) { 10587 mounted = true; 10588 } else { 10589 final String status = Environment.getExternalStorageState(); 10590 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10591 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10592 } 10593 10594 if (mounted) { 10595 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10596 10597 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10598 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10599 10600 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10601 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10602 10603 // Always subtract cache size, since it's a subdirectory 10604 mStats.externalDataSize -= mStats.externalCacheSize; 10605 10606 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10607 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10608 10609 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10610 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10611 } 10612 } 10613 } 10614 10615 @Override 10616 void handleReturnCode() { 10617 if (mObserver != null) { 10618 try { 10619 mObserver.onGetStatsCompleted(mStats, mSuccess); 10620 } catch (RemoteException e) { 10621 Slog.i(TAG, "Observer no longer exists."); 10622 } 10623 } 10624 } 10625 10626 @Override 10627 void handleServiceError() { 10628 Slog.e(TAG, "Could not measure application " + mStats.packageName 10629 + " external storage"); 10630 } 10631 } 10632 10633 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10634 throws RemoteException { 10635 long result = 0; 10636 for (File path : paths) { 10637 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10638 } 10639 return result; 10640 } 10641 10642 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10643 for (File path : paths) { 10644 try { 10645 mcs.clearDirectory(path.getAbsolutePath()); 10646 } catch (RemoteException e) { 10647 } 10648 } 10649 } 10650 10651 static class OriginInfo { 10652 /** 10653 * Location where install is coming from, before it has been 10654 * copied/renamed into place. This could be a single monolithic APK 10655 * file, or a cluster directory. This location may be untrusted. 10656 */ 10657 final File file; 10658 final String cid; 10659 10660 /** 10661 * Flag indicating that {@link #file} or {@link #cid} has already been 10662 * staged, meaning downstream users don't need to defensively copy the 10663 * contents. 10664 */ 10665 final boolean staged; 10666 10667 /** 10668 * Flag indicating that {@link #file} or {@link #cid} is an already 10669 * installed app that is being moved. 10670 */ 10671 final boolean existing; 10672 10673 final String resolvedPath; 10674 final File resolvedFile; 10675 10676 static OriginInfo fromNothing() { 10677 return new OriginInfo(null, null, false, false); 10678 } 10679 10680 static OriginInfo fromUntrustedFile(File file) { 10681 return new OriginInfo(file, null, false, false); 10682 } 10683 10684 static OriginInfo fromExistingFile(File file) { 10685 return new OriginInfo(file, null, false, true); 10686 } 10687 10688 static OriginInfo fromStagedFile(File file) { 10689 return new OriginInfo(file, null, true, false); 10690 } 10691 10692 static OriginInfo fromStagedContainer(String cid) { 10693 return new OriginInfo(null, cid, true, false); 10694 } 10695 10696 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10697 this.file = file; 10698 this.cid = cid; 10699 this.staged = staged; 10700 this.existing = existing; 10701 10702 if (cid != null) { 10703 resolvedPath = PackageHelper.getSdDir(cid); 10704 resolvedFile = new File(resolvedPath); 10705 } else if (file != null) { 10706 resolvedPath = file.getAbsolutePath(); 10707 resolvedFile = file; 10708 } else { 10709 resolvedPath = null; 10710 resolvedFile = null; 10711 } 10712 } 10713 } 10714 10715 class MoveInfo { 10716 final int moveId; 10717 final String fromUuid; 10718 final String toUuid; 10719 final String packageName; 10720 final String dataAppName; 10721 final int appId; 10722 final String seinfo; 10723 10724 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10725 String dataAppName, int appId, String seinfo) { 10726 this.moveId = moveId; 10727 this.fromUuid = fromUuid; 10728 this.toUuid = toUuid; 10729 this.packageName = packageName; 10730 this.dataAppName = dataAppName; 10731 this.appId = appId; 10732 this.seinfo = seinfo; 10733 } 10734 } 10735 10736 class InstallParams extends HandlerParams { 10737 final OriginInfo origin; 10738 final MoveInfo move; 10739 final IPackageInstallObserver2 observer; 10740 int installFlags; 10741 final String installerPackageName; 10742 final String volumeUuid; 10743 final VerificationParams verificationParams; 10744 private InstallArgs mArgs; 10745 private int mRet; 10746 final String packageAbiOverride; 10747 final String[] grantedRuntimePermissions; 10748 10749 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10750 int installFlags, String installerPackageName, String volumeUuid, 10751 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10752 String[] grantedPermissions) { 10753 super(user); 10754 this.origin = origin; 10755 this.move = move; 10756 this.observer = observer; 10757 this.installFlags = installFlags; 10758 this.installerPackageName = installerPackageName; 10759 this.volumeUuid = volumeUuid; 10760 this.verificationParams = verificationParams; 10761 this.packageAbiOverride = packageAbiOverride; 10762 this.grantedRuntimePermissions = grantedPermissions; 10763 } 10764 10765 @Override 10766 public String toString() { 10767 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10768 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10769 } 10770 10771 public ManifestDigest getManifestDigest() { 10772 if (verificationParams == null) { 10773 return null; 10774 } 10775 return verificationParams.getManifestDigest(); 10776 } 10777 10778 private int installLocationPolicy(PackageInfoLite pkgLite) { 10779 String packageName = pkgLite.packageName; 10780 int installLocation = pkgLite.installLocation; 10781 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10782 // reader 10783 synchronized (mPackages) { 10784 PackageParser.Package pkg = mPackages.get(packageName); 10785 if (pkg != null) { 10786 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10787 // Check for downgrading. 10788 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10789 try { 10790 checkDowngrade(pkg, pkgLite); 10791 } catch (PackageManagerException e) { 10792 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10793 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10794 } 10795 } 10796 // Check for updated system application. 10797 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10798 if (onSd) { 10799 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10800 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10801 } 10802 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10803 } else { 10804 if (onSd) { 10805 // Install flag overrides everything. 10806 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10807 } 10808 // If current upgrade specifies particular preference 10809 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10810 // Application explicitly specified internal. 10811 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10812 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10813 // App explictly prefers external. Let policy decide 10814 } else { 10815 // Prefer previous location 10816 if (isExternal(pkg)) { 10817 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10818 } 10819 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10820 } 10821 } 10822 } else { 10823 // Invalid install. Return error code 10824 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10825 } 10826 } 10827 } 10828 // All the special cases have been taken care of. 10829 // Return result based on recommended install location. 10830 if (onSd) { 10831 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10832 } 10833 return pkgLite.recommendedInstallLocation; 10834 } 10835 10836 /* 10837 * Invoke remote method to get package information and install 10838 * location values. Override install location based on default 10839 * policy if needed and then create install arguments based 10840 * on the install location. 10841 */ 10842 public void handleStartCopy() throws RemoteException { 10843 int ret = PackageManager.INSTALL_SUCCEEDED; 10844 10845 // If we're already staged, we've firmly committed to an install location 10846 if (origin.staged) { 10847 if (origin.file != null) { 10848 installFlags |= PackageManager.INSTALL_INTERNAL; 10849 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10850 } else if (origin.cid != null) { 10851 installFlags |= PackageManager.INSTALL_EXTERNAL; 10852 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10853 } else { 10854 throw new IllegalStateException("Invalid stage location"); 10855 } 10856 } 10857 10858 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10859 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10860 PackageInfoLite pkgLite = null; 10861 10862 if (onInt && onSd) { 10863 // Check if both bits are set. 10864 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10865 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10866 } else { 10867 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10868 packageAbiOverride); 10869 10870 /* 10871 * If we have too little free space, try to free cache 10872 * before giving up. 10873 */ 10874 if (!origin.staged && pkgLite.recommendedInstallLocation 10875 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10876 // TODO: focus freeing disk space on the target device 10877 final StorageManager storage = StorageManager.from(mContext); 10878 final long lowThreshold = storage.getStorageLowBytes( 10879 Environment.getDataDirectory()); 10880 10881 final long sizeBytes = mContainerService.calculateInstalledSize( 10882 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10883 10884 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10885 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10886 installFlags, packageAbiOverride); 10887 } 10888 10889 /* 10890 * The cache free must have deleted the file we 10891 * downloaded to install. 10892 * 10893 * TODO: fix the "freeCache" call to not delete 10894 * the file we care about. 10895 */ 10896 if (pkgLite.recommendedInstallLocation 10897 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10898 pkgLite.recommendedInstallLocation 10899 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10900 } 10901 } 10902 } 10903 10904 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10905 int loc = pkgLite.recommendedInstallLocation; 10906 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10907 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10908 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10909 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10910 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10911 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10912 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10913 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10914 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10915 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10916 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10917 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10918 } else { 10919 // Override with defaults if needed. 10920 loc = installLocationPolicy(pkgLite); 10921 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10922 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10923 } else if (!onSd && !onInt) { 10924 // Override install location with flags 10925 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10926 // Set the flag to install on external media. 10927 installFlags |= PackageManager.INSTALL_EXTERNAL; 10928 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10929 } else { 10930 // Make sure the flag for installing on external 10931 // media is unset 10932 installFlags |= PackageManager.INSTALL_INTERNAL; 10933 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10934 } 10935 } 10936 } 10937 } 10938 10939 final InstallArgs args = createInstallArgs(this); 10940 mArgs = args; 10941 10942 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10943 // TODO: http://b/22976637 10944 // Apps installed for "all" users use the device owner to verify the app 10945 UserHandle verifierUser = getUser(); 10946 if (verifierUser == UserHandle.ALL) { 10947 verifierUser = UserHandle.SYSTEM; 10948 } 10949 10950 /* 10951 * Determine if we have any installed package verifiers. If we 10952 * do, then we'll defer to them to verify the packages. 10953 */ 10954 final int requiredUid = mRequiredVerifierPackage == null ? -1 10955 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10956 if (!origin.existing && requiredUid != -1 10957 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10958 final Intent verification = new Intent( 10959 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10960 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10961 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10962 PACKAGE_MIME_TYPE); 10963 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10964 10965 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10966 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10967 verifierUser.getIdentifier()); 10968 10969 if (DEBUG_VERIFY) { 10970 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10971 + verification.toString() + " with " + pkgLite.verifiers.length 10972 + " optional verifiers"); 10973 } 10974 10975 final int verificationId = mPendingVerificationToken++; 10976 10977 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10978 10979 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10980 installerPackageName); 10981 10982 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10983 installFlags); 10984 10985 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10986 pkgLite.packageName); 10987 10988 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10989 pkgLite.versionCode); 10990 10991 if (verificationParams != null) { 10992 if (verificationParams.getVerificationURI() != null) { 10993 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10994 verificationParams.getVerificationURI()); 10995 } 10996 if (verificationParams.getOriginatingURI() != null) { 10997 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10998 verificationParams.getOriginatingURI()); 10999 } 11000 if (verificationParams.getReferrer() != null) { 11001 verification.putExtra(Intent.EXTRA_REFERRER, 11002 verificationParams.getReferrer()); 11003 } 11004 if (verificationParams.getOriginatingUid() >= 0) { 11005 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11006 verificationParams.getOriginatingUid()); 11007 } 11008 if (verificationParams.getInstallerUid() >= 0) { 11009 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11010 verificationParams.getInstallerUid()); 11011 } 11012 } 11013 11014 final PackageVerificationState verificationState = new PackageVerificationState( 11015 requiredUid, args); 11016 11017 mPendingVerification.append(verificationId, verificationState); 11018 11019 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11020 receivers, verificationState); 11021 11022 /* 11023 * If any sufficient verifiers were listed in the package 11024 * manifest, attempt to ask them. 11025 */ 11026 if (sufficientVerifiers != null) { 11027 final int N = sufficientVerifiers.size(); 11028 if (N == 0) { 11029 Slog.i(TAG, "Additional verifiers required, but none installed."); 11030 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11031 } else { 11032 for (int i = 0; i < N; i++) { 11033 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11034 11035 final Intent sufficientIntent = new Intent(verification); 11036 sufficientIntent.setComponent(verifierComponent); 11037 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11038 } 11039 } 11040 } 11041 11042 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11043 mRequiredVerifierPackage, receivers); 11044 if (ret == PackageManager.INSTALL_SUCCEEDED 11045 && mRequiredVerifierPackage != null) { 11046 Trace.asyncTraceBegin( 11047 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11048 /* 11049 * Send the intent to the required verification agent, 11050 * but only start the verification timeout after the 11051 * target BroadcastReceivers have run. 11052 */ 11053 verification.setComponent(requiredVerifierComponent); 11054 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11055 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11056 new BroadcastReceiver() { 11057 @Override 11058 public void onReceive(Context context, Intent intent) { 11059 final Message msg = mHandler 11060 .obtainMessage(CHECK_PENDING_VERIFICATION); 11061 msg.arg1 = verificationId; 11062 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11063 } 11064 }, null, 0, null, null); 11065 11066 /* 11067 * We don't want the copy to proceed until verification 11068 * succeeds, so null out this field. 11069 */ 11070 mArgs = null; 11071 } 11072 } else { 11073 /* 11074 * No package verification is enabled, so immediately start 11075 * the remote call to initiate copy using temporary file. 11076 */ 11077 ret = args.copyApk(mContainerService, true); 11078 } 11079 } 11080 11081 mRet = ret; 11082 } 11083 11084 @Override 11085 void handleReturnCode() { 11086 // If mArgs is null, then MCS couldn't be reached. When it 11087 // reconnects, it will try again to install. At that point, this 11088 // will succeed. 11089 if (mArgs != null) { 11090 processPendingInstall(mArgs, mRet); 11091 } 11092 } 11093 11094 @Override 11095 void handleServiceError() { 11096 mArgs = createInstallArgs(this); 11097 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11098 } 11099 11100 public boolean isForwardLocked() { 11101 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11102 } 11103 } 11104 11105 /** 11106 * Used during creation of InstallArgs 11107 * 11108 * @param installFlags package installation flags 11109 * @return true if should be installed on external storage 11110 */ 11111 private static boolean installOnExternalAsec(int installFlags) { 11112 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11113 return false; 11114 } 11115 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11116 return true; 11117 } 11118 return false; 11119 } 11120 11121 /** 11122 * Used during creation of InstallArgs 11123 * 11124 * @param installFlags package installation flags 11125 * @return true if should be installed as forward locked 11126 */ 11127 private static boolean installForwardLocked(int installFlags) { 11128 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11129 } 11130 11131 private InstallArgs createInstallArgs(InstallParams params) { 11132 if (params.move != null) { 11133 return new MoveInstallArgs(params); 11134 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11135 return new AsecInstallArgs(params); 11136 } else { 11137 return new FileInstallArgs(params); 11138 } 11139 } 11140 11141 /** 11142 * Create args that describe an existing installed package. Typically used 11143 * when cleaning up old installs, or used as a move source. 11144 */ 11145 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11146 String resourcePath, String[] instructionSets) { 11147 final boolean isInAsec; 11148 if (installOnExternalAsec(installFlags)) { 11149 /* Apps on SD card are always in ASEC containers. */ 11150 isInAsec = true; 11151 } else if (installForwardLocked(installFlags) 11152 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11153 /* 11154 * Forward-locked apps are only in ASEC containers if they're the 11155 * new style 11156 */ 11157 isInAsec = true; 11158 } else { 11159 isInAsec = false; 11160 } 11161 11162 if (isInAsec) { 11163 return new AsecInstallArgs(codePath, instructionSets, 11164 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11165 } else { 11166 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11167 } 11168 } 11169 11170 static abstract class InstallArgs { 11171 /** @see InstallParams#origin */ 11172 final OriginInfo origin; 11173 /** @see InstallParams#move */ 11174 final MoveInfo move; 11175 11176 final IPackageInstallObserver2 observer; 11177 // Always refers to PackageManager flags only 11178 final int installFlags; 11179 final String installerPackageName; 11180 final String volumeUuid; 11181 final ManifestDigest manifestDigest; 11182 final UserHandle user; 11183 final String abiOverride; 11184 final String[] installGrantPermissions; 11185 /** If non-null, drop an async trace when the install completes */ 11186 final String traceMethod; 11187 final int traceCookie; 11188 11189 // The list of instruction sets supported by this app. This is currently 11190 // only used during the rmdex() phase to clean up resources. We can get rid of this 11191 // if we move dex files under the common app path. 11192 /* nullable */ String[] instructionSets; 11193 11194 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11195 int installFlags, String installerPackageName, String volumeUuid, 11196 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11197 String abiOverride, String[] installGrantPermissions, 11198 String traceMethod, int traceCookie) { 11199 this.origin = origin; 11200 this.move = move; 11201 this.installFlags = installFlags; 11202 this.observer = observer; 11203 this.installerPackageName = installerPackageName; 11204 this.volumeUuid = volumeUuid; 11205 this.manifestDigest = manifestDigest; 11206 this.user = user; 11207 this.instructionSets = instructionSets; 11208 this.abiOverride = abiOverride; 11209 this.installGrantPermissions = installGrantPermissions; 11210 this.traceMethod = traceMethod; 11211 this.traceCookie = traceCookie; 11212 } 11213 11214 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11215 abstract int doPreInstall(int status); 11216 11217 /** 11218 * Rename package into final resting place. All paths on the given 11219 * scanned package should be updated to reflect the rename. 11220 */ 11221 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11222 abstract int doPostInstall(int status, int uid); 11223 11224 /** @see PackageSettingBase#codePathString */ 11225 abstract String getCodePath(); 11226 /** @see PackageSettingBase#resourcePathString */ 11227 abstract String getResourcePath(); 11228 11229 // Need installer lock especially for dex file removal. 11230 abstract void cleanUpResourcesLI(); 11231 abstract boolean doPostDeleteLI(boolean delete); 11232 11233 /** 11234 * Called before the source arguments are copied. This is used mostly 11235 * for MoveParams when it needs to read the source file to put it in the 11236 * destination. 11237 */ 11238 int doPreCopy() { 11239 return PackageManager.INSTALL_SUCCEEDED; 11240 } 11241 11242 /** 11243 * Called after the source arguments are copied. This is used mostly for 11244 * MoveParams when it needs to read the source file to put it in the 11245 * destination. 11246 * 11247 * @return 11248 */ 11249 int doPostCopy(int uid) { 11250 return PackageManager.INSTALL_SUCCEEDED; 11251 } 11252 11253 protected boolean isFwdLocked() { 11254 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11255 } 11256 11257 protected boolean isExternalAsec() { 11258 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11259 } 11260 11261 UserHandle getUser() { 11262 return user; 11263 } 11264 } 11265 11266 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11267 if (!allCodePaths.isEmpty()) { 11268 if (instructionSets == null) { 11269 throw new IllegalStateException("instructionSet == null"); 11270 } 11271 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11272 for (String codePath : allCodePaths) { 11273 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11274 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11275 if (retCode < 0) { 11276 Slog.w(TAG, "Couldn't remove dex file for package: " 11277 + " at location " + codePath + ", retcode=" + retCode); 11278 // we don't consider this to be a failure of the core package deletion 11279 } 11280 } 11281 } 11282 } 11283 } 11284 11285 /** 11286 * Logic to handle installation of non-ASEC applications, including copying 11287 * and renaming logic. 11288 */ 11289 class FileInstallArgs extends InstallArgs { 11290 private File codeFile; 11291 private File resourceFile; 11292 11293 // Example topology: 11294 // /data/app/com.example/base.apk 11295 // /data/app/com.example/split_foo.apk 11296 // /data/app/com.example/lib/arm/libfoo.so 11297 // /data/app/com.example/lib/arm64/libfoo.so 11298 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11299 11300 /** New install */ 11301 FileInstallArgs(InstallParams params) { 11302 super(params.origin, params.move, params.observer, params.installFlags, 11303 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11304 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11305 params.grantedRuntimePermissions, 11306 params.traceMethod, params.traceCookie); 11307 if (isFwdLocked()) { 11308 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11309 } 11310 } 11311 11312 /** Existing install */ 11313 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11314 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11315 null, null, null, 0); 11316 this.codeFile = (codePath != null) ? new File(codePath) : null; 11317 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11318 } 11319 11320 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11321 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11322 try { 11323 return doCopyApk(imcs, temp); 11324 } finally { 11325 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11326 } 11327 } 11328 11329 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11330 if (origin.staged) { 11331 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11332 codeFile = origin.file; 11333 resourceFile = origin.file; 11334 return PackageManager.INSTALL_SUCCEEDED; 11335 } 11336 11337 try { 11338 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11339 codeFile = tempDir; 11340 resourceFile = tempDir; 11341 } catch (IOException e) { 11342 Slog.w(TAG, "Failed to create copy file: " + e); 11343 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11344 } 11345 11346 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11347 @Override 11348 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11349 if (!FileUtils.isValidExtFilename(name)) { 11350 throw new IllegalArgumentException("Invalid filename: " + name); 11351 } 11352 try { 11353 final File file = new File(codeFile, name); 11354 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11355 O_RDWR | O_CREAT, 0644); 11356 Os.chmod(file.getAbsolutePath(), 0644); 11357 return new ParcelFileDescriptor(fd); 11358 } catch (ErrnoException e) { 11359 throw new RemoteException("Failed to open: " + e.getMessage()); 11360 } 11361 } 11362 }; 11363 11364 int ret = PackageManager.INSTALL_SUCCEEDED; 11365 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11366 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11367 Slog.e(TAG, "Failed to copy package"); 11368 return ret; 11369 } 11370 11371 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11372 NativeLibraryHelper.Handle handle = null; 11373 try { 11374 handle = NativeLibraryHelper.Handle.create(codeFile); 11375 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11376 abiOverride); 11377 } catch (IOException e) { 11378 Slog.e(TAG, "Copying native libraries failed", e); 11379 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11380 } finally { 11381 IoUtils.closeQuietly(handle); 11382 } 11383 11384 return ret; 11385 } 11386 11387 int doPreInstall(int status) { 11388 if (status != PackageManager.INSTALL_SUCCEEDED) { 11389 cleanUp(); 11390 } 11391 return status; 11392 } 11393 11394 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11395 if (status != PackageManager.INSTALL_SUCCEEDED) { 11396 cleanUp(); 11397 return false; 11398 } 11399 11400 final File targetDir = codeFile.getParentFile(); 11401 final File beforeCodeFile = codeFile; 11402 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11403 11404 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11405 try { 11406 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11407 } catch (ErrnoException e) { 11408 Slog.w(TAG, "Failed to rename", e); 11409 return false; 11410 } 11411 11412 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11413 Slog.w(TAG, "Failed to restorecon"); 11414 return false; 11415 } 11416 11417 // Reflect the rename internally 11418 codeFile = afterCodeFile; 11419 resourceFile = afterCodeFile; 11420 11421 // Reflect the rename in scanned details 11422 pkg.codePath = afterCodeFile.getAbsolutePath(); 11423 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11424 pkg.baseCodePath); 11425 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11426 pkg.splitCodePaths); 11427 11428 // Reflect the rename in app info 11429 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11430 pkg.applicationInfo.setCodePath(pkg.codePath); 11431 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11432 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11433 pkg.applicationInfo.setResourcePath(pkg.codePath); 11434 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11435 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11436 11437 return true; 11438 } 11439 11440 int doPostInstall(int status, int uid) { 11441 if (status != PackageManager.INSTALL_SUCCEEDED) { 11442 cleanUp(); 11443 } 11444 return status; 11445 } 11446 11447 @Override 11448 String getCodePath() { 11449 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11450 } 11451 11452 @Override 11453 String getResourcePath() { 11454 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11455 } 11456 11457 private boolean cleanUp() { 11458 if (codeFile == null || !codeFile.exists()) { 11459 return false; 11460 } 11461 11462 if (codeFile.isDirectory()) { 11463 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11464 } else { 11465 codeFile.delete(); 11466 } 11467 11468 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11469 resourceFile.delete(); 11470 } 11471 11472 return true; 11473 } 11474 11475 void cleanUpResourcesLI() { 11476 // Try enumerating all code paths before deleting 11477 List<String> allCodePaths = Collections.EMPTY_LIST; 11478 if (codeFile != null && codeFile.exists()) { 11479 try { 11480 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11481 allCodePaths = pkg.getAllCodePaths(); 11482 } catch (PackageParserException e) { 11483 // Ignored; we tried our best 11484 } 11485 } 11486 11487 cleanUp(); 11488 removeDexFiles(allCodePaths, instructionSets); 11489 } 11490 11491 boolean doPostDeleteLI(boolean delete) { 11492 // XXX err, shouldn't we respect the delete flag? 11493 cleanUpResourcesLI(); 11494 return true; 11495 } 11496 } 11497 11498 private boolean isAsecExternal(String cid) { 11499 final String asecPath = PackageHelper.getSdFilesystem(cid); 11500 return !asecPath.startsWith(mAsecInternalPath); 11501 } 11502 11503 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11504 PackageManagerException { 11505 if (copyRet < 0) { 11506 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11507 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11508 throw new PackageManagerException(copyRet, message); 11509 } 11510 } 11511 } 11512 11513 /** 11514 * Extract the MountService "container ID" from the full code path of an 11515 * .apk. 11516 */ 11517 static String cidFromCodePath(String fullCodePath) { 11518 int eidx = fullCodePath.lastIndexOf("/"); 11519 String subStr1 = fullCodePath.substring(0, eidx); 11520 int sidx = subStr1.lastIndexOf("/"); 11521 return subStr1.substring(sidx+1, eidx); 11522 } 11523 11524 /** 11525 * Logic to handle installation of ASEC applications, including copying and 11526 * renaming logic. 11527 */ 11528 class AsecInstallArgs extends InstallArgs { 11529 static final String RES_FILE_NAME = "pkg.apk"; 11530 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11531 11532 String cid; 11533 String packagePath; 11534 String resourcePath; 11535 11536 /** New install */ 11537 AsecInstallArgs(InstallParams params) { 11538 super(params.origin, params.move, params.observer, params.installFlags, 11539 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11540 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11541 params.grantedRuntimePermissions, 11542 params.traceMethod, params.traceCookie); 11543 } 11544 11545 /** Existing install */ 11546 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11547 boolean isExternal, boolean isForwardLocked) { 11548 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11549 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11550 instructionSets, null, null, null, 0); 11551 // Hackily pretend we're still looking at a full code path 11552 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11553 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11554 } 11555 11556 // Extract cid from fullCodePath 11557 int eidx = fullCodePath.lastIndexOf("/"); 11558 String subStr1 = fullCodePath.substring(0, eidx); 11559 int sidx = subStr1.lastIndexOf("/"); 11560 cid = subStr1.substring(sidx+1, eidx); 11561 setMountPath(subStr1); 11562 } 11563 11564 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11565 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11566 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11567 instructionSets, null, null, null, 0); 11568 this.cid = cid; 11569 setMountPath(PackageHelper.getSdDir(cid)); 11570 } 11571 11572 void createCopyFile() { 11573 cid = mInstallerService.allocateExternalStageCidLegacy(); 11574 } 11575 11576 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11577 if (origin.staged) { 11578 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11579 cid = origin.cid; 11580 setMountPath(PackageHelper.getSdDir(cid)); 11581 return PackageManager.INSTALL_SUCCEEDED; 11582 } 11583 11584 if (temp) { 11585 createCopyFile(); 11586 } else { 11587 /* 11588 * Pre-emptively destroy the container since it's destroyed if 11589 * copying fails due to it existing anyway. 11590 */ 11591 PackageHelper.destroySdDir(cid); 11592 } 11593 11594 final String newMountPath = imcs.copyPackageToContainer( 11595 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11596 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11597 11598 if (newMountPath != null) { 11599 setMountPath(newMountPath); 11600 return PackageManager.INSTALL_SUCCEEDED; 11601 } else { 11602 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11603 } 11604 } 11605 11606 @Override 11607 String getCodePath() { 11608 return packagePath; 11609 } 11610 11611 @Override 11612 String getResourcePath() { 11613 return resourcePath; 11614 } 11615 11616 int doPreInstall(int status) { 11617 if (status != PackageManager.INSTALL_SUCCEEDED) { 11618 // Destroy container 11619 PackageHelper.destroySdDir(cid); 11620 } else { 11621 boolean mounted = PackageHelper.isContainerMounted(cid); 11622 if (!mounted) { 11623 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11624 Process.SYSTEM_UID); 11625 if (newMountPath != null) { 11626 setMountPath(newMountPath); 11627 } else { 11628 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11629 } 11630 } 11631 } 11632 return status; 11633 } 11634 11635 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11636 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11637 String newMountPath = null; 11638 if (PackageHelper.isContainerMounted(cid)) { 11639 // Unmount the container 11640 if (!PackageHelper.unMountSdDir(cid)) { 11641 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11642 return false; 11643 } 11644 } 11645 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11646 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11647 " which might be stale. Will try to clean up."); 11648 // Clean up the stale container and proceed to recreate. 11649 if (!PackageHelper.destroySdDir(newCacheId)) { 11650 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11651 return false; 11652 } 11653 // Successfully cleaned up stale container. Try to rename again. 11654 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11655 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11656 + " inspite of cleaning it up."); 11657 return false; 11658 } 11659 } 11660 if (!PackageHelper.isContainerMounted(newCacheId)) { 11661 Slog.w(TAG, "Mounting container " + newCacheId); 11662 newMountPath = PackageHelper.mountSdDir(newCacheId, 11663 getEncryptKey(), Process.SYSTEM_UID); 11664 } else { 11665 newMountPath = PackageHelper.getSdDir(newCacheId); 11666 } 11667 if (newMountPath == null) { 11668 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11669 return false; 11670 } 11671 Log.i(TAG, "Succesfully renamed " + cid + 11672 " to " + newCacheId + 11673 " at new path: " + newMountPath); 11674 cid = newCacheId; 11675 11676 final File beforeCodeFile = new File(packagePath); 11677 setMountPath(newMountPath); 11678 final File afterCodeFile = new File(packagePath); 11679 11680 // Reflect the rename in scanned details 11681 pkg.codePath = afterCodeFile.getAbsolutePath(); 11682 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11683 pkg.baseCodePath); 11684 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11685 pkg.splitCodePaths); 11686 11687 // Reflect the rename in app info 11688 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11689 pkg.applicationInfo.setCodePath(pkg.codePath); 11690 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11691 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11692 pkg.applicationInfo.setResourcePath(pkg.codePath); 11693 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11694 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11695 11696 return true; 11697 } 11698 11699 private void setMountPath(String mountPath) { 11700 final File mountFile = new File(mountPath); 11701 11702 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11703 if (monolithicFile.exists()) { 11704 packagePath = monolithicFile.getAbsolutePath(); 11705 if (isFwdLocked()) { 11706 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11707 } else { 11708 resourcePath = packagePath; 11709 } 11710 } else { 11711 packagePath = mountFile.getAbsolutePath(); 11712 resourcePath = packagePath; 11713 } 11714 } 11715 11716 int doPostInstall(int status, int uid) { 11717 if (status != PackageManager.INSTALL_SUCCEEDED) { 11718 cleanUp(); 11719 } else { 11720 final int groupOwner; 11721 final String protectedFile; 11722 if (isFwdLocked()) { 11723 groupOwner = UserHandle.getSharedAppGid(uid); 11724 protectedFile = RES_FILE_NAME; 11725 } else { 11726 groupOwner = -1; 11727 protectedFile = null; 11728 } 11729 11730 if (uid < Process.FIRST_APPLICATION_UID 11731 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11732 Slog.e(TAG, "Failed to finalize " + cid); 11733 PackageHelper.destroySdDir(cid); 11734 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11735 } 11736 11737 boolean mounted = PackageHelper.isContainerMounted(cid); 11738 if (!mounted) { 11739 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11740 } 11741 } 11742 return status; 11743 } 11744 11745 private void cleanUp() { 11746 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11747 11748 // Destroy secure container 11749 PackageHelper.destroySdDir(cid); 11750 } 11751 11752 private List<String> getAllCodePaths() { 11753 final File codeFile = new File(getCodePath()); 11754 if (codeFile != null && codeFile.exists()) { 11755 try { 11756 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11757 return pkg.getAllCodePaths(); 11758 } catch (PackageParserException e) { 11759 // Ignored; we tried our best 11760 } 11761 } 11762 return Collections.EMPTY_LIST; 11763 } 11764 11765 void cleanUpResourcesLI() { 11766 // Enumerate all code paths before deleting 11767 cleanUpResourcesLI(getAllCodePaths()); 11768 } 11769 11770 private void cleanUpResourcesLI(List<String> allCodePaths) { 11771 cleanUp(); 11772 removeDexFiles(allCodePaths, instructionSets); 11773 } 11774 11775 String getPackageName() { 11776 return getAsecPackageName(cid); 11777 } 11778 11779 boolean doPostDeleteLI(boolean delete) { 11780 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11781 final List<String> allCodePaths = getAllCodePaths(); 11782 boolean mounted = PackageHelper.isContainerMounted(cid); 11783 if (mounted) { 11784 // Unmount first 11785 if (PackageHelper.unMountSdDir(cid)) { 11786 mounted = false; 11787 } 11788 } 11789 if (!mounted && delete) { 11790 cleanUpResourcesLI(allCodePaths); 11791 } 11792 return !mounted; 11793 } 11794 11795 @Override 11796 int doPreCopy() { 11797 if (isFwdLocked()) { 11798 if (!PackageHelper.fixSdPermissions(cid, 11799 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11800 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11801 } 11802 } 11803 11804 return PackageManager.INSTALL_SUCCEEDED; 11805 } 11806 11807 @Override 11808 int doPostCopy(int uid) { 11809 if (isFwdLocked()) { 11810 if (uid < Process.FIRST_APPLICATION_UID 11811 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11812 RES_FILE_NAME)) { 11813 Slog.e(TAG, "Failed to finalize " + cid); 11814 PackageHelper.destroySdDir(cid); 11815 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11816 } 11817 } 11818 11819 return PackageManager.INSTALL_SUCCEEDED; 11820 } 11821 } 11822 11823 /** 11824 * Logic to handle movement of existing installed applications. 11825 */ 11826 class MoveInstallArgs extends InstallArgs { 11827 private File codeFile; 11828 private File resourceFile; 11829 11830 /** New install */ 11831 MoveInstallArgs(InstallParams params) { 11832 super(params.origin, params.move, params.observer, params.installFlags, 11833 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11834 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11835 params.grantedRuntimePermissions, 11836 params.traceMethod, params.traceCookie); 11837 } 11838 11839 int copyApk(IMediaContainerService imcs, boolean temp) { 11840 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11841 + move.fromUuid + " to " + move.toUuid); 11842 synchronized (mInstaller) { 11843 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11844 move.dataAppName, move.appId, move.seinfo) != 0) { 11845 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11846 } 11847 } 11848 11849 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11850 resourceFile = codeFile; 11851 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11852 11853 return PackageManager.INSTALL_SUCCEEDED; 11854 } 11855 11856 int doPreInstall(int status) { 11857 if (status != PackageManager.INSTALL_SUCCEEDED) { 11858 cleanUp(move.toUuid); 11859 } 11860 return status; 11861 } 11862 11863 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11864 if (status != PackageManager.INSTALL_SUCCEEDED) { 11865 cleanUp(move.toUuid); 11866 return false; 11867 } 11868 11869 // Reflect the move in app info 11870 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11871 pkg.applicationInfo.setCodePath(pkg.codePath); 11872 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11873 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11874 pkg.applicationInfo.setResourcePath(pkg.codePath); 11875 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11876 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11877 11878 return true; 11879 } 11880 11881 int doPostInstall(int status, int uid) { 11882 if (status == PackageManager.INSTALL_SUCCEEDED) { 11883 cleanUp(move.fromUuid); 11884 } else { 11885 cleanUp(move.toUuid); 11886 } 11887 return status; 11888 } 11889 11890 @Override 11891 String getCodePath() { 11892 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11893 } 11894 11895 @Override 11896 String getResourcePath() { 11897 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11898 } 11899 11900 private boolean cleanUp(String volumeUuid) { 11901 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11902 move.dataAppName); 11903 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11904 synchronized (mInstallLock) { 11905 // Clean up both app data and code 11906 removeDataDirsLI(volumeUuid, move.packageName); 11907 if (codeFile.isDirectory()) { 11908 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11909 } else { 11910 codeFile.delete(); 11911 } 11912 } 11913 return true; 11914 } 11915 11916 void cleanUpResourcesLI() { 11917 throw new UnsupportedOperationException(); 11918 } 11919 11920 boolean doPostDeleteLI(boolean delete) { 11921 throw new UnsupportedOperationException(); 11922 } 11923 } 11924 11925 static String getAsecPackageName(String packageCid) { 11926 int idx = packageCid.lastIndexOf("-"); 11927 if (idx == -1) { 11928 return packageCid; 11929 } 11930 return packageCid.substring(0, idx); 11931 } 11932 11933 // Utility method used to create code paths based on package name and available index. 11934 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11935 String idxStr = ""; 11936 int idx = 1; 11937 // Fall back to default value of idx=1 if prefix is not 11938 // part of oldCodePath 11939 if (oldCodePath != null) { 11940 String subStr = oldCodePath; 11941 // Drop the suffix right away 11942 if (suffix != null && subStr.endsWith(suffix)) { 11943 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11944 } 11945 // If oldCodePath already contains prefix find out the 11946 // ending index to either increment or decrement. 11947 int sidx = subStr.lastIndexOf(prefix); 11948 if (sidx != -1) { 11949 subStr = subStr.substring(sidx + prefix.length()); 11950 if (subStr != null) { 11951 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11952 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11953 } 11954 try { 11955 idx = Integer.parseInt(subStr); 11956 if (idx <= 1) { 11957 idx++; 11958 } else { 11959 idx--; 11960 } 11961 } catch(NumberFormatException e) { 11962 } 11963 } 11964 } 11965 } 11966 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11967 return prefix + idxStr; 11968 } 11969 11970 private File getNextCodePath(File targetDir, String packageName) { 11971 int suffix = 1; 11972 File result; 11973 do { 11974 result = new File(targetDir, packageName + "-" + suffix); 11975 suffix++; 11976 } while (result.exists()); 11977 return result; 11978 } 11979 11980 // Utility method that returns the relative package path with respect 11981 // to the installation directory. Like say for /data/data/com.test-1.apk 11982 // string com.test-1 is returned. 11983 static String deriveCodePathName(String codePath) { 11984 if (codePath == null) { 11985 return null; 11986 } 11987 final File codeFile = new File(codePath); 11988 final String name = codeFile.getName(); 11989 if (codeFile.isDirectory()) { 11990 return name; 11991 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11992 final int lastDot = name.lastIndexOf('.'); 11993 return name.substring(0, lastDot); 11994 } else { 11995 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11996 return null; 11997 } 11998 } 11999 12000 class PackageInstalledInfo { 12001 String name; 12002 int uid; 12003 // The set of users that originally had this package installed. 12004 int[] origUsers; 12005 // The set of users that now have this package installed. 12006 int[] newUsers; 12007 PackageParser.Package pkg; 12008 int returnCode; 12009 String returnMsg; 12010 PackageRemovedInfo removedInfo; 12011 12012 public void setError(int code, String msg) { 12013 returnCode = code; 12014 returnMsg = msg; 12015 Slog.w(TAG, msg); 12016 } 12017 12018 public void setError(String msg, PackageParserException e) { 12019 returnCode = e.error; 12020 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12021 Slog.w(TAG, msg, e); 12022 } 12023 12024 public void setError(String msg, PackageManagerException e) { 12025 returnCode = e.error; 12026 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12027 Slog.w(TAG, msg, e); 12028 } 12029 12030 // In some error cases we want to convey more info back to the observer 12031 String origPackage; 12032 String origPermission; 12033 } 12034 12035 /* 12036 * Install a non-existing package. 12037 */ 12038 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12039 UserHandle user, String installerPackageName, String volumeUuid, 12040 PackageInstalledInfo res) { 12041 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12042 12043 // Remember this for later, in case we need to rollback this install 12044 String pkgName = pkg.packageName; 12045 12046 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12047 // TODO: b/23350563 12048 final boolean dataDirExists = Environment 12049 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12050 12051 synchronized(mPackages) { 12052 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12053 // A package with the same name is already installed, though 12054 // it has been renamed to an older name. The package we 12055 // are trying to install should be installed as an update to 12056 // the existing one, but that has not been requested, so bail. 12057 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12058 + " without first uninstalling package running as " 12059 + mSettings.mRenamedPackages.get(pkgName)); 12060 return; 12061 } 12062 if (mPackages.containsKey(pkgName)) { 12063 // Don't allow installation over an existing package with the same name. 12064 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12065 + " without first uninstalling."); 12066 return; 12067 } 12068 } 12069 12070 try { 12071 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12072 System.currentTimeMillis(), user); 12073 12074 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12075 // delete the partially installed application. the data directory will have to be 12076 // restored if it was already existing 12077 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12078 // remove package from internal structures. Note that we want deletePackageX to 12079 // delete the package data and cache directories that it created in 12080 // scanPackageLocked, unless those directories existed before we even tried to 12081 // install. 12082 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12083 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12084 res.removedInfo, true); 12085 } 12086 12087 } catch (PackageManagerException e) { 12088 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12089 } 12090 12091 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12092 } 12093 12094 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12095 // Can't rotate keys during boot or if sharedUser. 12096 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12097 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12098 return false; 12099 } 12100 // app is using upgradeKeySets; make sure all are valid 12101 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12102 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12103 for (int i = 0; i < upgradeKeySets.length; i++) { 12104 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12105 Slog.wtf(TAG, "Package " 12106 + (oldPs.name != null ? oldPs.name : "<null>") 12107 + " contains upgrade-key-set reference to unknown key-set: " 12108 + upgradeKeySets[i] 12109 + " reverting to signatures check."); 12110 return false; 12111 } 12112 } 12113 return true; 12114 } 12115 12116 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12117 // Upgrade keysets are being used. Determine if new package has a superset of the 12118 // required keys. 12119 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12120 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12121 for (int i = 0; i < upgradeKeySets.length; i++) { 12122 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12123 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12124 return true; 12125 } 12126 } 12127 return false; 12128 } 12129 12130 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12131 UserHandle user, String installerPackageName, String volumeUuid, 12132 PackageInstalledInfo res) { 12133 final PackageParser.Package oldPackage; 12134 final String pkgName = pkg.packageName; 12135 final int[] allUsers; 12136 final boolean[] perUserInstalled; 12137 12138 // First find the old package info and check signatures 12139 synchronized(mPackages) { 12140 oldPackage = mPackages.get(pkgName); 12141 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12142 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12143 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12144 if(!checkUpgradeKeySetLP(ps, pkg)) { 12145 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12146 "New package not signed by keys specified by upgrade-keysets: " 12147 + pkgName); 12148 return; 12149 } 12150 } else { 12151 // default to original signature matching 12152 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12153 != PackageManager.SIGNATURE_MATCH) { 12154 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12155 "New package has a different signature: " + pkgName); 12156 return; 12157 } 12158 } 12159 12160 // In case of rollback, remember per-user/profile install state 12161 allUsers = sUserManager.getUserIds(); 12162 perUserInstalled = new boolean[allUsers.length]; 12163 for (int i = 0; i < allUsers.length; i++) { 12164 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12165 } 12166 } 12167 12168 boolean sysPkg = (isSystemApp(oldPackage)); 12169 if (sysPkg) { 12170 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12171 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12172 } else { 12173 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12174 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12175 } 12176 } 12177 12178 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12179 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12180 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12181 String volumeUuid, PackageInstalledInfo res) { 12182 String pkgName = deletedPackage.packageName; 12183 boolean deletedPkg = true; 12184 boolean updatedSettings = false; 12185 12186 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12187 + deletedPackage); 12188 long origUpdateTime; 12189 if (pkg.mExtras != null) { 12190 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12191 } else { 12192 origUpdateTime = 0; 12193 } 12194 12195 // First delete the existing package while retaining the data directory 12196 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12197 res.removedInfo, true)) { 12198 // If the existing package wasn't successfully deleted 12199 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12200 deletedPkg = false; 12201 } else { 12202 // Successfully deleted the old package; proceed with replace. 12203 12204 // If deleted package lived in a container, give users a chance to 12205 // relinquish resources before killing. 12206 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12207 if (DEBUG_INSTALL) { 12208 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12209 } 12210 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12211 final ArrayList<String> pkgList = new ArrayList<String>(1); 12212 pkgList.add(deletedPackage.applicationInfo.packageName); 12213 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12214 } 12215 12216 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12217 try { 12218 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12219 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12220 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12221 perUserInstalled, res, user); 12222 updatedSettings = true; 12223 } catch (PackageManagerException e) { 12224 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12225 } 12226 } 12227 12228 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12229 // remove package from internal structures. Note that we want deletePackageX to 12230 // delete the package data and cache directories that it created in 12231 // scanPackageLocked, unless those directories existed before we even tried to 12232 // install. 12233 if(updatedSettings) { 12234 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12235 deletePackageLI( 12236 pkgName, null, true, allUsers, perUserInstalled, 12237 PackageManager.DELETE_KEEP_DATA, 12238 res.removedInfo, true); 12239 } 12240 // Since we failed to install the new package we need to restore the old 12241 // package that we deleted. 12242 if (deletedPkg) { 12243 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12244 File restoreFile = new File(deletedPackage.codePath); 12245 // Parse old package 12246 boolean oldExternal = isExternal(deletedPackage); 12247 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12248 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12249 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12250 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12251 try { 12252 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12253 null); 12254 } catch (PackageManagerException e) { 12255 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12256 + e.getMessage()); 12257 return; 12258 } 12259 // Restore of old package succeeded. Update permissions. 12260 // writer 12261 synchronized (mPackages) { 12262 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12263 UPDATE_PERMISSIONS_ALL); 12264 // can downgrade to reader 12265 mSettings.writeLPr(); 12266 } 12267 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12268 } 12269 } 12270 } 12271 12272 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12273 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12274 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12275 String volumeUuid, PackageInstalledInfo res) { 12276 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12277 + ", old=" + deletedPackage); 12278 boolean disabledSystem = false; 12279 boolean updatedSettings = false; 12280 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12281 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12282 != 0) { 12283 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12284 } 12285 String packageName = deletedPackage.packageName; 12286 if (packageName == null) { 12287 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12288 "Attempt to delete null packageName."); 12289 return; 12290 } 12291 PackageParser.Package oldPkg; 12292 PackageSetting oldPkgSetting; 12293 // reader 12294 synchronized (mPackages) { 12295 oldPkg = mPackages.get(packageName); 12296 oldPkgSetting = mSettings.mPackages.get(packageName); 12297 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12298 (oldPkgSetting == null)) { 12299 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12300 "Couldn't find package:" + packageName + " information"); 12301 return; 12302 } 12303 } 12304 12305 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12306 12307 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12308 res.removedInfo.removedPackage = packageName; 12309 // Remove existing system package 12310 removePackageLI(oldPkgSetting, true); 12311 // writer 12312 synchronized (mPackages) { 12313 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12314 if (!disabledSystem && deletedPackage != null) { 12315 // We didn't need to disable the .apk as a current system package, 12316 // which means we are replacing another update that is already 12317 // installed. We need to make sure to delete the older one's .apk. 12318 res.removedInfo.args = createInstallArgsForExisting(0, 12319 deletedPackage.applicationInfo.getCodePath(), 12320 deletedPackage.applicationInfo.getResourcePath(), 12321 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12322 } else { 12323 res.removedInfo.args = null; 12324 } 12325 } 12326 12327 // Successfully disabled the old package. Now proceed with re-installation 12328 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12329 12330 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12331 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12332 12333 PackageParser.Package newPackage = null; 12334 try { 12335 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12336 if (newPackage.mExtras != null) { 12337 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12338 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12339 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12340 12341 // is the update attempting to change shared user? that isn't going to work... 12342 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12343 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12344 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12345 + " to " + newPkgSetting.sharedUser); 12346 updatedSettings = true; 12347 } 12348 } 12349 12350 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12351 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12352 perUserInstalled, res, user); 12353 updatedSettings = true; 12354 } 12355 12356 } catch (PackageManagerException e) { 12357 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12358 } 12359 12360 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12361 // Re installation failed. Restore old information 12362 // Remove new pkg information 12363 if (newPackage != null) { 12364 removeInstalledPackageLI(newPackage, true); 12365 } 12366 // Add back the old system package 12367 try { 12368 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12369 } catch (PackageManagerException e) { 12370 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12371 } 12372 // Restore the old system information in Settings 12373 synchronized (mPackages) { 12374 if (disabledSystem) { 12375 mSettings.enableSystemPackageLPw(packageName); 12376 } 12377 if (updatedSettings) { 12378 mSettings.setInstallerPackageName(packageName, 12379 oldPkgSetting.installerPackageName); 12380 } 12381 mSettings.writeLPr(); 12382 } 12383 } 12384 } 12385 12386 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12387 // Collect all used permissions in the UID 12388 ArraySet<String> usedPermissions = new ArraySet<>(); 12389 final int packageCount = su.packages.size(); 12390 for (int i = 0; i < packageCount; i++) { 12391 PackageSetting ps = su.packages.valueAt(i); 12392 if (ps.pkg == null) { 12393 continue; 12394 } 12395 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12396 for (int j = 0; j < requestedPermCount; j++) { 12397 String permission = ps.pkg.requestedPermissions.get(j); 12398 BasePermission bp = mSettings.mPermissions.get(permission); 12399 if (bp != null) { 12400 usedPermissions.add(permission); 12401 } 12402 } 12403 } 12404 12405 PermissionsState permissionsState = su.getPermissionsState(); 12406 // Prune install permissions 12407 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12408 final int installPermCount = installPermStates.size(); 12409 for (int i = installPermCount - 1; i >= 0; i--) { 12410 PermissionState permissionState = installPermStates.get(i); 12411 if (!usedPermissions.contains(permissionState.getName())) { 12412 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12413 if (bp != null) { 12414 permissionsState.revokeInstallPermission(bp); 12415 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12416 PackageManager.MASK_PERMISSION_FLAGS, 0); 12417 } 12418 } 12419 } 12420 12421 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12422 12423 // Prune runtime permissions 12424 for (int userId : allUserIds) { 12425 List<PermissionState> runtimePermStates = permissionsState 12426 .getRuntimePermissionStates(userId); 12427 final int runtimePermCount = runtimePermStates.size(); 12428 for (int i = runtimePermCount - 1; i >= 0; i--) { 12429 PermissionState permissionState = runtimePermStates.get(i); 12430 if (!usedPermissions.contains(permissionState.getName())) { 12431 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12432 if (bp != null) { 12433 permissionsState.revokeRuntimePermission(bp, userId); 12434 permissionsState.updatePermissionFlags(bp, userId, 12435 PackageManager.MASK_PERMISSION_FLAGS, 0); 12436 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12437 runtimePermissionChangedUserIds, userId); 12438 } 12439 } 12440 } 12441 } 12442 12443 return runtimePermissionChangedUserIds; 12444 } 12445 12446 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12447 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12448 UserHandle user) { 12449 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12450 12451 String pkgName = newPackage.packageName; 12452 synchronized (mPackages) { 12453 //write settings. the installStatus will be incomplete at this stage. 12454 //note that the new package setting would have already been 12455 //added to mPackages. It hasn't been persisted yet. 12456 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12457 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12458 mSettings.writeLPr(); 12459 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12460 } 12461 12462 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12463 synchronized (mPackages) { 12464 updatePermissionsLPw(newPackage.packageName, newPackage, 12465 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12466 ? UPDATE_PERMISSIONS_ALL : 0)); 12467 // For system-bundled packages, we assume that installing an upgraded version 12468 // of the package implies that the user actually wants to run that new code, 12469 // so we enable the package. 12470 PackageSetting ps = mSettings.mPackages.get(pkgName); 12471 if (ps != null) { 12472 if (isSystemApp(newPackage)) { 12473 // NB: implicit assumption that system package upgrades apply to all users 12474 if (DEBUG_INSTALL) { 12475 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12476 } 12477 if (res.origUsers != null) { 12478 for (int userHandle : res.origUsers) { 12479 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12480 userHandle, installerPackageName); 12481 } 12482 } 12483 // Also convey the prior install/uninstall state 12484 if (allUsers != null && perUserInstalled != null) { 12485 for (int i = 0; i < allUsers.length; i++) { 12486 if (DEBUG_INSTALL) { 12487 Slog.d(TAG, " user " + allUsers[i] 12488 + " => " + perUserInstalled[i]); 12489 } 12490 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12491 } 12492 // these install state changes will be persisted in the 12493 // upcoming call to mSettings.writeLPr(). 12494 } 12495 } 12496 // It's implied that when a user requests installation, they want the app to be 12497 // installed and enabled. 12498 int userId = user.getIdentifier(); 12499 if (userId != UserHandle.USER_ALL) { 12500 ps.setInstalled(true, userId); 12501 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12502 } 12503 } 12504 res.name = pkgName; 12505 res.uid = newPackage.applicationInfo.uid; 12506 res.pkg = newPackage; 12507 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12508 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12509 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12510 //to update install status 12511 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12512 mSettings.writeLPr(); 12513 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12514 } 12515 12516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12517 } 12518 12519 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12520 try { 12521 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12522 installPackageLI(args, res); 12523 } finally { 12524 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12525 } 12526 } 12527 12528 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12529 final int installFlags = args.installFlags; 12530 final String installerPackageName = args.installerPackageName; 12531 final String volumeUuid = args.volumeUuid; 12532 final File tmpPackageFile = new File(args.getCodePath()); 12533 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12534 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12535 || (args.volumeUuid != null)); 12536 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12537 boolean replace = false; 12538 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12539 if (args.move != null) { 12540 // moving a complete application; perfom an initial scan on the new install location 12541 scanFlags |= SCAN_INITIAL; 12542 } 12543 // Result object to be returned 12544 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12545 12546 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12547 12548 // Retrieve PackageSettings and parse package 12549 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12550 | PackageParser.PARSE_ENFORCE_CODE 12551 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12552 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12553 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12554 PackageParser pp = new PackageParser(); 12555 pp.setSeparateProcesses(mSeparateProcesses); 12556 pp.setDisplayMetrics(mMetrics); 12557 12558 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12559 final PackageParser.Package pkg; 12560 try { 12561 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12562 } catch (PackageParserException e) { 12563 res.setError("Failed parse during installPackageLI", e); 12564 return; 12565 } finally { 12566 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12567 } 12568 12569 // Mark that we have an install time CPU ABI override. 12570 pkg.cpuAbiOverride = args.abiOverride; 12571 12572 String pkgName = res.name = pkg.packageName; 12573 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12574 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12575 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12576 return; 12577 } 12578 } 12579 12580 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12581 try { 12582 pp.collectCertificates(pkg, parseFlags); 12583 } catch (PackageParserException e) { 12584 res.setError("Failed collect during installPackageLI", e); 12585 return; 12586 } finally { 12587 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12588 } 12589 12590 /* If the installer passed in a manifest digest, compare it now. */ 12591 if (args.manifestDigest != null) { 12592 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12593 try { 12594 pp.collectManifestDigest(pkg); 12595 } catch (PackageParserException e) { 12596 res.setError("Failed collect during installPackageLI", e); 12597 return; 12598 } finally { 12599 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12600 } 12601 12602 if (DEBUG_INSTALL) { 12603 final String parsedManifest = pkg.manifestDigest == null ? "null" 12604 : pkg.manifestDigest.toString(); 12605 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12606 + parsedManifest); 12607 } 12608 12609 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12610 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12611 return; 12612 } 12613 } else if (DEBUG_INSTALL) { 12614 final String parsedManifest = pkg.manifestDigest == null 12615 ? "null" : pkg.manifestDigest.toString(); 12616 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12617 } 12618 12619 // Get rid of all references to package scan path via parser. 12620 pp = null; 12621 String oldCodePath = null; 12622 boolean systemApp = false; 12623 synchronized (mPackages) { 12624 // Check if installing already existing package 12625 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12626 String oldName = mSettings.mRenamedPackages.get(pkgName); 12627 if (pkg.mOriginalPackages != null 12628 && pkg.mOriginalPackages.contains(oldName) 12629 && mPackages.containsKey(oldName)) { 12630 // This package is derived from an original package, 12631 // and this device has been updating from that original 12632 // name. We must continue using the original name, so 12633 // rename the new package here. 12634 pkg.setPackageName(oldName); 12635 pkgName = pkg.packageName; 12636 replace = true; 12637 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12638 + oldName + " pkgName=" + pkgName); 12639 } else if (mPackages.containsKey(pkgName)) { 12640 // This package, under its official name, already exists 12641 // on the device; we should replace it. 12642 replace = true; 12643 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12644 } 12645 12646 // Prevent apps opting out from runtime permissions 12647 if (replace) { 12648 PackageParser.Package oldPackage = mPackages.get(pkgName); 12649 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12650 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12651 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12652 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12653 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12654 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12655 + " doesn't support runtime permissions but the old" 12656 + " target SDK " + oldTargetSdk + " does."); 12657 return; 12658 } 12659 } 12660 } 12661 12662 PackageSetting ps = mSettings.mPackages.get(pkgName); 12663 if (ps != null) { 12664 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12665 12666 // Quick sanity check that we're signed correctly if updating; 12667 // we'll check this again later when scanning, but we want to 12668 // bail early here before tripping over redefined permissions. 12669 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12670 if (!checkUpgradeKeySetLP(ps, pkg)) { 12671 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12672 + pkg.packageName + " upgrade keys do not match the " 12673 + "previously installed version"); 12674 return; 12675 } 12676 } else { 12677 try { 12678 verifySignaturesLP(ps, pkg); 12679 } catch (PackageManagerException e) { 12680 res.setError(e.error, e.getMessage()); 12681 return; 12682 } 12683 } 12684 12685 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12686 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12687 systemApp = (ps.pkg.applicationInfo.flags & 12688 ApplicationInfo.FLAG_SYSTEM) != 0; 12689 } 12690 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12691 } 12692 12693 // Check whether the newly-scanned package wants to define an already-defined perm 12694 int N = pkg.permissions.size(); 12695 for (int i = N-1; i >= 0; i--) { 12696 PackageParser.Permission perm = pkg.permissions.get(i); 12697 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12698 if (bp != null) { 12699 // If the defining package is signed with our cert, it's okay. This 12700 // also includes the "updating the same package" case, of course. 12701 // "updating same package" could also involve key-rotation. 12702 final boolean sigsOk; 12703 if (bp.sourcePackage.equals(pkg.packageName) 12704 && (bp.packageSetting instanceof PackageSetting) 12705 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12706 scanFlags))) { 12707 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12708 } else { 12709 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12710 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12711 } 12712 if (!sigsOk) { 12713 // If the owning package is the system itself, we log but allow 12714 // install to proceed; we fail the install on all other permission 12715 // redefinitions. 12716 if (!bp.sourcePackage.equals("android")) { 12717 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12718 + pkg.packageName + " attempting to redeclare permission " 12719 + perm.info.name + " already owned by " + bp.sourcePackage); 12720 res.origPermission = perm.info.name; 12721 res.origPackage = bp.sourcePackage; 12722 return; 12723 } else { 12724 Slog.w(TAG, "Package " + pkg.packageName 12725 + " attempting to redeclare system permission " 12726 + perm.info.name + "; ignoring new declaration"); 12727 pkg.permissions.remove(i); 12728 } 12729 } 12730 } 12731 } 12732 12733 } 12734 12735 if (systemApp && onExternal) { 12736 // Disable updates to system apps on sdcard 12737 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12738 "Cannot install updates to system apps on sdcard"); 12739 return; 12740 } 12741 12742 if (args.move != null) { 12743 // We did an in-place move, so dex is ready to roll 12744 scanFlags |= SCAN_NO_DEX; 12745 scanFlags |= SCAN_MOVE; 12746 12747 synchronized (mPackages) { 12748 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12749 if (ps == null) { 12750 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12751 "Missing settings for moved package " + pkgName); 12752 } 12753 12754 // We moved the entire application as-is, so bring over the 12755 // previously derived ABI information. 12756 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12757 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12758 } 12759 12760 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12761 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12762 scanFlags |= SCAN_NO_DEX; 12763 12764 try { 12765 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12766 true /* extract libs */); 12767 } catch (PackageManagerException pme) { 12768 Slog.e(TAG, "Error deriving application ABI", pme); 12769 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12770 return; 12771 } 12772 } 12773 12774 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12775 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12776 return; 12777 } 12778 12779 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12780 12781 if (replace) { 12782 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12783 installerPackageName, volumeUuid, res); 12784 } else { 12785 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12786 args.user, installerPackageName, volumeUuid, res); 12787 } 12788 synchronized (mPackages) { 12789 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12790 if (ps != null) { 12791 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12792 } 12793 } 12794 } 12795 12796 private void startIntentFilterVerifications(int userId, boolean replacing, 12797 PackageParser.Package pkg) { 12798 if (mIntentFilterVerifierComponent == null) { 12799 Slog.w(TAG, "No IntentFilter verification will not be done as " 12800 + "there is no IntentFilterVerifier available!"); 12801 return; 12802 } 12803 12804 final int verifierUid = getPackageUid( 12805 mIntentFilterVerifierComponent.getPackageName(), 12806 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12807 12808 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12809 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12810 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12811 mHandler.sendMessage(msg); 12812 } 12813 12814 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12815 PackageParser.Package pkg) { 12816 int size = pkg.activities.size(); 12817 if (size == 0) { 12818 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12819 "No activity, so no need to verify any IntentFilter!"); 12820 return; 12821 } 12822 12823 final boolean hasDomainURLs = hasDomainURLs(pkg); 12824 if (!hasDomainURLs) { 12825 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12826 "No domain URLs, so no need to verify any IntentFilter!"); 12827 return; 12828 } 12829 12830 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12831 + " if any IntentFilter from the " + size 12832 + " Activities needs verification ..."); 12833 12834 int count = 0; 12835 final String packageName = pkg.packageName; 12836 12837 synchronized (mPackages) { 12838 // If this is a new install and we see that we've already run verification for this 12839 // package, we have nothing to do: it means the state was restored from backup. 12840 if (!replacing) { 12841 IntentFilterVerificationInfo ivi = 12842 mSettings.getIntentFilterVerificationLPr(packageName); 12843 if (ivi != null) { 12844 if (DEBUG_DOMAIN_VERIFICATION) { 12845 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12846 + ivi.getStatusString()); 12847 } 12848 return; 12849 } 12850 } 12851 12852 // If any filters need to be verified, then all need to be. 12853 boolean needToVerify = false; 12854 for (PackageParser.Activity a : pkg.activities) { 12855 for (ActivityIntentInfo filter : a.intents) { 12856 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12857 if (DEBUG_DOMAIN_VERIFICATION) { 12858 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12859 } 12860 needToVerify = true; 12861 break; 12862 } 12863 } 12864 } 12865 12866 if (needToVerify) { 12867 final int verificationId = mIntentFilterVerificationToken++; 12868 for (PackageParser.Activity a : pkg.activities) { 12869 for (ActivityIntentInfo filter : a.intents) { 12870 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12871 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12872 "Verification needed for IntentFilter:" + filter.toString()); 12873 mIntentFilterVerifier.addOneIntentFilterVerification( 12874 verifierUid, userId, verificationId, filter, packageName); 12875 count++; 12876 } 12877 } 12878 } 12879 } 12880 } 12881 12882 if (count > 0) { 12883 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12884 + " IntentFilter verification" + (count > 1 ? "s" : "") 12885 + " for userId:" + userId); 12886 mIntentFilterVerifier.startVerifications(userId); 12887 } else { 12888 if (DEBUG_DOMAIN_VERIFICATION) { 12889 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12890 } 12891 } 12892 } 12893 12894 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12895 final ComponentName cn = filter.activity.getComponentName(); 12896 final String packageName = cn.getPackageName(); 12897 12898 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12899 packageName); 12900 if (ivi == null) { 12901 return true; 12902 } 12903 int status = ivi.getStatus(); 12904 switch (status) { 12905 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12906 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12907 return true; 12908 12909 default: 12910 // Nothing to do 12911 return false; 12912 } 12913 } 12914 12915 private static boolean isMultiArch(PackageSetting ps) { 12916 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12917 } 12918 12919 private static boolean isMultiArch(ApplicationInfo info) { 12920 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12921 } 12922 12923 private static boolean isExternal(PackageParser.Package pkg) { 12924 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12925 } 12926 12927 private static boolean isExternal(PackageSetting ps) { 12928 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12929 } 12930 12931 private static boolean isExternal(ApplicationInfo info) { 12932 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12933 } 12934 12935 private static boolean isSystemApp(PackageParser.Package pkg) { 12936 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12937 } 12938 12939 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12940 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12941 } 12942 12943 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12944 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12945 } 12946 12947 private static boolean isSystemApp(PackageSetting ps) { 12948 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12949 } 12950 12951 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12952 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12953 } 12954 12955 private int packageFlagsToInstallFlags(PackageSetting ps) { 12956 int installFlags = 0; 12957 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12958 // This existing package was an external ASEC install when we have 12959 // the external flag without a UUID 12960 installFlags |= PackageManager.INSTALL_EXTERNAL; 12961 } 12962 if (ps.isForwardLocked()) { 12963 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12964 } 12965 return installFlags; 12966 } 12967 12968 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12969 if (isExternal(pkg)) { 12970 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12971 return StorageManager.UUID_PRIMARY_PHYSICAL; 12972 } else { 12973 return pkg.volumeUuid; 12974 } 12975 } else { 12976 return StorageManager.UUID_PRIVATE_INTERNAL; 12977 } 12978 } 12979 12980 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12981 if (isExternal(pkg)) { 12982 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12983 return mSettings.getExternalVersion(); 12984 } else { 12985 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12986 } 12987 } else { 12988 return mSettings.getInternalVersion(); 12989 } 12990 } 12991 12992 private void deleteTempPackageFiles() { 12993 final FilenameFilter filter = new FilenameFilter() { 12994 public boolean accept(File dir, String name) { 12995 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12996 } 12997 }; 12998 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12999 file.delete(); 13000 } 13001 } 13002 13003 @Override 13004 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13005 int flags) { 13006 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13007 flags); 13008 } 13009 13010 @Override 13011 public void deletePackage(final String packageName, 13012 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13013 mContext.enforceCallingOrSelfPermission( 13014 android.Manifest.permission.DELETE_PACKAGES, null); 13015 Preconditions.checkNotNull(packageName); 13016 Preconditions.checkNotNull(observer); 13017 final int uid = Binder.getCallingUid(); 13018 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13019 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13020 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13021 mContext.enforceCallingOrSelfPermission( 13022 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13023 "deletePackage for user " + userId); 13024 } 13025 13026 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13027 try { 13028 observer.onPackageDeleted(packageName, 13029 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13030 } catch (RemoteException re) { 13031 } 13032 return; 13033 } 13034 13035 for (int currentUserId : users) { 13036 if (getBlockUninstallForUser(packageName, currentUserId)) { 13037 try { 13038 observer.onPackageDeleted(packageName, 13039 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13040 } catch (RemoteException re) { 13041 } 13042 return; 13043 } 13044 } 13045 13046 if (DEBUG_REMOVE) { 13047 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13048 } 13049 // Queue up an async operation since the package deletion may take a little while. 13050 mHandler.post(new Runnable() { 13051 public void run() { 13052 mHandler.removeCallbacks(this); 13053 final int returnCode = deletePackageX(packageName, userId, flags); 13054 try { 13055 observer.onPackageDeleted(packageName, returnCode, null); 13056 } catch (RemoteException e) { 13057 Log.i(TAG, "Observer no longer exists."); 13058 } //end catch 13059 } //end run 13060 }); 13061 } 13062 13063 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13064 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13065 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13066 try { 13067 if (dpm != null) { 13068 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwner(); 13069 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13070 : deviceOwnerComponentName.getPackageName(); 13071 // Does the package contains the device owner? 13072 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13073 // this check is probably not needed, since DO should be registered as a device 13074 // admin on some user too. (Original bug for this: b/17657954) 13075 if (packageName.equals(deviceOwnerPackageName)) { 13076 return true; 13077 } 13078 // Does it contain a device admin for any user? 13079 int[] users; 13080 if (userId == UserHandle.USER_ALL) { 13081 users = sUserManager.getUserIds(); 13082 } else { 13083 users = new int[]{userId}; 13084 } 13085 for (int i = 0; i < users.length; ++i) { 13086 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13087 return true; 13088 } 13089 } 13090 } 13091 } catch (RemoteException e) { 13092 } 13093 return false; 13094 } 13095 13096 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13097 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13098 } 13099 13100 /** 13101 * This method is an internal method that could be get invoked either 13102 * to delete an installed package or to clean up a failed installation. 13103 * After deleting an installed package, a broadcast is sent to notify any 13104 * listeners that the package has been installed. For cleaning up a failed 13105 * installation, the broadcast is not necessary since the package's 13106 * installation wouldn't have sent the initial broadcast either 13107 * The key steps in deleting a package are 13108 * deleting the package information in internal structures like mPackages, 13109 * deleting the packages base directories through installd 13110 * updating mSettings to reflect current status 13111 * persisting settings for later use 13112 * sending a broadcast if necessary 13113 */ 13114 private int deletePackageX(String packageName, int userId, int flags) { 13115 final PackageRemovedInfo info = new PackageRemovedInfo(); 13116 final boolean res; 13117 13118 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13119 ? UserHandle.ALL : new UserHandle(userId); 13120 13121 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13122 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13123 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13124 } 13125 13126 boolean removedForAllUsers = false; 13127 boolean systemUpdate = false; 13128 13129 // for the uninstall-updates case and restricted profiles, remember the per- 13130 // userhandle installed state 13131 int[] allUsers; 13132 boolean[] perUserInstalled; 13133 synchronized (mPackages) { 13134 PackageSetting ps = mSettings.mPackages.get(packageName); 13135 allUsers = sUserManager.getUserIds(); 13136 perUserInstalled = new boolean[allUsers.length]; 13137 for (int i = 0; i < allUsers.length; i++) { 13138 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13139 } 13140 } 13141 13142 synchronized (mInstallLock) { 13143 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13144 res = deletePackageLI(packageName, removeForUser, 13145 true, allUsers, perUserInstalled, 13146 flags | REMOVE_CHATTY, info, true); 13147 systemUpdate = info.isRemovedPackageSystemUpdate; 13148 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13149 removedForAllUsers = true; 13150 } 13151 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13152 + " removedForAllUsers=" + removedForAllUsers); 13153 } 13154 13155 if (res) { 13156 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13157 13158 // If the removed package was a system update, the old system package 13159 // was re-enabled; we need to broadcast this information 13160 if (systemUpdate) { 13161 Bundle extras = new Bundle(1); 13162 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13163 ? info.removedAppId : info.uid); 13164 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13165 13166 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13167 extras, 0, null, null, null); 13168 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13169 extras, 0, null, null, null); 13170 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13171 null, 0, packageName, null, null); 13172 } 13173 } 13174 // Force a gc here. 13175 Runtime.getRuntime().gc(); 13176 // Delete the resources here after sending the broadcast to let 13177 // other processes clean up before deleting resources. 13178 if (info.args != null) { 13179 synchronized (mInstallLock) { 13180 info.args.doPostDeleteLI(true); 13181 } 13182 } 13183 13184 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13185 } 13186 13187 class PackageRemovedInfo { 13188 String removedPackage; 13189 int uid = -1; 13190 int removedAppId = -1; 13191 int[] removedUsers = null; 13192 boolean isRemovedPackageSystemUpdate = false; 13193 // Clean up resources deleted packages. 13194 InstallArgs args = null; 13195 13196 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13197 Bundle extras = new Bundle(1); 13198 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13199 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13200 if (replacing) { 13201 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13202 } 13203 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13204 if (removedPackage != null) { 13205 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13206 extras, 0, null, null, removedUsers); 13207 if (fullRemove && !replacing) { 13208 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13209 extras, 0, null, null, removedUsers); 13210 } 13211 } 13212 if (removedAppId >= 0) { 13213 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13214 removedUsers); 13215 } 13216 } 13217 } 13218 13219 /* 13220 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13221 * flag is not set, the data directory is removed as well. 13222 * make sure this flag is set for partially installed apps. If not its meaningless to 13223 * delete a partially installed application. 13224 */ 13225 private void removePackageDataLI(PackageSetting ps, 13226 int[] allUserHandles, boolean[] perUserInstalled, 13227 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13228 String packageName = ps.name; 13229 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13230 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13231 // Retrieve object to delete permissions for shared user later on 13232 final PackageSetting deletedPs; 13233 // reader 13234 synchronized (mPackages) { 13235 deletedPs = mSettings.mPackages.get(packageName); 13236 if (outInfo != null) { 13237 outInfo.removedPackage = packageName; 13238 outInfo.removedUsers = deletedPs != null 13239 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13240 : null; 13241 } 13242 } 13243 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13244 removeDataDirsLI(ps.volumeUuid, packageName); 13245 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13246 } 13247 // writer 13248 synchronized (mPackages) { 13249 if (deletedPs != null) { 13250 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13251 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13252 clearDefaultBrowserIfNeeded(packageName); 13253 if (outInfo != null) { 13254 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13255 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13256 } 13257 updatePermissionsLPw(deletedPs.name, null, 0); 13258 if (deletedPs.sharedUser != null) { 13259 // Remove permissions associated with package. Since runtime 13260 // permissions are per user we have to kill the removed package 13261 // or packages running under the shared user of the removed 13262 // package if revoking the permissions requested only by the removed 13263 // package is successful and this causes a change in gids. 13264 for (int userId : UserManagerService.getInstance().getUserIds()) { 13265 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13266 userId); 13267 if (userIdToKill == UserHandle.USER_ALL 13268 || userIdToKill >= UserHandle.USER_SYSTEM) { 13269 // If gids changed for this user, kill all affected packages. 13270 mHandler.post(new Runnable() { 13271 @Override 13272 public void run() { 13273 // This has to happen with no lock held. 13274 killApplication(deletedPs.name, deletedPs.appId, 13275 KILL_APP_REASON_GIDS_CHANGED); 13276 } 13277 }); 13278 break; 13279 } 13280 } 13281 } 13282 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13283 } 13284 // make sure to preserve per-user disabled state if this removal was just 13285 // a downgrade of a system app to the factory package 13286 if (allUserHandles != null && perUserInstalled != null) { 13287 if (DEBUG_REMOVE) { 13288 Slog.d(TAG, "Propagating install state across downgrade"); 13289 } 13290 for (int i = 0; i < allUserHandles.length; i++) { 13291 if (DEBUG_REMOVE) { 13292 Slog.d(TAG, " user " + allUserHandles[i] 13293 + " => " + perUserInstalled[i]); 13294 } 13295 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13296 } 13297 } 13298 } 13299 // can downgrade to reader 13300 if (writeSettings) { 13301 // Save settings now 13302 mSettings.writeLPr(); 13303 } 13304 } 13305 if (outInfo != null) { 13306 // A user ID was deleted here. Go through all users and remove it 13307 // from KeyStore. 13308 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13309 } 13310 } 13311 13312 static boolean locationIsPrivileged(File path) { 13313 try { 13314 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13315 .getCanonicalPath(); 13316 return path.getCanonicalPath().startsWith(privilegedAppDir); 13317 } catch (IOException e) { 13318 Slog.e(TAG, "Unable to access code path " + path); 13319 } 13320 return false; 13321 } 13322 13323 /* 13324 * Tries to delete system package. 13325 */ 13326 private boolean deleteSystemPackageLI(PackageSetting newPs, 13327 int[] allUserHandles, boolean[] perUserInstalled, 13328 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13329 final boolean applyUserRestrictions 13330 = (allUserHandles != null) && (perUserInstalled != null); 13331 PackageSetting disabledPs = null; 13332 // Confirm if the system package has been updated 13333 // An updated system app can be deleted. This will also have to restore 13334 // the system pkg from system partition 13335 // reader 13336 synchronized (mPackages) { 13337 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13338 } 13339 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13340 + " disabledPs=" + disabledPs); 13341 if (disabledPs == null) { 13342 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13343 return false; 13344 } else if (DEBUG_REMOVE) { 13345 Slog.d(TAG, "Deleting system pkg from data partition"); 13346 } 13347 if (DEBUG_REMOVE) { 13348 if (applyUserRestrictions) { 13349 Slog.d(TAG, "Remembering install states:"); 13350 for (int i = 0; i < allUserHandles.length; i++) { 13351 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13352 } 13353 } 13354 } 13355 // Delete the updated package 13356 outInfo.isRemovedPackageSystemUpdate = true; 13357 if (disabledPs.versionCode < newPs.versionCode) { 13358 // Delete data for downgrades 13359 flags &= ~PackageManager.DELETE_KEEP_DATA; 13360 } else { 13361 // Preserve data by setting flag 13362 flags |= PackageManager.DELETE_KEEP_DATA; 13363 } 13364 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13365 allUserHandles, perUserInstalled, outInfo, writeSettings); 13366 if (!ret) { 13367 return false; 13368 } 13369 // writer 13370 synchronized (mPackages) { 13371 // Reinstate the old system package 13372 mSettings.enableSystemPackageLPw(newPs.name); 13373 // Remove any native libraries from the upgraded package. 13374 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13375 } 13376 // Install the system package 13377 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13378 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13379 if (locationIsPrivileged(disabledPs.codePath)) { 13380 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13381 } 13382 13383 final PackageParser.Package newPkg; 13384 try { 13385 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13386 } catch (PackageManagerException e) { 13387 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13388 return false; 13389 } 13390 13391 // writer 13392 synchronized (mPackages) { 13393 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13394 13395 // Propagate the permissions state as we do not want to drop on the floor 13396 // runtime permissions. The update permissions method below will take 13397 // care of removing obsolete permissions and grant install permissions. 13398 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13399 updatePermissionsLPw(newPkg.packageName, newPkg, 13400 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13401 13402 if (applyUserRestrictions) { 13403 if (DEBUG_REMOVE) { 13404 Slog.d(TAG, "Propagating install state across reinstall"); 13405 } 13406 for (int i = 0; i < allUserHandles.length; i++) { 13407 if (DEBUG_REMOVE) { 13408 Slog.d(TAG, " user " + allUserHandles[i] 13409 + " => " + perUserInstalled[i]); 13410 } 13411 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13412 13413 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13414 } 13415 // Regardless of writeSettings we need to ensure that this restriction 13416 // state propagation is persisted 13417 mSettings.writeAllUsersPackageRestrictionsLPr(); 13418 } 13419 // can downgrade to reader here 13420 if (writeSettings) { 13421 mSettings.writeLPr(); 13422 } 13423 } 13424 return true; 13425 } 13426 13427 private boolean deleteInstalledPackageLI(PackageSetting ps, 13428 boolean deleteCodeAndResources, int flags, 13429 int[] allUserHandles, boolean[] perUserInstalled, 13430 PackageRemovedInfo outInfo, boolean writeSettings) { 13431 if (outInfo != null) { 13432 outInfo.uid = ps.appId; 13433 } 13434 13435 // Delete package data from internal structures and also remove data if flag is set 13436 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13437 13438 // Delete application code and resources 13439 if (deleteCodeAndResources && (outInfo != null)) { 13440 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13441 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13442 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13443 } 13444 return true; 13445 } 13446 13447 @Override 13448 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13449 int userId) { 13450 mContext.enforceCallingOrSelfPermission( 13451 android.Manifest.permission.DELETE_PACKAGES, null); 13452 synchronized (mPackages) { 13453 PackageSetting ps = mSettings.mPackages.get(packageName); 13454 if (ps == null) { 13455 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13456 return false; 13457 } 13458 if (!ps.getInstalled(userId)) { 13459 // Can't block uninstall for an app that is not installed or enabled. 13460 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13461 return false; 13462 } 13463 ps.setBlockUninstall(blockUninstall, userId); 13464 mSettings.writePackageRestrictionsLPr(userId); 13465 } 13466 return true; 13467 } 13468 13469 @Override 13470 public boolean getBlockUninstallForUser(String packageName, int userId) { 13471 synchronized (mPackages) { 13472 PackageSetting ps = mSettings.mPackages.get(packageName); 13473 if (ps == null) { 13474 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13475 return false; 13476 } 13477 return ps.getBlockUninstall(userId); 13478 } 13479 } 13480 13481 /* 13482 * This method handles package deletion in general 13483 */ 13484 private boolean deletePackageLI(String packageName, UserHandle user, 13485 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13486 int flags, PackageRemovedInfo outInfo, 13487 boolean writeSettings) { 13488 if (packageName == null) { 13489 Slog.w(TAG, "Attempt to delete null packageName."); 13490 return false; 13491 } 13492 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13493 PackageSetting ps; 13494 boolean dataOnly = false; 13495 int removeUser = -1; 13496 int appId = -1; 13497 synchronized (mPackages) { 13498 ps = mSettings.mPackages.get(packageName); 13499 if (ps == null) { 13500 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13501 return false; 13502 } 13503 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13504 && user.getIdentifier() != UserHandle.USER_ALL) { 13505 // The caller is asking that the package only be deleted for a single 13506 // user. To do this, we just mark its uninstalled state and delete 13507 // its data. If this is a system app, we only allow this to happen if 13508 // they have set the special DELETE_SYSTEM_APP which requests different 13509 // semantics than normal for uninstalling system apps. 13510 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13511 final int userId = user.getIdentifier(); 13512 ps.setUserState(userId, 13513 COMPONENT_ENABLED_STATE_DEFAULT, 13514 false, //installed 13515 true, //stopped 13516 true, //notLaunched 13517 false, //hidden 13518 null, null, null, 13519 false, // blockUninstall 13520 ps.readUserState(userId).domainVerificationStatus, 0); 13521 if (!isSystemApp(ps)) { 13522 // Do not uninstall the APK if an app should be cached 13523 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13524 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13525 // Other user still have this package installed, so all 13526 // we need to do is clear this user's data and save that 13527 // it is uninstalled. 13528 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13529 removeUser = user.getIdentifier(); 13530 appId = ps.appId; 13531 scheduleWritePackageRestrictionsLocked(removeUser); 13532 } else { 13533 // We need to set it back to 'installed' so the uninstall 13534 // broadcasts will be sent correctly. 13535 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13536 ps.setInstalled(true, user.getIdentifier()); 13537 } 13538 } else { 13539 // This is a system app, so we assume that the 13540 // other users still have this package installed, so all 13541 // we need to do is clear this user's data and save that 13542 // it is uninstalled. 13543 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13544 removeUser = user.getIdentifier(); 13545 appId = ps.appId; 13546 scheduleWritePackageRestrictionsLocked(removeUser); 13547 } 13548 } 13549 } 13550 13551 if (removeUser >= 0) { 13552 // From above, we determined that we are deleting this only 13553 // for a single user. Continue the work here. 13554 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13555 if (outInfo != null) { 13556 outInfo.removedPackage = packageName; 13557 outInfo.removedAppId = appId; 13558 outInfo.removedUsers = new int[] {removeUser}; 13559 } 13560 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13561 removeKeystoreDataIfNeeded(removeUser, appId); 13562 schedulePackageCleaning(packageName, removeUser, false); 13563 synchronized (mPackages) { 13564 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13565 scheduleWritePackageRestrictionsLocked(removeUser); 13566 } 13567 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13568 } 13569 return true; 13570 } 13571 13572 if (dataOnly) { 13573 // Delete application data first 13574 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13575 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13576 return true; 13577 } 13578 13579 boolean ret = false; 13580 if (isSystemApp(ps)) { 13581 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13582 // When an updated system application is deleted we delete the existing resources as well and 13583 // fall back to existing code in system partition 13584 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13585 flags, outInfo, writeSettings); 13586 } else { 13587 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13588 // Kill application pre-emptively especially for apps on sd. 13589 killApplication(packageName, ps.appId, "uninstall pkg"); 13590 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13591 allUserHandles, perUserInstalled, 13592 outInfo, writeSettings); 13593 } 13594 13595 return ret; 13596 } 13597 13598 private final class ClearStorageConnection implements ServiceConnection { 13599 IMediaContainerService mContainerService; 13600 13601 @Override 13602 public void onServiceConnected(ComponentName name, IBinder service) { 13603 synchronized (this) { 13604 mContainerService = IMediaContainerService.Stub.asInterface(service); 13605 notifyAll(); 13606 } 13607 } 13608 13609 @Override 13610 public void onServiceDisconnected(ComponentName name) { 13611 } 13612 } 13613 13614 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13615 final boolean mounted; 13616 if (Environment.isExternalStorageEmulated()) { 13617 mounted = true; 13618 } else { 13619 final String status = Environment.getExternalStorageState(); 13620 13621 mounted = status.equals(Environment.MEDIA_MOUNTED) 13622 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13623 } 13624 13625 if (!mounted) { 13626 return; 13627 } 13628 13629 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13630 int[] users; 13631 if (userId == UserHandle.USER_ALL) { 13632 users = sUserManager.getUserIds(); 13633 } else { 13634 users = new int[] { userId }; 13635 } 13636 final ClearStorageConnection conn = new ClearStorageConnection(); 13637 if (mContext.bindServiceAsUser( 13638 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13639 try { 13640 for (int curUser : users) { 13641 long timeout = SystemClock.uptimeMillis() + 5000; 13642 synchronized (conn) { 13643 long now = SystemClock.uptimeMillis(); 13644 while (conn.mContainerService == null && now < timeout) { 13645 try { 13646 conn.wait(timeout - now); 13647 } catch (InterruptedException e) { 13648 } 13649 } 13650 } 13651 if (conn.mContainerService == null) { 13652 return; 13653 } 13654 13655 final UserEnvironment userEnv = new UserEnvironment(curUser); 13656 clearDirectory(conn.mContainerService, 13657 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13658 if (allData) { 13659 clearDirectory(conn.mContainerService, 13660 userEnv.buildExternalStorageAppDataDirs(packageName)); 13661 clearDirectory(conn.mContainerService, 13662 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13663 } 13664 } 13665 } finally { 13666 mContext.unbindService(conn); 13667 } 13668 } 13669 } 13670 13671 @Override 13672 public void clearApplicationUserData(final String packageName, 13673 final IPackageDataObserver observer, final int userId) { 13674 mContext.enforceCallingOrSelfPermission( 13675 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13676 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13677 // Queue up an async operation since the package deletion may take a little while. 13678 mHandler.post(new Runnable() { 13679 public void run() { 13680 mHandler.removeCallbacks(this); 13681 final boolean succeeded; 13682 synchronized (mInstallLock) { 13683 succeeded = clearApplicationUserDataLI(packageName, userId); 13684 } 13685 clearExternalStorageDataSync(packageName, userId, true); 13686 if (succeeded) { 13687 // invoke DeviceStorageMonitor's update method to clear any notifications 13688 DeviceStorageMonitorInternal 13689 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13690 if (dsm != null) { 13691 dsm.checkMemory(); 13692 } 13693 } 13694 if(observer != null) { 13695 try { 13696 observer.onRemoveCompleted(packageName, succeeded); 13697 } catch (RemoteException e) { 13698 Log.i(TAG, "Observer no longer exists."); 13699 } 13700 } //end if observer 13701 } //end run 13702 }); 13703 } 13704 13705 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13706 if (packageName == null) { 13707 Slog.w(TAG, "Attempt to delete null packageName."); 13708 return false; 13709 } 13710 13711 // Try finding details about the requested package 13712 PackageParser.Package pkg; 13713 synchronized (mPackages) { 13714 pkg = mPackages.get(packageName); 13715 if (pkg == null) { 13716 final PackageSetting ps = mSettings.mPackages.get(packageName); 13717 if (ps != null) { 13718 pkg = ps.pkg; 13719 } 13720 } 13721 13722 if (pkg == null) { 13723 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13724 return false; 13725 } 13726 13727 PackageSetting ps = (PackageSetting) pkg.mExtras; 13728 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13729 } 13730 13731 // Always delete data directories for package, even if we found no other 13732 // record of app. This helps users recover from UID mismatches without 13733 // resorting to a full data wipe. 13734 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13735 if (retCode < 0) { 13736 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13737 return false; 13738 } 13739 13740 final int appId = pkg.applicationInfo.uid; 13741 removeKeystoreDataIfNeeded(userId, appId); 13742 13743 // Create a native library symlink only if we have native libraries 13744 // and if the native libraries are 32 bit libraries. We do not provide 13745 // this symlink for 64 bit libraries. 13746 if (pkg.applicationInfo.primaryCpuAbi != null && 13747 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13748 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13749 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13750 nativeLibPath, userId) < 0) { 13751 Slog.w(TAG, "Failed linking native library dir"); 13752 return false; 13753 } 13754 } 13755 13756 return true; 13757 } 13758 13759 /** 13760 * Reverts user permission state changes (permissions and flags) in 13761 * all packages for a given user. 13762 * 13763 * @param userId The device user for which to do a reset. 13764 */ 13765 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13766 final int packageCount = mPackages.size(); 13767 for (int i = 0; i < packageCount; i++) { 13768 PackageParser.Package pkg = mPackages.valueAt(i); 13769 PackageSetting ps = (PackageSetting) pkg.mExtras; 13770 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13771 } 13772 } 13773 13774 /** 13775 * Reverts user permission state changes (permissions and flags). 13776 * 13777 * @param ps The package for which to reset. 13778 * @param userId The device user for which to do a reset. 13779 */ 13780 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13781 final PackageSetting ps, final int userId) { 13782 if (ps.pkg == null) { 13783 return; 13784 } 13785 13786 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13787 | FLAG_PERMISSION_USER_FIXED 13788 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13789 13790 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13791 | FLAG_PERMISSION_POLICY_FIXED; 13792 13793 boolean writeInstallPermissions = false; 13794 boolean writeRuntimePermissions = false; 13795 13796 final int permissionCount = ps.pkg.requestedPermissions.size(); 13797 for (int i = 0; i < permissionCount; i++) { 13798 String permission = ps.pkg.requestedPermissions.get(i); 13799 13800 BasePermission bp = mSettings.mPermissions.get(permission); 13801 if (bp == null) { 13802 continue; 13803 } 13804 13805 // If shared user we just reset the state to which only this app contributed. 13806 if (ps.sharedUser != null) { 13807 boolean used = false; 13808 final int packageCount = ps.sharedUser.packages.size(); 13809 for (int j = 0; j < packageCount; j++) { 13810 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13811 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13812 && pkg.pkg.requestedPermissions.contains(permission)) { 13813 used = true; 13814 break; 13815 } 13816 } 13817 if (used) { 13818 continue; 13819 } 13820 } 13821 13822 PermissionsState permissionsState = ps.getPermissionsState(); 13823 13824 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13825 13826 // Always clear the user settable flags. 13827 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13828 bp.name) != null; 13829 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13830 if (hasInstallState) { 13831 writeInstallPermissions = true; 13832 } else { 13833 writeRuntimePermissions = true; 13834 } 13835 } 13836 13837 // Below is only runtime permission handling. 13838 if (!bp.isRuntime()) { 13839 continue; 13840 } 13841 13842 // Never clobber system or policy. 13843 if ((oldFlags & policyOrSystemFlags) != 0) { 13844 continue; 13845 } 13846 13847 // If this permission was granted by default, make sure it is. 13848 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13849 if (permissionsState.grantRuntimePermission(bp, userId) 13850 != PERMISSION_OPERATION_FAILURE) { 13851 writeRuntimePermissions = true; 13852 } 13853 } else { 13854 // Otherwise, reset the permission. 13855 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13856 switch (revokeResult) { 13857 case PERMISSION_OPERATION_SUCCESS: { 13858 writeRuntimePermissions = true; 13859 } break; 13860 13861 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13862 writeRuntimePermissions = true; 13863 final int appId = ps.appId; 13864 mHandler.post(new Runnable() { 13865 @Override 13866 public void run() { 13867 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13868 } 13869 }); 13870 } break; 13871 } 13872 } 13873 } 13874 13875 // Synchronously write as we are taking permissions away. 13876 if (writeRuntimePermissions) { 13877 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13878 } 13879 13880 // Synchronously write as we are taking permissions away. 13881 if (writeInstallPermissions) { 13882 mSettings.writeLPr(); 13883 } 13884 } 13885 13886 /** 13887 * Remove entries from the keystore daemon. Will only remove it if the 13888 * {@code appId} is valid. 13889 */ 13890 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13891 if (appId < 0) { 13892 return; 13893 } 13894 13895 final KeyStore keyStore = KeyStore.getInstance(); 13896 if (keyStore != null) { 13897 if (userId == UserHandle.USER_ALL) { 13898 for (final int individual : sUserManager.getUserIds()) { 13899 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13900 } 13901 } else { 13902 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13903 } 13904 } else { 13905 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13906 } 13907 } 13908 13909 @Override 13910 public void deleteApplicationCacheFiles(final String packageName, 13911 final IPackageDataObserver observer) { 13912 mContext.enforceCallingOrSelfPermission( 13913 android.Manifest.permission.DELETE_CACHE_FILES, null); 13914 // Queue up an async operation since the package deletion may take a little while. 13915 final int userId = UserHandle.getCallingUserId(); 13916 mHandler.post(new Runnable() { 13917 public void run() { 13918 mHandler.removeCallbacks(this); 13919 final boolean succeded; 13920 synchronized (mInstallLock) { 13921 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13922 } 13923 clearExternalStorageDataSync(packageName, userId, false); 13924 if (observer != null) { 13925 try { 13926 observer.onRemoveCompleted(packageName, succeded); 13927 } catch (RemoteException e) { 13928 Log.i(TAG, "Observer no longer exists."); 13929 } 13930 } //end if observer 13931 } //end run 13932 }); 13933 } 13934 13935 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13936 if (packageName == null) { 13937 Slog.w(TAG, "Attempt to delete null packageName."); 13938 return false; 13939 } 13940 PackageParser.Package p; 13941 synchronized (mPackages) { 13942 p = mPackages.get(packageName); 13943 } 13944 if (p == null) { 13945 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13946 return false; 13947 } 13948 final ApplicationInfo applicationInfo = p.applicationInfo; 13949 if (applicationInfo == null) { 13950 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13951 return false; 13952 } 13953 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13954 if (retCode < 0) { 13955 Slog.w(TAG, "Couldn't remove cache files for package: " 13956 + packageName + " u" + userId); 13957 return false; 13958 } 13959 return true; 13960 } 13961 13962 @Override 13963 public void getPackageSizeInfo(final String packageName, int userHandle, 13964 final IPackageStatsObserver observer) { 13965 mContext.enforceCallingOrSelfPermission( 13966 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13967 if (packageName == null) { 13968 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13969 } 13970 13971 PackageStats stats = new PackageStats(packageName, userHandle); 13972 13973 /* 13974 * Queue up an async operation since the package measurement may take a 13975 * little while. 13976 */ 13977 Message msg = mHandler.obtainMessage(INIT_COPY); 13978 msg.obj = new MeasureParams(stats, observer); 13979 mHandler.sendMessage(msg); 13980 } 13981 13982 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13983 PackageStats pStats) { 13984 if (packageName == null) { 13985 Slog.w(TAG, "Attempt to get size of null packageName."); 13986 return false; 13987 } 13988 PackageParser.Package p; 13989 boolean dataOnly = false; 13990 String libDirRoot = null; 13991 String asecPath = null; 13992 PackageSetting ps = null; 13993 synchronized (mPackages) { 13994 p = mPackages.get(packageName); 13995 ps = mSettings.mPackages.get(packageName); 13996 if(p == null) { 13997 dataOnly = true; 13998 if((ps == null) || (ps.pkg == null)) { 13999 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14000 return false; 14001 } 14002 p = ps.pkg; 14003 } 14004 if (ps != null) { 14005 libDirRoot = ps.legacyNativeLibraryPathString; 14006 } 14007 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14008 final long token = Binder.clearCallingIdentity(); 14009 try { 14010 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14011 if (secureContainerId != null) { 14012 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14013 } 14014 } finally { 14015 Binder.restoreCallingIdentity(token); 14016 } 14017 } 14018 } 14019 String publicSrcDir = null; 14020 if(!dataOnly) { 14021 final ApplicationInfo applicationInfo = p.applicationInfo; 14022 if (applicationInfo == null) { 14023 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14024 return false; 14025 } 14026 if (p.isForwardLocked()) { 14027 publicSrcDir = applicationInfo.getBaseResourcePath(); 14028 } 14029 } 14030 // TODO: extend to measure size of split APKs 14031 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14032 // not just the first level. 14033 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14034 // just the primary. 14035 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14036 14037 String apkPath; 14038 File packageDir = new File(p.codePath); 14039 14040 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14041 apkPath = packageDir.getAbsolutePath(); 14042 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14043 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14044 libDirRoot = null; 14045 } 14046 } else { 14047 apkPath = p.baseCodePath; 14048 } 14049 14050 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14051 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14052 if (res < 0) { 14053 return false; 14054 } 14055 14056 // Fix-up for forward-locked applications in ASEC containers. 14057 if (!isExternal(p)) { 14058 pStats.codeSize += pStats.externalCodeSize; 14059 pStats.externalCodeSize = 0L; 14060 } 14061 14062 return true; 14063 } 14064 14065 14066 @Override 14067 public void addPackageToPreferred(String packageName) { 14068 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14069 } 14070 14071 @Override 14072 public void removePackageFromPreferred(String packageName) { 14073 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14074 } 14075 14076 @Override 14077 public List<PackageInfo> getPreferredPackages(int flags) { 14078 return new ArrayList<PackageInfo>(); 14079 } 14080 14081 private int getUidTargetSdkVersionLockedLPr(int uid) { 14082 Object obj = mSettings.getUserIdLPr(uid); 14083 if (obj instanceof SharedUserSetting) { 14084 final SharedUserSetting sus = (SharedUserSetting) obj; 14085 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14086 final Iterator<PackageSetting> it = sus.packages.iterator(); 14087 while (it.hasNext()) { 14088 final PackageSetting ps = it.next(); 14089 if (ps.pkg != null) { 14090 int v = ps.pkg.applicationInfo.targetSdkVersion; 14091 if (v < vers) vers = v; 14092 } 14093 } 14094 return vers; 14095 } else if (obj instanceof PackageSetting) { 14096 final PackageSetting ps = (PackageSetting) obj; 14097 if (ps.pkg != null) { 14098 return ps.pkg.applicationInfo.targetSdkVersion; 14099 } 14100 } 14101 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14102 } 14103 14104 @Override 14105 public void addPreferredActivity(IntentFilter filter, int match, 14106 ComponentName[] set, ComponentName activity, int userId) { 14107 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14108 "Adding preferred"); 14109 } 14110 14111 private void addPreferredActivityInternal(IntentFilter filter, int match, 14112 ComponentName[] set, ComponentName activity, boolean always, int userId, 14113 String opname) { 14114 // writer 14115 int callingUid = Binder.getCallingUid(); 14116 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14117 if (filter.countActions() == 0) { 14118 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14119 return; 14120 } 14121 synchronized (mPackages) { 14122 if (mContext.checkCallingOrSelfPermission( 14123 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14124 != PackageManager.PERMISSION_GRANTED) { 14125 if (getUidTargetSdkVersionLockedLPr(callingUid) 14126 < Build.VERSION_CODES.FROYO) { 14127 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14128 + callingUid); 14129 return; 14130 } 14131 mContext.enforceCallingOrSelfPermission( 14132 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14133 } 14134 14135 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14136 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14137 + userId + ":"); 14138 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14139 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14140 scheduleWritePackageRestrictionsLocked(userId); 14141 } 14142 } 14143 14144 @Override 14145 public void replacePreferredActivity(IntentFilter filter, int match, 14146 ComponentName[] set, ComponentName activity, int userId) { 14147 if (filter.countActions() != 1) { 14148 throw new IllegalArgumentException( 14149 "replacePreferredActivity expects filter to have only 1 action."); 14150 } 14151 if (filter.countDataAuthorities() != 0 14152 || filter.countDataPaths() != 0 14153 || filter.countDataSchemes() > 1 14154 || filter.countDataTypes() != 0) { 14155 throw new IllegalArgumentException( 14156 "replacePreferredActivity expects filter to have no data authorities, " + 14157 "paths, or types; and at most one scheme."); 14158 } 14159 14160 final int callingUid = Binder.getCallingUid(); 14161 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14162 synchronized (mPackages) { 14163 if (mContext.checkCallingOrSelfPermission( 14164 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14165 != PackageManager.PERMISSION_GRANTED) { 14166 if (getUidTargetSdkVersionLockedLPr(callingUid) 14167 < Build.VERSION_CODES.FROYO) { 14168 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14169 + Binder.getCallingUid()); 14170 return; 14171 } 14172 mContext.enforceCallingOrSelfPermission( 14173 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14174 } 14175 14176 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14177 if (pir != null) { 14178 // Get all of the existing entries that exactly match this filter. 14179 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14180 if (existing != null && existing.size() == 1) { 14181 PreferredActivity cur = existing.get(0); 14182 if (DEBUG_PREFERRED) { 14183 Slog.i(TAG, "Checking replace of preferred:"); 14184 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14185 if (!cur.mPref.mAlways) { 14186 Slog.i(TAG, " -- CUR; not mAlways!"); 14187 } else { 14188 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14189 Slog.i(TAG, " -- CUR: mSet=" 14190 + Arrays.toString(cur.mPref.mSetComponents)); 14191 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14192 Slog.i(TAG, " -- NEW: mMatch=" 14193 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14194 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14195 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14196 } 14197 } 14198 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14199 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14200 && cur.mPref.sameSet(set)) { 14201 // Setting the preferred activity to what it happens to be already 14202 if (DEBUG_PREFERRED) { 14203 Slog.i(TAG, "Replacing with same preferred activity " 14204 + cur.mPref.mShortComponent + " for user " 14205 + userId + ":"); 14206 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14207 } 14208 return; 14209 } 14210 } 14211 14212 if (existing != null) { 14213 if (DEBUG_PREFERRED) { 14214 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14215 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14216 } 14217 for (int i = 0; i < existing.size(); i++) { 14218 PreferredActivity pa = existing.get(i); 14219 if (DEBUG_PREFERRED) { 14220 Slog.i(TAG, "Removing existing preferred activity " 14221 + pa.mPref.mComponent + ":"); 14222 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14223 } 14224 pir.removeFilter(pa); 14225 } 14226 } 14227 } 14228 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14229 "Replacing preferred"); 14230 } 14231 } 14232 14233 @Override 14234 public void clearPackagePreferredActivities(String packageName) { 14235 final int uid = Binder.getCallingUid(); 14236 // writer 14237 synchronized (mPackages) { 14238 PackageParser.Package pkg = mPackages.get(packageName); 14239 if (pkg == null || pkg.applicationInfo.uid != uid) { 14240 if (mContext.checkCallingOrSelfPermission( 14241 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14242 != PackageManager.PERMISSION_GRANTED) { 14243 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14244 < Build.VERSION_CODES.FROYO) { 14245 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14246 + Binder.getCallingUid()); 14247 return; 14248 } 14249 mContext.enforceCallingOrSelfPermission( 14250 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14251 } 14252 } 14253 14254 int user = UserHandle.getCallingUserId(); 14255 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14256 scheduleWritePackageRestrictionsLocked(user); 14257 } 14258 } 14259 } 14260 14261 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14262 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14263 ArrayList<PreferredActivity> removed = null; 14264 boolean changed = false; 14265 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14266 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14267 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14268 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14269 continue; 14270 } 14271 Iterator<PreferredActivity> it = pir.filterIterator(); 14272 while (it.hasNext()) { 14273 PreferredActivity pa = it.next(); 14274 // Mark entry for removal only if it matches the package name 14275 // and the entry is of type "always". 14276 if (packageName == null || 14277 (pa.mPref.mComponent.getPackageName().equals(packageName) 14278 && pa.mPref.mAlways)) { 14279 if (removed == null) { 14280 removed = new ArrayList<PreferredActivity>(); 14281 } 14282 removed.add(pa); 14283 } 14284 } 14285 if (removed != null) { 14286 for (int j=0; j<removed.size(); j++) { 14287 PreferredActivity pa = removed.get(j); 14288 pir.removeFilter(pa); 14289 } 14290 changed = true; 14291 } 14292 } 14293 return changed; 14294 } 14295 14296 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14297 private void clearIntentFilterVerificationsLPw(int userId) { 14298 final int packageCount = mPackages.size(); 14299 for (int i = 0; i < packageCount; i++) { 14300 PackageParser.Package pkg = mPackages.valueAt(i); 14301 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14302 } 14303 } 14304 14305 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14306 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14307 if (userId == UserHandle.USER_ALL) { 14308 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14309 sUserManager.getUserIds())) { 14310 for (int oneUserId : sUserManager.getUserIds()) { 14311 scheduleWritePackageRestrictionsLocked(oneUserId); 14312 } 14313 } 14314 } else { 14315 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14316 scheduleWritePackageRestrictionsLocked(userId); 14317 } 14318 } 14319 } 14320 14321 void clearDefaultBrowserIfNeeded(String packageName) { 14322 for (int oneUserId : sUserManager.getUserIds()) { 14323 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14324 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14325 if (packageName.equals(defaultBrowserPackageName)) { 14326 setDefaultBrowserPackageName(null, oneUserId); 14327 } 14328 } 14329 } 14330 14331 @Override 14332 public void resetApplicationPreferences(int userId) { 14333 mContext.enforceCallingOrSelfPermission( 14334 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14335 // writer 14336 synchronized (mPackages) { 14337 final long identity = Binder.clearCallingIdentity(); 14338 try { 14339 clearPackagePreferredActivitiesLPw(null, userId); 14340 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14341 // TODO: We have to reset the default SMS and Phone. This requires 14342 // significant refactoring to keep all default apps in the package 14343 // manager (cleaner but more work) or have the services provide 14344 // callbacks to the package manager to request a default app reset. 14345 applyFactoryDefaultBrowserLPw(userId); 14346 clearIntentFilterVerificationsLPw(userId); 14347 primeDomainVerificationsLPw(userId); 14348 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14349 scheduleWritePackageRestrictionsLocked(userId); 14350 } finally { 14351 Binder.restoreCallingIdentity(identity); 14352 } 14353 } 14354 } 14355 14356 @Override 14357 public int getPreferredActivities(List<IntentFilter> outFilters, 14358 List<ComponentName> outActivities, String packageName) { 14359 14360 int num = 0; 14361 final int userId = UserHandle.getCallingUserId(); 14362 // reader 14363 synchronized (mPackages) { 14364 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14365 if (pir != null) { 14366 final Iterator<PreferredActivity> it = pir.filterIterator(); 14367 while (it.hasNext()) { 14368 final PreferredActivity pa = it.next(); 14369 if (packageName == null 14370 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14371 && pa.mPref.mAlways)) { 14372 if (outFilters != null) { 14373 outFilters.add(new IntentFilter(pa)); 14374 } 14375 if (outActivities != null) { 14376 outActivities.add(pa.mPref.mComponent); 14377 } 14378 } 14379 } 14380 } 14381 } 14382 14383 return num; 14384 } 14385 14386 @Override 14387 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14388 int userId) { 14389 int callingUid = Binder.getCallingUid(); 14390 if (callingUid != Process.SYSTEM_UID) { 14391 throw new SecurityException( 14392 "addPersistentPreferredActivity can only be run by the system"); 14393 } 14394 if (filter.countActions() == 0) { 14395 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14396 return; 14397 } 14398 synchronized (mPackages) { 14399 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14400 " :"); 14401 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14402 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14403 new PersistentPreferredActivity(filter, activity)); 14404 scheduleWritePackageRestrictionsLocked(userId); 14405 } 14406 } 14407 14408 @Override 14409 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14410 int callingUid = Binder.getCallingUid(); 14411 if (callingUid != Process.SYSTEM_UID) { 14412 throw new SecurityException( 14413 "clearPackagePersistentPreferredActivities can only be run by the system"); 14414 } 14415 ArrayList<PersistentPreferredActivity> removed = null; 14416 boolean changed = false; 14417 synchronized (mPackages) { 14418 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14419 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14420 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14421 .valueAt(i); 14422 if (userId != thisUserId) { 14423 continue; 14424 } 14425 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14426 while (it.hasNext()) { 14427 PersistentPreferredActivity ppa = it.next(); 14428 // Mark entry for removal only if it matches the package name. 14429 if (ppa.mComponent.getPackageName().equals(packageName)) { 14430 if (removed == null) { 14431 removed = new ArrayList<PersistentPreferredActivity>(); 14432 } 14433 removed.add(ppa); 14434 } 14435 } 14436 if (removed != null) { 14437 for (int j=0; j<removed.size(); j++) { 14438 PersistentPreferredActivity ppa = removed.get(j); 14439 ppir.removeFilter(ppa); 14440 } 14441 changed = true; 14442 } 14443 } 14444 14445 if (changed) { 14446 scheduleWritePackageRestrictionsLocked(userId); 14447 } 14448 } 14449 } 14450 14451 /** 14452 * Common machinery for picking apart a restored XML blob and passing 14453 * it to a caller-supplied functor to be applied to the running system. 14454 */ 14455 private void restoreFromXml(XmlPullParser parser, int userId, 14456 String expectedStartTag, BlobXmlRestorer functor) 14457 throws IOException, XmlPullParserException { 14458 int type; 14459 while ((type = parser.next()) != XmlPullParser.START_TAG 14460 && type != XmlPullParser.END_DOCUMENT) { 14461 } 14462 if (type != XmlPullParser.START_TAG) { 14463 // oops didn't find a start tag?! 14464 if (DEBUG_BACKUP) { 14465 Slog.e(TAG, "Didn't find start tag during restore"); 14466 } 14467 return; 14468 } 14469 14470 // this is supposed to be TAG_PREFERRED_BACKUP 14471 if (!expectedStartTag.equals(parser.getName())) { 14472 if (DEBUG_BACKUP) { 14473 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14474 } 14475 return; 14476 } 14477 14478 // skip interfering stuff, then we're aligned with the backing implementation 14479 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14480 functor.apply(parser, userId); 14481 } 14482 14483 private interface BlobXmlRestorer { 14484 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14485 } 14486 14487 /** 14488 * Non-Binder method, support for the backup/restore mechanism: write the 14489 * full set of preferred activities in its canonical XML format. Returns the 14490 * XML output as a byte array, or null if there is none. 14491 */ 14492 @Override 14493 public byte[] getPreferredActivityBackup(int userId) { 14494 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14495 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14496 } 14497 14498 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14499 try { 14500 final XmlSerializer serializer = new FastXmlSerializer(); 14501 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14502 serializer.startDocument(null, true); 14503 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14504 14505 synchronized (mPackages) { 14506 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14507 } 14508 14509 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14510 serializer.endDocument(); 14511 serializer.flush(); 14512 } catch (Exception e) { 14513 if (DEBUG_BACKUP) { 14514 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14515 } 14516 return null; 14517 } 14518 14519 return dataStream.toByteArray(); 14520 } 14521 14522 @Override 14523 public void restorePreferredActivities(byte[] backup, int userId) { 14524 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14525 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14526 } 14527 14528 try { 14529 final XmlPullParser parser = Xml.newPullParser(); 14530 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14531 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14532 new BlobXmlRestorer() { 14533 @Override 14534 public void apply(XmlPullParser parser, int userId) 14535 throws XmlPullParserException, IOException { 14536 synchronized (mPackages) { 14537 mSettings.readPreferredActivitiesLPw(parser, userId); 14538 } 14539 } 14540 } ); 14541 } catch (Exception e) { 14542 if (DEBUG_BACKUP) { 14543 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14544 } 14545 } 14546 } 14547 14548 /** 14549 * Non-Binder method, support for the backup/restore mechanism: write the 14550 * default browser (etc) settings in its canonical XML format. Returns the default 14551 * browser XML representation as a byte array, or null if there is none. 14552 */ 14553 @Override 14554 public byte[] getDefaultAppsBackup(int userId) { 14555 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14556 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14557 } 14558 14559 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14560 try { 14561 final XmlSerializer serializer = new FastXmlSerializer(); 14562 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14563 serializer.startDocument(null, true); 14564 serializer.startTag(null, TAG_DEFAULT_APPS); 14565 14566 synchronized (mPackages) { 14567 mSettings.writeDefaultAppsLPr(serializer, userId); 14568 } 14569 14570 serializer.endTag(null, TAG_DEFAULT_APPS); 14571 serializer.endDocument(); 14572 serializer.flush(); 14573 } catch (Exception e) { 14574 if (DEBUG_BACKUP) { 14575 Slog.e(TAG, "Unable to write default apps for backup", e); 14576 } 14577 return null; 14578 } 14579 14580 return dataStream.toByteArray(); 14581 } 14582 14583 @Override 14584 public void restoreDefaultApps(byte[] backup, int userId) { 14585 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14586 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14587 } 14588 14589 try { 14590 final XmlPullParser parser = Xml.newPullParser(); 14591 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14592 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14593 new BlobXmlRestorer() { 14594 @Override 14595 public void apply(XmlPullParser parser, int userId) 14596 throws XmlPullParserException, IOException { 14597 synchronized (mPackages) { 14598 mSettings.readDefaultAppsLPw(parser, userId); 14599 } 14600 } 14601 } ); 14602 } catch (Exception e) { 14603 if (DEBUG_BACKUP) { 14604 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14605 } 14606 } 14607 } 14608 14609 @Override 14610 public byte[] getIntentFilterVerificationBackup(int userId) { 14611 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14612 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14613 } 14614 14615 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14616 try { 14617 final XmlSerializer serializer = new FastXmlSerializer(); 14618 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14619 serializer.startDocument(null, true); 14620 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14621 14622 synchronized (mPackages) { 14623 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14624 } 14625 14626 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14627 serializer.endDocument(); 14628 serializer.flush(); 14629 } catch (Exception e) { 14630 if (DEBUG_BACKUP) { 14631 Slog.e(TAG, "Unable to write default apps for backup", e); 14632 } 14633 return null; 14634 } 14635 14636 return dataStream.toByteArray(); 14637 } 14638 14639 @Override 14640 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14641 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14642 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14643 } 14644 14645 try { 14646 final XmlPullParser parser = Xml.newPullParser(); 14647 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14648 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14649 new BlobXmlRestorer() { 14650 @Override 14651 public void apply(XmlPullParser parser, int userId) 14652 throws XmlPullParserException, IOException { 14653 synchronized (mPackages) { 14654 mSettings.readAllDomainVerificationsLPr(parser, userId); 14655 mSettings.writeLPr(); 14656 } 14657 } 14658 } ); 14659 } catch (Exception e) { 14660 if (DEBUG_BACKUP) { 14661 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14662 } 14663 } 14664 } 14665 14666 @Override 14667 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14668 int sourceUserId, int targetUserId, int flags) { 14669 mContext.enforceCallingOrSelfPermission( 14670 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14671 int callingUid = Binder.getCallingUid(); 14672 enforceOwnerRights(ownerPackage, callingUid); 14673 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14674 if (intentFilter.countActions() == 0) { 14675 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14676 return; 14677 } 14678 synchronized (mPackages) { 14679 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14680 ownerPackage, targetUserId, flags); 14681 CrossProfileIntentResolver resolver = 14682 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14683 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14684 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14685 if (existing != null) { 14686 int size = existing.size(); 14687 for (int i = 0; i < size; i++) { 14688 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14689 return; 14690 } 14691 } 14692 } 14693 resolver.addFilter(newFilter); 14694 scheduleWritePackageRestrictionsLocked(sourceUserId); 14695 } 14696 } 14697 14698 @Override 14699 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14700 mContext.enforceCallingOrSelfPermission( 14701 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14702 int callingUid = Binder.getCallingUid(); 14703 enforceOwnerRights(ownerPackage, callingUid); 14704 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14705 synchronized (mPackages) { 14706 CrossProfileIntentResolver resolver = 14707 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14708 ArraySet<CrossProfileIntentFilter> set = 14709 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14710 for (CrossProfileIntentFilter filter : set) { 14711 if (filter.getOwnerPackage().equals(ownerPackage)) { 14712 resolver.removeFilter(filter); 14713 } 14714 } 14715 scheduleWritePackageRestrictionsLocked(sourceUserId); 14716 } 14717 } 14718 14719 // Enforcing that callingUid is owning pkg on userId 14720 private void enforceOwnerRights(String pkg, int callingUid) { 14721 // The system owns everything. 14722 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14723 return; 14724 } 14725 int callingUserId = UserHandle.getUserId(callingUid); 14726 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14727 if (pi == null) { 14728 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14729 + callingUserId); 14730 } 14731 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14732 throw new SecurityException("Calling uid " + callingUid 14733 + " does not own package " + pkg); 14734 } 14735 } 14736 14737 @Override 14738 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14739 Intent intent = new Intent(Intent.ACTION_MAIN); 14740 intent.addCategory(Intent.CATEGORY_HOME); 14741 14742 final int callingUserId = UserHandle.getCallingUserId(); 14743 List<ResolveInfo> list = queryIntentActivities(intent, null, 14744 PackageManager.GET_META_DATA, callingUserId); 14745 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14746 true, false, false, callingUserId); 14747 14748 allHomeCandidates.clear(); 14749 if (list != null) { 14750 for (ResolveInfo ri : list) { 14751 allHomeCandidates.add(ri); 14752 } 14753 } 14754 return (preferred == null || preferred.activityInfo == null) 14755 ? null 14756 : new ComponentName(preferred.activityInfo.packageName, 14757 preferred.activityInfo.name); 14758 } 14759 14760 @Override 14761 public void setApplicationEnabledSetting(String appPackageName, 14762 int newState, int flags, int userId, String callingPackage) { 14763 if (!sUserManager.exists(userId)) return; 14764 if (callingPackage == null) { 14765 callingPackage = Integer.toString(Binder.getCallingUid()); 14766 } 14767 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14768 } 14769 14770 @Override 14771 public void setComponentEnabledSetting(ComponentName componentName, 14772 int newState, int flags, int userId) { 14773 if (!sUserManager.exists(userId)) return; 14774 setEnabledSetting(componentName.getPackageName(), 14775 componentName.getClassName(), newState, flags, userId, null); 14776 } 14777 14778 private void setEnabledSetting(final String packageName, String className, int newState, 14779 final int flags, int userId, String callingPackage) { 14780 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14781 || newState == COMPONENT_ENABLED_STATE_ENABLED 14782 || newState == COMPONENT_ENABLED_STATE_DISABLED 14783 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14784 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14785 throw new IllegalArgumentException("Invalid new component state: " 14786 + newState); 14787 } 14788 PackageSetting pkgSetting; 14789 final int uid = Binder.getCallingUid(); 14790 final int permission = mContext.checkCallingOrSelfPermission( 14791 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14792 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14793 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14794 boolean sendNow = false; 14795 boolean isApp = (className == null); 14796 String componentName = isApp ? packageName : className; 14797 int packageUid = -1; 14798 ArrayList<String> components; 14799 14800 // writer 14801 synchronized (mPackages) { 14802 pkgSetting = mSettings.mPackages.get(packageName); 14803 if (pkgSetting == null) { 14804 if (className == null) { 14805 throw new IllegalArgumentException( 14806 "Unknown package: " + packageName); 14807 } 14808 throw new IllegalArgumentException( 14809 "Unknown component: " + packageName 14810 + "/" + className); 14811 } 14812 // Allow root and verify that userId is not being specified by a different user 14813 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14814 throw new SecurityException( 14815 "Permission Denial: attempt to change component state from pid=" 14816 + Binder.getCallingPid() 14817 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14818 } 14819 if (className == null) { 14820 // We're dealing with an application/package level state change 14821 if (pkgSetting.getEnabled(userId) == newState) { 14822 // Nothing to do 14823 return; 14824 } 14825 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14826 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14827 // Don't care about who enables an app. 14828 callingPackage = null; 14829 } 14830 pkgSetting.setEnabled(newState, userId, callingPackage); 14831 // pkgSetting.pkg.mSetEnabled = newState; 14832 } else { 14833 // We're dealing with a component level state change 14834 // First, verify that this is a valid class name. 14835 PackageParser.Package pkg = pkgSetting.pkg; 14836 if (pkg == null || !pkg.hasComponentClassName(className)) { 14837 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14838 throw new IllegalArgumentException("Component class " + className 14839 + " does not exist in " + packageName); 14840 } else { 14841 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14842 + className + " does not exist in " + packageName); 14843 } 14844 } 14845 switch (newState) { 14846 case COMPONENT_ENABLED_STATE_ENABLED: 14847 if (!pkgSetting.enableComponentLPw(className, userId)) { 14848 return; 14849 } 14850 break; 14851 case COMPONENT_ENABLED_STATE_DISABLED: 14852 if (!pkgSetting.disableComponentLPw(className, userId)) { 14853 return; 14854 } 14855 break; 14856 case COMPONENT_ENABLED_STATE_DEFAULT: 14857 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14858 return; 14859 } 14860 break; 14861 default: 14862 Slog.e(TAG, "Invalid new component state: " + newState); 14863 return; 14864 } 14865 } 14866 scheduleWritePackageRestrictionsLocked(userId); 14867 components = mPendingBroadcasts.get(userId, packageName); 14868 final boolean newPackage = components == null; 14869 if (newPackage) { 14870 components = new ArrayList<String>(); 14871 } 14872 if (!components.contains(componentName)) { 14873 components.add(componentName); 14874 } 14875 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14876 sendNow = true; 14877 // Purge entry from pending broadcast list if another one exists already 14878 // since we are sending one right away. 14879 mPendingBroadcasts.remove(userId, packageName); 14880 } else { 14881 if (newPackage) { 14882 mPendingBroadcasts.put(userId, packageName, components); 14883 } 14884 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14885 // Schedule a message 14886 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14887 } 14888 } 14889 } 14890 14891 long callingId = Binder.clearCallingIdentity(); 14892 try { 14893 if (sendNow) { 14894 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14895 sendPackageChangedBroadcast(packageName, 14896 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14897 } 14898 } finally { 14899 Binder.restoreCallingIdentity(callingId); 14900 } 14901 } 14902 14903 private void sendPackageChangedBroadcast(String packageName, 14904 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14905 if (DEBUG_INSTALL) 14906 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14907 + componentNames); 14908 Bundle extras = new Bundle(4); 14909 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14910 String nameList[] = new String[componentNames.size()]; 14911 componentNames.toArray(nameList); 14912 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14913 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14914 extras.putInt(Intent.EXTRA_UID, packageUid); 14915 // If this is not reporting a change of the overall package, then only send it 14916 // to registered receivers. We don't want to launch a swath of apps for every 14917 // little component state change. 14918 final int flags = !componentNames.contains(packageName) 14919 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 14920 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 14921 new int[] {UserHandle.getUserId(packageUid)}); 14922 } 14923 14924 @Override 14925 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14926 if (!sUserManager.exists(userId)) return; 14927 final int uid = Binder.getCallingUid(); 14928 final int permission = mContext.checkCallingOrSelfPermission( 14929 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14930 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14931 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14932 // writer 14933 synchronized (mPackages) { 14934 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14935 allowedByPermission, uid, userId)) { 14936 scheduleWritePackageRestrictionsLocked(userId); 14937 } 14938 } 14939 } 14940 14941 @Override 14942 public String getInstallerPackageName(String packageName) { 14943 // reader 14944 synchronized (mPackages) { 14945 return mSettings.getInstallerPackageNameLPr(packageName); 14946 } 14947 } 14948 14949 @Override 14950 public int getApplicationEnabledSetting(String packageName, int userId) { 14951 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14952 int uid = Binder.getCallingUid(); 14953 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14954 // reader 14955 synchronized (mPackages) { 14956 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14957 } 14958 } 14959 14960 @Override 14961 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14962 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14963 int uid = Binder.getCallingUid(); 14964 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14965 // reader 14966 synchronized (mPackages) { 14967 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14968 } 14969 } 14970 14971 @Override 14972 public void enterSafeMode() { 14973 enforceSystemOrRoot("Only the system can request entering safe mode"); 14974 14975 if (!mSystemReady) { 14976 mSafeMode = true; 14977 } 14978 } 14979 14980 @Override 14981 public void systemReady() { 14982 mSystemReady = true; 14983 14984 // Read the compatibilty setting when the system is ready. 14985 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14986 mContext.getContentResolver(), 14987 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14988 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14989 if (DEBUG_SETTINGS) { 14990 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14991 } 14992 14993 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14994 14995 synchronized (mPackages) { 14996 // Verify that all of the preferred activity components actually 14997 // exist. It is possible for applications to be updated and at 14998 // that point remove a previously declared activity component that 14999 // had been set as a preferred activity. We try to clean this up 15000 // the next time we encounter that preferred activity, but it is 15001 // possible for the user flow to never be able to return to that 15002 // situation so here we do a sanity check to make sure we haven't 15003 // left any junk around. 15004 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15005 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15006 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15007 removed.clear(); 15008 for (PreferredActivity pa : pir.filterSet()) { 15009 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15010 removed.add(pa); 15011 } 15012 } 15013 if (removed.size() > 0) { 15014 for (int r=0; r<removed.size(); r++) { 15015 PreferredActivity pa = removed.get(r); 15016 Slog.w(TAG, "Removing dangling preferred activity: " 15017 + pa.mPref.mComponent); 15018 pir.removeFilter(pa); 15019 } 15020 mSettings.writePackageRestrictionsLPr( 15021 mSettings.mPreferredActivities.keyAt(i)); 15022 } 15023 } 15024 15025 for (int userId : UserManagerService.getInstance().getUserIds()) { 15026 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15027 grantPermissionsUserIds = ArrayUtils.appendInt( 15028 grantPermissionsUserIds, userId); 15029 } 15030 } 15031 } 15032 sUserManager.systemReady(); 15033 15034 // If we upgraded grant all default permissions before kicking off. 15035 for (int userId : grantPermissionsUserIds) { 15036 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15037 } 15038 15039 // Kick off any messages waiting for system ready 15040 if (mPostSystemReadyMessages != null) { 15041 for (Message msg : mPostSystemReadyMessages) { 15042 msg.sendToTarget(); 15043 } 15044 mPostSystemReadyMessages = null; 15045 } 15046 15047 // Watch for external volumes that come and go over time 15048 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15049 storage.registerListener(mStorageListener); 15050 15051 mInstallerService.systemReady(); 15052 mPackageDexOptimizer.systemReady(); 15053 15054 MountServiceInternal mountServiceInternal = LocalServices.getService( 15055 MountServiceInternal.class); 15056 mountServiceInternal.addExternalStoragePolicy( 15057 new MountServiceInternal.ExternalStorageMountPolicy() { 15058 @Override 15059 public int getMountMode(int uid, String packageName) { 15060 if (Process.isIsolated(uid)) { 15061 return Zygote.MOUNT_EXTERNAL_NONE; 15062 } 15063 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15064 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15065 } 15066 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15067 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15068 } 15069 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15070 return Zygote.MOUNT_EXTERNAL_READ; 15071 } 15072 return Zygote.MOUNT_EXTERNAL_WRITE; 15073 } 15074 15075 @Override 15076 public boolean hasExternalStorage(int uid, String packageName) { 15077 return true; 15078 } 15079 }); 15080 } 15081 15082 @Override 15083 public boolean isSafeMode() { 15084 return mSafeMode; 15085 } 15086 15087 @Override 15088 public boolean hasSystemUidErrors() { 15089 return mHasSystemUidErrors; 15090 } 15091 15092 static String arrayToString(int[] array) { 15093 StringBuffer buf = new StringBuffer(128); 15094 buf.append('['); 15095 if (array != null) { 15096 for (int i=0; i<array.length; i++) { 15097 if (i > 0) buf.append(", "); 15098 buf.append(array[i]); 15099 } 15100 } 15101 buf.append(']'); 15102 return buf.toString(); 15103 } 15104 15105 static class DumpState { 15106 public static final int DUMP_LIBS = 1 << 0; 15107 public static final int DUMP_FEATURES = 1 << 1; 15108 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15109 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15110 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15111 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15112 public static final int DUMP_PERMISSIONS = 1 << 6; 15113 public static final int DUMP_PACKAGES = 1 << 7; 15114 public static final int DUMP_SHARED_USERS = 1 << 8; 15115 public static final int DUMP_MESSAGES = 1 << 9; 15116 public static final int DUMP_PROVIDERS = 1 << 10; 15117 public static final int DUMP_VERIFIERS = 1 << 11; 15118 public static final int DUMP_PREFERRED = 1 << 12; 15119 public static final int DUMP_PREFERRED_XML = 1 << 13; 15120 public static final int DUMP_KEYSETS = 1 << 14; 15121 public static final int DUMP_VERSION = 1 << 15; 15122 public static final int DUMP_INSTALLS = 1 << 16; 15123 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15124 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15125 15126 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15127 15128 private int mTypes; 15129 15130 private int mOptions; 15131 15132 private boolean mTitlePrinted; 15133 15134 private SharedUserSetting mSharedUser; 15135 15136 public boolean isDumping(int type) { 15137 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15138 return true; 15139 } 15140 15141 return (mTypes & type) != 0; 15142 } 15143 15144 public void setDump(int type) { 15145 mTypes |= type; 15146 } 15147 15148 public boolean isOptionEnabled(int option) { 15149 return (mOptions & option) != 0; 15150 } 15151 15152 public void setOptionEnabled(int option) { 15153 mOptions |= option; 15154 } 15155 15156 public boolean onTitlePrinted() { 15157 final boolean printed = mTitlePrinted; 15158 mTitlePrinted = true; 15159 return printed; 15160 } 15161 15162 public boolean getTitlePrinted() { 15163 return mTitlePrinted; 15164 } 15165 15166 public void setTitlePrinted(boolean enabled) { 15167 mTitlePrinted = enabled; 15168 } 15169 15170 public SharedUserSetting getSharedUser() { 15171 return mSharedUser; 15172 } 15173 15174 public void setSharedUser(SharedUserSetting user) { 15175 mSharedUser = user; 15176 } 15177 } 15178 15179 @Override 15180 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15181 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15182 (new PackageManagerShellCommand(this)).exec( 15183 this, in, out, err, args, resultReceiver); 15184 } 15185 15186 @Override 15187 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15188 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15189 != PackageManager.PERMISSION_GRANTED) { 15190 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15191 + Binder.getCallingPid() 15192 + ", uid=" + Binder.getCallingUid() 15193 + " without permission " 15194 + android.Manifest.permission.DUMP); 15195 return; 15196 } 15197 15198 DumpState dumpState = new DumpState(); 15199 boolean fullPreferred = false; 15200 boolean checkin = false; 15201 15202 String packageName = null; 15203 ArraySet<String> permissionNames = null; 15204 15205 int opti = 0; 15206 while (opti < args.length) { 15207 String opt = args[opti]; 15208 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15209 break; 15210 } 15211 opti++; 15212 15213 if ("-a".equals(opt)) { 15214 // Right now we only know how to print all. 15215 } else if ("-h".equals(opt)) { 15216 pw.println("Package manager dump options:"); 15217 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15218 pw.println(" --checkin: dump for a checkin"); 15219 pw.println(" -f: print details of intent filters"); 15220 pw.println(" -h: print this help"); 15221 pw.println(" cmd may be one of:"); 15222 pw.println(" l[ibraries]: list known shared libraries"); 15223 pw.println(" f[eatures]: list device features"); 15224 pw.println(" k[eysets]: print known keysets"); 15225 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15226 pw.println(" perm[issions]: dump permissions"); 15227 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15228 pw.println(" pref[erred]: print preferred package settings"); 15229 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15230 pw.println(" prov[iders]: dump content providers"); 15231 pw.println(" p[ackages]: dump installed packages"); 15232 pw.println(" s[hared-users]: dump shared user IDs"); 15233 pw.println(" m[essages]: print collected runtime messages"); 15234 pw.println(" v[erifiers]: print package verifier info"); 15235 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15236 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15237 pw.println(" version: print database version info"); 15238 pw.println(" write: write current settings now"); 15239 pw.println(" installs: details about install sessions"); 15240 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15241 pw.println(" <package.name>: info about given package"); 15242 return; 15243 } else if ("--checkin".equals(opt)) { 15244 checkin = true; 15245 } else if ("-f".equals(opt)) { 15246 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15247 } else { 15248 pw.println("Unknown argument: " + opt + "; use -h for help"); 15249 } 15250 } 15251 15252 // Is the caller requesting to dump a particular piece of data? 15253 if (opti < args.length) { 15254 String cmd = args[opti]; 15255 opti++; 15256 // Is this a package name? 15257 if ("android".equals(cmd) || cmd.contains(".")) { 15258 packageName = cmd; 15259 // When dumping a single package, we always dump all of its 15260 // filter information since the amount of data will be reasonable. 15261 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15262 } else if ("check-permission".equals(cmd)) { 15263 if (opti >= args.length) { 15264 pw.println("Error: check-permission missing permission argument"); 15265 return; 15266 } 15267 String perm = args[opti]; 15268 opti++; 15269 if (opti >= args.length) { 15270 pw.println("Error: check-permission missing package argument"); 15271 return; 15272 } 15273 String pkg = args[opti]; 15274 opti++; 15275 int user = UserHandle.getUserId(Binder.getCallingUid()); 15276 if (opti < args.length) { 15277 try { 15278 user = Integer.parseInt(args[opti]); 15279 } catch (NumberFormatException e) { 15280 pw.println("Error: check-permission user argument is not a number: " 15281 + args[opti]); 15282 return; 15283 } 15284 } 15285 pw.println(checkPermission(perm, pkg, user)); 15286 return; 15287 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15288 dumpState.setDump(DumpState.DUMP_LIBS); 15289 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15290 dumpState.setDump(DumpState.DUMP_FEATURES); 15291 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15292 if (opti >= args.length) { 15293 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15294 | DumpState.DUMP_SERVICE_RESOLVERS 15295 | DumpState.DUMP_RECEIVER_RESOLVERS 15296 | DumpState.DUMP_CONTENT_RESOLVERS); 15297 } else { 15298 while (opti < args.length) { 15299 String name = args[opti]; 15300 if ("a".equals(name) || "activity".equals(name)) { 15301 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15302 } else if ("s".equals(name) || "service".equals(name)) { 15303 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15304 } else if ("r".equals(name) || "receiver".equals(name)) { 15305 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15306 } else if ("c".equals(name) || "content".equals(name)) { 15307 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15308 } else { 15309 pw.println("Error: unknown resolver table type: " + name); 15310 return; 15311 } 15312 opti++; 15313 } 15314 } 15315 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15316 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15317 } else if ("permission".equals(cmd)) { 15318 if (opti >= args.length) { 15319 pw.println("Error: permission requires permission name"); 15320 return; 15321 } 15322 permissionNames = new ArraySet<>(); 15323 while (opti < args.length) { 15324 permissionNames.add(args[opti]); 15325 opti++; 15326 } 15327 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15328 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15329 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15330 dumpState.setDump(DumpState.DUMP_PREFERRED); 15331 } else if ("preferred-xml".equals(cmd)) { 15332 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15333 if (opti < args.length && "--full".equals(args[opti])) { 15334 fullPreferred = true; 15335 opti++; 15336 } 15337 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15338 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15339 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15340 dumpState.setDump(DumpState.DUMP_PACKAGES); 15341 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15342 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15343 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15344 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15345 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15346 dumpState.setDump(DumpState.DUMP_MESSAGES); 15347 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15348 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15349 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15350 || "intent-filter-verifiers".equals(cmd)) { 15351 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15352 } else if ("version".equals(cmd)) { 15353 dumpState.setDump(DumpState.DUMP_VERSION); 15354 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15355 dumpState.setDump(DumpState.DUMP_KEYSETS); 15356 } else if ("installs".equals(cmd)) { 15357 dumpState.setDump(DumpState.DUMP_INSTALLS); 15358 } else if ("write".equals(cmd)) { 15359 synchronized (mPackages) { 15360 mSettings.writeLPr(); 15361 pw.println("Settings written."); 15362 return; 15363 } 15364 } 15365 } 15366 15367 if (checkin) { 15368 pw.println("vers,1"); 15369 } 15370 15371 // reader 15372 synchronized (mPackages) { 15373 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15374 if (!checkin) { 15375 if (dumpState.onTitlePrinted()) 15376 pw.println(); 15377 pw.println("Database versions:"); 15378 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15379 } 15380 } 15381 15382 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15383 if (!checkin) { 15384 if (dumpState.onTitlePrinted()) 15385 pw.println(); 15386 pw.println("Verifiers:"); 15387 pw.print(" Required: "); 15388 pw.print(mRequiredVerifierPackage); 15389 pw.print(" (uid="); 15390 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15391 pw.println(")"); 15392 } else if (mRequiredVerifierPackage != null) { 15393 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15394 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15395 } 15396 } 15397 15398 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15399 packageName == null) { 15400 if (mIntentFilterVerifierComponent != null) { 15401 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15402 if (!checkin) { 15403 if (dumpState.onTitlePrinted()) 15404 pw.println(); 15405 pw.println("Intent Filter Verifier:"); 15406 pw.print(" Using: "); 15407 pw.print(verifierPackageName); 15408 pw.print(" (uid="); 15409 pw.print(getPackageUid(verifierPackageName, 0)); 15410 pw.println(")"); 15411 } else if (verifierPackageName != null) { 15412 pw.print("ifv,"); pw.print(verifierPackageName); 15413 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15414 } 15415 } else { 15416 pw.println(); 15417 pw.println("No Intent Filter Verifier available!"); 15418 } 15419 } 15420 15421 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15422 boolean printedHeader = false; 15423 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15424 while (it.hasNext()) { 15425 String name = it.next(); 15426 SharedLibraryEntry ent = mSharedLibraries.get(name); 15427 if (!checkin) { 15428 if (!printedHeader) { 15429 if (dumpState.onTitlePrinted()) 15430 pw.println(); 15431 pw.println("Libraries:"); 15432 printedHeader = true; 15433 } 15434 pw.print(" "); 15435 } else { 15436 pw.print("lib,"); 15437 } 15438 pw.print(name); 15439 if (!checkin) { 15440 pw.print(" -> "); 15441 } 15442 if (ent.path != null) { 15443 if (!checkin) { 15444 pw.print("(jar) "); 15445 pw.print(ent.path); 15446 } else { 15447 pw.print(",jar,"); 15448 pw.print(ent.path); 15449 } 15450 } else { 15451 if (!checkin) { 15452 pw.print("(apk) "); 15453 pw.print(ent.apk); 15454 } else { 15455 pw.print(",apk,"); 15456 pw.print(ent.apk); 15457 } 15458 } 15459 pw.println(); 15460 } 15461 } 15462 15463 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15464 if (dumpState.onTitlePrinted()) 15465 pw.println(); 15466 if (!checkin) { 15467 pw.println("Features:"); 15468 } 15469 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15470 while (it.hasNext()) { 15471 String name = it.next(); 15472 if (!checkin) { 15473 pw.print(" "); 15474 } else { 15475 pw.print("feat,"); 15476 } 15477 pw.println(name); 15478 } 15479 } 15480 15481 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15482 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15483 : "Activity Resolver Table:", " ", packageName, 15484 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15485 dumpState.setTitlePrinted(true); 15486 } 15487 } 15488 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15489 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15490 : "Receiver Resolver Table:", " ", packageName, 15491 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15492 dumpState.setTitlePrinted(true); 15493 } 15494 } 15495 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15496 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15497 : "Service Resolver Table:", " ", packageName, 15498 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15499 dumpState.setTitlePrinted(true); 15500 } 15501 } 15502 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15503 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15504 : "Provider Resolver Table:", " ", packageName, 15505 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15506 dumpState.setTitlePrinted(true); 15507 } 15508 } 15509 15510 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15511 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15512 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15513 int user = mSettings.mPreferredActivities.keyAt(i); 15514 if (pir.dump(pw, 15515 dumpState.getTitlePrinted() 15516 ? "\nPreferred Activities User " + user + ":" 15517 : "Preferred Activities User " + user + ":", " ", 15518 packageName, true, false)) { 15519 dumpState.setTitlePrinted(true); 15520 } 15521 } 15522 } 15523 15524 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15525 pw.flush(); 15526 FileOutputStream fout = new FileOutputStream(fd); 15527 BufferedOutputStream str = new BufferedOutputStream(fout); 15528 XmlSerializer serializer = new FastXmlSerializer(); 15529 try { 15530 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15531 serializer.startDocument(null, true); 15532 serializer.setFeature( 15533 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15534 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15535 serializer.endDocument(); 15536 serializer.flush(); 15537 } catch (IllegalArgumentException e) { 15538 pw.println("Failed writing: " + e); 15539 } catch (IllegalStateException e) { 15540 pw.println("Failed writing: " + e); 15541 } catch (IOException e) { 15542 pw.println("Failed writing: " + e); 15543 } 15544 } 15545 15546 if (!checkin 15547 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15548 && packageName == null) { 15549 pw.println(); 15550 int count = mSettings.mPackages.size(); 15551 if (count == 0) { 15552 pw.println("No applications!"); 15553 pw.println(); 15554 } else { 15555 final String prefix = " "; 15556 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15557 if (allPackageSettings.size() == 0) { 15558 pw.println("No domain preferred apps!"); 15559 pw.println(); 15560 } else { 15561 pw.println("App verification status:"); 15562 pw.println(); 15563 count = 0; 15564 for (PackageSetting ps : allPackageSettings) { 15565 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15566 if (ivi == null || ivi.getPackageName() == null) continue; 15567 pw.println(prefix + "Package: " + ivi.getPackageName()); 15568 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15569 pw.println(prefix + "Status: " + ivi.getStatusString()); 15570 pw.println(); 15571 count++; 15572 } 15573 if (count == 0) { 15574 pw.println(prefix + "No app verification established."); 15575 pw.println(); 15576 } 15577 for (int userId : sUserManager.getUserIds()) { 15578 pw.println("App linkages for user " + userId + ":"); 15579 pw.println(); 15580 count = 0; 15581 for (PackageSetting ps : allPackageSettings) { 15582 final long status = ps.getDomainVerificationStatusForUser(userId); 15583 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15584 continue; 15585 } 15586 pw.println(prefix + "Package: " + ps.name); 15587 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15588 String statusStr = IntentFilterVerificationInfo. 15589 getStatusStringFromValue(status); 15590 pw.println(prefix + "Status: " + statusStr); 15591 pw.println(); 15592 count++; 15593 } 15594 if (count == 0) { 15595 pw.println(prefix + "No configured app linkages."); 15596 pw.println(); 15597 } 15598 } 15599 } 15600 } 15601 } 15602 15603 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15604 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15605 if (packageName == null && permissionNames == null) { 15606 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15607 if (iperm == 0) { 15608 if (dumpState.onTitlePrinted()) 15609 pw.println(); 15610 pw.println("AppOp Permissions:"); 15611 } 15612 pw.print(" AppOp Permission "); 15613 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15614 pw.println(":"); 15615 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15616 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15617 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15618 } 15619 } 15620 } 15621 } 15622 15623 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15624 boolean printedSomething = false; 15625 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15626 if (packageName != null && !packageName.equals(p.info.packageName)) { 15627 continue; 15628 } 15629 if (!printedSomething) { 15630 if (dumpState.onTitlePrinted()) 15631 pw.println(); 15632 pw.println("Registered ContentProviders:"); 15633 printedSomething = true; 15634 } 15635 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15636 pw.print(" "); pw.println(p.toString()); 15637 } 15638 printedSomething = false; 15639 for (Map.Entry<String, PackageParser.Provider> entry : 15640 mProvidersByAuthority.entrySet()) { 15641 PackageParser.Provider p = entry.getValue(); 15642 if (packageName != null && !packageName.equals(p.info.packageName)) { 15643 continue; 15644 } 15645 if (!printedSomething) { 15646 if (dumpState.onTitlePrinted()) 15647 pw.println(); 15648 pw.println("ContentProvider Authorities:"); 15649 printedSomething = true; 15650 } 15651 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15652 pw.print(" "); pw.println(p.toString()); 15653 if (p.info != null && p.info.applicationInfo != null) { 15654 final String appInfo = p.info.applicationInfo.toString(); 15655 pw.print(" applicationInfo="); pw.println(appInfo); 15656 } 15657 } 15658 } 15659 15660 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15661 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15662 } 15663 15664 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15665 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15666 } 15667 15668 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15669 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15670 } 15671 15672 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15673 // XXX should handle packageName != null by dumping only install data that 15674 // the given package is involved with. 15675 if (dumpState.onTitlePrinted()) pw.println(); 15676 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15677 } 15678 15679 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15680 if (dumpState.onTitlePrinted()) pw.println(); 15681 mSettings.dumpReadMessagesLPr(pw, dumpState); 15682 15683 pw.println(); 15684 pw.println("Package warning messages:"); 15685 BufferedReader in = null; 15686 String line = null; 15687 try { 15688 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15689 while ((line = in.readLine()) != null) { 15690 if (line.contains("ignored: updated version")) continue; 15691 pw.println(line); 15692 } 15693 } catch (IOException ignored) { 15694 } finally { 15695 IoUtils.closeQuietly(in); 15696 } 15697 } 15698 15699 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15700 BufferedReader in = null; 15701 String line = null; 15702 try { 15703 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15704 while ((line = in.readLine()) != null) { 15705 if (line.contains("ignored: updated version")) continue; 15706 pw.print("msg,"); 15707 pw.println(line); 15708 } 15709 } catch (IOException ignored) { 15710 } finally { 15711 IoUtils.closeQuietly(in); 15712 } 15713 } 15714 } 15715 } 15716 15717 private String dumpDomainString(String packageName) { 15718 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15719 List<IntentFilter> filters = getAllIntentFilters(packageName); 15720 15721 ArraySet<String> result = new ArraySet<>(); 15722 if (iviList.size() > 0) { 15723 for (IntentFilterVerificationInfo ivi : iviList) { 15724 for (String host : ivi.getDomains()) { 15725 result.add(host); 15726 } 15727 } 15728 } 15729 if (filters != null && filters.size() > 0) { 15730 for (IntentFilter filter : filters) { 15731 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15732 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15733 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15734 result.addAll(filter.getHostsList()); 15735 } 15736 } 15737 } 15738 15739 StringBuilder sb = new StringBuilder(result.size() * 16); 15740 for (String domain : result) { 15741 if (sb.length() > 0) sb.append(" "); 15742 sb.append(domain); 15743 } 15744 return sb.toString(); 15745 } 15746 15747 // ------- apps on sdcard specific code ------- 15748 static final boolean DEBUG_SD_INSTALL = false; 15749 15750 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15751 15752 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15753 15754 private boolean mMediaMounted = false; 15755 15756 static String getEncryptKey() { 15757 try { 15758 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15759 SD_ENCRYPTION_KEYSTORE_NAME); 15760 if (sdEncKey == null) { 15761 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15762 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15763 if (sdEncKey == null) { 15764 Slog.e(TAG, "Failed to create encryption keys"); 15765 return null; 15766 } 15767 } 15768 return sdEncKey; 15769 } catch (NoSuchAlgorithmException nsae) { 15770 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15771 return null; 15772 } catch (IOException ioe) { 15773 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15774 return null; 15775 } 15776 } 15777 15778 /* 15779 * Update media status on PackageManager. 15780 */ 15781 @Override 15782 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15783 int callingUid = Binder.getCallingUid(); 15784 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15785 throw new SecurityException("Media status can only be updated by the system"); 15786 } 15787 // reader; this apparently protects mMediaMounted, but should probably 15788 // be a different lock in that case. 15789 synchronized (mPackages) { 15790 Log.i(TAG, "Updating external media status from " 15791 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15792 + (mediaStatus ? "mounted" : "unmounted")); 15793 if (DEBUG_SD_INSTALL) 15794 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15795 + ", mMediaMounted=" + mMediaMounted); 15796 if (mediaStatus == mMediaMounted) { 15797 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15798 : 0, -1); 15799 mHandler.sendMessage(msg); 15800 return; 15801 } 15802 mMediaMounted = mediaStatus; 15803 } 15804 // Queue up an async operation since the package installation may take a 15805 // little while. 15806 mHandler.post(new Runnable() { 15807 public void run() { 15808 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15809 } 15810 }); 15811 } 15812 15813 /** 15814 * Called by MountService when the initial ASECs to scan are available. 15815 * Should block until all the ASEC containers are finished being scanned. 15816 */ 15817 public void scanAvailableAsecs() { 15818 updateExternalMediaStatusInner(true, false, false); 15819 if (mShouldRestoreconData) { 15820 SELinuxMMAC.setRestoreconDone(); 15821 mShouldRestoreconData = false; 15822 } 15823 } 15824 15825 /* 15826 * Collect information of applications on external media, map them against 15827 * existing containers and update information based on current mount status. 15828 * Please note that we always have to report status if reportStatus has been 15829 * set to true especially when unloading packages. 15830 */ 15831 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15832 boolean externalStorage) { 15833 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15834 int[] uidArr = EmptyArray.INT; 15835 15836 final String[] list = PackageHelper.getSecureContainerList(); 15837 if (ArrayUtils.isEmpty(list)) { 15838 Log.i(TAG, "No secure containers found"); 15839 } else { 15840 // Process list of secure containers and categorize them 15841 // as active or stale based on their package internal state. 15842 15843 // reader 15844 synchronized (mPackages) { 15845 for (String cid : list) { 15846 // Leave stages untouched for now; installer service owns them 15847 if (PackageInstallerService.isStageName(cid)) continue; 15848 15849 if (DEBUG_SD_INSTALL) 15850 Log.i(TAG, "Processing container " + cid); 15851 String pkgName = getAsecPackageName(cid); 15852 if (pkgName == null) { 15853 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15854 continue; 15855 } 15856 if (DEBUG_SD_INSTALL) 15857 Log.i(TAG, "Looking for pkg : " + pkgName); 15858 15859 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15860 if (ps == null) { 15861 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15862 continue; 15863 } 15864 15865 /* 15866 * Skip packages that are not external if we're unmounting 15867 * external storage. 15868 */ 15869 if (externalStorage && !isMounted && !isExternal(ps)) { 15870 continue; 15871 } 15872 15873 final AsecInstallArgs args = new AsecInstallArgs(cid, 15874 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15875 // The package status is changed only if the code path 15876 // matches between settings and the container id. 15877 if (ps.codePathString != null 15878 && ps.codePathString.startsWith(args.getCodePath())) { 15879 if (DEBUG_SD_INSTALL) { 15880 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15881 + " at code path: " + ps.codePathString); 15882 } 15883 15884 // We do have a valid package installed on sdcard 15885 processCids.put(args, ps.codePathString); 15886 final int uid = ps.appId; 15887 if (uid != -1) { 15888 uidArr = ArrayUtils.appendInt(uidArr, uid); 15889 } 15890 } else { 15891 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15892 + ps.codePathString); 15893 } 15894 } 15895 } 15896 15897 Arrays.sort(uidArr); 15898 } 15899 15900 // Process packages with valid entries. 15901 if (isMounted) { 15902 if (DEBUG_SD_INSTALL) 15903 Log.i(TAG, "Loading packages"); 15904 loadMediaPackages(processCids, uidArr, externalStorage); 15905 startCleaningPackages(); 15906 mInstallerService.onSecureContainersAvailable(); 15907 } else { 15908 if (DEBUG_SD_INSTALL) 15909 Log.i(TAG, "Unloading packages"); 15910 unloadMediaPackages(processCids, uidArr, reportStatus); 15911 } 15912 } 15913 15914 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15915 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15916 final int size = infos.size(); 15917 final String[] packageNames = new String[size]; 15918 final int[] packageUids = new int[size]; 15919 for (int i = 0; i < size; i++) { 15920 final ApplicationInfo info = infos.get(i); 15921 packageNames[i] = info.packageName; 15922 packageUids[i] = info.uid; 15923 } 15924 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15925 finishedReceiver); 15926 } 15927 15928 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15929 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15930 sendResourcesChangedBroadcast(mediaStatus, replacing, 15931 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15932 } 15933 15934 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15935 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15936 int size = pkgList.length; 15937 if (size > 0) { 15938 // Send broadcasts here 15939 Bundle extras = new Bundle(); 15940 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15941 if (uidArr != null) { 15942 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15943 } 15944 if (replacing) { 15945 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15946 } 15947 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15948 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15949 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 15950 } 15951 } 15952 15953 /* 15954 * Look at potentially valid container ids from processCids If package 15955 * information doesn't match the one on record or package scanning fails, 15956 * the cid is added to list of removeCids. We currently don't delete stale 15957 * containers. 15958 */ 15959 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15960 boolean externalStorage) { 15961 ArrayList<String> pkgList = new ArrayList<String>(); 15962 Set<AsecInstallArgs> keys = processCids.keySet(); 15963 15964 for (AsecInstallArgs args : keys) { 15965 String codePath = processCids.get(args); 15966 if (DEBUG_SD_INSTALL) 15967 Log.i(TAG, "Loading container : " + args.cid); 15968 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15969 try { 15970 // Make sure there are no container errors first. 15971 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15972 Slog.e(TAG, "Failed to mount cid : " + args.cid 15973 + " when installing from sdcard"); 15974 continue; 15975 } 15976 // Check code path here. 15977 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15978 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15979 + " does not match one in settings " + codePath); 15980 continue; 15981 } 15982 // Parse package 15983 int parseFlags = mDefParseFlags; 15984 if (args.isExternalAsec()) { 15985 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15986 } 15987 if (args.isFwdLocked()) { 15988 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15989 } 15990 15991 synchronized (mInstallLock) { 15992 PackageParser.Package pkg = null; 15993 try { 15994 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15995 } catch (PackageManagerException e) { 15996 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15997 } 15998 // Scan the package 15999 if (pkg != null) { 16000 /* 16001 * TODO why is the lock being held? doPostInstall is 16002 * called in other places without the lock. This needs 16003 * to be straightened out. 16004 */ 16005 // writer 16006 synchronized (mPackages) { 16007 retCode = PackageManager.INSTALL_SUCCEEDED; 16008 pkgList.add(pkg.packageName); 16009 // Post process args 16010 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16011 pkg.applicationInfo.uid); 16012 } 16013 } else { 16014 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16015 } 16016 } 16017 16018 } finally { 16019 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16020 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16021 } 16022 } 16023 } 16024 // writer 16025 synchronized (mPackages) { 16026 // If the platform SDK has changed since the last time we booted, 16027 // we need to re-grant app permission to catch any new ones that 16028 // appear. This is really a hack, and means that apps can in some 16029 // cases get permissions that the user didn't initially explicitly 16030 // allow... it would be nice to have some better way to handle 16031 // this situation. 16032 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16033 : mSettings.getInternalVersion(); 16034 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16035 : StorageManager.UUID_PRIVATE_INTERNAL; 16036 16037 int updateFlags = UPDATE_PERMISSIONS_ALL; 16038 if (ver.sdkVersion != mSdkVersion) { 16039 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16040 + mSdkVersion + "; regranting permissions for external"); 16041 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16042 } 16043 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16044 16045 // Yay, everything is now upgraded 16046 ver.forceCurrent(); 16047 16048 // can downgrade to reader 16049 // Persist settings 16050 mSettings.writeLPr(); 16051 } 16052 // Send a broadcast to let everyone know we are done processing 16053 if (pkgList.size() > 0) { 16054 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16055 } 16056 } 16057 16058 /* 16059 * Utility method to unload a list of specified containers 16060 */ 16061 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16062 // Just unmount all valid containers. 16063 for (AsecInstallArgs arg : cidArgs) { 16064 synchronized (mInstallLock) { 16065 arg.doPostDeleteLI(false); 16066 } 16067 } 16068 } 16069 16070 /* 16071 * Unload packages mounted on external media. This involves deleting package 16072 * data from internal structures, sending broadcasts about diabled packages, 16073 * gc'ing to free up references, unmounting all secure containers 16074 * corresponding to packages on external media, and posting a 16075 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16076 * that we always have to post this message if status has been requested no 16077 * matter what. 16078 */ 16079 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16080 final boolean reportStatus) { 16081 if (DEBUG_SD_INSTALL) 16082 Log.i(TAG, "unloading media packages"); 16083 ArrayList<String> pkgList = new ArrayList<String>(); 16084 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16085 final Set<AsecInstallArgs> keys = processCids.keySet(); 16086 for (AsecInstallArgs args : keys) { 16087 String pkgName = args.getPackageName(); 16088 if (DEBUG_SD_INSTALL) 16089 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16090 // Delete package internally 16091 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16092 synchronized (mInstallLock) { 16093 boolean res = deletePackageLI(pkgName, null, false, null, null, 16094 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16095 if (res) { 16096 pkgList.add(pkgName); 16097 } else { 16098 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16099 failedList.add(args); 16100 } 16101 } 16102 } 16103 16104 // reader 16105 synchronized (mPackages) { 16106 // We didn't update the settings after removing each package; 16107 // write them now for all packages. 16108 mSettings.writeLPr(); 16109 } 16110 16111 // We have to absolutely send UPDATED_MEDIA_STATUS only 16112 // after confirming that all the receivers processed the ordered 16113 // broadcast when packages get disabled, force a gc to clean things up. 16114 // and unload all the containers. 16115 if (pkgList.size() > 0) { 16116 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16117 new IIntentReceiver.Stub() { 16118 public void performReceive(Intent intent, int resultCode, String data, 16119 Bundle extras, boolean ordered, boolean sticky, 16120 int sendingUser) throws RemoteException { 16121 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16122 reportStatus ? 1 : 0, 1, keys); 16123 mHandler.sendMessage(msg); 16124 } 16125 }); 16126 } else { 16127 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16128 keys); 16129 mHandler.sendMessage(msg); 16130 } 16131 } 16132 16133 private void loadPrivatePackages(final VolumeInfo vol) { 16134 mHandler.post(new Runnable() { 16135 @Override 16136 public void run() { 16137 loadPrivatePackagesInner(vol); 16138 } 16139 }); 16140 } 16141 16142 private void loadPrivatePackagesInner(VolumeInfo vol) { 16143 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16144 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16145 16146 final VersionInfo ver; 16147 final List<PackageSetting> packages; 16148 synchronized (mPackages) { 16149 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16150 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16151 } 16152 16153 for (PackageSetting ps : packages) { 16154 synchronized (mInstallLock) { 16155 final PackageParser.Package pkg; 16156 try { 16157 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16158 loaded.add(pkg.applicationInfo); 16159 } catch (PackageManagerException e) { 16160 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16161 } 16162 16163 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16164 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16165 } 16166 } 16167 } 16168 16169 synchronized (mPackages) { 16170 int updateFlags = UPDATE_PERMISSIONS_ALL; 16171 if (ver.sdkVersion != mSdkVersion) { 16172 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16173 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16174 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16175 } 16176 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16177 16178 // Yay, everything is now upgraded 16179 ver.forceCurrent(); 16180 16181 mSettings.writeLPr(); 16182 } 16183 16184 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16185 sendResourcesChangedBroadcast(true, false, loaded, null); 16186 } 16187 16188 private void unloadPrivatePackages(final VolumeInfo vol) { 16189 mHandler.post(new Runnable() { 16190 @Override 16191 public void run() { 16192 unloadPrivatePackagesInner(vol); 16193 } 16194 }); 16195 } 16196 16197 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16198 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16199 synchronized (mInstallLock) { 16200 synchronized (mPackages) { 16201 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16202 for (PackageSetting ps : packages) { 16203 if (ps.pkg == null) continue; 16204 16205 final ApplicationInfo info = ps.pkg.applicationInfo; 16206 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16207 if (deletePackageLI(ps.name, null, false, null, null, 16208 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16209 unloaded.add(info); 16210 } else { 16211 Slog.w(TAG, "Failed to unload " + ps.codePath); 16212 } 16213 } 16214 16215 mSettings.writeLPr(); 16216 } 16217 } 16218 16219 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16220 sendResourcesChangedBroadcast(false, false, unloaded, null); 16221 } 16222 16223 /** 16224 * Examine all users present on given mounted volume, and destroy data 16225 * belonging to users that are no longer valid, or whose user ID has been 16226 * recycled. 16227 */ 16228 private void reconcileUsers(String volumeUuid) { 16229 final File[] files = FileUtils 16230 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16231 for (File file : files) { 16232 if (!file.isDirectory()) continue; 16233 16234 final int userId; 16235 final UserInfo info; 16236 try { 16237 userId = Integer.parseInt(file.getName()); 16238 info = sUserManager.getUserInfo(userId); 16239 } catch (NumberFormatException e) { 16240 Slog.w(TAG, "Invalid user directory " + file); 16241 continue; 16242 } 16243 16244 boolean destroyUser = false; 16245 if (info == null) { 16246 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16247 + " because no matching user was found"); 16248 destroyUser = true; 16249 } else { 16250 try { 16251 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16252 } catch (IOException e) { 16253 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16254 + " because we failed to enforce serial number: " + e); 16255 destroyUser = true; 16256 } 16257 } 16258 16259 if (destroyUser) { 16260 synchronized (mInstallLock) { 16261 mInstaller.removeUserDataDirs(volumeUuid, userId); 16262 } 16263 } 16264 } 16265 16266 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16267 final UserManager um = mContext.getSystemService(UserManager.class); 16268 for (UserInfo user : um.getUsers()) { 16269 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16270 if (userDir.exists()) continue; 16271 16272 try { 16273 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber); 16274 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16275 } catch (IOException e) { 16276 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16277 } 16278 } 16279 } 16280 16281 /** 16282 * Examine all apps present on given mounted volume, and destroy apps that 16283 * aren't expected, either due to uninstallation or reinstallation on 16284 * another volume. 16285 */ 16286 private void reconcileApps(String volumeUuid) { 16287 final File[] files = FileUtils 16288 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16289 for (File file : files) { 16290 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16291 && !PackageInstallerService.isStageName(file.getName()); 16292 if (!isPackage) { 16293 // Ignore entries which are not packages 16294 continue; 16295 } 16296 16297 boolean destroyApp = false; 16298 String packageName = null; 16299 try { 16300 final PackageLite pkg = PackageParser.parsePackageLite(file, 16301 PackageParser.PARSE_MUST_BE_APK); 16302 packageName = pkg.packageName; 16303 16304 synchronized (mPackages) { 16305 final PackageSetting ps = mSettings.mPackages.get(packageName); 16306 if (ps == null) { 16307 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16308 + volumeUuid + " because we found no install record"); 16309 destroyApp = true; 16310 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16311 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16312 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16313 destroyApp = true; 16314 } 16315 } 16316 16317 } catch (PackageParserException e) { 16318 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16319 destroyApp = true; 16320 } 16321 16322 if (destroyApp) { 16323 synchronized (mInstallLock) { 16324 if (packageName != null) { 16325 removeDataDirsLI(volumeUuid, packageName); 16326 } 16327 if (file.isDirectory()) { 16328 mInstaller.rmPackageDir(file.getAbsolutePath()); 16329 } else { 16330 file.delete(); 16331 } 16332 } 16333 } 16334 } 16335 } 16336 16337 private void unfreezePackage(String packageName) { 16338 synchronized (mPackages) { 16339 final PackageSetting ps = mSettings.mPackages.get(packageName); 16340 if (ps != null) { 16341 ps.frozen = false; 16342 } 16343 } 16344 } 16345 16346 @Override 16347 public int movePackage(final String packageName, final String volumeUuid) { 16348 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16349 16350 final int moveId = mNextMoveId.getAndIncrement(); 16351 mHandler.post(new Runnable() { 16352 @Override 16353 public void run() { 16354 try { 16355 movePackageInternal(packageName, volumeUuid, moveId); 16356 } catch (PackageManagerException e) { 16357 Slog.w(TAG, "Failed to move " + packageName, e); 16358 mMoveCallbacks.notifyStatusChanged(moveId, 16359 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16360 } 16361 } 16362 }); 16363 return moveId; 16364 } 16365 16366 private void movePackageInternal(final String packageName, final String volumeUuid, 16367 final int moveId) throws PackageManagerException { 16368 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16369 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16370 final PackageManager pm = mContext.getPackageManager(); 16371 16372 final boolean currentAsec; 16373 final String currentVolumeUuid; 16374 final File codeFile; 16375 final String installerPackageName; 16376 final String packageAbiOverride; 16377 final int appId; 16378 final String seinfo; 16379 final String label; 16380 16381 // reader 16382 synchronized (mPackages) { 16383 final PackageParser.Package pkg = mPackages.get(packageName); 16384 final PackageSetting ps = mSettings.mPackages.get(packageName); 16385 if (pkg == null || ps == null) { 16386 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16387 } 16388 16389 if (pkg.applicationInfo.isSystemApp()) { 16390 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16391 "Cannot move system application"); 16392 } 16393 16394 if (pkg.applicationInfo.isExternalAsec()) { 16395 currentAsec = true; 16396 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16397 } else if (pkg.applicationInfo.isForwardLocked()) { 16398 currentAsec = true; 16399 currentVolumeUuid = "forward_locked"; 16400 } else { 16401 currentAsec = false; 16402 currentVolumeUuid = ps.volumeUuid; 16403 16404 final File probe = new File(pkg.codePath); 16405 final File probeOat = new File(probe, "oat"); 16406 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16407 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16408 "Move only supported for modern cluster style installs"); 16409 } 16410 } 16411 16412 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16413 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16414 "Package already moved to " + volumeUuid); 16415 } 16416 16417 if (ps.frozen) { 16418 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16419 "Failed to move already frozen package"); 16420 } 16421 ps.frozen = true; 16422 16423 codeFile = new File(pkg.codePath); 16424 installerPackageName = ps.installerPackageName; 16425 packageAbiOverride = ps.cpuAbiOverrideString; 16426 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16427 seinfo = pkg.applicationInfo.seinfo; 16428 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16429 } 16430 16431 // Now that we're guarded by frozen state, kill app during move 16432 final long token = Binder.clearCallingIdentity(); 16433 try { 16434 killApplication(packageName, appId, "move pkg"); 16435 } finally { 16436 Binder.restoreCallingIdentity(token); 16437 } 16438 16439 final Bundle extras = new Bundle(); 16440 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16441 extras.putString(Intent.EXTRA_TITLE, label); 16442 mMoveCallbacks.notifyCreated(moveId, extras); 16443 16444 int installFlags; 16445 final boolean moveCompleteApp; 16446 final File measurePath; 16447 16448 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16449 installFlags = INSTALL_INTERNAL; 16450 moveCompleteApp = !currentAsec; 16451 measurePath = Environment.getDataAppDirectory(volumeUuid); 16452 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16453 installFlags = INSTALL_EXTERNAL; 16454 moveCompleteApp = false; 16455 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16456 } else { 16457 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16458 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16459 || !volume.isMountedWritable()) { 16460 unfreezePackage(packageName); 16461 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16462 "Move location not mounted private volume"); 16463 } 16464 16465 Preconditions.checkState(!currentAsec); 16466 16467 installFlags = INSTALL_INTERNAL; 16468 moveCompleteApp = true; 16469 measurePath = Environment.getDataAppDirectory(volumeUuid); 16470 } 16471 16472 final PackageStats stats = new PackageStats(null, -1); 16473 synchronized (mInstaller) { 16474 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16475 unfreezePackage(packageName); 16476 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16477 "Failed to measure package size"); 16478 } 16479 } 16480 16481 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16482 + stats.dataSize); 16483 16484 final long startFreeBytes = measurePath.getFreeSpace(); 16485 final long sizeBytes; 16486 if (moveCompleteApp) { 16487 sizeBytes = stats.codeSize + stats.dataSize; 16488 } else { 16489 sizeBytes = stats.codeSize; 16490 } 16491 16492 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16493 unfreezePackage(packageName); 16494 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16495 "Not enough free space to move"); 16496 } 16497 16498 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16499 16500 final CountDownLatch installedLatch = new CountDownLatch(1); 16501 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16502 @Override 16503 public void onUserActionRequired(Intent intent) throws RemoteException { 16504 throw new IllegalStateException(); 16505 } 16506 16507 @Override 16508 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16509 Bundle extras) throws RemoteException { 16510 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16511 + PackageManager.installStatusToString(returnCode, msg)); 16512 16513 installedLatch.countDown(); 16514 16515 // Regardless of success or failure of the move operation, 16516 // always unfreeze the package 16517 unfreezePackage(packageName); 16518 16519 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16520 switch (status) { 16521 case PackageInstaller.STATUS_SUCCESS: 16522 mMoveCallbacks.notifyStatusChanged(moveId, 16523 PackageManager.MOVE_SUCCEEDED); 16524 break; 16525 case PackageInstaller.STATUS_FAILURE_STORAGE: 16526 mMoveCallbacks.notifyStatusChanged(moveId, 16527 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16528 break; 16529 default: 16530 mMoveCallbacks.notifyStatusChanged(moveId, 16531 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16532 break; 16533 } 16534 } 16535 }; 16536 16537 final MoveInfo move; 16538 if (moveCompleteApp) { 16539 // Kick off a thread to report progress estimates 16540 new Thread() { 16541 @Override 16542 public void run() { 16543 while (true) { 16544 try { 16545 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16546 break; 16547 } 16548 } catch (InterruptedException ignored) { 16549 } 16550 16551 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16552 final int progress = 10 + (int) MathUtils.constrain( 16553 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16554 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16555 } 16556 } 16557 }.start(); 16558 16559 final String dataAppName = codeFile.getName(); 16560 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16561 dataAppName, appId, seinfo); 16562 } else { 16563 move = null; 16564 } 16565 16566 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16567 16568 final Message msg = mHandler.obtainMessage(INIT_COPY); 16569 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16570 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16571 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16572 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16573 msg.obj = params; 16574 16575 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16576 System.identityHashCode(msg.obj)); 16577 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16578 System.identityHashCode(msg.obj)); 16579 16580 mHandler.sendMessage(msg); 16581 } 16582 16583 @Override 16584 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16585 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16586 16587 final int realMoveId = mNextMoveId.getAndIncrement(); 16588 final Bundle extras = new Bundle(); 16589 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16590 mMoveCallbacks.notifyCreated(realMoveId, extras); 16591 16592 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16593 @Override 16594 public void onCreated(int moveId, Bundle extras) { 16595 // Ignored 16596 } 16597 16598 @Override 16599 public void onStatusChanged(int moveId, int status, long estMillis) { 16600 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16601 } 16602 }; 16603 16604 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16605 storage.setPrimaryStorageUuid(volumeUuid, callback); 16606 return realMoveId; 16607 } 16608 16609 @Override 16610 public int getMoveStatus(int moveId) { 16611 mContext.enforceCallingOrSelfPermission( 16612 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16613 return mMoveCallbacks.mLastStatus.get(moveId); 16614 } 16615 16616 @Override 16617 public void registerMoveCallback(IPackageMoveObserver callback) { 16618 mContext.enforceCallingOrSelfPermission( 16619 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16620 mMoveCallbacks.register(callback); 16621 } 16622 16623 @Override 16624 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16625 mContext.enforceCallingOrSelfPermission( 16626 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16627 mMoveCallbacks.unregister(callback); 16628 } 16629 16630 @Override 16631 public boolean setInstallLocation(int loc) { 16632 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16633 null); 16634 if (getInstallLocation() == loc) { 16635 return true; 16636 } 16637 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16638 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16639 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16640 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16641 return true; 16642 } 16643 return false; 16644 } 16645 16646 @Override 16647 public int getInstallLocation() { 16648 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16649 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16650 PackageHelper.APP_INSTALL_AUTO); 16651 } 16652 16653 /** Called by UserManagerService */ 16654 void cleanUpUser(UserManagerService userManager, int userHandle) { 16655 synchronized (mPackages) { 16656 mDirtyUsers.remove(userHandle); 16657 mUserNeedsBadging.delete(userHandle); 16658 mSettings.removeUserLPw(userHandle); 16659 mPendingBroadcasts.remove(userHandle); 16660 } 16661 synchronized (mInstallLock) { 16662 if (mInstaller != null) { 16663 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16664 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16665 final String volumeUuid = vol.getFsUuid(); 16666 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16667 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16668 } 16669 } 16670 synchronized (mPackages) { 16671 removeUnusedPackagesLILPw(userManager, userHandle); 16672 } 16673 } 16674 } 16675 16676 /** 16677 * We're removing userHandle and would like to remove any downloaded packages 16678 * that are no longer in use by any other user. 16679 * @param userHandle the user being removed 16680 */ 16681 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16682 final boolean DEBUG_CLEAN_APKS = false; 16683 int [] users = userManager.getUserIds(); 16684 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16685 while (psit.hasNext()) { 16686 PackageSetting ps = psit.next(); 16687 if (ps.pkg == null) { 16688 continue; 16689 } 16690 final String packageName = ps.pkg.packageName; 16691 // Skip over if system app 16692 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16693 continue; 16694 } 16695 if (DEBUG_CLEAN_APKS) { 16696 Slog.i(TAG, "Checking package " + packageName); 16697 } 16698 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 16699 if (keep) { 16700 if (DEBUG_CLEAN_APKS) { 16701 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 16702 } 16703 } else { 16704 for (int i = 0; i < users.length; i++) { 16705 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16706 keep = true; 16707 if (DEBUG_CLEAN_APKS) { 16708 Slog.i(TAG, " Keeping package " + packageName + " for user " 16709 + users[i]); 16710 } 16711 break; 16712 } 16713 } 16714 } 16715 if (!keep) { 16716 if (DEBUG_CLEAN_APKS) { 16717 Slog.i(TAG, " Removing package " + packageName); 16718 } 16719 mHandler.post(new Runnable() { 16720 public void run() { 16721 deletePackageX(packageName, userHandle, 0); 16722 } //end run 16723 }); 16724 } 16725 } 16726 } 16727 16728 /** Called by UserManagerService */ 16729 void createNewUser(int userHandle) { 16730 if (mInstaller != null) { 16731 synchronized (mInstallLock) { 16732 synchronized (mPackages) { 16733 mInstaller.createUserConfig(userHandle); 16734 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16735 } 16736 } 16737 synchronized (mPackages) { 16738 applyFactoryDefaultBrowserLPw(userHandle); 16739 primeDomainVerificationsLPw(userHandle); 16740 } 16741 } 16742 } 16743 16744 void newUserCreated(final int userHandle) { 16745 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16746 } 16747 16748 @Override 16749 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16750 mContext.enforceCallingOrSelfPermission( 16751 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16752 "Only package verification agents can read the verifier device identity"); 16753 16754 synchronized (mPackages) { 16755 return mSettings.getVerifierDeviceIdentityLPw(); 16756 } 16757 } 16758 16759 @Override 16760 public void setPermissionEnforced(String permission, boolean enforced) { 16761 // TODO: Now that we no longer change GID for storage, this should to away. 16762 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16763 "setPermissionEnforced"); 16764 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16765 synchronized (mPackages) { 16766 if (mSettings.mReadExternalStorageEnforced == null 16767 || mSettings.mReadExternalStorageEnforced != enforced) { 16768 mSettings.mReadExternalStorageEnforced = enforced; 16769 mSettings.writeLPr(); 16770 } 16771 } 16772 // kill any non-foreground processes so we restart them and 16773 // grant/revoke the GID. 16774 final IActivityManager am = ActivityManagerNative.getDefault(); 16775 if (am != null) { 16776 final long token = Binder.clearCallingIdentity(); 16777 try { 16778 am.killProcessesBelowForeground("setPermissionEnforcement"); 16779 } catch (RemoteException e) { 16780 } finally { 16781 Binder.restoreCallingIdentity(token); 16782 } 16783 } 16784 } else { 16785 throw new IllegalArgumentException("No selective enforcement for " + permission); 16786 } 16787 } 16788 16789 @Override 16790 @Deprecated 16791 public boolean isPermissionEnforced(String permission) { 16792 return true; 16793 } 16794 16795 @Override 16796 public boolean isStorageLow() { 16797 final long token = Binder.clearCallingIdentity(); 16798 try { 16799 final DeviceStorageMonitorInternal 16800 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16801 if (dsm != null) { 16802 return dsm.isMemoryLow(); 16803 } else { 16804 return false; 16805 } 16806 } finally { 16807 Binder.restoreCallingIdentity(token); 16808 } 16809 } 16810 16811 @Override 16812 public IPackageInstaller getPackageInstaller() { 16813 return mInstallerService; 16814 } 16815 16816 private boolean userNeedsBadging(int userId) { 16817 int index = mUserNeedsBadging.indexOfKey(userId); 16818 if (index < 0) { 16819 final UserInfo userInfo; 16820 final long token = Binder.clearCallingIdentity(); 16821 try { 16822 userInfo = sUserManager.getUserInfo(userId); 16823 } finally { 16824 Binder.restoreCallingIdentity(token); 16825 } 16826 final boolean b; 16827 if (userInfo != null && userInfo.isManagedProfile()) { 16828 b = true; 16829 } else { 16830 b = false; 16831 } 16832 mUserNeedsBadging.put(userId, b); 16833 return b; 16834 } 16835 return mUserNeedsBadging.valueAt(index); 16836 } 16837 16838 @Override 16839 public KeySet getKeySetByAlias(String packageName, String alias) { 16840 if (packageName == null || alias == null) { 16841 return null; 16842 } 16843 synchronized(mPackages) { 16844 final PackageParser.Package pkg = mPackages.get(packageName); 16845 if (pkg == null) { 16846 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16847 throw new IllegalArgumentException("Unknown package: " + packageName); 16848 } 16849 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16850 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16851 } 16852 } 16853 16854 @Override 16855 public KeySet getSigningKeySet(String packageName) { 16856 if (packageName == null) { 16857 return null; 16858 } 16859 synchronized(mPackages) { 16860 final PackageParser.Package pkg = mPackages.get(packageName); 16861 if (pkg == null) { 16862 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16863 throw new IllegalArgumentException("Unknown package: " + packageName); 16864 } 16865 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16866 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16867 throw new SecurityException("May not access signing KeySet of other apps."); 16868 } 16869 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16870 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16871 } 16872 } 16873 16874 @Override 16875 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16876 if (packageName == null || ks == null) { 16877 return false; 16878 } 16879 synchronized(mPackages) { 16880 final PackageParser.Package pkg = mPackages.get(packageName); 16881 if (pkg == null) { 16882 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16883 throw new IllegalArgumentException("Unknown package: " + packageName); 16884 } 16885 IBinder ksh = ks.getToken(); 16886 if (ksh instanceof KeySetHandle) { 16887 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16888 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16889 } 16890 return false; 16891 } 16892 } 16893 16894 @Override 16895 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16896 if (packageName == null || ks == null) { 16897 return false; 16898 } 16899 synchronized(mPackages) { 16900 final PackageParser.Package pkg = mPackages.get(packageName); 16901 if (pkg == null) { 16902 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16903 throw new IllegalArgumentException("Unknown package: " + packageName); 16904 } 16905 IBinder ksh = ks.getToken(); 16906 if (ksh instanceof KeySetHandle) { 16907 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16908 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16909 } 16910 return false; 16911 } 16912 } 16913 16914 private void deletePackageIfUnusedLPr(final String packageName) { 16915 PackageSetting ps = mSettings.mPackages.get(packageName); 16916 if (ps == null) { 16917 return; 16918 } 16919 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 16920 // TODO Implement atomic delete if package is unused 16921 // It is currently possible that the package will be deleted even if it is installed 16922 // after this method returns. 16923 mHandler.post(new Runnable() { 16924 public void run() { 16925 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 16926 } 16927 }); 16928 } 16929 } 16930 16931 /** 16932 * Check and throw if the given before/after packages would be considered a 16933 * downgrade. 16934 */ 16935 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16936 throws PackageManagerException { 16937 if (after.versionCode < before.mVersionCode) { 16938 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16939 "Update version code " + after.versionCode + " is older than current " 16940 + before.mVersionCode); 16941 } else if (after.versionCode == before.mVersionCode) { 16942 if (after.baseRevisionCode < before.baseRevisionCode) { 16943 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16944 "Update base revision code " + after.baseRevisionCode 16945 + " is older than current " + before.baseRevisionCode); 16946 } 16947 16948 if (!ArrayUtils.isEmpty(after.splitNames)) { 16949 for (int i = 0; i < after.splitNames.length; i++) { 16950 final String splitName = after.splitNames[i]; 16951 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16952 if (j != -1) { 16953 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16954 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16955 "Update split " + splitName + " revision code " 16956 + after.splitRevisionCodes[i] + " is older than current " 16957 + before.splitRevisionCodes[j]); 16958 } 16959 } 16960 } 16961 } 16962 } 16963 } 16964 16965 private static class MoveCallbacks extends Handler { 16966 private static final int MSG_CREATED = 1; 16967 private static final int MSG_STATUS_CHANGED = 2; 16968 16969 private final RemoteCallbackList<IPackageMoveObserver> 16970 mCallbacks = new RemoteCallbackList<>(); 16971 16972 private final SparseIntArray mLastStatus = new SparseIntArray(); 16973 16974 public MoveCallbacks(Looper looper) { 16975 super(looper); 16976 } 16977 16978 public void register(IPackageMoveObserver callback) { 16979 mCallbacks.register(callback); 16980 } 16981 16982 public void unregister(IPackageMoveObserver callback) { 16983 mCallbacks.unregister(callback); 16984 } 16985 16986 @Override 16987 public void handleMessage(Message msg) { 16988 final SomeArgs args = (SomeArgs) msg.obj; 16989 final int n = mCallbacks.beginBroadcast(); 16990 for (int i = 0; i < n; i++) { 16991 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16992 try { 16993 invokeCallback(callback, msg.what, args); 16994 } catch (RemoteException ignored) { 16995 } 16996 } 16997 mCallbacks.finishBroadcast(); 16998 args.recycle(); 16999 } 17000 17001 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17002 throws RemoteException { 17003 switch (what) { 17004 case MSG_CREATED: { 17005 callback.onCreated(args.argi1, (Bundle) args.arg2); 17006 break; 17007 } 17008 case MSG_STATUS_CHANGED: { 17009 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17010 break; 17011 } 17012 } 17013 } 17014 17015 private void notifyCreated(int moveId, Bundle extras) { 17016 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17017 17018 final SomeArgs args = SomeArgs.obtain(); 17019 args.argi1 = moveId; 17020 args.arg2 = extras; 17021 obtainMessage(MSG_CREATED, args).sendToTarget(); 17022 } 17023 17024 private void notifyStatusChanged(int moveId, int status) { 17025 notifyStatusChanged(moveId, status, -1); 17026 } 17027 17028 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17029 Slog.v(TAG, "Move " + moveId + " status " + status); 17030 17031 final SomeArgs args = SomeArgs.obtain(); 17032 args.argi1 = moveId; 17033 args.argi2 = status; 17034 args.arg3 = estMillis; 17035 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17036 17037 synchronized (mLastStatus) { 17038 mLastStatus.put(moveId, status); 17039 } 17040 } 17041 } 17042 17043 private final class OnPermissionChangeListeners extends Handler { 17044 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17045 17046 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17047 new RemoteCallbackList<>(); 17048 17049 public OnPermissionChangeListeners(Looper looper) { 17050 super(looper); 17051 } 17052 17053 @Override 17054 public void handleMessage(Message msg) { 17055 switch (msg.what) { 17056 case MSG_ON_PERMISSIONS_CHANGED: { 17057 final int uid = msg.arg1; 17058 handleOnPermissionsChanged(uid); 17059 } break; 17060 } 17061 } 17062 17063 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17064 mPermissionListeners.register(listener); 17065 17066 } 17067 17068 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17069 mPermissionListeners.unregister(listener); 17070 } 17071 17072 public void onPermissionsChanged(int uid) { 17073 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17074 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17075 } 17076 } 17077 17078 private void handleOnPermissionsChanged(int uid) { 17079 final int count = mPermissionListeners.beginBroadcast(); 17080 try { 17081 for (int i = 0; i < count; i++) { 17082 IOnPermissionsChangeListener callback = mPermissionListeners 17083 .getBroadcastItem(i); 17084 try { 17085 callback.onPermissionsChanged(uid); 17086 } catch (RemoteException e) { 17087 Log.e(TAG, "Permission listener is dead", e); 17088 } 17089 } 17090 } finally { 17091 mPermissionListeners.finishBroadcast(); 17092 } 17093 } 17094 } 17095 17096 private class PackageManagerInternalImpl extends PackageManagerInternal { 17097 @Override 17098 public void setLocationPackagesProvider(PackagesProvider provider) { 17099 synchronized (mPackages) { 17100 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17101 } 17102 } 17103 17104 @Override 17105 public void setImePackagesProvider(PackagesProvider provider) { 17106 synchronized (mPackages) { 17107 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17108 } 17109 } 17110 17111 @Override 17112 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17113 synchronized (mPackages) { 17114 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17115 } 17116 } 17117 17118 @Override 17119 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17120 synchronized (mPackages) { 17121 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17122 } 17123 } 17124 17125 @Override 17126 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17127 synchronized (mPackages) { 17128 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17129 } 17130 } 17131 17132 @Override 17133 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17134 synchronized (mPackages) { 17135 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17136 } 17137 } 17138 17139 @Override 17140 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17141 synchronized (mPackages) { 17142 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17143 } 17144 } 17145 17146 @Override 17147 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17148 synchronized (mPackages) { 17149 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17150 packageName, userId); 17151 } 17152 } 17153 17154 @Override 17155 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17156 synchronized (mPackages) { 17157 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17158 packageName, userId); 17159 } 17160 } 17161 @Override 17162 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17163 synchronized (mPackages) { 17164 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17165 packageName, userId); 17166 } 17167 } 17168 17169 @Override 17170 public void setKeepUninstalledPackages(final List<String> packageList) { 17171 Preconditions.checkNotNull(packageList); 17172 List<String> removedFromList = null; 17173 synchronized (mPackages) { 17174 if (mKeepUninstalledPackages != null) { 17175 final int packagesCount = mKeepUninstalledPackages.size(); 17176 for (int i = 0; i < packagesCount; i++) { 17177 String oldPackage = mKeepUninstalledPackages.get(i); 17178 if (packageList != null && packageList.contains(oldPackage)) { 17179 continue; 17180 } 17181 if (removedFromList == null) { 17182 removedFromList = new ArrayList<>(); 17183 } 17184 removedFromList.add(oldPackage); 17185 } 17186 } 17187 mKeepUninstalledPackages = new ArrayList<>(packageList); 17188 if (removedFromList != null) { 17189 final int removedCount = removedFromList.size(); 17190 for (int i = 0; i < removedCount; i++) { 17191 deletePackageIfUnusedLPr(removedFromList.get(i)); 17192 } 17193 } 17194 } 17195 } 17196 } 17197 17198 @Override 17199 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17200 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17201 synchronized (mPackages) { 17202 final long identity = Binder.clearCallingIdentity(); 17203 try { 17204 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17205 packageNames, userId); 17206 } finally { 17207 Binder.restoreCallingIdentity(identity); 17208 } 17209 } 17210 } 17211 17212 private static void enforceSystemOrPhoneCaller(String tag) { 17213 int callingUid = Binder.getCallingUid(); 17214 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17215 throw new SecurityException( 17216 "Cannot call " + tag + " from UID " + callingUid); 17217 } 17218 } 17219} 17220