PackageManagerService.java revision 3eef5a5273ed6fb1c2d96d80acea4553057d8d09
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.ResultReceiver; 166import android.os.SELinux; 167import android.os.ServiceManager; 168import android.os.SystemClock; 169import android.os.SystemProperties; 170import android.os.Trace; 171import android.os.UserHandle; 172import android.os.UserManager; 173import android.os.storage.IMountService; 174import android.os.storage.MountServiceInternal; 175import android.os.storage.StorageEventListener; 176import android.os.storage.StorageManager; 177import android.os.storage.VolumeInfo; 178import android.os.storage.VolumeRecord; 179import android.security.KeyStore; 180import android.security.SystemKeyStore; 181import android.system.ErrnoException; 182import android.system.Os; 183import android.system.StructStat; 184import android.text.TextUtils; 185import android.text.format.DateUtils; 186import android.util.ArrayMap; 187import android.util.ArraySet; 188import android.util.AtomicFile; 189import android.util.DisplayMetrics; 190import android.util.EventLog; 191import android.util.ExceptionUtils; 192import android.util.Log; 193import android.util.LogPrinter; 194import android.util.MathUtils; 195import android.util.PrintStreamPrinter; 196import android.util.Slog; 197import android.util.SparseArray; 198import android.util.SparseBooleanArray; 199import android.util.SparseIntArray; 200import android.util.Xml; 201import android.view.Display; 202 203import dalvik.system.DexFile; 204import dalvik.system.VMRuntime; 205 206import libcore.io.IoUtils; 207import libcore.util.EmptyArray; 208 209import com.android.internal.R; 210import com.android.internal.annotations.GuardedBy; 211import com.android.internal.app.IMediaContainerService; 212import com.android.internal.app.ResolverActivity; 213import com.android.internal.content.NativeLibraryHelper; 214import com.android.internal.content.PackageHelper; 215import com.android.internal.os.IParcelFileDescriptorFactory; 216import com.android.internal.os.SomeArgs; 217import com.android.internal.os.Zygote; 218import com.android.internal.util.ArrayUtils; 219import com.android.internal.util.FastPrintWriter; 220import com.android.internal.util.FastXmlSerializer; 221import com.android.internal.util.IndentingPrintWriter; 222import com.android.internal.util.Preconditions; 223import com.android.server.EventLogTags; 224import com.android.server.FgThread; 225import com.android.server.IntentResolver; 226import com.android.server.LocalServices; 227import com.android.server.ServiceThread; 228import com.android.server.SystemConfig; 229import com.android.server.Watchdog; 230import com.android.server.pm.PermissionsState.PermissionState; 231import com.android.server.pm.Settings.DatabaseVersion; 232import com.android.server.pm.Settings.VersionInfo; 233import com.android.server.storage.DeviceStorageMonitorInternal; 234 235import org.xmlpull.v1.XmlPullParser; 236import org.xmlpull.v1.XmlPullParserException; 237import org.xmlpull.v1.XmlSerializer; 238 239import java.io.BufferedInputStream; 240import java.io.BufferedOutputStream; 241import java.io.BufferedReader; 242import java.io.ByteArrayInputStream; 243import java.io.ByteArrayOutputStream; 244import java.io.File; 245import java.io.FileDescriptor; 246import java.io.FileNotFoundException; 247import java.io.FileOutputStream; 248import java.io.FileReader; 249import java.io.FilenameFilter; 250import java.io.IOException; 251import java.io.InputStream; 252import java.io.PrintWriter; 253import java.nio.charset.StandardCharsets; 254import java.security.NoSuchAlgorithmException; 255import java.security.PublicKey; 256import java.security.cert.CertificateEncodingException; 257import java.security.cert.CertificateException; 258import java.text.SimpleDateFormat; 259import java.util.ArrayList; 260import java.util.Arrays; 261import java.util.Collection; 262import java.util.Collections; 263import java.util.Comparator; 264import java.util.Date; 265import java.util.Iterator; 266import java.util.List; 267import java.util.Map; 268import java.util.Objects; 269import java.util.Set; 270import java.util.concurrent.CountDownLatch; 271import java.util.concurrent.TimeUnit; 272import java.util.concurrent.atomic.AtomicBoolean; 273import java.util.concurrent.atomic.AtomicInteger; 274import java.util.concurrent.atomic.AtomicLong; 275 276/** 277 * Keep track of all those .apks everywhere. 278 * 279 * This is very central to the platform's security; please run the unit 280 * tests whenever making modifications here: 281 * 282runtest -c android.content.pm.PackageManagerTests frameworks-core 283 * 284 * {@hide} 285 */ 286public class PackageManagerService extends IPackageManager.Stub { 287 static final String TAG = "PackageManager"; 288 static final boolean DEBUG_SETTINGS = false; 289 static final boolean DEBUG_PREFERRED = false; 290 static final boolean DEBUG_UPGRADE = false; 291 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 292 private static final boolean DEBUG_BACKUP = false; 293 private static final boolean DEBUG_INSTALL = false; 294 private static final boolean DEBUG_REMOVE = false; 295 private static final boolean DEBUG_BROADCASTS = false; 296 private static final boolean DEBUG_SHOW_INFO = false; 297 private static final boolean DEBUG_PACKAGE_INFO = false; 298 private static final boolean DEBUG_INTENT_MATCHING = false; 299 private static final boolean DEBUG_PACKAGE_SCANNING = false; 300 private static final boolean DEBUG_VERIFY = false; 301 private static final boolean DEBUG_DEXOPT = false; 302 private static final boolean DEBUG_ABI_SELECTION = false; 303 304 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 305 306 private static final int RADIO_UID = Process.PHONE_UID; 307 private static final int LOG_UID = Process.LOG_UID; 308 private static final int NFC_UID = Process.NFC_UID; 309 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 310 private static final int SHELL_UID = Process.SHELL_UID; 311 312 // Cap the size of permission trees that 3rd party apps can define 313 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 314 315 // Suffix used during package installation when copying/moving 316 // package apks to install directory. 317 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 318 319 static final int SCAN_NO_DEX = 1<<1; 320 static final int SCAN_FORCE_DEX = 1<<2; 321 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 322 static final int SCAN_NEW_INSTALL = 1<<4; 323 static final int SCAN_NO_PATHS = 1<<5; 324 static final int SCAN_UPDATE_TIME = 1<<6; 325 static final int SCAN_DEFER_DEX = 1<<7; 326 static final int SCAN_BOOTING = 1<<8; 327 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 328 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 329 static final int SCAN_REPLACING = 1<<11; 330 static final int SCAN_REQUIRE_KNOWN = 1<<12; 331 static final int SCAN_MOVE = 1<<13; 332 static final int SCAN_INITIAL = 1<<14; 333 334 static final int REMOVE_CHATTY = 1<<16; 335 336 private static final int[] EMPTY_INT_ARRAY = new int[0]; 337 338 /** 339 * Timeout (in milliseconds) after which the watchdog should declare that 340 * our handler thread is wedged. The usual default for such things is one 341 * minute but we sometimes do very lengthy I/O operations on this thread, 342 * such as installing multi-gigabyte applications, so ours needs to be longer. 343 */ 344 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 345 346 /** 347 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 348 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 349 * settings entry if available, otherwise we use the hardcoded default. If it's been 350 * more than this long since the last fstrim, we force one during the boot sequence. 351 * 352 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 353 * one gets run at the next available charging+idle time. This final mandatory 354 * no-fstrim check kicks in only of the other scheduling criteria is never met. 355 */ 356 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 357 358 /** 359 * Whether verification is enabled by default. 360 */ 361 private static final boolean DEFAULT_VERIFY_ENABLE = true; 362 363 /** 364 * The default maximum time to wait for the verification agent to return in 365 * milliseconds. 366 */ 367 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 368 369 /** 370 * The default response for package verification timeout. 371 * 372 * This can be either PackageManager.VERIFICATION_ALLOW or 373 * PackageManager.VERIFICATION_REJECT. 374 */ 375 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 376 377 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 378 379 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 380 DEFAULT_CONTAINER_PACKAGE, 381 "com.android.defcontainer.DefaultContainerService"); 382 383 private static final String KILL_APP_REASON_GIDS_CHANGED = 384 "permission grant or revoke changed gids"; 385 386 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 387 "permissions revoked"; 388 389 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 390 391 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 392 393 /** Permission grant: not grant the permission. */ 394 private static final int GRANT_DENIED = 1; 395 396 /** Permission grant: grant the permission as an install permission. */ 397 private static final int GRANT_INSTALL = 2; 398 399 /** Permission grant: grant the permission as an install permission for a legacy app. */ 400 private static final int GRANT_INSTALL_LEGACY = 3; 401 402 /** Permission grant: grant the permission as a runtime one. */ 403 private static final int GRANT_RUNTIME = 4; 404 405 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 406 private static final int GRANT_UPGRADE = 5; 407 408 /** Canonical intent used to identify what counts as a "web browser" app */ 409 private static final Intent sBrowserIntent; 410 static { 411 sBrowserIntent = new Intent(); 412 sBrowserIntent.setAction(Intent.ACTION_VIEW); 413 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 414 sBrowserIntent.setData(Uri.parse("http:")); 415 } 416 417 final ServiceThread mHandlerThread; 418 419 final PackageHandler mHandler; 420 421 /** 422 * Messages for {@link #mHandler} that need to wait for system ready before 423 * being dispatched. 424 */ 425 private ArrayList<Message> mPostSystemReadyMessages; 426 427 final int mSdkVersion = Build.VERSION.SDK_INT; 428 429 final Context mContext; 430 final boolean mFactoryTest; 431 final boolean mOnlyCore; 432 final boolean mLazyDexOpt; 433 final long mDexOptLRUThresholdInMills; 434 final DisplayMetrics mMetrics; 435 final int mDefParseFlags; 436 final String[] mSeparateProcesses; 437 final boolean mIsUpgrade; 438 439 // This is where all application persistent data goes. 440 final File mAppDataDir; 441 442 // This is where all application persistent data goes for secondary users. 443 final File mUserAppDataDir; 444 445 /** The location for ASEC container files on internal storage. */ 446 final String mAsecInternalPath; 447 448 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 449 // LOCK HELD. Can be called with mInstallLock held. 450 @GuardedBy("mInstallLock") 451 final Installer mInstaller; 452 453 /** Directory where installed third-party apps stored */ 454 final File mAppInstallDir; 455 456 /** 457 * Directory to which applications installed internally have their 458 * 32 bit native libraries copied. 459 */ 460 private File mAppLib32InstallDir; 461 462 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 463 // apps. 464 final File mDrmAppPrivateInstallDir; 465 466 // ---------------------------------------------------------------- 467 468 // Lock for state used when installing and doing other long running 469 // operations. Methods that must be called with this lock held have 470 // the suffix "LI". 471 final Object mInstallLock = new Object(); 472 473 // ---------------------------------------------------------------- 474 475 // Keys are String (package name), values are Package. This also serves 476 // as the lock for the global state. Methods that must be called with 477 // this lock held have the prefix "LP". 478 @GuardedBy("mPackages") 479 final ArrayMap<String, PackageParser.Package> mPackages = 480 new ArrayMap<String, PackageParser.Package>(); 481 482 // Tracks available target package names -> overlay package paths. 483 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 484 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 485 486 /** 487 * Tracks new system packages [received in an OTA] that we expect to 488 * find updated user-installed versions. Keys are package name, values 489 * are package location. 490 */ 491 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 492 493 /** 494 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 495 */ 496 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 497 /** 498 * Whether or not system app permissions should be promoted from install to runtime. 499 */ 500 boolean mPromoteSystemApps; 501 502 final Settings mSettings; 503 boolean mRestoredSettings; 504 505 // System configuration read by SystemConfig. 506 final int[] mGlobalGids; 507 final SparseArray<ArraySet<String>> mSystemPermissions; 508 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 509 510 // If mac_permissions.xml was found for seinfo labeling. 511 boolean mFoundPolicyFile; 512 513 // If a recursive restorecon of /data/data/<pkg> is needed. 514 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 515 516 public static final class SharedLibraryEntry { 517 public final String path; 518 public final String apk; 519 520 SharedLibraryEntry(String _path, String _apk) { 521 path = _path; 522 apk = _apk; 523 } 524 } 525 526 // Currently known shared libraries. 527 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 528 new ArrayMap<String, SharedLibraryEntry>(); 529 530 // All available activities, for your resolving pleasure. 531 final ActivityIntentResolver mActivities = 532 new ActivityIntentResolver(); 533 534 // All available receivers, for your resolving pleasure. 535 final ActivityIntentResolver mReceivers = 536 new ActivityIntentResolver(); 537 538 // All available services, for your resolving pleasure. 539 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 540 541 // All available providers, for your resolving pleasure. 542 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 543 544 // Mapping from provider base names (first directory in content URI codePath) 545 // to the provider information. 546 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 547 new ArrayMap<String, PackageParser.Provider>(); 548 549 // Mapping from instrumentation class names to info about them. 550 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 551 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 552 553 // Mapping from permission names to info about them. 554 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 555 new ArrayMap<String, PackageParser.PermissionGroup>(); 556 557 // Packages whose data we have transfered into another package, thus 558 // should no longer exist. 559 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 560 561 // Broadcast actions that are only available to the system. 562 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 563 564 /** List of packages waiting for verification. */ 565 final SparseArray<PackageVerificationState> mPendingVerification 566 = new SparseArray<PackageVerificationState>(); 567 568 /** Set of packages associated with each app op permission. */ 569 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 570 571 final PackageInstallerService mInstallerService; 572 573 private final PackageDexOptimizer mPackageDexOptimizer; 574 575 private AtomicInteger mNextMoveId = new AtomicInteger(); 576 private final MoveCallbacks mMoveCallbacks; 577 578 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 579 580 // Cache of users who need badging. 581 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 582 583 /** Token for keys in mPendingVerification. */ 584 private int mPendingVerificationToken = 0; 585 586 volatile boolean mSystemReady; 587 volatile boolean mSafeMode; 588 volatile boolean mHasSystemUidErrors; 589 590 ApplicationInfo mAndroidApplication; 591 final ActivityInfo mResolveActivity = new ActivityInfo(); 592 final ResolveInfo mResolveInfo = new ResolveInfo(); 593 ComponentName mResolveComponentName; 594 PackageParser.Package mPlatformPackage; 595 ComponentName mCustomResolverComponentName; 596 597 boolean mResolverReplaced = false; 598 599 private final ComponentName mIntentFilterVerifierComponent; 600 private int mIntentFilterVerificationToken = 0; 601 602 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 603 = new SparseArray<IntentFilterVerificationState>(); 604 605 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 606 new DefaultPermissionGrantPolicy(this); 607 608 private static class IFVerificationParams { 609 PackageParser.Package pkg; 610 boolean replacing; 611 int userId; 612 int verifierUid; 613 614 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 615 int _userId, int _verifierUid) { 616 pkg = _pkg; 617 replacing = _replacing; 618 userId = _userId; 619 replacing = _replacing; 620 verifierUid = _verifierUid; 621 } 622 } 623 624 private interface IntentFilterVerifier<T extends IntentFilter> { 625 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 626 T filter, String packageName); 627 void startVerifications(int userId); 628 void receiveVerificationResponse(int verificationId); 629 } 630 631 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 632 private Context mContext; 633 private ComponentName mIntentFilterVerifierComponent; 634 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 635 636 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 637 mContext = context; 638 mIntentFilterVerifierComponent = verifierComponent; 639 } 640 641 private String getDefaultScheme() { 642 return IntentFilter.SCHEME_HTTPS; 643 } 644 645 @Override 646 public void startVerifications(int userId) { 647 // Launch verifications requests 648 int count = mCurrentIntentFilterVerifications.size(); 649 for (int n=0; n<count; n++) { 650 int verificationId = mCurrentIntentFilterVerifications.get(n); 651 final IntentFilterVerificationState ivs = 652 mIntentFilterVerificationStates.get(verificationId); 653 654 String packageName = ivs.getPackageName(); 655 656 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 657 final int filterCount = filters.size(); 658 ArraySet<String> domainsSet = new ArraySet<>(); 659 for (int m=0; m<filterCount; m++) { 660 PackageParser.ActivityIntentInfo filter = filters.get(m); 661 domainsSet.addAll(filter.getHostsList()); 662 } 663 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 664 synchronized (mPackages) { 665 if (mSettings.createIntentFilterVerificationIfNeededLPw( 666 packageName, domainsList) != null) { 667 scheduleWriteSettingsLocked(); 668 } 669 } 670 sendVerificationRequest(userId, verificationId, ivs); 671 } 672 mCurrentIntentFilterVerifications.clear(); 673 } 674 675 private void sendVerificationRequest(int userId, int verificationId, 676 IntentFilterVerificationState ivs) { 677 678 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 679 verificationIntent.putExtra( 680 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 681 verificationId); 682 verificationIntent.putExtra( 683 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 684 getDefaultScheme()); 685 verificationIntent.putExtra( 686 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 687 ivs.getHostsString()); 688 verificationIntent.putExtra( 689 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 690 ivs.getPackageName()); 691 verificationIntent.setComponent(mIntentFilterVerifierComponent); 692 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 693 694 UserHandle user = new UserHandle(userId); 695 mContext.sendBroadcastAsUser(verificationIntent, user); 696 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 697 "Sending IntentFilter verification broadcast"); 698 } 699 700 public void receiveVerificationResponse(int verificationId) { 701 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 702 703 final boolean verified = ivs.isVerified(); 704 705 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 706 final int count = filters.size(); 707 if (DEBUG_DOMAIN_VERIFICATION) { 708 Slog.i(TAG, "Received verification response " + verificationId 709 + " for " + count + " filters, verified=" + verified); 710 } 711 for (int n=0; n<count; n++) { 712 PackageParser.ActivityIntentInfo filter = filters.get(n); 713 filter.setVerified(verified); 714 715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 716 + " verified with result:" + verified + " and hosts:" 717 + ivs.getHostsString()); 718 } 719 720 mIntentFilterVerificationStates.remove(verificationId); 721 722 final String packageName = ivs.getPackageName(); 723 IntentFilterVerificationInfo ivi = null; 724 725 synchronized (mPackages) { 726 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 727 } 728 if (ivi == null) { 729 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 730 + verificationId + " packageName:" + packageName); 731 return; 732 } 733 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 734 "Updating IntentFilterVerificationInfo for package " + packageName 735 +" verificationId:" + verificationId); 736 737 synchronized (mPackages) { 738 if (verified) { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 740 } else { 741 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 742 } 743 scheduleWriteSettingsLocked(); 744 745 final int userId = ivs.getUserId(); 746 if (userId != UserHandle.USER_ALL) { 747 final int userStatus = 748 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 749 750 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 751 boolean needUpdate = false; 752 753 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 754 // already been set by the User thru the Disambiguation dialog 755 switch (userStatus) { 756 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 757 if (verified) { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 759 } else { 760 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 761 } 762 needUpdate = true; 763 break; 764 765 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 766 if (verified) { 767 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 768 needUpdate = true; 769 } 770 break; 771 772 default: 773 // Nothing to do 774 } 775 776 if (needUpdate) { 777 mSettings.updateIntentFilterVerificationStatusLPw( 778 packageName, updatedStatus, userId); 779 scheduleWritePackageRestrictionsLocked(userId); 780 } 781 } 782 } 783 } 784 785 @Override 786 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 787 ActivityIntentInfo filter, String packageName) { 788 if (!hasValidDomains(filter)) { 789 return false; 790 } 791 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 792 if (ivs == null) { 793 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 794 packageName); 795 } 796 if (DEBUG_DOMAIN_VERIFICATION) { 797 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 798 } 799 ivs.addFilter(filter); 800 return true; 801 } 802 803 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 804 int userId, int verificationId, String packageName) { 805 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 806 verifierUid, userId, packageName); 807 ivs.setPendingState(); 808 synchronized (mPackages) { 809 mIntentFilterVerificationStates.append(verificationId, ivs); 810 mCurrentIntentFilterVerifications.add(verificationId); 811 } 812 return ivs; 813 } 814 } 815 816 private static boolean hasValidDomains(ActivityIntentInfo filter) { 817 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 818 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 819 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 820 } 821 822 private IntentFilterVerifier mIntentFilterVerifier; 823 824 // Set of pending broadcasts for aggregating enable/disable of components. 825 static class PendingPackageBroadcasts { 826 // for each user id, a map of <package name -> components within that package> 827 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 828 829 public PendingPackageBroadcasts() { 830 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 831 } 832 833 public ArrayList<String> get(int userId, String packageName) { 834 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 835 return packages.get(packageName); 836 } 837 838 public void put(int userId, String packageName, ArrayList<String> components) { 839 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 840 packages.put(packageName, components); 841 } 842 843 public void remove(int userId, String packageName) { 844 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 845 if (packages != null) { 846 packages.remove(packageName); 847 } 848 } 849 850 public void remove(int userId) { 851 mUidMap.remove(userId); 852 } 853 854 public int userIdCount() { 855 return mUidMap.size(); 856 } 857 858 public int userIdAt(int n) { 859 return mUidMap.keyAt(n); 860 } 861 862 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 863 return mUidMap.get(userId); 864 } 865 866 public int size() { 867 // total number of pending broadcast entries across all userIds 868 int num = 0; 869 for (int i = 0; i< mUidMap.size(); i++) { 870 num += mUidMap.valueAt(i).size(); 871 } 872 return num; 873 } 874 875 public void clear() { 876 mUidMap.clear(); 877 } 878 879 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 880 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 881 if (map == null) { 882 map = new ArrayMap<String, ArrayList<String>>(); 883 mUidMap.put(userId, map); 884 } 885 return map; 886 } 887 } 888 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 889 890 // Service Connection to remote media container service to copy 891 // package uri's from external media onto secure containers 892 // or internal storage. 893 private IMediaContainerService mContainerService = null; 894 895 static final int SEND_PENDING_BROADCAST = 1; 896 static final int MCS_BOUND = 3; 897 static final int END_COPY = 4; 898 static final int INIT_COPY = 5; 899 static final int MCS_UNBIND = 6; 900 static final int START_CLEANING_PACKAGE = 7; 901 static final int FIND_INSTALL_LOC = 8; 902 static final int POST_INSTALL = 9; 903 static final int MCS_RECONNECT = 10; 904 static final int MCS_GIVE_UP = 11; 905 static final int UPDATED_MEDIA_STATUS = 12; 906 static final int WRITE_SETTINGS = 13; 907 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 908 static final int PACKAGE_VERIFIED = 15; 909 static final int CHECK_PENDING_VERIFICATION = 16; 910 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 911 static final int INTENT_FILTER_VERIFIED = 18; 912 913 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 914 915 // Delay time in millisecs 916 static final int BROADCAST_DELAY = 10 * 1000; 917 918 static UserManagerService sUserManager; 919 920 // Stores a list of users whose package restrictions file needs to be updated 921 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 922 923 final private DefaultContainerConnection mDefContainerConn = 924 new DefaultContainerConnection(); 925 class DefaultContainerConnection implements ServiceConnection { 926 public void onServiceConnected(ComponentName name, IBinder service) { 927 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 928 IMediaContainerService imcs = 929 IMediaContainerService.Stub.asInterface(service); 930 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 931 } 932 933 public void onServiceDisconnected(ComponentName name) { 934 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 935 } 936 } 937 938 // Recordkeeping of restore-after-install operations that are currently in flight 939 // between the Package Manager and the Backup Manager 940 class PostInstallData { 941 public InstallArgs args; 942 public PackageInstalledInfo res; 943 944 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 945 args = _a; 946 res = _r; 947 } 948 } 949 950 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 951 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 952 953 // XML tags for backup/restore of various bits of state 954 private static final String TAG_PREFERRED_BACKUP = "pa"; 955 private static final String TAG_DEFAULT_APPS = "da"; 956 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 957 958 final String mRequiredVerifierPackage; 959 final String mRequiredInstallerPackage; 960 961 private final PackageUsage mPackageUsage = new PackageUsage(); 962 963 private class PackageUsage { 964 private static final int WRITE_INTERVAL 965 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 966 967 private final Object mFileLock = new Object(); 968 private final AtomicLong mLastWritten = new AtomicLong(0); 969 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 970 971 private boolean mIsHistoricalPackageUsageAvailable = true; 972 973 boolean isHistoricalPackageUsageAvailable() { 974 return mIsHistoricalPackageUsageAvailable; 975 } 976 977 void write(boolean force) { 978 if (force) { 979 writeInternal(); 980 return; 981 } 982 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 983 && !DEBUG_DEXOPT) { 984 return; 985 } 986 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 987 new Thread("PackageUsage_DiskWriter") { 988 @Override 989 public void run() { 990 try { 991 writeInternal(); 992 } finally { 993 mBackgroundWriteRunning.set(false); 994 } 995 } 996 }.start(); 997 } 998 } 999 1000 private void writeInternal() { 1001 synchronized (mPackages) { 1002 synchronized (mFileLock) { 1003 AtomicFile file = getFile(); 1004 FileOutputStream f = null; 1005 try { 1006 f = file.startWrite(); 1007 BufferedOutputStream out = new BufferedOutputStream(f); 1008 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1009 StringBuilder sb = new StringBuilder(); 1010 for (PackageParser.Package pkg : mPackages.values()) { 1011 if (pkg.mLastPackageUsageTimeInMills == 0) { 1012 continue; 1013 } 1014 sb.setLength(0); 1015 sb.append(pkg.packageName); 1016 sb.append(' '); 1017 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1018 sb.append('\n'); 1019 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1020 } 1021 out.flush(); 1022 file.finishWrite(f); 1023 } catch (IOException e) { 1024 if (f != null) { 1025 file.failWrite(f); 1026 } 1027 Log.e(TAG, "Failed to write package usage times", e); 1028 } 1029 } 1030 } 1031 mLastWritten.set(SystemClock.elapsedRealtime()); 1032 } 1033 1034 void readLP() { 1035 synchronized (mFileLock) { 1036 AtomicFile file = getFile(); 1037 BufferedInputStream in = null; 1038 try { 1039 in = new BufferedInputStream(file.openRead()); 1040 StringBuffer sb = new StringBuffer(); 1041 while (true) { 1042 String packageName = readToken(in, sb, ' '); 1043 if (packageName == null) { 1044 break; 1045 } 1046 String timeInMillisString = readToken(in, sb, '\n'); 1047 if (timeInMillisString == null) { 1048 throw new IOException("Failed to find last usage time for package " 1049 + packageName); 1050 } 1051 PackageParser.Package pkg = mPackages.get(packageName); 1052 if (pkg == null) { 1053 continue; 1054 } 1055 long timeInMillis; 1056 try { 1057 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1058 } catch (NumberFormatException e) { 1059 throw new IOException("Failed to parse " + timeInMillisString 1060 + " as a long.", e); 1061 } 1062 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1063 } 1064 } catch (FileNotFoundException expected) { 1065 mIsHistoricalPackageUsageAvailable = false; 1066 } catch (IOException e) { 1067 Log.w(TAG, "Failed to read package usage times", e); 1068 } finally { 1069 IoUtils.closeQuietly(in); 1070 } 1071 } 1072 mLastWritten.set(SystemClock.elapsedRealtime()); 1073 } 1074 1075 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1076 throws IOException { 1077 sb.setLength(0); 1078 while (true) { 1079 int ch = in.read(); 1080 if (ch == -1) { 1081 if (sb.length() == 0) { 1082 return null; 1083 } 1084 throw new IOException("Unexpected EOF"); 1085 } 1086 if (ch == endOfToken) { 1087 return sb.toString(); 1088 } 1089 sb.append((char)ch); 1090 } 1091 } 1092 1093 private AtomicFile getFile() { 1094 File dataDir = Environment.getDataDirectory(); 1095 File systemDir = new File(dataDir, "system"); 1096 File fname = new File(systemDir, "package-usage.list"); 1097 return new AtomicFile(fname); 1098 } 1099 } 1100 1101 class PackageHandler extends Handler { 1102 private boolean mBound = false; 1103 final ArrayList<HandlerParams> mPendingInstalls = 1104 new ArrayList<HandlerParams>(); 1105 1106 private boolean connectToService() { 1107 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1108 " DefaultContainerService"); 1109 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1111 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1112 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1113 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1114 mBound = true; 1115 return true; 1116 } 1117 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1118 return false; 1119 } 1120 1121 private void disconnectService() { 1122 mContainerService = null; 1123 mBound = false; 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1125 mContext.unbindService(mDefContainerConn); 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1127 } 1128 1129 PackageHandler(Looper looper) { 1130 super(looper); 1131 } 1132 1133 public void handleMessage(Message msg) { 1134 try { 1135 doHandleMessage(msg); 1136 } finally { 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1138 } 1139 } 1140 1141 void doHandleMessage(Message msg) { 1142 switch (msg.what) { 1143 case INIT_COPY: { 1144 HandlerParams params = (HandlerParams) msg.obj; 1145 int idx = mPendingInstalls.size(); 1146 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1147 // If a bind was already initiated we dont really 1148 // need to do anything. The pending install 1149 // will be processed later on. 1150 if (!mBound) { 1151 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1152 System.identityHashCode(mHandler)); 1153 // If this is the only one pending we might 1154 // have to bind to the service again. 1155 if (!connectToService()) { 1156 Slog.e(TAG, "Failed to bind to media container service"); 1157 params.serviceError(); 1158 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1159 System.identityHashCode(mHandler)); 1160 if (params.traceMethod != null) { 1161 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1162 params.traceCookie); 1163 } 1164 return; 1165 } else { 1166 // Once we bind to the service, the first 1167 // pending request will be processed. 1168 mPendingInstalls.add(idx, params); 1169 } 1170 } else { 1171 mPendingInstalls.add(idx, params); 1172 // Already bound to the service. Just make 1173 // sure we trigger off processing the first request. 1174 if (idx == 0) { 1175 mHandler.sendEmptyMessage(MCS_BOUND); 1176 } 1177 } 1178 break; 1179 } 1180 case MCS_BOUND: { 1181 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1182 if (msg.obj != null) { 1183 mContainerService = (IMediaContainerService) msg.obj; 1184 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1185 System.identityHashCode(mHandler)); 1186 } 1187 if (mContainerService == null) { 1188 if (!mBound) { 1189 // Something seriously wrong since we are not bound and we are not 1190 // waiting for connection. Bail out. 1191 Slog.e(TAG, "Cannot bind to media container service"); 1192 for (HandlerParams params : mPendingInstalls) { 1193 // Indicate service bind error 1194 params.serviceError(); 1195 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1196 System.identityHashCode(params)); 1197 if (params.traceMethod != null) { 1198 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1199 params.traceMethod, params.traceCookie); 1200 } 1201 return; 1202 } 1203 mPendingInstalls.clear(); 1204 } else { 1205 Slog.w(TAG, "Waiting to connect to media container service"); 1206 } 1207 } else if (mPendingInstalls.size() > 0) { 1208 HandlerParams params = mPendingInstalls.get(0); 1209 if (params != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1211 System.identityHashCode(params)); 1212 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1213 if (params.startCopy()) { 1214 // We are done... look for more work or to 1215 // go idle. 1216 if (DEBUG_SD_INSTALL) Log.i(TAG, 1217 "Checking for more work or unbind..."); 1218 // Delete pending install 1219 if (mPendingInstalls.size() > 0) { 1220 mPendingInstalls.remove(0); 1221 } 1222 if (mPendingInstalls.size() == 0) { 1223 if (mBound) { 1224 if (DEBUG_SD_INSTALL) Log.i(TAG, 1225 "Posting delayed MCS_UNBIND"); 1226 removeMessages(MCS_UNBIND); 1227 Message ubmsg = obtainMessage(MCS_UNBIND); 1228 // Unbind after a little delay, to avoid 1229 // continual thrashing. 1230 sendMessageDelayed(ubmsg, 10000); 1231 } 1232 } else { 1233 // There are more pending requests in queue. 1234 // Just post MCS_BOUND message to trigger processing 1235 // of next pending install. 1236 if (DEBUG_SD_INSTALL) Log.i(TAG, 1237 "Posting MCS_BOUND for next work"); 1238 mHandler.sendEmptyMessage(MCS_BOUND); 1239 } 1240 } 1241 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1242 } 1243 } else { 1244 // Should never happen ideally. 1245 Slog.w(TAG, "Empty queue"); 1246 } 1247 break; 1248 } 1249 case MCS_RECONNECT: { 1250 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1251 if (mPendingInstalls.size() > 0) { 1252 if (mBound) { 1253 disconnectService(); 1254 } 1255 if (!connectToService()) { 1256 Slog.e(TAG, "Failed to bind to media container service"); 1257 for (HandlerParams params : mPendingInstalls) { 1258 // Indicate service bind error 1259 params.serviceError(); 1260 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1261 System.identityHashCode(params)); 1262 } 1263 mPendingInstalls.clear(); 1264 } 1265 } 1266 break; 1267 } 1268 case MCS_UNBIND: { 1269 // If there is no actual work left, then time to unbind. 1270 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1271 1272 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1273 if (mBound) { 1274 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1275 1276 disconnectService(); 1277 } 1278 } else if (mPendingInstalls.size() > 0) { 1279 // There are more pending requests in queue. 1280 // Just post MCS_BOUND message to trigger processing 1281 // of next pending install. 1282 mHandler.sendEmptyMessage(MCS_BOUND); 1283 } 1284 1285 break; 1286 } 1287 case MCS_GIVE_UP: { 1288 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1289 HandlerParams params = mPendingInstalls.remove(0); 1290 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1291 System.identityHashCode(params)); 1292 break; 1293 } 1294 case SEND_PENDING_BROADCAST: { 1295 String packages[]; 1296 ArrayList<String> components[]; 1297 int size = 0; 1298 int uids[]; 1299 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1300 synchronized (mPackages) { 1301 if (mPendingBroadcasts == null) { 1302 return; 1303 } 1304 size = mPendingBroadcasts.size(); 1305 if (size <= 0) { 1306 // Nothing to be done. Just return 1307 return; 1308 } 1309 packages = new String[size]; 1310 components = new ArrayList[size]; 1311 uids = new int[size]; 1312 int i = 0; // filling out the above arrays 1313 1314 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1315 int packageUserId = mPendingBroadcasts.userIdAt(n); 1316 Iterator<Map.Entry<String, ArrayList<String>>> it 1317 = mPendingBroadcasts.packagesForUserId(packageUserId) 1318 .entrySet().iterator(); 1319 while (it.hasNext() && i < size) { 1320 Map.Entry<String, ArrayList<String>> ent = it.next(); 1321 packages[i] = ent.getKey(); 1322 components[i] = ent.getValue(); 1323 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1324 uids[i] = (ps != null) 1325 ? UserHandle.getUid(packageUserId, ps.appId) 1326 : -1; 1327 i++; 1328 } 1329 } 1330 size = i; 1331 mPendingBroadcasts.clear(); 1332 } 1333 // Send broadcasts 1334 for (int i = 0; i < size; i++) { 1335 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1336 } 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1338 break; 1339 } 1340 case START_CLEANING_PACKAGE: { 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 final String packageName = (String)msg.obj; 1343 final int userId = msg.arg1; 1344 final boolean andCode = msg.arg2 != 0; 1345 synchronized (mPackages) { 1346 if (userId == UserHandle.USER_ALL) { 1347 int[] users = sUserManager.getUserIds(); 1348 for (int user : users) { 1349 mSettings.addPackageToCleanLPw( 1350 new PackageCleanItem(user, packageName, andCode)); 1351 } 1352 } else { 1353 mSettings.addPackageToCleanLPw( 1354 new PackageCleanItem(userId, packageName, andCode)); 1355 } 1356 } 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 startCleaningPackages(); 1359 } break; 1360 case POST_INSTALL: { 1361 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1362 PostInstallData data = mRunningInstalls.get(msg.arg1); 1363 mRunningInstalls.delete(msg.arg1); 1364 boolean deleteOld = false; 1365 1366 if (data != null) { 1367 InstallArgs args = data.args; 1368 PackageInstalledInfo res = data.res; 1369 1370 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1371 final String packageName = res.pkg.applicationInfo.packageName; 1372 res.removedInfo.sendBroadcast(false, true, false); 1373 Bundle extras = new Bundle(1); 1374 extras.putInt(Intent.EXTRA_UID, res.uid); 1375 1376 // Now that we successfully installed the package, grant runtime 1377 // permissions if requested before broadcasting the install. 1378 if ((args.installFlags 1379 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1380 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1381 args.installGrantPermissions); 1382 } 1383 1384 // Determine the set of users who are adding this 1385 // package for the first time vs. those who are seeing 1386 // an update. 1387 int[] firstUsers; 1388 int[] updateUsers = new int[0]; 1389 if (res.origUsers == null || res.origUsers.length == 0) { 1390 firstUsers = res.newUsers; 1391 } else { 1392 firstUsers = new int[0]; 1393 for (int i=0; i<res.newUsers.length; i++) { 1394 int user = res.newUsers[i]; 1395 boolean isNew = true; 1396 for (int j=0; j<res.origUsers.length; j++) { 1397 if (res.origUsers[j] == user) { 1398 isNew = false; 1399 break; 1400 } 1401 } 1402 if (isNew) { 1403 int[] newFirst = new int[firstUsers.length+1]; 1404 System.arraycopy(firstUsers, 0, newFirst, 0, 1405 firstUsers.length); 1406 newFirst[firstUsers.length] = user; 1407 firstUsers = newFirst; 1408 } else { 1409 int[] newUpdate = new int[updateUsers.length+1]; 1410 System.arraycopy(updateUsers, 0, newUpdate, 0, 1411 updateUsers.length); 1412 newUpdate[updateUsers.length] = user; 1413 updateUsers = newUpdate; 1414 } 1415 } 1416 } 1417 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1418 packageName, extras, null, null, firstUsers); 1419 final boolean update = res.removedInfo.removedPackage != null; 1420 if (update) { 1421 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1422 } 1423 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1424 packageName, extras, null, null, updateUsers); 1425 if (update) { 1426 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1427 packageName, extras, null, null, updateUsers); 1428 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1429 null, null, packageName, null, updateUsers); 1430 1431 // treat asec-hosted packages like removable media on upgrade 1432 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1433 if (DEBUG_INSTALL) { 1434 Slog.i(TAG, "upgrading pkg " + res.pkg 1435 + " is ASEC-hosted -> AVAILABLE"); 1436 } 1437 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1438 ArrayList<String> pkgList = new ArrayList<String>(1); 1439 pkgList.add(packageName); 1440 sendResourcesChangedBroadcast(true, true, 1441 pkgList,uidArray, null); 1442 } 1443 } 1444 if (res.removedInfo.args != null) { 1445 // Remove the replaced package's older resources safely now 1446 deleteOld = true; 1447 } 1448 1449 // If this app is a browser and it's newly-installed for some 1450 // users, clear any default-browser state in those users 1451 if (firstUsers.length > 0) { 1452 // the app's nature doesn't depend on the user, so we can just 1453 // check its browser nature in any user and generalize. 1454 if (packageIsBrowser(packageName, firstUsers[0])) { 1455 synchronized (mPackages) { 1456 for (int userId : firstUsers) { 1457 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1458 } 1459 } 1460 } 1461 } 1462 // Log current value of "unknown sources" setting 1463 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1464 getUnknownSourcesSettings()); 1465 } 1466 // Force a gc to clear up things 1467 Runtime.getRuntime().gc(); 1468 // We delete after a gc for applications on sdcard. 1469 if (deleteOld) { 1470 synchronized (mInstallLock) { 1471 res.removedInfo.args.doPostDeleteLI(true); 1472 } 1473 } 1474 if (args.observer != null) { 1475 try { 1476 Bundle extras = extrasForInstallResult(res); 1477 args.observer.onPackageInstalled(res.name, res.returnCode, 1478 res.returnMsg, extras); 1479 } catch (RemoteException e) { 1480 Slog.i(TAG, "Observer no longer exists."); 1481 } 1482 } 1483 if (args.traceMethod != null) { 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1485 args.traceCookie); 1486 } 1487 return; 1488 } else { 1489 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1490 } 1491 1492 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1493 } break; 1494 case UPDATED_MEDIA_STATUS: { 1495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1496 boolean reportStatus = msg.arg1 == 1; 1497 boolean doGc = msg.arg2 == 1; 1498 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1499 if (doGc) { 1500 // Force a gc to clear up stale containers. 1501 Runtime.getRuntime().gc(); 1502 } 1503 if (msg.obj != null) { 1504 @SuppressWarnings("unchecked") 1505 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1506 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1507 // Unload containers 1508 unloadAllContainers(args); 1509 } 1510 if (reportStatus) { 1511 try { 1512 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1513 PackageHelper.getMountService().finishMediaUpdate(); 1514 } catch (RemoteException e) { 1515 Log.e(TAG, "MountService not running?"); 1516 } 1517 } 1518 } break; 1519 case WRITE_SETTINGS: { 1520 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1521 synchronized (mPackages) { 1522 removeMessages(WRITE_SETTINGS); 1523 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1524 mSettings.writeLPr(); 1525 mDirtyUsers.clear(); 1526 } 1527 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1528 } break; 1529 case WRITE_PACKAGE_RESTRICTIONS: { 1530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1531 synchronized (mPackages) { 1532 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1533 for (int userId : mDirtyUsers) { 1534 mSettings.writePackageRestrictionsLPr(userId); 1535 } 1536 mDirtyUsers.clear(); 1537 } 1538 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1539 } break; 1540 case CHECK_PENDING_VERIFICATION: { 1541 final int verificationId = msg.arg1; 1542 final PackageVerificationState state = mPendingVerification.get(verificationId); 1543 1544 if ((state != null) && !state.timeoutExtended()) { 1545 final InstallArgs args = state.getInstallArgs(); 1546 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1547 1548 Slog.i(TAG, "Verification timed out for " + originUri); 1549 mPendingVerification.remove(verificationId); 1550 1551 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1552 1553 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1554 Slog.i(TAG, "Continuing with installation of " + originUri); 1555 state.setVerifierResponse(Binder.getCallingUid(), 1556 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1557 broadcastPackageVerified(verificationId, originUri, 1558 PackageManager.VERIFICATION_ALLOW, 1559 state.getInstallArgs().getUser()); 1560 try { 1561 ret = args.copyApk(mContainerService, true); 1562 } catch (RemoteException e) { 1563 Slog.e(TAG, "Could not contact the ContainerService"); 1564 } 1565 } else { 1566 broadcastPackageVerified(verificationId, originUri, 1567 PackageManager.VERIFICATION_REJECT, 1568 state.getInstallArgs().getUser()); 1569 } 1570 1571 Trace.asyncTraceEnd( 1572 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1573 1574 processPendingInstall(args, ret); 1575 mHandler.sendEmptyMessage(MCS_UNBIND); 1576 } 1577 break; 1578 } 1579 case PACKAGE_VERIFIED: { 1580 final int verificationId = msg.arg1; 1581 1582 final PackageVerificationState state = mPendingVerification.get(verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1585 break; 1586 } 1587 1588 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1589 1590 state.setVerifierResponse(response.callerUid, response.code); 1591 1592 if (state.isVerificationComplete()) { 1593 mPendingVerification.remove(verificationId); 1594 1595 final InstallArgs args = state.getInstallArgs(); 1596 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1597 1598 int ret; 1599 if (state.isInstallAllowed()) { 1600 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1601 broadcastPackageVerified(verificationId, originUri, 1602 response.code, state.getInstallArgs().getUser()); 1603 try { 1604 ret = args.copyApk(mContainerService, true); 1605 } catch (RemoteException e) { 1606 Slog.e(TAG, "Could not contact the ContainerService"); 1607 } 1608 } else { 1609 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1610 } 1611 1612 Trace.asyncTraceEnd( 1613 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1614 1615 processPendingInstall(args, ret); 1616 mHandler.sendEmptyMessage(MCS_UNBIND); 1617 } 1618 1619 break; 1620 } 1621 case START_INTENT_FILTER_VERIFICATIONS: { 1622 IFVerificationParams params = (IFVerificationParams) msg.obj; 1623 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1624 params.replacing, params.pkg); 1625 break; 1626 } 1627 case INTENT_FILTER_VERIFIED: { 1628 final int verificationId = msg.arg1; 1629 1630 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1631 verificationId); 1632 if (state == null) { 1633 Slog.w(TAG, "Invalid IntentFilter verification token " 1634 + verificationId + " received"); 1635 break; 1636 } 1637 1638 final int userId = state.getUserId(); 1639 1640 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1641 "Processing IntentFilter verification with token:" 1642 + verificationId + " and userId:" + userId); 1643 1644 final IntentFilterVerificationResponse response = 1645 (IntentFilterVerificationResponse) msg.obj; 1646 1647 state.setVerifierResponse(response.callerUid, response.code); 1648 1649 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1650 "IntentFilter verification with token:" + verificationId 1651 + " and userId:" + userId 1652 + " is settings verifier response with response code:" 1653 + response.code); 1654 1655 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1656 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1657 + response.getFailedDomainsString()); 1658 } 1659 1660 if (state.isVerificationComplete()) { 1661 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1662 } else { 1663 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1664 "IntentFilter verification with token:" + verificationId 1665 + " was not said to be complete"); 1666 } 1667 1668 break; 1669 } 1670 } 1671 } 1672 } 1673 1674 private StorageEventListener mStorageListener = new StorageEventListener() { 1675 @Override 1676 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1677 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1678 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1679 final String volumeUuid = vol.getFsUuid(); 1680 1681 // Clean up any users or apps that were removed or recreated 1682 // while this volume was missing 1683 reconcileUsers(volumeUuid); 1684 reconcileApps(volumeUuid); 1685 1686 // Clean up any install sessions that expired or were 1687 // cancelled while this volume was missing 1688 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1689 1690 loadPrivatePackages(vol); 1691 1692 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1693 unloadPrivatePackages(vol); 1694 } 1695 } 1696 1697 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1698 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1699 updateExternalMediaStatus(true, false); 1700 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1701 updateExternalMediaStatus(false, false); 1702 } 1703 } 1704 } 1705 1706 @Override 1707 public void onVolumeForgotten(String fsUuid) { 1708 if (TextUtils.isEmpty(fsUuid)) { 1709 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1710 return; 1711 } 1712 1713 // Remove any apps installed on the forgotten volume 1714 synchronized (mPackages) { 1715 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1716 for (PackageSetting ps : packages) { 1717 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1718 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1719 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1720 } 1721 1722 mSettings.onVolumeForgotten(fsUuid); 1723 mSettings.writeLPr(); 1724 } 1725 } 1726 }; 1727 1728 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1729 String[] grantedPermissions) { 1730 if (userId >= UserHandle.USER_SYSTEM) { 1731 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1732 } else if (userId == UserHandle.USER_ALL) { 1733 final int[] userIds; 1734 synchronized (mPackages) { 1735 userIds = UserManagerService.getInstance().getUserIds(); 1736 } 1737 for (int someUserId : userIds) { 1738 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1739 } 1740 } 1741 1742 // We could have touched GID membership, so flush out packages.list 1743 synchronized (mPackages) { 1744 mSettings.writePackageListLPr(); 1745 } 1746 } 1747 1748 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1749 String[] grantedPermissions) { 1750 SettingBase sb = (SettingBase) pkg.mExtras; 1751 if (sb == null) { 1752 return; 1753 } 1754 1755 PermissionsState permissionsState = sb.getPermissionsState(); 1756 1757 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1758 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1759 1760 synchronized (mPackages) { 1761 for (String permission : pkg.requestedPermissions) { 1762 BasePermission bp = mSettings.mPermissions.get(permission); 1763 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1764 && (grantedPermissions == null 1765 || ArrayUtils.contains(grantedPermissions, permission))) { 1766 final int flags = permissionsState.getPermissionFlags(permission, userId); 1767 // Installer cannot change immutable permissions. 1768 if ((flags & immutableFlags) == 0) { 1769 grantRuntimePermission(pkg.packageName, permission, userId); 1770 } 1771 } 1772 } 1773 } 1774 } 1775 1776 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1777 Bundle extras = null; 1778 switch (res.returnCode) { 1779 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1780 extras = new Bundle(); 1781 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1782 res.origPermission); 1783 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1784 res.origPackage); 1785 break; 1786 } 1787 case PackageManager.INSTALL_SUCCEEDED: { 1788 extras = new Bundle(); 1789 extras.putBoolean(Intent.EXTRA_REPLACING, 1790 res.removedInfo != null && res.removedInfo.removedPackage != null); 1791 break; 1792 } 1793 } 1794 return extras; 1795 } 1796 1797 void scheduleWriteSettingsLocked() { 1798 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1799 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1800 } 1801 } 1802 1803 void scheduleWritePackageRestrictionsLocked(int userId) { 1804 if (!sUserManager.exists(userId)) return; 1805 mDirtyUsers.add(userId); 1806 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1807 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1808 } 1809 } 1810 1811 public static PackageManagerService main(Context context, Installer installer, 1812 boolean factoryTest, boolean onlyCore) { 1813 PackageManagerService m = new PackageManagerService(context, installer, 1814 factoryTest, onlyCore); 1815 ServiceManager.addService("package", m); 1816 return m; 1817 } 1818 1819 static String[] splitString(String str, char sep) { 1820 int count = 1; 1821 int i = 0; 1822 while ((i=str.indexOf(sep, i)) >= 0) { 1823 count++; 1824 i++; 1825 } 1826 1827 String[] res = new String[count]; 1828 i=0; 1829 count = 0; 1830 int lastI=0; 1831 while ((i=str.indexOf(sep, i)) >= 0) { 1832 res[count] = str.substring(lastI, i); 1833 count++; 1834 i++; 1835 lastI = i; 1836 } 1837 res[count] = str.substring(lastI, str.length()); 1838 return res; 1839 } 1840 1841 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1842 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1843 Context.DISPLAY_SERVICE); 1844 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1845 } 1846 1847 public PackageManagerService(Context context, Installer installer, 1848 boolean factoryTest, boolean onlyCore) { 1849 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1850 SystemClock.uptimeMillis()); 1851 1852 if (mSdkVersion <= 0) { 1853 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1854 } 1855 1856 mContext = context; 1857 mFactoryTest = factoryTest; 1858 mOnlyCore = onlyCore; 1859 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1860 mMetrics = new DisplayMetrics(); 1861 mSettings = new Settings(mPackages); 1862 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1863 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1864 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1865 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1866 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1867 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1868 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1869 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1870 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1871 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1872 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1873 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1874 1875 // TODO: add a property to control this? 1876 long dexOptLRUThresholdInMinutes; 1877 if (mLazyDexOpt) { 1878 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1879 } else { 1880 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1881 } 1882 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1883 1884 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1885 if (separateProcesses != null && separateProcesses.length() > 0) { 1886 if ("*".equals(separateProcesses)) { 1887 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1888 mSeparateProcesses = null; 1889 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1890 } else { 1891 mDefParseFlags = 0; 1892 mSeparateProcesses = separateProcesses.split(","); 1893 Slog.w(TAG, "Running with debug.separate_processes: " 1894 + separateProcesses); 1895 } 1896 } else { 1897 mDefParseFlags = 0; 1898 mSeparateProcesses = null; 1899 } 1900 1901 mInstaller = installer; 1902 mPackageDexOptimizer = new PackageDexOptimizer(this); 1903 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1904 1905 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1906 FgThread.get().getLooper()); 1907 1908 getDefaultDisplayMetrics(context, mMetrics); 1909 1910 SystemConfig systemConfig = SystemConfig.getInstance(); 1911 mGlobalGids = systemConfig.getGlobalGids(); 1912 mSystemPermissions = systemConfig.getSystemPermissions(); 1913 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1914 1915 synchronized (mInstallLock) { 1916 // writer 1917 synchronized (mPackages) { 1918 mHandlerThread = new ServiceThread(TAG, 1919 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1920 mHandlerThread.start(); 1921 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1922 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1923 1924 File dataDir = Environment.getDataDirectory(); 1925 mAppDataDir = new File(dataDir, "data"); 1926 mAppInstallDir = new File(dataDir, "app"); 1927 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1928 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1929 mUserAppDataDir = new File(dataDir, "user"); 1930 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1931 1932 sUserManager = new UserManagerService(context, this, 1933 mInstallLock, mPackages); 1934 1935 // Propagate permission configuration in to package manager. 1936 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1937 = systemConfig.getPermissions(); 1938 for (int i=0; i<permConfig.size(); i++) { 1939 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1940 BasePermission bp = mSettings.mPermissions.get(perm.name); 1941 if (bp == null) { 1942 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1943 mSettings.mPermissions.put(perm.name, bp); 1944 } 1945 if (perm.gids != null) { 1946 bp.setGids(perm.gids, perm.perUser); 1947 } 1948 } 1949 1950 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1951 for (int i=0; i<libConfig.size(); i++) { 1952 mSharedLibraries.put(libConfig.keyAt(i), 1953 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1954 } 1955 1956 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1957 1958 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1959 1960 String customResolverActivity = Resources.getSystem().getString( 1961 R.string.config_customResolverActivity); 1962 if (TextUtils.isEmpty(customResolverActivity)) { 1963 customResolverActivity = null; 1964 } else { 1965 mCustomResolverComponentName = ComponentName.unflattenFromString( 1966 customResolverActivity); 1967 } 1968 1969 long startTime = SystemClock.uptimeMillis(); 1970 1971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1972 startTime); 1973 1974 // Set flag to monitor and not change apk file paths when 1975 // scanning install directories. 1976 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1977 1978 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1979 1980 /** 1981 * Add everything in the in the boot class path to the 1982 * list of process files because dexopt will have been run 1983 * if necessary during zygote startup. 1984 */ 1985 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1986 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1987 1988 if (bootClassPath != null) { 1989 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1990 for (String element : bootClassPathElements) { 1991 alreadyDexOpted.add(element); 1992 } 1993 } else { 1994 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1995 } 1996 1997 if (systemServerClassPath != null) { 1998 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1999 for (String element : systemServerClassPathElements) { 2000 alreadyDexOpted.add(element); 2001 } 2002 } else { 2003 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2004 } 2005 2006 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2007 final String[] dexCodeInstructionSets = 2008 getDexCodeInstructionSets( 2009 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2010 2011 /** 2012 * Ensure all external libraries have had dexopt run on them. 2013 */ 2014 if (mSharedLibraries.size() > 0) { 2015 // NOTE: For now, we're compiling these system "shared libraries" 2016 // (and framework jars) into all available architectures. It's possible 2017 // to compile them only when we come across an app that uses them (there's 2018 // already logic for that in scanPackageLI) but that adds some complexity. 2019 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2020 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2021 final String lib = libEntry.path; 2022 if (lib == null) { 2023 continue; 2024 } 2025 2026 try { 2027 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2028 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2029 alreadyDexOpted.add(lib); 2030 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2031 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2032 } 2033 } catch (FileNotFoundException e) { 2034 Slog.w(TAG, "Library not found: " + lib); 2035 } catch (IOException e) { 2036 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2037 + e.getMessage()); 2038 } 2039 } 2040 } 2041 } 2042 2043 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2044 2045 // Gross hack for now: we know this file doesn't contain any 2046 // code, so don't dexopt it to avoid the resulting log spew. 2047 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2048 2049 // Gross hack for now: we know this file is only part of 2050 // the boot class path for art, so don't dexopt it to 2051 // avoid the resulting log spew. 2052 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2053 2054 /** 2055 * There are a number of commands implemented in Java, which 2056 * we currently need to do the dexopt on so that they can be 2057 * run from a non-root shell. 2058 */ 2059 String[] frameworkFiles = frameworkDir.list(); 2060 if (frameworkFiles != null) { 2061 // TODO: We could compile these only for the most preferred ABI. We should 2062 // first double check that the dex files for these commands are not referenced 2063 // by other system apps. 2064 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2065 for (int i=0; i<frameworkFiles.length; i++) { 2066 File libPath = new File(frameworkDir, frameworkFiles[i]); 2067 String path = libPath.getPath(); 2068 // Skip the file if we already did it. 2069 if (alreadyDexOpted.contains(path)) { 2070 continue; 2071 } 2072 // Skip the file if it is not a type we want to dexopt. 2073 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2074 continue; 2075 } 2076 try { 2077 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2078 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2079 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2080 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2081 } 2082 } catch (FileNotFoundException e) { 2083 Slog.w(TAG, "Jar not found: " + path); 2084 } catch (IOException e) { 2085 Slog.w(TAG, "Exception reading jar: " + path, e); 2086 } 2087 } 2088 } 2089 } 2090 2091 final VersionInfo ver = mSettings.getInternalVersion(); 2092 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2093 // when upgrading from pre-M, promote system app permissions from install to runtime 2094 mPromoteSystemApps = 2095 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2096 2097 // save off the names of pre-existing system packages prior to scanning; we don't 2098 // want to automatically grant runtime permissions for new system apps 2099 if (mPromoteSystemApps) { 2100 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2101 while (pkgSettingIter.hasNext()) { 2102 PackageSetting ps = pkgSettingIter.next(); 2103 if (isSystemApp(ps)) { 2104 mExistingSystemPackages.add(ps.name); 2105 } 2106 } 2107 } 2108 2109 // Collect vendor overlay packages. 2110 // (Do this before scanning any apps.) 2111 // For security and version matching reason, only consider 2112 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2113 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2114 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2116 2117 // Find base frameworks (resource packages without code). 2118 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2119 | PackageParser.PARSE_IS_SYSTEM_DIR 2120 | PackageParser.PARSE_IS_PRIVILEGED, 2121 scanFlags | SCAN_NO_DEX, 0); 2122 2123 // Collected privileged system packages. 2124 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2125 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2126 | PackageParser.PARSE_IS_SYSTEM_DIR 2127 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2128 2129 // Collect ordinary system packages. 2130 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2131 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2132 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2133 2134 // Collect all vendor packages. 2135 File vendorAppDir = new File("/vendor/app"); 2136 try { 2137 vendorAppDir = vendorAppDir.getCanonicalFile(); 2138 } catch (IOException e) { 2139 // failed to look up canonical path, continue with original one 2140 } 2141 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2142 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2143 2144 // Collect all OEM packages. 2145 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2146 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2147 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2148 2149 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2150 mInstaller.moveFiles(); 2151 2152 // Prune any system packages that no longer exist. 2153 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2154 if (!mOnlyCore) { 2155 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2156 while (psit.hasNext()) { 2157 PackageSetting ps = psit.next(); 2158 2159 /* 2160 * If this is not a system app, it can't be a 2161 * disable system app. 2162 */ 2163 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2164 continue; 2165 } 2166 2167 /* 2168 * If the package is scanned, it's not erased. 2169 */ 2170 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2171 if (scannedPkg != null) { 2172 /* 2173 * If the system app is both scanned and in the 2174 * disabled packages list, then it must have been 2175 * added via OTA. Remove it from the currently 2176 * scanned package so the previously user-installed 2177 * application can be scanned. 2178 */ 2179 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2180 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2181 + ps.name + "; removing system app. Last known codePath=" 2182 + ps.codePathString + ", installStatus=" + ps.installStatus 2183 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2184 + scannedPkg.mVersionCode); 2185 removePackageLI(ps, true); 2186 mExpectingBetter.put(ps.name, ps.codePath); 2187 } 2188 2189 continue; 2190 } 2191 2192 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2193 psit.remove(); 2194 logCriticalInfo(Log.WARN, "System package " + ps.name 2195 + " no longer exists; wiping its data"); 2196 removeDataDirsLI(null, ps.name); 2197 } else { 2198 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2199 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2200 possiblyDeletedUpdatedSystemApps.add(ps.name); 2201 } 2202 } 2203 } 2204 } 2205 2206 //look for any incomplete package installations 2207 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2208 //clean up list 2209 for(int i = 0; i < deletePkgsList.size(); i++) { 2210 //clean up here 2211 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2212 } 2213 //delete tmp files 2214 deleteTempPackageFiles(); 2215 2216 // Remove any shared userIDs that have no associated packages 2217 mSettings.pruneSharedUsersLPw(); 2218 2219 if (!mOnlyCore) { 2220 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2221 SystemClock.uptimeMillis()); 2222 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2223 2224 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2225 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2226 2227 /** 2228 * Remove disable package settings for any updated system 2229 * apps that were removed via an OTA. If they're not a 2230 * previously-updated app, remove them completely. 2231 * Otherwise, just revoke their system-level permissions. 2232 */ 2233 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2234 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2235 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2236 2237 String msg; 2238 if (deletedPkg == null) { 2239 msg = "Updated system package " + deletedAppName 2240 + " no longer exists; wiping its data"; 2241 removeDataDirsLI(null, deletedAppName); 2242 } else { 2243 msg = "Updated system app + " + deletedAppName 2244 + " no longer present; removing system privileges for " 2245 + deletedAppName; 2246 2247 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2248 2249 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2250 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2251 } 2252 logCriticalInfo(Log.WARN, msg); 2253 } 2254 2255 /** 2256 * Make sure all system apps that we expected to appear on 2257 * the userdata partition actually showed up. If they never 2258 * appeared, crawl back and revive the system version. 2259 */ 2260 for (int i = 0; i < mExpectingBetter.size(); i++) { 2261 final String packageName = mExpectingBetter.keyAt(i); 2262 if (!mPackages.containsKey(packageName)) { 2263 final File scanFile = mExpectingBetter.valueAt(i); 2264 2265 logCriticalInfo(Log.WARN, "Expected better " + packageName 2266 + " but never showed up; reverting to system"); 2267 2268 final int reparseFlags; 2269 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2270 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2271 | PackageParser.PARSE_IS_SYSTEM_DIR 2272 | PackageParser.PARSE_IS_PRIVILEGED; 2273 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2274 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2275 | PackageParser.PARSE_IS_SYSTEM_DIR; 2276 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2277 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2278 | PackageParser.PARSE_IS_SYSTEM_DIR; 2279 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2280 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2281 | PackageParser.PARSE_IS_SYSTEM_DIR; 2282 } else { 2283 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2284 continue; 2285 } 2286 2287 mSettings.enableSystemPackageLPw(packageName); 2288 2289 try { 2290 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2291 } catch (PackageManagerException e) { 2292 Slog.e(TAG, "Failed to parse original system package: " 2293 + e.getMessage()); 2294 } 2295 } 2296 } 2297 } 2298 mExpectingBetter.clear(); 2299 2300 // Now that we know all of the shared libraries, update all clients to have 2301 // the correct library paths. 2302 updateAllSharedLibrariesLPw(); 2303 2304 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2305 // NOTE: We ignore potential failures here during a system scan (like 2306 // the rest of the commands above) because there's precious little we 2307 // can do about it. A settings error is reported, though. 2308 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2309 false /* force dexopt */, false /* defer dexopt */, 2310 false /* boot complete */); 2311 } 2312 2313 // Now that we know all the packages we are keeping, 2314 // read and update their last usage times. 2315 mPackageUsage.readLP(); 2316 2317 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2318 SystemClock.uptimeMillis()); 2319 Slog.i(TAG, "Time to scan packages: " 2320 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2321 + " seconds"); 2322 2323 // If the platform SDK has changed since the last time we booted, 2324 // we need to re-grant app permission to catch any new ones that 2325 // appear. This is really a hack, and means that apps can in some 2326 // cases get permissions that the user didn't initially explicitly 2327 // allow... it would be nice to have some better way to handle 2328 // this situation. 2329 int updateFlags = UPDATE_PERMISSIONS_ALL; 2330 if (ver.sdkVersion != mSdkVersion) { 2331 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2332 + mSdkVersion + "; regranting permissions for internal storage"); 2333 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2334 } 2335 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2336 ver.sdkVersion = mSdkVersion; 2337 2338 // If this is the first boot or an update from pre-M, and it is a normal 2339 // boot, then we need to initialize the default preferred apps across 2340 // all defined users. 2341 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2342 for (UserInfo user : sUserManager.getUsers(true)) { 2343 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2344 applyFactoryDefaultBrowserLPw(user.id); 2345 primeDomainVerificationsLPw(user.id); 2346 } 2347 } 2348 2349 // If this is first boot after an OTA, and a normal boot, then 2350 // we need to clear code cache directories. 2351 if (mIsUpgrade && !onlyCore) { 2352 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2353 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2354 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2355 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2356 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2357 } 2358 } 2359 ver.fingerprint = Build.FINGERPRINT; 2360 } 2361 2362 checkDefaultBrowser(); 2363 2364 // clear only after permissions and other defaults have been updated 2365 mExistingSystemPackages.clear(); 2366 mPromoteSystemApps = false; 2367 2368 // All the changes are done during package scanning. 2369 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2370 2371 // can downgrade to reader 2372 mSettings.writeLPr(); 2373 2374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2375 SystemClock.uptimeMillis()); 2376 2377 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2378 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2379 2380 mInstallerService = new PackageInstallerService(context, this); 2381 2382 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2383 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2384 mIntentFilterVerifierComponent); 2385 2386 } // synchronized (mPackages) 2387 } // synchronized (mInstallLock) 2388 2389 // Now after opening every single application zip, make sure they 2390 // are all flushed. Not really needed, but keeps things nice and 2391 // tidy. 2392 Runtime.getRuntime().gc(); 2393 2394 // The initial scanning above does many calls into installd while 2395 // holding the mPackages lock, but we're mostly interested in yelling 2396 // once we have a booted system. 2397 mInstaller.setWarnIfHeld(mPackages); 2398 2399 // Expose private service for system components to use. 2400 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2401 } 2402 2403 @Override 2404 public boolean isFirstBoot() { 2405 return !mRestoredSettings; 2406 } 2407 2408 @Override 2409 public boolean isOnlyCoreApps() { 2410 return mOnlyCore; 2411 } 2412 2413 @Override 2414 public boolean isUpgrade() { 2415 return mIsUpgrade; 2416 } 2417 2418 private String getRequiredVerifierLPr() { 2419 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2420 // We only care about verifier that's installed under system user. 2421 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2422 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2423 2424 String requiredVerifier = null; 2425 2426 final int N = receivers.size(); 2427 for (int i = 0; i < N; i++) { 2428 final ResolveInfo info = receivers.get(i); 2429 2430 if (info.activityInfo == null) { 2431 continue; 2432 } 2433 2434 final String packageName = info.activityInfo.packageName; 2435 2436 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2437 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2438 continue; 2439 } 2440 2441 if (requiredVerifier != null) { 2442 throw new RuntimeException("There can be only one required verifier"); 2443 } 2444 2445 requiredVerifier = packageName; 2446 } 2447 2448 return requiredVerifier; 2449 } 2450 2451 private String getRequiredInstallerLPr() { 2452 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2453 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2454 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2455 2456 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2457 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2458 2459 String requiredInstaller = null; 2460 2461 final int N = installers.size(); 2462 for (int i = 0; i < N; i++) { 2463 final ResolveInfo info = installers.get(i); 2464 final String packageName = info.activityInfo.packageName; 2465 2466 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2467 continue; 2468 } 2469 2470 if (requiredInstaller != null) { 2471 throw new RuntimeException("There must be one required installer"); 2472 } 2473 2474 requiredInstaller = packageName; 2475 } 2476 2477 if (requiredInstaller == null) { 2478 throw new RuntimeException("There must be one required installer"); 2479 } 2480 2481 return requiredInstaller; 2482 } 2483 2484 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2485 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2486 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2487 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2488 2489 ComponentName verifierComponentName = null; 2490 2491 int priority = -1000; 2492 final int N = receivers.size(); 2493 for (int i = 0; i < N; i++) { 2494 final ResolveInfo info = receivers.get(i); 2495 2496 if (info.activityInfo == null) { 2497 continue; 2498 } 2499 2500 final String packageName = info.activityInfo.packageName; 2501 2502 final PackageSetting ps = mSettings.mPackages.get(packageName); 2503 if (ps == null) { 2504 continue; 2505 } 2506 2507 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2508 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2509 continue; 2510 } 2511 2512 // Select the IntentFilterVerifier with the highest priority 2513 if (priority < info.priority) { 2514 priority = info.priority; 2515 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2516 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2517 + verifierComponentName + " with priority: " + info.priority); 2518 } 2519 } 2520 2521 return verifierComponentName; 2522 } 2523 2524 private void primeDomainVerificationsLPw(int userId) { 2525 if (DEBUG_DOMAIN_VERIFICATION) { 2526 Slog.d(TAG, "Priming domain verifications in user " + userId); 2527 } 2528 2529 SystemConfig systemConfig = SystemConfig.getInstance(); 2530 ArraySet<String> packages = systemConfig.getLinkedApps(); 2531 ArraySet<String> domains = new ArraySet<String>(); 2532 2533 for (String packageName : packages) { 2534 PackageParser.Package pkg = mPackages.get(packageName); 2535 if (pkg != null) { 2536 if (!pkg.isSystemApp()) { 2537 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2538 continue; 2539 } 2540 2541 domains.clear(); 2542 for (PackageParser.Activity a : pkg.activities) { 2543 for (ActivityIntentInfo filter : a.intents) { 2544 if (hasValidDomains(filter)) { 2545 domains.addAll(filter.getHostsList()); 2546 } 2547 } 2548 } 2549 2550 if (domains.size() > 0) { 2551 if (DEBUG_DOMAIN_VERIFICATION) { 2552 Slog.v(TAG, " + " + packageName); 2553 } 2554 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2555 // state w.r.t. the formal app-linkage "no verification attempted" state; 2556 // and then 'always' in the per-user state actually used for intent resolution. 2557 final IntentFilterVerificationInfo ivi; 2558 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2559 new ArrayList<String>(domains)); 2560 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2561 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2562 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2563 } else { 2564 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2565 + "' does not handle web links"); 2566 } 2567 } else { 2568 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2569 } 2570 } 2571 2572 scheduleWritePackageRestrictionsLocked(userId); 2573 scheduleWriteSettingsLocked(); 2574 } 2575 2576 private void applyFactoryDefaultBrowserLPw(int userId) { 2577 // The default browser app's package name is stored in a string resource, 2578 // with a product-specific overlay used for vendor customization. 2579 String browserPkg = mContext.getResources().getString( 2580 com.android.internal.R.string.default_browser); 2581 if (!TextUtils.isEmpty(browserPkg)) { 2582 // non-empty string => required to be a known package 2583 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2584 if (ps == null) { 2585 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2586 browserPkg = null; 2587 } else { 2588 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2589 } 2590 } 2591 2592 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2593 // default. If there's more than one, just leave everything alone. 2594 if (browserPkg == null) { 2595 calculateDefaultBrowserLPw(userId); 2596 } 2597 } 2598 2599 private void calculateDefaultBrowserLPw(int userId) { 2600 List<String> allBrowsers = resolveAllBrowserApps(userId); 2601 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2602 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2603 } 2604 2605 private List<String> resolveAllBrowserApps(int userId) { 2606 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2607 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2608 PackageManager.MATCH_ALL, userId); 2609 2610 final int count = list.size(); 2611 List<String> result = new ArrayList<String>(count); 2612 for (int i=0; i<count; i++) { 2613 ResolveInfo info = list.get(i); 2614 if (info.activityInfo == null 2615 || !info.handleAllWebDataURI 2616 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2617 || result.contains(info.activityInfo.packageName)) { 2618 continue; 2619 } 2620 result.add(info.activityInfo.packageName); 2621 } 2622 2623 return result; 2624 } 2625 2626 private boolean packageIsBrowser(String packageName, int userId) { 2627 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2628 PackageManager.MATCH_ALL, userId); 2629 final int N = list.size(); 2630 for (int i = 0; i < N; i++) { 2631 ResolveInfo info = list.get(i); 2632 if (packageName.equals(info.activityInfo.packageName)) { 2633 return true; 2634 } 2635 } 2636 return false; 2637 } 2638 2639 private void checkDefaultBrowser() { 2640 final int myUserId = UserHandle.myUserId(); 2641 final String packageName = getDefaultBrowserPackageName(myUserId); 2642 if (packageName != null) { 2643 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2644 if (info == null) { 2645 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2646 synchronized (mPackages) { 2647 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2648 } 2649 } 2650 } 2651 } 2652 2653 @Override 2654 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2655 throws RemoteException { 2656 try { 2657 return super.onTransact(code, data, reply, flags); 2658 } catch (RuntimeException e) { 2659 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2660 Slog.wtf(TAG, "Package Manager Crash", e); 2661 } 2662 throw e; 2663 } 2664 } 2665 2666 void cleanupInstallFailedPackage(PackageSetting ps) { 2667 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2668 2669 removeDataDirsLI(ps.volumeUuid, ps.name); 2670 if (ps.codePath != null) { 2671 if (ps.codePath.isDirectory()) { 2672 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2673 } else { 2674 ps.codePath.delete(); 2675 } 2676 } 2677 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2678 if (ps.resourcePath.isDirectory()) { 2679 FileUtils.deleteContents(ps.resourcePath); 2680 } 2681 ps.resourcePath.delete(); 2682 } 2683 mSettings.removePackageLPw(ps.name); 2684 } 2685 2686 static int[] appendInts(int[] cur, int[] add) { 2687 if (add == null) return cur; 2688 if (cur == null) return add; 2689 final int N = add.length; 2690 for (int i=0; i<N; i++) { 2691 cur = appendInt(cur, add[i]); 2692 } 2693 return cur; 2694 } 2695 2696 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2697 if (!sUserManager.exists(userId)) return null; 2698 final PackageSetting ps = (PackageSetting) p.mExtras; 2699 if (ps == null) { 2700 return null; 2701 } 2702 2703 final PermissionsState permissionsState = ps.getPermissionsState(); 2704 2705 final int[] gids = permissionsState.computeGids(userId); 2706 final Set<String> permissions = permissionsState.getPermissions(userId); 2707 final PackageUserState state = ps.readUserState(userId); 2708 2709 return PackageParser.generatePackageInfo(p, gids, flags, 2710 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2711 } 2712 2713 @Override 2714 public boolean isPackageFrozen(String packageName) { 2715 synchronized (mPackages) { 2716 final PackageSetting ps = mSettings.mPackages.get(packageName); 2717 if (ps != null) { 2718 return ps.frozen; 2719 } 2720 } 2721 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2722 return true; 2723 } 2724 2725 @Override 2726 public boolean isPackageAvailable(String packageName, int userId) { 2727 if (!sUserManager.exists(userId)) return false; 2728 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2729 synchronized (mPackages) { 2730 PackageParser.Package p = mPackages.get(packageName); 2731 if (p != null) { 2732 final PackageSetting ps = (PackageSetting) p.mExtras; 2733 if (ps != null) { 2734 final PackageUserState state = ps.readUserState(userId); 2735 if (state != null) { 2736 return PackageParser.isAvailable(state); 2737 } 2738 } 2739 } 2740 } 2741 return false; 2742 } 2743 2744 @Override 2745 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2746 if (!sUserManager.exists(userId)) return null; 2747 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2748 // reader 2749 synchronized (mPackages) { 2750 PackageParser.Package p = mPackages.get(packageName); 2751 if (DEBUG_PACKAGE_INFO) 2752 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2753 if (p != null) { 2754 return generatePackageInfo(p, flags, userId); 2755 } 2756 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2757 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2758 } 2759 } 2760 return null; 2761 } 2762 2763 @Override 2764 public String[] currentToCanonicalPackageNames(String[] names) { 2765 String[] out = new String[names.length]; 2766 // reader 2767 synchronized (mPackages) { 2768 for (int i=names.length-1; i>=0; i--) { 2769 PackageSetting ps = mSettings.mPackages.get(names[i]); 2770 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2771 } 2772 } 2773 return out; 2774 } 2775 2776 @Override 2777 public String[] canonicalToCurrentPackageNames(String[] names) { 2778 String[] out = new String[names.length]; 2779 // reader 2780 synchronized (mPackages) { 2781 for (int i=names.length-1; i>=0; i--) { 2782 String cur = mSettings.mRenamedPackages.get(names[i]); 2783 out[i] = cur != null ? cur : names[i]; 2784 } 2785 } 2786 return out; 2787 } 2788 2789 @Override 2790 public int getPackageUid(String packageName, int userId) { 2791 return getPackageUidEtc(packageName, 0, userId); 2792 } 2793 2794 @Override 2795 public int getPackageUidEtc(String packageName, int flags, int userId) { 2796 if (!sUserManager.exists(userId)) return -1; 2797 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2798 2799 // reader 2800 synchronized (mPackages) { 2801 final PackageParser.Package p = mPackages.get(packageName); 2802 if (p != null) { 2803 return UserHandle.getUid(userId, p.applicationInfo.uid); 2804 } 2805 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2806 final PackageSetting ps = mSettings.mPackages.get(packageName); 2807 if (ps != null) { 2808 return UserHandle.getUid(userId, ps.appId); 2809 } 2810 } 2811 } 2812 2813 return -1; 2814 } 2815 2816 @Override 2817 public int[] getPackageGids(String packageName, int userId) { 2818 return getPackageGidsEtc(packageName, 0, userId); 2819 } 2820 2821 @Override 2822 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2823 if (!sUserManager.exists(userId)) { 2824 return null; 2825 } 2826 2827 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2828 "getPackageGids"); 2829 2830 // reader 2831 synchronized (mPackages) { 2832 final PackageParser.Package p = mPackages.get(packageName); 2833 if (p != null) { 2834 PackageSetting ps = (PackageSetting) p.mExtras; 2835 return ps.getPermissionsState().computeGids(userId); 2836 } 2837 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2838 final PackageSetting ps = mSettings.mPackages.get(packageName); 2839 if (ps != null) { 2840 return ps.getPermissionsState().computeGids(userId); 2841 } 2842 } 2843 } 2844 2845 return null; 2846 } 2847 2848 static PermissionInfo generatePermissionInfo( 2849 BasePermission bp, int flags) { 2850 if (bp.perm != null) { 2851 return PackageParser.generatePermissionInfo(bp.perm, flags); 2852 } 2853 PermissionInfo pi = new PermissionInfo(); 2854 pi.name = bp.name; 2855 pi.packageName = bp.sourcePackage; 2856 pi.nonLocalizedLabel = bp.name; 2857 pi.protectionLevel = bp.protectionLevel; 2858 return pi; 2859 } 2860 2861 @Override 2862 public PermissionInfo getPermissionInfo(String name, int flags) { 2863 // reader 2864 synchronized (mPackages) { 2865 final BasePermission p = mSettings.mPermissions.get(name); 2866 if (p != null) { 2867 return generatePermissionInfo(p, flags); 2868 } 2869 return null; 2870 } 2871 } 2872 2873 @Override 2874 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2875 // reader 2876 synchronized (mPackages) { 2877 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2878 for (BasePermission p : mSettings.mPermissions.values()) { 2879 if (group == null) { 2880 if (p.perm == null || p.perm.info.group == null) { 2881 out.add(generatePermissionInfo(p, flags)); 2882 } 2883 } else { 2884 if (p.perm != null && group.equals(p.perm.info.group)) { 2885 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2886 } 2887 } 2888 } 2889 2890 if (out.size() > 0) { 2891 return out; 2892 } 2893 return mPermissionGroups.containsKey(group) ? out : null; 2894 } 2895 } 2896 2897 @Override 2898 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2899 // reader 2900 synchronized (mPackages) { 2901 return PackageParser.generatePermissionGroupInfo( 2902 mPermissionGroups.get(name), flags); 2903 } 2904 } 2905 2906 @Override 2907 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2908 // reader 2909 synchronized (mPackages) { 2910 final int N = mPermissionGroups.size(); 2911 ArrayList<PermissionGroupInfo> out 2912 = new ArrayList<PermissionGroupInfo>(N); 2913 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2914 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2915 } 2916 return out; 2917 } 2918 } 2919 2920 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2921 int userId) { 2922 if (!sUserManager.exists(userId)) return null; 2923 PackageSetting ps = mSettings.mPackages.get(packageName); 2924 if (ps != null) { 2925 if (ps.pkg == null) { 2926 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2927 flags, userId); 2928 if (pInfo != null) { 2929 return pInfo.applicationInfo; 2930 } 2931 return null; 2932 } 2933 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2934 ps.readUserState(userId), userId); 2935 } 2936 return null; 2937 } 2938 2939 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2940 int userId) { 2941 if (!sUserManager.exists(userId)) return null; 2942 PackageSetting ps = mSettings.mPackages.get(packageName); 2943 if (ps != null) { 2944 PackageParser.Package pkg = ps.pkg; 2945 if (pkg == null) { 2946 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2947 return null; 2948 } 2949 // Only data remains, so we aren't worried about code paths 2950 pkg = new PackageParser.Package(packageName); 2951 pkg.applicationInfo.packageName = packageName; 2952 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2953 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2954 pkg.applicationInfo.uid = ps.appId; 2955 pkg.applicationInfo.initForUser(userId); 2956 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2957 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2958 } 2959 return generatePackageInfo(pkg, flags, userId); 2960 } 2961 return null; 2962 } 2963 2964 @Override 2965 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2966 if (!sUserManager.exists(userId)) return null; 2967 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2968 // writer 2969 synchronized (mPackages) { 2970 PackageParser.Package p = mPackages.get(packageName); 2971 if (DEBUG_PACKAGE_INFO) Log.v( 2972 TAG, "getApplicationInfo " + packageName 2973 + ": " + p); 2974 if (p != null) { 2975 PackageSetting ps = mSettings.mPackages.get(packageName); 2976 if (ps == null) return null; 2977 // Note: isEnabledLP() does not apply here - always return info 2978 return PackageParser.generateApplicationInfo( 2979 p, flags, ps.readUserState(userId), userId); 2980 } 2981 if ("android".equals(packageName)||"system".equals(packageName)) { 2982 return mAndroidApplication; 2983 } 2984 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2985 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2986 } 2987 } 2988 return null; 2989 } 2990 2991 @Override 2992 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2993 final IPackageDataObserver observer) { 2994 mContext.enforceCallingOrSelfPermission( 2995 android.Manifest.permission.CLEAR_APP_CACHE, null); 2996 // Queue up an async operation since clearing cache may take a little while. 2997 mHandler.post(new Runnable() { 2998 public void run() { 2999 mHandler.removeCallbacks(this); 3000 int retCode = -1; 3001 synchronized (mInstallLock) { 3002 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3003 if (retCode < 0) { 3004 Slog.w(TAG, "Couldn't clear application caches"); 3005 } 3006 } 3007 if (observer != null) { 3008 try { 3009 observer.onRemoveCompleted(null, (retCode >= 0)); 3010 } catch (RemoteException e) { 3011 Slog.w(TAG, "RemoveException when invoking call back"); 3012 } 3013 } 3014 } 3015 }); 3016 } 3017 3018 @Override 3019 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3020 final IntentSender pi) { 3021 mContext.enforceCallingOrSelfPermission( 3022 android.Manifest.permission.CLEAR_APP_CACHE, null); 3023 // Queue up an async operation since clearing cache may take a little while. 3024 mHandler.post(new Runnable() { 3025 public void run() { 3026 mHandler.removeCallbacks(this); 3027 int retCode = -1; 3028 synchronized (mInstallLock) { 3029 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3030 if (retCode < 0) { 3031 Slog.w(TAG, "Couldn't clear application caches"); 3032 } 3033 } 3034 if(pi != null) { 3035 try { 3036 // Callback via pending intent 3037 int code = (retCode >= 0) ? 1 : 0; 3038 pi.sendIntent(null, code, null, 3039 null, null); 3040 } catch (SendIntentException e1) { 3041 Slog.i(TAG, "Failed to send pending intent"); 3042 } 3043 } 3044 } 3045 }); 3046 } 3047 3048 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3049 synchronized (mInstallLock) { 3050 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3051 throw new IOException("Failed to free enough space"); 3052 } 3053 } 3054 } 3055 3056 /** 3057 * Augment the given flags depending on current user running state. This is 3058 * purposefully done before acquiring {@link #mPackages} lock. 3059 */ 3060 private int augmentFlagsForUser(int flags, int userId) { 3061 // TODO: bring back once locking fixed 3062// final IActivityManager am = ActivityManagerNative.getDefault(); 3063// if (am == null) { 3064// // We must be early in boot, so the best we can do is assume the 3065// // user is fully running. 3066// return flags; 3067// } 3068// final long token = Binder.clearCallingIdentity(); 3069// try { 3070// if (am.isUserRunning(userId, ActivityManager.FLAG_WITH_AMNESIA)) { 3071// flags |= PackageManager.FLAG_USER_RUNNING_WITH_AMNESIA; 3072// } 3073// } catch (RemoteException e) { 3074// throw e.rethrowAsRuntimeException(); 3075// } finally { 3076// Binder.restoreCallingIdentity(token); 3077// } 3078 return flags; 3079 } 3080 3081 @Override 3082 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3083 if (!sUserManager.exists(userId)) return null; 3084 flags = augmentFlagsForUser(flags, userId); 3085 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3086 synchronized (mPackages) { 3087 PackageParser.Activity a = mActivities.mActivities.get(component); 3088 3089 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3090 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3091 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3092 if (ps == null) return null; 3093 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3094 userId); 3095 } 3096 if (mResolveComponentName.equals(component)) { 3097 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3098 new PackageUserState(), userId); 3099 } 3100 } 3101 return null; 3102 } 3103 3104 @Override 3105 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3106 String resolvedType) { 3107 synchronized (mPackages) { 3108 if (component.equals(mResolveComponentName)) { 3109 // The resolver supports EVERYTHING! 3110 return true; 3111 } 3112 PackageParser.Activity a = mActivities.mActivities.get(component); 3113 if (a == null) { 3114 return false; 3115 } 3116 for (int i=0; i<a.intents.size(); i++) { 3117 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3118 intent.getData(), intent.getCategories(), TAG) >= 0) { 3119 return true; 3120 } 3121 } 3122 return false; 3123 } 3124 } 3125 3126 @Override 3127 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3128 if (!sUserManager.exists(userId)) return null; 3129 flags = augmentFlagsForUser(flags, userId); 3130 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3131 synchronized (mPackages) { 3132 PackageParser.Activity a = mReceivers.mActivities.get(component); 3133 if (DEBUG_PACKAGE_INFO) Log.v( 3134 TAG, "getReceiverInfo " + component + ": " + a); 3135 if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) { 3136 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3137 if (ps == null) return null; 3138 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3139 userId); 3140 } 3141 } 3142 return null; 3143 } 3144 3145 @Override 3146 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3147 if (!sUserManager.exists(userId)) return null; 3148 flags = augmentFlagsForUser(flags, userId); 3149 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3150 synchronized (mPackages) { 3151 PackageParser.Service s = mServices.mServices.get(component); 3152 if (DEBUG_PACKAGE_INFO) Log.v( 3153 TAG, "getServiceInfo " + component + ": " + s); 3154 if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) { 3155 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3156 if (ps == null) return null; 3157 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3158 userId); 3159 } 3160 } 3161 return null; 3162 } 3163 3164 @Override 3165 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3166 if (!sUserManager.exists(userId)) return null; 3167 flags = augmentFlagsForUser(flags, userId); 3168 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3169 synchronized (mPackages) { 3170 PackageParser.Provider p = mProviders.mProviders.get(component); 3171 if (DEBUG_PACKAGE_INFO) Log.v( 3172 TAG, "getProviderInfo " + component + ": " + p); 3173 if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) { 3174 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3175 if (ps == null) return null; 3176 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3177 userId); 3178 } 3179 } 3180 return null; 3181 } 3182 3183 @Override 3184 public String[] getSystemSharedLibraryNames() { 3185 Set<String> libSet; 3186 synchronized (mPackages) { 3187 libSet = mSharedLibraries.keySet(); 3188 int size = libSet.size(); 3189 if (size > 0) { 3190 String[] libs = new String[size]; 3191 libSet.toArray(libs); 3192 return libs; 3193 } 3194 } 3195 return null; 3196 } 3197 3198 /** 3199 * @hide 3200 */ 3201 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3202 synchronized (mPackages) { 3203 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3204 if (lib != null && lib.apk != null) { 3205 return mPackages.get(lib.apk); 3206 } 3207 } 3208 return null; 3209 } 3210 3211 @Override 3212 public FeatureInfo[] getSystemAvailableFeatures() { 3213 Collection<FeatureInfo> featSet; 3214 synchronized (mPackages) { 3215 featSet = mAvailableFeatures.values(); 3216 int size = featSet.size(); 3217 if (size > 0) { 3218 FeatureInfo[] features = new FeatureInfo[size+1]; 3219 featSet.toArray(features); 3220 FeatureInfo fi = new FeatureInfo(); 3221 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3222 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3223 features[size] = fi; 3224 return features; 3225 } 3226 } 3227 return null; 3228 } 3229 3230 @Override 3231 public boolean hasSystemFeature(String name) { 3232 synchronized (mPackages) { 3233 return mAvailableFeatures.containsKey(name); 3234 } 3235 } 3236 3237 private void checkValidCaller(int uid, int userId) { 3238 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3239 return; 3240 3241 throw new SecurityException("Caller uid=" + uid 3242 + " is not privileged to communicate with user=" + userId); 3243 } 3244 3245 @Override 3246 public int checkPermission(String permName, String pkgName, int userId) { 3247 if (!sUserManager.exists(userId)) { 3248 return PackageManager.PERMISSION_DENIED; 3249 } 3250 3251 synchronized (mPackages) { 3252 final PackageParser.Package p = mPackages.get(pkgName); 3253 if (p != null && p.mExtras != null) { 3254 final PackageSetting ps = (PackageSetting) p.mExtras; 3255 final PermissionsState permissionsState = ps.getPermissionsState(); 3256 if (permissionsState.hasPermission(permName, userId)) { 3257 return PackageManager.PERMISSION_GRANTED; 3258 } 3259 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3260 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3261 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3262 return PackageManager.PERMISSION_GRANTED; 3263 } 3264 } 3265 } 3266 3267 return PackageManager.PERMISSION_DENIED; 3268 } 3269 3270 @Override 3271 public int checkUidPermission(String permName, int uid) { 3272 final int userId = UserHandle.getUserId(uid); 3273 3274 if (!sUserManager.exists(userId)) { 3275 return PackageManager.PERMISSION_DENIED; 3276 } 3277 3278 synchronized (mPackages) { 3279 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3280 if (obj != null) { 3281 final SettingBase ps = (SettingBase) obj; 3282 final PermissionsState permissionsState = ps.getPermissionsState(); 3283 if (permissionsState.hasPermission(permName, userId)) { 3284 return PackageManager.PERMISSION_GRANTED; 3285 } 3286 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3287 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3288 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3289 return PackageManager.PERMISSION_GRANTED; 3290 } 3291 } else { 3292 ArraySet<String> perms = mSystemPermissions.get(uid); 3293 if (perms != null) { 3294 if (perms.contains(permName)) { 3295 return PackageManager.PERMISSION_GRANTED; 3296 } 3297 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3298 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3299 return PackageManager.PERMISSION_GRANTED; 3300 } 3301 } 3302 } 3303 } 3304 3305 return PackageManager.PERMISSION_DENIED; 3306 } 3307 3308 @Override 3309 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3310 if (UserHandle.getCallingUserId() != userId) { 3311 mContext.enforceCallingPermission( 3312 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3313 "isPermissionRevokedByPolicy for user " + userId); 3314 } 3315 3316 if (checkPermission(permission, packageName, userId) 3317 == PackageManager.PERMISSION_GRANTED) { 3318 return false; 3319 } 3320 3321 final long identity = Binder.clearCallingIdentity(); 3322 try { 3323 final int flags = getPermissionFlags(permission, packageName, userId); 3324 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3325 } finally { 3326 Binder.restoreCallingIdentity(identity); 3327 } 3328 } 3329 3330 @Override 3331 public String getPermissionControllerPackageName() { 3332 synchronized (mPackages) { 3333 return mRequiredInstallerPackage; 3334 } 3335 } 3336 3337 /** 3338 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3339 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3340 * @param checkShell TODO(yamasani): 3341 * @param message the message to log on security exception 3342 */ 3343 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3344 boolean checkShell, String message) { 3345 if (userId < 0) { 3346 throw new IllegalArgumentException("Invalid userId " + userId); 3347 } 3348 if (checkShell) { 3349 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3350 } 3351 if (userId == UserHandle.getUserId(callingUid)) return; 3352 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3353 if (requireFullPermission) { 3354 mContext.enforceCallingOrSelfPermission( 3355 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3356 } else { 3357 try { 3358 mContext.enforceCallingOrSelfPermission( 3359 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3360 } catch (SecurityException se) { 3361 mContext.enforceCallingOrSelfPermission( 3362 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3363 } 3364 } 3365 } 3366 } 3367 3368 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3369 if (callingUid == Process.SHELL_UID) { 3370 if (userHandle >= 0 3371 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3372 throw new SecurityException("Shell does not have permission to access user " 3373 + userHandle); 3374 } else if (userHandle < 0) { 3375 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3376 + Debug.getCallers(3)); 3377 } 3378 } 3379 } 3380 3381 private BasePermission findPermissionTreeLP(String permName) { 3382 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3383 if (permName.startsWith(bp.name) && 3384 permName.length() > bp.name.length() && 3385 permName.charAt(bp.name.length()) == '.') { 3386 return bp; 3387 } 3388 } 3389 return null; 3390 } 3391 3392 private BasePermission checkPermissionTreeLP(String permName) { 3393 if (permName != null) { 3394 BasePermission bp = findPermissionTreeLP(permName); 3395 if (bp != null) { 3396 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3397 return bp; 3398 } 3399 throw new SecurityException("Calling uid " 3400 + Binder.getCallingUid() 3401 + " is not allowed to add to permission tree " 3402 + bp.name + " owned by uid " + bp.uid); 3403 } 3404 } 3405 throw new SecurityException("No permission tree found for " + permName); 3406 } 3407 3408 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3409 if (s1 == null) { 3410 return s2 == null; 3411 } 3412 if (s2 == null) { 3413 return false; 3414 } 3415 if (s1.getClass() != s2.getClass()) { 3416 return false; 3417 } 3418 return s1.equals(s2); 3419 } 3420 3421 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3422 if (pi1.icon != pi2.icon) return false; 3423 if (pi1.logo != pi2.logo) return false; 3424 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3425 if (!compareStrings(pi1.name, pi2.name)) return false; 3426 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3427 // We'll take care of setting this one. 3428 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3429 // These are not currently stored in settings. 3430 //if (!compareStrings(pi1.group, pi2.group)) return false; 3431 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3432 //if (pi1.labelRes != pi2.labelRes) return false; 3433 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3434 return true; 3435 } 3436 3437 int permissionInfoFootprint(PermissionInfo info) { 3438 int size = info.name.length(); 3439 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3440 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3441 return size; 3442 } 3443 3444 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3445 int size = 0; 3446 for (BasePermission perm : mSettings.mPermissions.values()) { 3447 if (perm.uid == tree.uid) { 3448 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3449 } 3450 } 3451 return size; 3452 } 3453 3454 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3455 // We calculate the max size of permissions defined by this uid and throw 3456 // if that plus the size of 'info' would exceed our stated maximum. 3457 if (tree.uid != Process.SYSTEM_UID) { 3458 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3459 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3460 throw new SecurityException("Permission tree size cap exceeded"); 3461 } 3462 } 3463 } 3464 3465 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3466 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3467 throw new SecurityException("Label must be specified in permission"); 3468 } 3469 BasePermission tree = checkPermissionTreeLP(info.name); 3470 BasePermission bp = mSettings.mPermissions.get(info.name); 3471 boolean added = bp == null; 3472 boolean changed = true; 3473 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3474 if (added) { 3475 enforcePermissionCapLocked(info, tree); 3476 bp = new BasePermission(info.name, tree.sourcePackage, 3477 BasePermission.TYPE_DYNAMIC); 3478 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3479 throw new SecurityException( 3480 "Not allowed to modify non-dynamic permission " 3481 + info.name); 3482 } else { 3483 if (bp.protectionLevel == fixedLevel 3484 && bp.perm.owner.equals(tree.perm.owner) 3485 && bp.uid == tree.uid 3486 && comparePermissionInfos(bp.perm.info, info)) { 3487 changed = false; 3488 } 3489 } 3490 bp.protectionLevel = fixedLevel; 3491 info = new PermissionInfo(info); 3492 info.protectionLevel = fixedLevel; 3493 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3494 bp.perm.info.packageName = tree.perm.info.packageName; 3495 bp.uid = tree.uid; 3496 if (added) { 3497 mSettings.mPermissions.put(info.name, bp); 3498 } 3499 if (changed) { 3500 if (!async) { 3501 mSettings.writeLPr(); 3502 } else { 3503 scheduleWriteSettingsLocked(); 3504 } 3505 } 3506 return added; 3507 } 3508 3509 @Override 3510 public boolean addPermission(PermissionInfo info) { 3511 synchronized (mPackages) { 3512 return addPermissionLocked(info, false); 3513 } 3514 } 3515 3516 @Override 3517 public boolean addPermissionAsync(PermissionInfo info) { 3518 synchronized (mPackages) { 3519 return addPermissionLocked(info, true); 3520 } 3521 } 3522 3523 @Override 3524 public void removePermission(String name) { 3525 synchronized (mPackages) { 3526 checkPermissionTreeLP(name); 3527 BasePermission bp = mSettings.mPermissions.get(name); 3528 if (bp != null) { 3529 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3530 throw new SecurityException( 3531 "Not allowed to modify non-dynamic permission " 3532 + name); 3533 } 3534 mSettings.mPermissions.remove(name); 3535 mSettings.writeLPr(); 3536 } 3537 } 3538 } 3539 3540 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3541 BasePermission bp) { 3542 int index = pkg.requestedPermissions.indexOf(bp.name); 3543 if (index == -1) { 3544 throw new SecurityException("Package " + pkg.packageName 3545 + " has not requested permission " + bp.name); 3546 } 3547 if (!bp.isRuntime() && !bp.isDevelopment()) { 3548 throw new SecurityException("Permission " + bp.name 3549 + " is not a changeable permission type"); 3550 } 3551 } 3552 3553 @Override 3554 public void grantRuntimePermission(String packageName, String name, final int userId) { 3555 if (!sUserManager.exists(userId)) { 3556 Log.e(TAG, "No such user:" + userId); 3557 return; 3558 } 3559 3560 mContext.enforceCallingOrSelfPermission( 3561 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3562 "grantRuntimePermission"); 3563 3564 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3565 "grantRuntimePermission"); 3566 3567 final int uid; 3568 final SettingBase sb; 3569 3570 synchronized (mPackages) { 3571 final PackageParser.Package pkg = mPackages.get(packageName); 3572 if (pkg == null) { 3573 throw new IllegalArgumentException("Unknown package: " + packageName); 3574 } 3575 3576 final BasePermission bp = mSettings.mPermissions.get(name); 3577 if (bp == null) { 3578 throw new IllegalArgumentException("Unknown permission: " + name); 3579 } 3580 3581 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3582 3583 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3584 sb = (SettingBase) pkg.mExtras; 3585 if (sb == null) { 3586 throw new IllegalArgumentException("Unknown package: " + packageName); 3587 } 3588 3589 final PermissionsState permissionsState = sb.getPermissionsState(); 3590 3591 final int flags = permissionsState.getPermissionFlags(name, userId); 3592 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3593 throw new SecurityException("Cannot grant system fixed permission: " 3594 + name + " for package: " + packageName); 3595 } 3596 3597 if (bp.isDevelopment()) { 3598 // Development permissions must be handled specially, since they are not 3599 // normal runtime permissions. For now they apply to all users. 3600 if (permissionsState.grantInstallPermission(bp) != 3601 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3602 scheduleWriteSettingsLocked(); 3603 } 3604 return; 3605 } 3606 3607 final int result = permissionsState.grantRuntimePermission(bp, userId); 3608 switch (result) { 3609 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3610 return; 3611 } 3612 3613 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3614 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3615 mHandler.post(new Runnable() { 3616 @Override 3617 public void run() { 3618 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3619 } 3620 }); 3621 } 3622 break; 3623 } 3624 3625 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3626 3627 // Not critical if that is lost - app has to request again. 3628 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3629 } 3630 3631 // Only need to do this if user is initialized. Otherwise it's a new user 3632 // and there are no processes running as the user yet and there's no need 3633 // to make an expensive call to remount processes for the changed permissions. 3634 if (READ_EXTERNAL_STORAGE.equals(name) 3635 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3636 final long token = Binder.clearCallingIdentity(); 3637 try { 3638 if (sUserManager.isInitialized(userId)) { 3639 MountServiceInternal mountServiceInternal = LocalServices.getService( 3640 MountServiceInternal.class); 3641 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3642 } 3643 } finally { 3644 Binder.restoreCallingIdentity(token); 3645 } 3646 } 3647 } 3648 3649 @Override 3650 public void revokeRuntimePermission(String packageName, String name, int userId) { 3651 if (!sUserManager.exists(userId)) { 3652 Log.e(TAG, "No such user:" + userId); 3653 return; 3654 } 3655 3656 mContext.enforceCallingOrSelfPermission( 3657 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3658 "revokeRuntimePermission"); 3659 3660 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3661 "revokeRuntimePermission"); 3662 3663 final int appId; 3664 3665 synchronized (mPackages) { 3666 final PackageParser.Package pkg = mPackages.get(packageName); 3667 if (pkg == null) { 3668 throw new IllegalArgumentException("Unknown package: " + packageName); 3669 } 3670 3671 final BasePermission bp = mSettings.mPermissions.get(name); 3672 if (bp == null) { 3673 throw new IllegalArgumentException("Unknown permission: " + name); 3674 } 3675 3676 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3677 3678 SettingBase sb = (SettingBase) pkg.mExtras; 3679 if (sb == null) { 3680 throw new IllegalArgumentException("Unknown package: " + packageName); 3681 } 3682 3683 final PermissionsState permissionsState = sb.getPermissionsState(); 3684 3685 final int flags = permissionsState.getPermissionFlags(name, userId); 3686 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3687 throw new SecurityException("Cannot revoke system fixed permission: " 3688 + name + " for package: " + packageName); 3689 } 3690 3691 if (bp.isDevelopment()) { 3692 // Development permissions must be handled specially, since they are not 3693 // normal runtime permissions. For now they apply to all users. 3694 if (permissionsState.revokeInstallPermission(bp) != 3695 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3696 scheduleWriteSettingsLocked(); 3697 } 3698 return; 3699 } 3700 3701 if (permissionsState.revokeRuntimePermission(bp, userId) == 3702 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3703 return; 3704 } 3705 3706 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3707 3708 // Critical, after this call app should never have the permission. 3709 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3710 3711 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3712 } 3713 3714 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3715 } 3716 3717 @Override 3718 public void resetRuntimePermissions() { 3719 mContext.enforceCallingOrSelfPermission( 3720 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3721 "revokeRuntimePermission"); 3722 3723 int callingUid = Binder.getCallingUid(); 3724 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3725 mContext.enforceCallingOrSelfPermission( 3726 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3727 "resetRuntimePermissions"); 3728 } 3729 3730 synchronized (mPackages) { 3731 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3732 for (int userId : UserManagerService.getInstance().getUserIds()) { 3733 final int packageCount = mPackages.size(); 3734 for (int i = 0; i < packageCount; i++) { 3735 PackageParser.Package pkg = mPackages.valueAt(i); 3736 if (!(pkg.mExtras instanceof PackageSetting)) { 3737 continue; 3738 } 3739 PackageSetting ps = (PackageSetting) pkg.mExtras; 3740 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3741 } 3742 } 3743 } 3744 } 3745 3746 @Override 3747 public int getPermissionFlags(String name, String packageName, int userId) { 3748 if (!sUserManager.exists(userId)) { 3749 return 0; 3750 } 3751 3752 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3753 3754 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3755 "getPermissionFlags"); 3756 3757 synchronized (mPackages) { 3758 final PackageParser.Package pkg = mPackages.get(packageName); 3759 if (pkg == null) { 3760 throw new IllegalArgumentException("Unknown package: " + packageName); 3761 } 3762 3763 final BasePermission bp = mSettings.mPermissions.get(name); 3764 if (bp == null) { 3765 throw new IllegalArgumentException("Unknown permission: " + name); 3766 } 3767 3768 SettingBase sb = (SettingBase) pkg.mExtras; 3769 if (sb == null) { 3770 throw new IllegalArgumentException("Unknown package: " + packageName); 3771 } 3772 3773 PermissionsState permissionsState = sb.getPermissionsState(); 3774 return permissionsState.getPermissionFlags(name, userId); 3775 } 3776 } 3777 3778 @Override 3779 public void updatePermissionFlags(String name, String packageName, int flagMask, 3780 int flagValues, int userId) { 3781 if (!sUserManager.exists(userId)) { 3782 return; 3783 } 3784 3785 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3786 3787 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3788 "updatePermissionFlags"); 3789 3790 // Only the system can change these flags and nothing else. 3791 if (getCallingUid() != Process.SYSTEM_UID) { 3792 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3793 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3794 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3795 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3796 } 3797 3798 synchronized (mPackages) { 3799 final PackageParser.Package pkg = mPackages.get(packageName); 3800 if (pkg == null) { 3801 throw new IllegalArgumentException("Unknown package: " + packageName); 3802 } 3803 3804 final BasePermission bp = mSettings.mPermissions.get(name); 3805 if (bp == null) { 3806 throw new IllegalArgumentException("Unknown permission: " + name); 3807 } 3808 3809 SettingBase sb = (SettingBase) pkg.mExtras; 3810 if (sb == null) { 3811 throw new IllegalArgumentException("Unknown package: " + packageName); 3812 } 3813 3814 PermissionsState permissionsState = sb.getPermissionsState(); 3815 3816 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3817 3818 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3819 // Install and runtime permissions are stored in different places, 3820 // so figure out what permission changed and persist the change. 3821 if (permissionsState.getInstallPermissionState(name) != null) { 3822 scheduleWriteSettingsLocked(); 3823 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3824 || hadState) { 3825 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3826 } 3827 } 3828 } 3829 } 3830 3831 /** 3832 * Update the permission flags for all packages and runtime permissions of a user in order 3833 * to allow device or profile owner to remove POLICY_FIXED. 3834 */ 3835 @Override 3836 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3837 if (!sUserManager.exists(userId)) { 3838 return; 3839 } 3840 3841 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3842 3843 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3844 "updatePermissionFlagsForAllApps"); 3845 3846 // Only the system can change system fixed flags. 3847 if (getCallingUid() != Process.SYSTEM_UID) { 3848 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3849 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3850 } 3851 3852 synchronized (mPackages) { 3853 boolean changed = false; 3854 final int packageCount = mPackages.size(); 3855 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3856 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3857 SettingBase sb = (SettingBase) pkg.mExtras; 3858 if (sb == null) { 3859 continue; 3860 } 3861 PermissionsState permissionsState = sb.getPermissionsState(); 3862 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3863 userId, flagMask, flagValues); 3864 } 3865 if (changed) { 3866 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3867 } 3868 } 3869 } 3870 3871 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3872 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3873 != PackageManager.PERMISSION_GRANTED 3874 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3875 != PackageManager.PERMISSION_GRANTED) { 3876 throw new SecurityException(message + " requires " 3877 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3878 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3879 } 3880 } 3881 3882 @Override 3883 public boolean shouldShowRequestPermissionRationale(String permissionName, 3884 String packageName, int userId) { 3885 if (UserHandle.getCallingUserId() != userId) { 3886 mContext.enforceCallingPermission( 3887 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3888 "canShowRequestPermissionRationale for user " + userId); 3889 } 3890 3891 final int uid = getPackageUid(packageName, userId); 3892 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3893 return false; 3894 } 3895 3896 if (checkPermission(permissionName, packageName, userId) 3897 == PackageManager.PERMISSION_GRANTED) { 3898 return false; 3899 } 3900 3901 final int flags; 3902 3903 final long identity = Binder.clearCallingIdentity(); 3904 try { 3905 flags = getPermissionFlags(permissionName, 3906 packageName, userId); 3907 } finally { 3908 Binder.restoreCallingIdentity(identity); 3909 } 3910 3911 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3912 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3913 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3914 3915 if ((flags & fixedFlags) != 0) { 3916 return false; 3917 } 3918 3919 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3920 } 3921 3922 @Override 3923 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3924 mContext.enforceCallingOrSelfPermission( 3925 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3926 "addOnPermissionsChangeListener"); 3927 3928 synchronized (mPackages) { 3929 mOnPermissionChangeListeners.addListenerLocked(listener); 3930 } 3931 } 3932 3933 @Override 3934 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3935 synchronized (mPackages) { 3936 mOnPermissionChangeListeners.removeListenerLocked(listener); 3937 } 3938 } 3939 3940 @Override 3941 public boolean isProtectedBroadcast(String actionName) { 3942 synchronized (mPackages) { 3943 return mProtectedBroadcasts.contains(actionName); 3944 } 3945 } 3946 3947 @Override 3948 public int checkSignatures(String pkg1, String pkg2) { 3949 synchronized (mPackages) { 3950 final PackageParser.Package p1 = mPackages.get(pkg1); 3951 final PackageParser.Package p2 = mPackages.get(pkg2); 3952 if (p1 == null || p1.mExtras == null 3953 || p2 == null || p2.mExtras == null) { 3954 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3955 } 3956 return compareSignatures(p1.mSignatures, p2.mSignatures); 3957 } 3958 } 3959 3960 @Override 3961 public int checkUidSignatures(int uid1, int uid2) { 3962 // Map to base uids. 3963 uid1 = UserHandle.getAppId(uid1); 3964 uid2 = UserHandle.getAppId(uid2); 3965 // reader 3966 synchronized (mPackages) { 3967 Signature[] s1; 3968 Signature[] s2; 3969 Object obj = mSettings.getUserIdLPr(uid1); 3970 if (obj != null) { 3971 if (obj instanceof SharedUserSetting) { 3972 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3973 } else if (obj instanceof PackageSetting) { 3974 s1 = ((PackageSetting)obj).signatures.mSignatures; 3975 } else { 3976 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3977 } 3978 } else { 3979 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3980 } 3981 obj = mSettings.getUserIdLPr(uid2); 3982 if (obj != null) { 3983 if (obj instanceof SharedUserSetting) { 3984 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3985 } else if (obj instanceof PackageSetting) { 3986 s2 = ((PackageSetting)obj).signatures.mSignatures; 3987 } else { 3988 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3989 } 3990 } else { 3991 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3992 } 3993 return compareSignatures(s1, s2); 3994 } 3995 } 3996 3997 private void killUid(int appId, int userId, String reason) { 3998 final long identity = Binder.clearCallingIdentity(); 3999 try { 4000 IActivityManager am = ActivityManagerNative.getDefault(); 4001 if (am != null) { 4002 try { 4003 am.killUid(appId, userId, reason); 4004 } catch (RemoteException e) { 4005 /* ignore - same process */ 4006 } 4007 } 4008 } finally { 4009 Binder.restoreCallingIdentity(identity); 4010 } 4011 } 4012 4013 /** 4014 * Compares two sets of signatures. Returns: 4015 * <br /> 4016 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4017 * <br /> 4018 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4019 * <br /> 4020 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4021 * <br /> 4022 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4023 * <br /> 4024 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4025 */ 4026 static int compareSignatures(Signature[] s1, Signature[] s2) { 4027 if (s1 == null) { 4028 return s2 == null 4029 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4030 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4031 } 4032 4033 if (s2 == null) { 4034 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4035 } 4036 4037 if (s1.length != s2.length) { 4038 return PackageManager.SIGNATURE_NO_MATCH; 4039 } 4040 4041 // Since both signature sets are of size 1, we can compare without HashSets. 4042 if (s1.length == 1) { 4043 return s1[0].equals(s2[0]) ? 4044 PackageManager.SIGNATURE_MATCH : 4045 PackageManager.SIGNATURE_NO_MATCH; 4046 } 4047 4048 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4049 for (Signature sig : s1) { 4050 set1.add(sig); 4051 } 4052 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4053 for (Signature sig : s2) { 4054 set2.add(sig); 4055 } 4056 // Make sure s2 contains all signatures in s1. 4057 if (set1.equals(set2)) { 4058 return PackageManager.SIGNATURE_MATCH; 4059 } 4060 return PackageManager.SIGNATURE_NO_MATCH; 4061 } 4062 4063 /** 4064 * If the database version for this type of package (internal storage or 4065 * external storage) is less than the version where package signatures 4066 * were updated, return true. 4067 */ 4068 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4069 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4070 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4071 } 4072 4073 /** 4074 * Used for backward compatibility to make sure any packages with 4075 * certificate chains get upgraded to the new style. {@code existingSigs} 4076 * will be in the old format (since they were stored on disk from before the 4077 * system upgrade) and {@code scannedSigs} will be in the newer format. 4078 */ 4079 private int compareSignaturesCompat(PackageSignatures existingSigs, 4080 PackageParser.Package scannedPkg) { 4081 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4082 return PackageManager.SIGNATURE_NO_MATCH; 4083 } 4084 4085 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4086 for (Signature sig : existingSigs.mSignatures) { 4087 existingSet.add(sig); 4088 } 4089 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4090 for (Signature sig : scannedPkg.mSignatures) { 4091 try { 4092 Signature[] chainSignatures = sig.getChainSignatures(); 4093 for (Signature chainSig : chainSignatures) { 4094 scannedCompatSet.add(chainSig); 4095 } 4096 } catch (CertificateEncodingException e) { 4097 scannedCompatSet.add(sig); 4098 } 4099 } 4100 /* 4101 * Make sure the expanded scanned set contains all signatures in the 4102 * existing one. 4103 */ 4104 if (scannedCompatSet.equals(existingSet)) { 4105 // Migrate the old signatures to the new scheme. 4106 existingSigs.assignSignatures(scannedPkg.mSignatures); 4107 // The new KeySets will be re-added later in the scanning process. 4108 synchronized (mPackages) { 4109 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4110 } 4111 return PackageManager.SIGNATURE_MATCH; 4112 } 4113 return PackageManager.SIGNATURE_NO_MATCH; 4114 } 4115 4116 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4117 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4118 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4119 } 4120 4121 private int compareSignaturesRecover(PackageSignatures existingSigs, 4122 PackageParser.Package scannedPkg) { 4123 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4124 return PackageManager.SIGNATURE_NO_MATCH; 4125 } 4126 4127 String msg = null; 4128 try { 4129 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4130 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4131 + scannedPkg.packageName); 4132 return PackageManager.SIGNATURE_MATCH; 4133 } 4134 } catch (CertificateException e) { 4135 msg = e.getMessage(); 4136 } 4137 4138 logCriticalInfo(Log.INFO, 4139 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4140 return PackageManager.SIGNATURE_NO_MATCH; 4141 } 4142 4143 @Override 4144 public String[] getPackagesForUid(int uid) { 4145 uid = UserHandle.getAppId(uid); 4146 // reader 4147 synchronized (mPackages) { 4148 Object obj = mSettings.getUserIdLPr(uid); 4149 if (obj instanceof SharedUserSetting) { 4150 final SharedUserSetting sus = (SharedUserSetting) obj; 4151 final int N = sus.packages.size(); 4152 final String[] res = new String[N]; 4153 final Iterator<PackageSetting> it = sus.packages.iterator(); 4154 int i = 0; 4155 while (it.hasNext()) { 4156 res[i++] = it.next().name; 4157 } 4158 return res; 4159 } else if (obj instanceof PackageSetting) { 4160 final PackageSetting ps = (PackageSetting) obj; 4161 return new String[] { ps.name }; 4162 } 4163 } 4164 return null; 4165 } 4166 4167 @Override 4168 public String getNameForUid(int uid) { 4169 // reader 4170 synchronized (mPackages) { 4171 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4172 if (obj instanceof SharedUserSetting) { 4173 final SharedUserSetting sus = (SharedUserSetting) obj; 4174 return sus.name + ":" + sus.userId; 4175 } else if (obj instanceof PackageSetting) { 4176 final PackageSetting ps = (PackageSetting) obj; 4177 return ps.name; 4178 } 4179 } 4180 return null; 4181 } 4182 4183 @Override 4184 public int getUidForSharedUser(String sharedUserName) { 4185 if(sharedUserName == null) { 4186 return -1; 4187 } 4188 // reader 4189 synchronized (mPackages) { 4190 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4191 if (suid == null) { 4192 return -1; 4193 } 4194 return suid.userId; 4195 } 4196 } 4197 4198 @Override 4199 public int getFlagsForUid(int uid) { 4200 synchronized (mPackages) { 4201 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4202 if (obj instanceof SharedUserSetting) { 4203 final SharedUserSetting sus = (SharedUserSetting) obj; 4204 return sus.pkgFlags; 4205 } else if (obj instanceof PackageSetting) { 4206 final PackageSetting ps = (PackageSetting) obj; 4207 return ps.pkgFlags; 4208 } 4209 } 4210 return 0; 4211 } 4212 4213 @Override 4214 public int getPrivateFlagsForUid(int uid) { 4215 synchronized (mPackages) { 4216 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4217 if (obj instanceof SharedUserSetting) { 4218 final SharedUserSetting sus = (SharedUserSetting) obj; 4219 return sus.pkgPrivateFlags; 4220 } else if (obj instanceof PackageSetting) { 4221 final PackageSetting ps = (PackageSetting) obj; 4222 return ps.pkgPrivateFlags; 4223 } 4224 } 4225 return 0; 4226 } 4227 4228 @Override 4229 public boolean isUidPrivileged(int uid) { 4230 uid = UserHandle.getAppId(uid); 4231 // reader 4232 synchronized (mPackages) { 4233 Object obj = mSettings.getUserIdLPr(uid); 4234 if (obj instanceof SharedUserSetting) { 4235 final SharedUserSetting sus = (SharedUserSetting) obj; 4236 final Iterator<PackageSetting> it = sus.packages.iterator(); 4237 while (it.hasNext()) { 4238 if (it.next().isPrivileged()) { 4239 return true; 4240 } 4241 } 4242 } else if (obj instanceof PackageSetting) { 4243 final PackageSetting ps = (PackageSetting) obj; 4244 return ps.isPrivileged(); 4245 } 4246 } 4247 return false; 4248 } 4249 4250 @Override 4251 public String[] getAppOpPermissionPackages(String permissionName) { 4252 synchronized (mPackages) { 4253 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4254 if (pkgs == null) { 4255 return null; 4256 } 4257 return pkgs.toArray(new String[pkgs.size()]); 4258 } 4259 } 4260 4261 @Override 4262 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4263 int flags, int userId) { 4264 if (!sUserManager.exists(userId)) return null; 4265 flags = augmentFlagsForUser(flags, userId); 4266 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4267 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4268 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4269 } 4270 4271 @Override 4272 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4273 IntentFilter filter, int match, ComponentName activity) { 4274 final int userId = UserHandle.getCallingUserId(); 4275 if (DEBUG_PREFERRED) { 4276 Log.v(TAG, "setLastChosenActivity intent=" + intent 4277 + " resolvedType=" + resolvedType 4278 + " flags=" + flags 4279 + " filter=" + filter 4280 + " match=" + match 4281 + " activity=" + activity); 4282 filter.dump(new PrintStreamPrinter(System.out), " "); 4283 } 4284 intent.setComponent(null); 4285 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4286 // Find any earlier preferred or last chosen entries and nuke them 4287 findPreferredActivity(intent, resolvedType, 4288 flags, query, 0, false, true, false, userId); 4289 // Add the new activity as the last chosen for this filter 4290 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4291 "Setting last chosen"); 4292 } 4293 4294 @Override 4295 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4296 final int userId = UserHandle.getCallingUserId(); 4297 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4298 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4299 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4300 false, false, false, userId); 4301 } 4302 4303 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4304 int flags, List<ResolveInfo> query, int userId) { 4305 if (query != null) { 4306 final int N = query.size(); 4307 if (N == 1) { 4308 return query.get(0); 4309 } else if (N > 1) { 4310 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4311 // If there is more than one activity with the same priority, 4312 // then let the user decide between them. 4313 ResolveInfo r0 = query.get(0); 4314 ResolveInfo r1 = query.get(1); 4315 if (DEBUG_INTENT_MATCHING || debug) { 4316 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4317 + r1.activityInfo.name + "=" + r1.priority); 4318 } 4319 // If the first activity has a higher priority, or a different 4320 // default, then it is always desireable to pick it. 4321 if (r0.priority != r1.priority 4322 || r0.preferredOrder != r1.preferredOrder 4323 || r0.isDefault != r1.isDefault) { 4324 return query.get(0); 4325 } 4326 // If we have saved a preference for a preferred activity for 4327 // this Intent, use that. 4328 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4329 flags, query, r0.priority, true, false, debug, userId); 4330 if (ri != null) { 4331 return ri; 4332 } 4333 ri = new ResolveInfo(mResolveInfo); 4334 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4335 ri.activityInfo.applicationInfo = new ApplicationInfo( 4336 ri.activityInfo.applicationInfo); 4337 if (userId != 0) { 4338 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4339 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4340 } 4341 // Make sure that the resolver is displayable in car mode 4342 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4343 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4344 return ri; 4345 } 4346 } 4347 return null; 4348 } 4349 4350 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4351 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4352 final int N = query.size(); 4353 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4354 .get(userId); 4355 // Get the list of persistent preferred activities that handle the intent 4356 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4357 List<PersistentPreferredActivity> pprefs = ppir != null 4358 ? ppir.queryIntent(intent, resolvedType, 4359 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4360 : null; 4361 if (pprefs != null && pprefs.size() > 0) { 4362 final int M = pprefs.size(); 4363 for (int i=0; i<M; i++) { 4364 final PersistentPreferredActivity ppa = pprefs.get(i); 4365 if (DEBUG_PREFERRED || debug) { 4366 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4367 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4368 + "\n component=" + ppa.mComponent); 4369 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4370 } 4371 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4372 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4373 if (DEBUG_PREFERRED || debug) { 4374 Slog.v(TAG, "Found persistent preferred activity:"); 4375 if (ai != null) { 4376 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4377 } else { 4378 Slog.v(TAG, " null"); 4379 } 4380 } 4381 if (ai == null) { 4382 // This previously registered persistent preferred activity 4383 // component is no longer known. Ignore it and do NOT remove it. 4384 continue; 4385 } 4386 for (int j=0; j<N; j++) { 4387 final ResolveInfo ri = query.get(j); 4388 if (!ri.activityInfo.applicationInfo.packageName 4389 .equals(ai.applicationInfo.packageName)) { 4390 continue; 4391 } 4392 if (!ri.activityInfo.name.equals(ai.name)) { 4393 continue; 4394 } 4395 // Found a persistent preference that can handle the intent. 4396 if (DEBUG_PREFERRED || debug) { 4397 Slog.v(TAG, "Returning persistent preferred activity: " + 4398 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4399 } 4400 return ri; 4401 } 4402 } 4403 } 4404 return null; 4405 } 4406 4407 // TODO: handle preferred activities missing while user has amnesia 4408 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4409 List<ResolveInfo> query, int priority, boolean always, 4410 boolean removeMatches, boolean debug, int userId) { 4411 if (!sUserManager.exists(userId)) return null; 4412 flags = augmentFlagsForUser(flags, userId); 4413 // writer 4414 synchronized (mPackages) { 4415 if (intent.getSelector() != null) { 4416 intent = intent.getSelector(); 4417 } 4418 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4419 4420 // Try to find a matching persistent preferred activity. 4421 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4422 debug, userId); 4423 4424 // If a persistent preferred activity matched, use it. 4425 if (pri != null) { 4426 return pri; 4427 } 4428 4429 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4430 // Get the list of preferred activities that handle the intent 4431 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4432 List<PreferredActivity> prefs = pir != null 4433 ? pir.queryIntent(intent, resolvedType, 4434 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4435 : null; 4436 if (prefs != null && prefs.size() > 0) { 4437 boolean changed = false; 4438 try { 4439 // First figure out how good the original match set is. 4440 // We will only allow preferred activities that came 4441 // from the same match quality. 4442 int match = 0; 4443 4444 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4445 4446 final int N = query.size(); 4447 for (int j=0; j<N; j++) { 4448 final ResolveInfo ri = query.get(j); 4449 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4450 + ": 0x" + Integer.toHexString(match)); 4451 if (ri.match > match) { 4452 match = ri.match; 4453 } 4454 } 4455 4456 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4457 + Integer.toHexString(match)); 4458 4459 match &= IntentFilter.MATCH_CATEGORY_MASK; 4460 final int M = prefs.size(); 4461 for (int i=0; i<M; i++) { 4462 final PreferredActivity pa = prefs.get(i); 4463 if (DEBUG_PREFERRED || debug) { 4464 Slog.v(TAG, "Checking PreferredActivity ds=" 4465 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4466 + "\n component=" + pa.mPref.mComponent); 4467 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4468 } 4469 if (pa.mPref.mMatch != match) { 4470 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4471 + Integer.toHexString(pa.mPref.mMatch)); 4472 continue; 4473 } 4474 // If it's not an "always" type preferred activity and that's what we're 4475 // looking for, skip it. 4476 if (always && !pa.mPref.mAlways) { 4477 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4478 continue; 4479 } 4480 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4481 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4482 if (DEBUG_PREFERRED || debug) { 4483 Slog.v(TAG, "Found preferred activity:"); 4484 if (ai != null) { 4485 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4486 } else { 4487 Slog.v(TAG, " null"); 4488 } 4489 } 4490 if (ai == null) { 4491 // This previously registered preferred activity 4492 // component is no longer known. Most likely an update 4493 // to the app was installed and in the new version this 4494 // component no longer exists. Clean it up by removing 4495 // it from the preferred activities list, and skip it. 4496 Slog.w(TAG, "Removing dangling preferred activity: " 4497 + pa.mPref.mComponent); 4498 pir.removeFilter(pa); 4499 changed = true; 4500 continue; 4501 } 4502 for (int j=0; j<N; j++) { 4503 final ResolveInfo ri = query.get(j); 4504 if (!ri.activityInfo.applicationInfo.packageName 4505 .equals(ai.applicationInfo.packageName)) { 4506 continue; 4507 } 4508 if (!ri.activityInfo.name.equals(ai.name)) { 4509 continue; 4510 } 4511 4512 if (removeMatches) { 4513 pir.removeFilter(pa); 4514 changed = true; 4515 if (DEBUG_PREFERRED) { 4516 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4517 } 4518 break; 4519 } 4520 4521 // Okay we found a previously set preferred or last chosen app. 4522 // If the result set is different from when this 4523 // was created, we need to clear it and re-ask the 4524 // user their preference, if we're looking for an "always" type entry. 4525 if (always && !pa.mPref.sameSet(query)) { 4526 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4527 + intent + " type " + resolvedType); 4528 if (DEBUG_PREFERRED) { 4529 Slog.v(TAG, "Removing preferred activity since set changed " 4530 + pa.mPref.mComponent); 4531 } 4532 pir.removeFilter(pa); 4533 // Re-add the filter as a "last chosen" entry (!always) 4534 PreferredActivity lastChosen = new PreferredActivity( 4535 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4536 pir.addFilter(lastChosen); 4537 changed = true; 4538 return null; 4539 } 4540 4541 // Yay! Either the set matched or we're looking for the last chosen 4542 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4543 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4544 return ri; 4545 } 4546 } 4547 } finally { 4548 if (changed) { 4549 if (DEBUG_PREFERRED) { 4550 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4551 } 4552 scheduleWritePackageRestrictionsLocked(userId); 4553 } 4554 } 4555 } 4556 } 4557 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4558 return null; 4559 } 4560 4561 /* 4562 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4563 */ 4564 @Override 4565 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4566 int targetUserId) { 4567 mContext.enforceCallingOrSelfPermission( 4568 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4569 List<CrossProfileIntentFilter> matches = 4570 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4571 if (matches != null) { 4572 int size = matches.size(); 4573 for (int i = 0; i < size; i++) { 4574 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4575 } 4576 } 4577 if (hasWebURI(intent)) { 4578 // cross-profile app linking works only towards the parent. 4579 final UserInfo parent = getProfileParent(sourceUserId); 4580 synchronized(mPackages) { 4581 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4582 intent, resolvedType, 0, sourceUserId, parent.id); 4583 return xpDomainInfo != null; 4584 } 4585 } 4586 return false; 4587 } 4588 4589 private UserInfo getProfileParent(int userId) { 4590 final long identity = Binder.clearCallingIdentity(); 4591 try { 4592 return sUserManager.getProfileParent(userId); 4593 } finally { 4594 Binder.restoreCallingIdentity(identity); 4595 } 4596 } 4597 4598 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4599 String resolvedType, int userId) { 4600 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4601 if (resolver != null) { 4602 return resolver.queryIntent(intent, resolvedType, false, userId); 4603 } 4604 return null; 4605 } 4606 4607 @Override 4608 public List<ResolveInfo> queryIntentActivities(Intent intent, 4609 String resolvedType, int flags, int userId) { 4610 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4611 flags = augmentFlagsForUser(flags, userId); 4612 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4613 ComponentName comp = intent.getComponent(); 4614 if (comp == null) { 4615 if (intent.getSelector() != null) { 4616 intent = intent.getSelector(); 4617 comp = intent.getComponent(); 4618 } 4619 } 4620 4621 if (comp != null) { 4622 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4623 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4624 if (ai != null) { 4625 final ResolveInfo ri = new ResolveInfo(); 4626 ri.activityInfo = ai; 4627 list.add(ri); 4628 } 4629 return list; 4630 } 4631 4632 // reader 4633 synchronized (mPackages) { 4634 final String pkgName = intent.getPackage(); 4635 if (pkgName == null) { 4636 List<CrossProfileIntentFilter> matchingFilters = 4637 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4638 // Check for results that need to skip the current profile. 4639 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4640 resolvedType, flags, userId); 4641 if (xpResolveInfo != null) { 4642 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4643 result.add(xpResolveInfo); 4644 return filterIfNotSystemUser(result, userId); 4645 } 4646 4647 // Check for results in the current profile. 4648 List<ResolveInfo> result = mActivities.queryIntent( 4649 intent, resolvedType, flags, userId); 4650 4651 // Check for cross profile results. 4652 xpResolveInfo = queryCrossProfileIntents( 4653 matchingFilters, intent, resolvedType, flags, userId); 4654 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4655 result.add(xpResolveInfo); 4656 Collections.sort(result, mResolvePrioritySorter); 4657 } 4658 result = filterIfNotSystemUser(result, userId); 4659 if (hasWebURI(intent)) { 4660 CrossProfileDomainInfo xpDomainInfo = null; 4661 final UserInfo parent = getProfileParent(userId); 4662 if (parent != null) { 4663 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4664 flags, userId, parent.id); 4665 } 4666 if (xpDomainInfo != null) { 4667 if (xpResolveInfo != null) { 4668 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4669 // in the result. 4670 result.remove(xpResolveInfo); 4671 } 4672 if (result.size() == 0) { 4673 result.add(xpDomainInfo.resolveInfo); 4674 return result; 4675 } 4676 } else if (result.size() <= 1) { 4677 return result; 4678 } 4679 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4680 xpDomainInfo, userId); 4681 Collections.sort(result, mResolvePrioritySorter); 4682 } 4683 return result; 4684 } 4685 final PackageParser.Package pkg = mPackages.get(pkgName); 4686 if (pkg != null) { 4687 return filterIfNotSystemUser( 4688 mActivities.queryIntentForPackage( 4689 intent, resolvedType, flags, pkg.activities, userId), 4690 userId); 4691 } 4692 return new ArrayList<ResolveInfo>(); 4693 } 4694 } 4695 4696 private static class CrossProfileDomainInfo { 4697 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4698 ResolveInfo resolveInfo; 4699 /* Best domain verification status of the activities found in the other profile */ 4700 int bestDomainVerificationStatus; 4701 } 4702 4703 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4704 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4705 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4706 sourceUserId)) { 4707 return null; 4708 } 4709 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4710 resolvedType, flags, parentUserId); 4711 4712 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4713 return null; 4714 } 4715 CrossProfileDomainInfo result = null; 4716 int size = resultTargetUser.size(); 4717 for (int i = 0; i < size; i++) { 4718 ResolveInfo riTargetUser = resultTargetUser.get(i); 4719 // Intent filter verification is only for filters that specify a host. So don't return 4720 // those that handle all web uris. 4721 if (riTargetUser.handleAllWebDataURI) { 4722 continue; 4723 } 4724 String packageName = riTargetUser.activityInfo.packageName; 4725 PackageSetting ps = mSettings.mPackages.get(packageName); 4726 if (ps == null) { 4727 continue; 4728 } 4729 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4730 int status = (int)(verificationState >> 32); 4731 if (result == null) { 4732 result = new CrossProfileDomainInfo(); 4733 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4734 sourceUserId, parentUserId); 4735 result.bestDomainVerificationStatus = status; 4736 } else { 4737 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4738 result.bestDomainVerificationStatus); 4739 } 4740 } 4741 // Don't consider matches with status NEVER across profiles. 4742 if (result != null && result.bestDomainVerificationStatus 4743 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4744 return null; 4745 } 4746 return result; 4747 } 4748 4749 /** 4750 * Verification statuses are ordered from the worse to the best, except for 4751 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4752 */ 4753 private int bestDomainVerificationStatus(int status1, int status2) { 4754 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4755 return status2; 4756 } 4757 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4758 return status1; 4759 } 4760 return (int) MathUtils.max(status1, status2); 4761 } 4762 4763 private boolean isUserEnabled(int userId) { 4764 long callingId = Binder.clearCallingIdentity(); 4765 try { 4766 UserInfo userInfo = sUserManager.getUserInfo(userId); 4767 return userInfo != null && userInfo.isEnabled(); 4768 } finally { 4769 Binder.restoreCallingIdentity(callingId); 4770 } 4771 } 4772 4773 /** 4774 * Filter out activities with systemUserOnly flag set, when current user is not System. 4775 * 4776 * @return filtered list 4777 */ 4778 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4779 if (userId == UserHandle.USER_SYSTEM) { 4780 return resolveInfos; 4781 } 4782 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4783 ResolveInfo info = resolveInfos.get(i); 4784 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4785 resolveInfos.remove(i); 4786 } 4787 } 4788 return resolveInfos; 4789 } 4790 4791 private static boolean hasWebURI(Intent intent) { 4792 if (intent.getData() == null) { 4793 return false; 4794 } 4795 final String scheme = intent.getScheme(); 4796 if (TextUtils.isEmpty(scheme)) { 4797 return false; 4798 } 4799 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4800 } 4801 4802 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4803 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4804 int userId) { 4805 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4806 4807 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4808 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4809 candidates.size()); 4810 } 4811 4812 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4813 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4814 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4815 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4816 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4817 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4818 4819 synchronized (mPackages) { 4820 final int count = candidates.size(); 4821 // First, try to use linked apps. Partition the candidates into four lists: 4822 // one for the final results, one for the "do not use ever", one for "undefined status" 4823 // and finally one for "browser app type". 4824 for (int n=0; n<count; n++) { 4825 ResolveInfo info = candidates.get(n); 4826 String packageName = info.activityInfo.packageName; 4827 PackageSetting ps = mSettings.mPackages.get(packageName); 4828 if (ps != null) { 4829 // Add to the special match all list (Browser use case) 4830 if (info.handleAllWebDataURI) { 4831 matchAllList.add(info); 4832 continue; 4833 } 4834 // Try to get the status from User settings first 4835 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4836 int status = (int)(packedStatus >> 32); 4837 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4838 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4839 if (DEBUG_DOMAIN_VERIFICATION) { 4840 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4841 + " : linkgen=" + linkGeneration); 4842 } 4843 // Use link-enabled generation as preferredOrder, i.e. 4844 // prefer newly-enabled over earlier-enabled. 4845 info.preferredOrder = linkGeneration; 4846 alwaysList.add(info); 4847 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4848 if (DEBUG_DOMAIN_VERIFICATION) { 4849 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4850 } 4851 neverList.add(info); 4852 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4853 if (DEBUG_DOMAIN_VERIFICATION) { 4854 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4855 } 4856 alwaysAskList.add(info); 4857 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4858 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4859 if (DEBUG_DOMAIN_VERIFICATION) { 4860 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4861 } 4862 undefinedList.add(info); 4863 } 4864 } 4865 } 4866 4867 // We'll want to include browser possibilities in a few cases 4868 boolean includeBrowser = false; 4869 4870 // First try to add the "always" resolution(s) for the current user, if any 4871 if (alwaysList.size() > 0) { 4872 result.addAll(alwaysList); 4873 } else { 4874 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4875 result.addAll(undefinedList); 4876 // Maybe add one for the other profile. 4877 if (xpDomainInfo != null && ( 4878 xpDomainInfo.bestDomainVerificationStatus 4879 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4880 result.add(xpDomainInfo.resolveInfo); 4881 } 4882 includeBrowser = true; 4883 } 4884 4885 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4886 // If there were 'always' entries their preferred order has been set, so we also 4887 // back that off to make the alternatives equivalent 4888 if (alwaysAskList.size() > 0) { 4889 for (ResolveInfo i : result) { 4890 i.preferredOrder = 0; 4891 } 4892 result.addAll(alwaysAskList); 4893 includeBrowser = true; 4894 } 4895 4896 if (includeBrowser) { 4897 // Also add browsers (all of them or only the default one) 4898 if (DEBUG_DOMAIN_VERIFICATION) { 4899 Slog.v(TAG, " ...including browsers in candidate set"); 4900 } 4901 if ((matchFlags & MATCH_ALL) != 0) { 4902 result.addAll(matchAllList); 4903 } else { 4904 // Browser/generic handling case. If there's a default browser, go straight 4905 // to that (but only if there is no other higher-priority match). 4906 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4907 int maxMatchPrio = 0; 4908 ResolveInfo defaultBrowserMatch = null; 4909 final int numCandidates = matchAllList.size(); 4910 for (int n = 0; n < numCandidates; n++) { 4911 ResolveInfo info = matchAllList.get(n); 4912 // track the highest overall match priority... 4913 if (info.priority > maxMatchPrio) { 4914 maxMatchPrio = info.priority; 4915 } 4916 // ...and the highest-priority default browser match 4917 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4918 if (defaultBrowserMatch == null 4919 || (defaultBrowserMatch.priority < info.priority)) { 4920 if (debug) { 4921 Slog.v(TAG, "Considering default browser match " + info); 4922 } 4923 defaultBrowserMatch = info; 4924 } 4925 } 4926 } 4927 if (defaultBrowserMatch != null 4928 && defaultBrowserMatch.priority >= maxMatchPrio 4929 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4930 { 4931 if (debug) { 4932 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4933 } 4934 result.add(defaultBrowserMatch); 4935 } else { 4936 result.addAll(matchAllList); 4937 } 4938 } 4939 4940 // If there is nothing selected, add all candidates and remove the ones that the user 4941 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4942 if (result.size() == 0) { 4943 result.addAll(candidates); 4944 result.removeAll(neverList); 4945 } 4946 } 4947 } 4948 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4949 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4950 result.size()); 4951 for (ResolveInfo info : result) { 4952 Slog.v(TAG, " + " + info.activityInfo); 4953 } 4954 } 4955 return result; 4956 } 4957 4958 // Returns a packed value as a long: 4959 // 4960 // high 'int'-sized word: link status: undefined/ask/never/always. 4961 // low 'int'-sized word: relative priority among 'always' results. 4962 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4963 long result = ps.getDomainVerificationStatusForUser(userId); 4964 // if none available, get the master status 4965 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4966 if (ps.getIntentFilterVerificationInfo() != null) { 4967 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4968 } 4969 } 4970 return result; 4971 } 4972 4973 private ResolveInfo querySkipCurrentProfileIntents( 4974 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4975 int flags, int sourceUserId) { 4976 if (matchingFilters != null) { 4977 int size = matchingFilters.size(); 4978 for (int i = 0; i < size; i ++) { 4979 CrossProfileIntentFilter filter = matchingFilters.get(i); 4980 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4981 // Checking if there are activities in the target user that can handle the 4982 // intent. 4983 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4984 resolvedType, flags, sourceUserId); 4985 if (resolveInfo != null) { 4986 return resolveInfo; 4987 } 4988 } 4989 } 4990 } 4991 return null; 4992 } 4993 4994 // Return matching ResolveInfo if any for skip current profile intent filters. 4995 private ResolveInfo queryCrossProfileIntents( 4996 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4997 int flags, int sourceUserId) { 4998 if (matchingFilters != null) { 4999 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5000 // match the same intent. For performance reasons, it is better not to 5001 // run queryIntent twice for the same userId 5002 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5003 int size = matchingFilters.size(); 5004 for (int i = 0; i < size; i++) { 5005 CrossProfileIntentFilter filter = matchingFilters.get(i); 5006 int targetUserId = filter.getTargetUserId(); 5007 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 5008 && !alreadyTriedUserIds.get(targetUserId)) { 5009 // Checking if there are activities in the target user that can handle the 5010 // intent. 5011 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5012 resolvedType, flags, sourceUserId); 5013 if (resolveInfo != null) return resolveInfo; 5014 alreadyTriedUserIds.put(targetUserId, true); 5015 } 5016 } 5017 } 5018 return null; 5019 } 5020 5021 /** 5022 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5023 * will forward the intent to the filter's target user. 5024 * Otherwise, returns null. 5025 */ 5026 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5027 String resolvedType, int flags, int sourceUserId) { 5028 int targetUserId = filter.getTargetUserId(); 5029 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5030 resolvedType, flags, targetUserId); 5031 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5032 && isUserEnabled(targetUserId)) { 5033 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5034 } 5035 return null; 5036 } 5037 5038 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5039 int sourceUserId, int targetUserId) { 5040 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5041 long ident = Binder.clearCallingIdentity(); 5042 boolean targetIsProfile; 5043 try { 5044 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5045 } finally { 5046 Binder.restoreCallingIdentity(ident); 5047 } 5048 String className; 5049 if (targetIsProfile) { 5050 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5051 } else { 5052 className = FORWARD_INTENT_TO_PARENT; 5053 } 5054 ComponentName forwardingActivityComponentName = new ComponentName( 5055 mAndroidApplication.packageName, className); 5056 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5057 sourceUserId); 5058 if (!targetIsProfile) { 5059 forwardingActivityInfo.showUserIcon = targetUserId; 5060 forwardingResolveInfo.noResourceId = true; 5061 } 5062 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5063 forwardingResolveInfo.priority = 0; 5064 forwardingResolveInfo.preferredOrder = 0; 5065 forwardingResolveInfo.match = 0; 5066 forwardingResolveInfo.isDefault = true; 5067 forwardingResolveInfo.filter = filter; 5068 forwardingResolveInfo.targetUserId = targetUserId; 5069 return forwardingResolveInfo; 5070 } 5071 5072 @Override 5073 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5074 Intent[] specifics, String[] specificTypes, Intent intent, 5075 String resolvedType, int flags, int userId) { 5076 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5077 flags = augmentFlagsForUser(flags, userId); 5078 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5079 false, "query intent activity options"); 5080 final String resultsAction = intent.getAction(); 5081 5082 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5083 | PackageManager.GET_RESOLVED_FILTER, userId); 5084 5085 if (DEBUG_INTENT_MATCHING) { 5086 Log.v(TAG, "Query " + intent + ": " + results); 5087 } 5088 5089 int specificsPos = 0; 5090 int N; 5091 5092 // todo: note that the algorithm used here is O(N^2). This 5093 // isn't a problem in our current environment, but if we start running 5094 // into situations where we have more than 5 or 10 matches then this 5095 // should probably be changed to something smarter... 5096 5097 // First we go through and resolve each of the specific items 5098 // that were supplied, taking care of removing any corresponding 5099 // duplicate items in the generic resolve list. 5100 if (specifics != null) { 5101 for (int i=0; i<specifics.length; i++) { 5102 final Intent sintent = specifics[i]; 5103 if (sintent == null) { 5104 continue; 5105 } 5106 5107 if (DEBUG_INTENT_MATCHING) { 5108 Log.v(TAG, "Specific #" + i + ": " + sintent); 5109 } 5110 5111 String action = sintent.getAction(); 5112 if (resultsAction != null && resultsAction.equals(action)) { 5113 // If this action was explicitly requested, then don't 5114 // remove things that have it. 5115 action = null; 5116 } 5117 5118 ResolveInfo ri = null; 5119 ActivityInfo ai = null; 5120 5121 ComponentName comp = sintent.getComponent(); 5122 if (comp == null) { 5123 ri = resolveIntent( 5124 sintent, 5125 specificTypes != null ? specificTypes[i] : null, 5126 flags, userId); 5127 if (ri == null) { 5128 continue; 5129 } 5130 if (ri == mResolveInfo) { 5131 // ACK! Must do something better with this. 5132 } 5133 ai = ri.activityInfo; 5134 comp = new ComponentName(ai.applicationInfo.packageName, 5135 ai.name); 5136 } else { 5137 ai = getActivityInfo(comp, flags, userId); 5138 if (ai == null) { 5139 continue; 5140 } 5141 } 5142 5143 // Look for any generic query activities that are duplicates 5144 // of this specific one, and remove them from the results. 5145 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5146 N = results.size(); 5147 int j; 5148 for (j=specificsPos; j<N; j++) { 5149 ResolveInfo sri = results.get(j); 5150 if ((sri.activityInfo.name.equals(comp.getClassName()) 5151 && sri.activityInfo.applicationInfo.packageName.equals( 5152 comp.getPackageName())) 5153 || (action != null && sri.filter.matchAction(action))) { 5154 results.remove(j); 5155 if (DEBUG_INTENT_MATCHING) Log.v( 5156 TAG, "Removing duplicate item from " + j 5157 + " due to specific " + specificsPos); 5158 if (ri == null) { 5159 ri = sri; 5160 } 5161 j--; 5162 N--; 5163 } 5164 } 5165 5166 // Add this specific item to its proper place. 5167 if (ri == null) { 5168 ri = new ResolveInfo(); 5169 ri.activityInfo = ai; 5170 } 5171 results.add(specificsPos, ri); 5172 ri.specificIndex = i; 5173 specificsPos++; 5174 } 5175 } 5176 5177 // Now we go through the remaining generic results and remove any 5178 // duplicate actions that are found here. 5179 N = results.size(); 5180 for (int i=specificsPos; i<N-1; i++) { 5181 final ResolveInfo rii = results.get(i); 5182 if (rii.filter == null) { 5183 continue; 5184 } 5185 5186 // Iterate over all of the actions of this result's intent 5187 // filter... typically this should be just one. 5188 final Iterator<String> it = rii.filter.actionsIterator(); 5189 if (it == null) { 5190 continue; 5191 } 5192 while (it.hasNext()) { 5193 final String action = it.next(); 5194 if (resultsAction != null && resultsAction.equals(action)) { 5195 // If this action was explicitly requested, then don't 5196 // remove things that have it. 5197 continue; 5198 } 5199 for (int j=i+1; j<N; j++) { 5200 final ResolveInfo rij = results.get(j); 5201 if (rij.filter != null && rij.filter.hasAction(action)) { 5202 results.remove(j); 5203 if (DEBUG_INTENT_MATCHING) Log.v( 5204 TAG, "Removing duplicate item from " + j 5205 + " due to action " + action + " at " + i); 5206 j--; 5207 N--; 5208 } 5209 } 5210 } 5211 5212 // If the caller didn't request filter information, drop it now 5213 // so we don't have to marshall/unmarshall it. 5214 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5215 rii.filter = null; 5216 } 5217 } 5218 5219 // Filter out the caller activity if so requested. 5220 if (caller != null) { 5221 N = results.size(); 5222 for (int i=0; i<N; i++) { 5223 ActivityInfo ainfo = results.get(i).activityInfo; 5224 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5225 && caller.getClassName().equals(ainfo.name)) { 5226 results.remove(i); 5227 break; 5228 } 5229 } 5230 } 5231 5232 // If the caller didn't request filter information, 5233 // drop them now so we don't have to 5234 // marshall/unmarshall it. 5235 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5236 N = results.size(); 5237 for (int i=0; i<N; i++) { 5238 results.get(i).filter = null; 5239 } 5240 } 5241 5242 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5243 return results; 5244 } 5245 5246 @Override 5247 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5248 int userId) { 5249 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5250 flags = augmentFlagsForUser(flags, userId); 5251 ComponentName comp = intent.getComponent(); 5252 if (comp == null) { 5253 if (intent.getSelector() != null) { 5254 intent = intent.getSelector(); 5255 comp = intent.getComponent(); 5256 } 5257 } 5258 if (comp != null) { 5259 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5260 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5261 if (ai != null) { 5262 ResolveInfo ri = new ResolveInfo(); 5263 ri.activityInfo = ai; 5264 list.add(ri); 5265 } 5266 return list; 5267 } 5268 5269 // reader 5270 synchronized (mPackages) { 5271 String pkgName = intent.getPackage(); 5272 if (pkgName == null) { 5273 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5274 } 5275 final PackageParser.Package pkg = mPackages.get(pkgName); 5276 if (pkg != null) { 5277 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5278 userId); 5279 } 5280 return null; 5281 } 5282 } 5283 5284 @Override 5285 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5286 if (!sUserManager.exists(userId)) return null; 5287 flags = augmentFlagsForUser(flags, userId); 5288 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5289 if (query != null) { 5290 if (query.size() >= 1) { 5291 // If there is more than one service with the same priority, 5292 // just arbitrarily pick the first one. 5293 return query.get(0); 5294 } 5295 } 5296 return null; 5297 } 5298 5299 @Override 5300 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5301 int userId) { 5302 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5303 flags = augmentFlagsForUser(flags, userId); 5304 ComponentName comp = intent.getComponent(); 5305 if (comp == null) { 5306 if (intent.getSelector() != null) { 5307 intent = intent.getSelector(); 5308 comp = intent.getComponent(); 5309 } 5310 } 5311 if (comp != null) { 5312 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5313 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5314 if (si != null) { 5315 final ResolveInfo ri = new ResolveInfo(); 5316 ri.serviceInfo = si; 5317 list.add(ri); 5318 } 5319 return list; 5320 } 5321 5322 // reader 5323 synchronized (mPackages) { 5324 String pkgName = intent.getPackage(); 5325 if (pkgName == null) { 5326 return mServices.queryIntent(intent, resolvedType, flags, userId); 5327 } 5328 final PackageParser.Package pkg = mPackages.get(pkgName); 5329 if (pkg != null) { 5330 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5331 userId); 5332 } 5333 return null; 5334 } 5335 } 5336 5337 @Override 5338 public List<ResolveInfo> queryIntentContentProviders( 5339 Intent intent, String resolvedType, int flags, int userId) { 5340 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5341 flags = augmentFlagsForUser(flags, userId); 5342 ComponentName comp = intent.getComponent(); 5343 if (comp == null) { 5344 if (intent.getSelector() != null) { 5345 intent = intent.getSelector(); 5346 comp = intent.getComponent(); 5347 } 5348 } 5349 if (comp != null) { 5350 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5351 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5352 if (pi != null) { 5353 final ResolveInfo ri = new ResolveInfo(); 5354 ri.providerInfo = pi; 5355 list.add(ri); 5356 } 5357 return list; 5358 } 5359 5360 // reader 5361 synchronized (mPackages) { 5362 String pkgName = intent.getPackage(); 5363 if (pkgName == null) { 5364 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5365 } 5366 final PackageParser.Package pkg = mPackages.get(pkgName); 5367 if (pkg != null) { 5368 return mProviders.queryIntentForPackage( 5369 intent, resolvedType, flags, pkg.providers, userId); 5370 } 5371 return null; 5372 } 5373 } 5374 5375 @Override 5376 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5377 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5378 5379 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5380 5381 // writer 5382 synchronized (mPackages) { 5383 ArrayList<PackageInfo> list; 5384 if (listUninstalled) { 5385 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5386 for (PackageSetting ps : mSettings.mPackages.values()) { 5387 PackageInfo pi; 5388 if (ps.pkg != null) { 5389 pi = generatePackageInfo(ps.pkg, flags, userId); 5390 } else { 5391 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5392 } 5393 if (pi != null) { 5394 list.add(pi); 5395 } 5396 } 5397 } else { 5398 list = new ArrayList<PackageInfo>(mPackages.size()); 5399 for (PackageParser.Package p : mPackages.values()) { 5400 PackageInfo pi = generatePackageInfo(p, flags, userId); 5401 if (pi != null) { 5402 list.add(pi); 5403 } 5404 } 5405 } 5406 5407 return new ParceledListSlice<PackageInfo>(list); 5408 } 5409 } 5410 5411 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5412 String[] permissions, boolean[] tmp, int flags, int userId) { 5413 int numMatch = 0; 5414 final PermissionsState permissionsState = ps.getPermissionsState(); 5415 for (int i=0; i<permissions.length; i++) { 5416 final String permission = permissions[i]; 5417 if (permissionsState.hasPermission(permission, userId)) { 5418 tmp[i] = true; 5419 numMatch++; 5420 } else { 5421 tmp[i] = false; 5422 } 5423 } 5424 if (numMatch == 0) { 5425 return; 5426 } 5427 PackageInfo pi; 5428 if (ps.pkg != null) { 5429 pi = generatePackageInfo(ps.pkg, flags, userId); 5430 } else { 5431 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5432 } 5433 // The above might return null in cases of uninstalled apps or install-state 5434 // skew across users/profiles. 5435 if (pi != null) { 5436 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5437 if (numMatch == permissions.length) { 5438 pi.requestedPermissions = permissions; 5439 } else { 5440 pi.requestedPermissions = new String[numMatch]; 5441 numMatch = 0; 5442 for (int i=0; i<permissions.length; i++) { 5443 if (tmp[i]) { 5444 pi.requestedPermissions[numMatch] = permissions[i]; 5445 numMatch++; 5446 } 5447 } 5448 } 5449 } 5450 list.add(pi); 5451 } 5452 } 5453 5454 @Override 5455 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5456 String[] permissions, int flags, int userId) { 5457 if (!sUserManager.exists(userId)) return null; 5458 flags = augmentFlagsForUser(flags, userId); 5459 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5460 5461 // writer 5462 synchronized (mPackages) { 5463 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5464 boolean[] tmpBools = new boolean[permissions.length]; 5465 if (listUninstalled) { 5466 for (PackageSetting ps : mSettings.mPackages.values()) { 5467 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5468 } 5469 } else { 5470 for (PackageParser.Package pkg : mPackages.values()) { 5471 PackageSetting ps = (PackageSetting)pkg.mExtras; 5472 if (ps != null) { 5473 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5474 userId); 5475 } 5476 } 5477 } 5478 5479 return new ParceledListSlice<PackageInfo>(list); 5480 } 5481 } 5482 5483 @Override 5484 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5485 if (!sUserManager.exists(userId)) return null; 5486 flags = augmentFlagsForUser(flags, userId); 5487 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5488 5489 // writer 5490 synchronized (mPackages) { 5491 ArrayList<ApplicationInfo> list; 5492 if (listUninstalled) { 5493 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5494 for (PackageSetting ps : mSettings.mPackages.values()) { 5495 ApplicationInfo ai; 5496 if (ps.pkg != null) { 5497 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5498 ps.readUserState(userId), userId); 5499 } else { 5500 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5501 } 5502 if (ai != null) { 5503 list.add(ai); 5504 } 5505 } 5506 } else { 5507 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5508 for (PackageParser.Package p : mPackages.values()) { 5509 if (p.mExtras != null) { 5510 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5511 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5512 if (ai != null) { 5513 list.add(ai); 5514 } 5515 } 5516 } 5517 } 5518 5519 return new ParceledListSlice<ApplicationInfo>(list); 5520 } 5521 } 5522 5523 public List<ApplicationInfo> getPersistentApplications(int flags) { 5524 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5525 5526 // reader 5527 synchronized (mPackages) { 5528 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5529 final int userId = UserHandle.getCallingUserId(); 5530 while (i.hasNext()) { 5531 final PackageParser.Package p = i.next(); 5532 if (p.applicationInfo != null 5533 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5534 && (!mSafeMode || isSystemApp(p))) { 5535 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5536 if (ps != null) { 5537 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5538 ps.readUserState(userId), userId); 5539 if (ai != null) { 5540 finalList.add(ai); 5541 } 5542 } 5543 } 5544 } 5545 } 5546 5547 return finalList; 5548 } 5549 5550 @Override 5551 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5552 if (!sUserManager.exists(userId)) return null; 5553 flags = augmentFlagsForUser(flags, userId); 5554 // reader 5555 synchronized (mPackages) { 5556 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5557 PackageSetting ps = provider != null 5558 ? mSettings.mPackages.get(provider.owner.packageName) 5559 : null; 5560 return ps != null 5561 && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId) 5562 && (!mSafeMode || (provider.info.applicationInfo.flags 5563 &ApplicationInfo.FLAG_SYSTEM) != 0) 5564 ? PackageParser.generateProviderInfo(provider, flags, 5565 ps.readUserState(userId), userId) 5566 : null; 5567 } 5568 } 5569 5570 /** 5571 * @deprecated 5572 */ 5573 @Deprecated 5574 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5575 // reader 5576 synchronized (mPackages) { 5577 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5578 .entrySet().iterator(); 5579 final int userId = UserHandle.getCallingUserId(); 5580 while (i.hasNext()) { 5581 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5582 PackageParser.Provider p = entry.getValue(); 5583 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5584 5585 if (ps != null && p.syncable 5586 && (!mSafeMode || (p.info.applicationInfo.flags 5587 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5588 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5589 ps.readUserState(userId), userId); 5590 if (info != null) { 5591 outNames.add(entry.getKey()); 5592 outInfo.add(info); 5593 } 5594 } 5595 } 5596 } 5597 } 5598 5599 @Override 5600 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5601 int uid, int flags) { 5602 final int userId = processName != null ? UserHandle.getUserId(uid) 5603 : UserHandle.getCallingUserId(); 5604 if (!sUserManager.exists(userId)) return null; 5605 flags = augmentFlagsForUser(flags, userId); 5606 5607 ArrayList<ProviderInfo> finalList = null; 5608 // reader 5609 synchronized (mPackages) { 5610 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5611 while (i.hasNext()) { 5612 final PackageParser.Provider p = i.next(); 5613 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5614 if (ps != null && p.info.authority != null 5615 && (processName == null 5616 || (p.info.processName.equals(processName) 5617 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5618 && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId) 5619 && (!mSafeMode 5620 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5621 if (finalList == null) { 5622 finalList = new ArrayList<ProviderInfo>(3); 5623 } 5624 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5625 ps.readUserState(userId), userId); 5626 if (info != null) { 5627 finalList.add(info); 5628 } 5629 } 5630 } 5631 } 5632 5633 if (finalList != null) { 5634 Collections.sort(finalList, mProviderInitOrderSorter); 5635 return new ParceledListSlice<ProviderInfo>(finalList); 5636 } 5637 5638 return null; 5639 } 5640 5641 @Override 5642 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5643 int flags) { 5644 // reader 5645 synchronized (mPackages) { 5646 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5647 return PackageParser.generateInstrumentationInfo(i, flags); 5648 } 5649 } 5650 5651 @Override 5652 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5653 int flags) { 5654 ArrayList<InstrumentationInfo> finalList = 5655 new ArrayList<InstrumentationInfo>(); 5656 5657 // reader 5658 synchronized (mPackages) { 5659 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5660 while (i.hasNext()) { 5661 final PackageParser.Instrumentation p = i.next(); 5662 if (targetPackage == null 5663 || targetPackage.equals(p.info.targetPackage)) { 5664 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5665 flags); 5666 if (ii != null) { 5667 finalList.add(ii); 5668 } 5669 } 5670 } 5671 } 5672 5673 return finalList; 5674 } 5675 5676 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5677 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5678 if (overlays == null) { 5679 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5680 return; 5681 } 5682 for (PackageParser.Package opkg : overlays.values()) { 5683 // Not much to do if idmap fails: we already logged the error 5684 // and we certainly don't want to abort installation of pkg simply 5685 // because an overlay didn't fit properly. For these reasons, 5686 // ignore the return value of createIdmapForPackagePairLI. 5687 createIdmapForPackagePairLI(pkg, opkg); 5688 } 5689 } 5690 5691 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5692 PackageParser.Package opkg) { 5693 if (!opkg.mTrustedOverlay) { 5694 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5695 opkg.baseCodePath + ": overlay not trusted"); 5696 return false; 5697 } 5698 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5699 if (overlaySet == null) { 5700 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5701 opkg.baseCodePath + " but target package has no known overlays"); 5702 return false; 5703 } 5704 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5705 // TODO: generate idmap for split APKs 5706 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5707 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5708 + opkg.baseCodePath); 5709 return false; 5710 } 5711 PackageParser.Package[] overlayArray = 5712 overlaySet.values().toArray(new PackageParser.Package[0]); 5713 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5714 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5715 return p1.mOverlayPriority - p2.mOverlayPriority; 5716 } 5717 }; 5718 Arrays.sort(overlayArray, cmp); 5719 5720 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5721 int i = 0; 5722 for (PackageParser.Package p : overlayArray) { 5723 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5724 } 5725 return true; 5726 } 5727 5728 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5729 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5730 try { 5731 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5732 } finally { 5733 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5734 } 5735 } 5736 5737 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5738 final File[] files = dir.listFiles(); 5739 if (ArrayUtils.isEmpty(files)) { 5740 Log.d(TAG, "No files in app dir " + dir); 5741 return; 5742 } 5743 5744 if (DEBUG_PACKAGE_SCANNING) { 5745 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5746 + " flags=0x" + Integer.toHexString(parseFlags)); 5747 } 5748 5749 for (File file : files) { 5750 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5751 && !PackageInstallerService.isStageName(file.getName()); 5752 if (!isPackage) { 5753 // Ignore entries which are not packages 5754 continue; 5755 } 5756 try { 5757 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5758 scanFlags, currentTime, null); 5759 } catch (PackageManagerException e) { 5760 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5761 5762 // Delete invalid userdata apps 5763 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5764 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5765 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5766 if (file.isDirectory()) { 5767 mInstaller.rmPackageDir(file.getAbsolutePath()); 5768 } else { 5769 file.delete(); 5770 } 5771 } 5772 } 5773 } 5774 } 5775 5776 private static File getSettingsProblemFile() { 5777 File dataDir = Environment.getDataDirectory(); 5778 File systemDir = new File(dataDir, "system"); 5779 File fname = new File(systemDir, "uiderrors.txt"); 5780 return fname; 5781 } 5782 5783 static void reportSettingsProblem(int priority, String msg) { 5784 logCriticalInfo(priority, msg); 5785 } 5786 5787 static void logCriticalInfo(int priority, String msg) { 5788 Slog.println(priority, TAG, msg); 5789 EventLogTags.writePmCriticalInfo(msg); 5790 try { 5791 File fname = getSettingsProblemFile(); 5792 FileOutputStream out = new FileOutputStream(fname, true); 5793 PrintWriter pw = new FastPrintWriter(out); 5794 SimpleDateFormat formatter = new SimpleDateFormat(); 5795 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5796 pw.println(dateString + ": " + msg); 5797 pw.close(); 5798 FileUtils.setPermissions( 5799 fname.toString(), 5800 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5801 -1, -1); 5802 } catch (java.io.IOException e) { 5803 } 5804 } 5805 5806 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5807 PackageParser.Package pkg, File srcFile, int parseFlags) 5808 throws PackageManagerException { 5809 if (ps != null 5810 && ps.codePath.equals(srcFile) 5811 && ps.timeStamp == srcFile.lastModified() 5812 && !isCompatSignatureUpdateNeeded(pkg) 5813 && !isRecoverSignatureUpdateNeeded(pkg)) { 5814 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5815 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5816 ArraySet<PublicKey> signingKs; 5817 synchronized (mPackages) { 5818 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5819 } 5820 if (ps.signatures.mSignatures != null 5821 && ps.signatures.mSignatures.length != 0 5822 && signingKs != null) { 5823 // Optimization: reuse the existing cached certificates 5824 // if the package appears to be unchanged. 5825 pkg.mSignatures = ps.signatures.mSignatures; 5826 pkg.mSigningKeys = signingKs; 5827 return; 5828 } 5829 5830 Slog.w(TAG, "PackageSetting for " + ps.name 5831 + " is missing signatures. Collecting certs again to recover them."); 5832 } else { 5833 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5834 } 5835 5836 try { 5837 pp.collectCertificates(pkg, parseFlags); 5838 pp.collectManifestDigest(pkg); 5839 } catch (PackageParserException e) { 5840 throw PackageManagerException.from(e); 5841 } 5842 } 5843 5844 /** 5845 * Traces a package scan. 5846 * @see #scanPackageLI(File, int, int, long, UserHandle) 5847 */ 5848 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5849 long currentTime, UserHandle user) throws PackageManagerException { 5850 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5851 try { 5852 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5853 } finally { 5854 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5855 } 5856 } 5857 5858 /** 5859 * Scans a package and returns the newly parsed package. 5860 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5861 */ 5862 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5863 long currentTime, UserHandle user) throws PackageManagerException { 5864 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5865 parseFlags |= mDefParseFlags; 5866 PackageParser pp = new PackageParser(); 5867 pp.setSeparateProcesses(mSeparateProcesses); 5868 pp.setOnlyCoreApps(mOnlyCore); 5869 pp.setDisplayMetrics(mMetrics); 5870 5871 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5872 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5873 } 5874 5875 final PackageParser.Package pkg; 5876 try { 5877 pkg = pp.parsePackage(scanFile, parseFlags); 5878 } catch (PackageParserException e) { 5879 throw PackageManagerException.from(e); 5880 } 5881 5882 PackageSetting ps = null; 5883 PackageSetting updatedPkg; 5884 // reader 5885 synchronized (mPackages) { 5886 // Look to see if we already know about this package. 5887 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5888 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5889 // This package has been renamed to its original name. Let's 5890 // use that. 5891 ps = mSettings.peekPackageLPr(oldName); 5892 } 5893 // If there was no original package, see one for the real package name. 5894 if (ps == null) { 5895 ps = mSettings.peekPackageLPr(pkg.packageName); 5896 } 5897 // Check to see if this package could be hiding/updating a system 5898 // package. Must look for it either under the original or real 5899 // package name depending on our state. 5900 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5901 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5902 } 5903 boolean updatedPkgBetter = false; 5904 // First check if this is a system package that may involve an update 5905 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5906 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5907 // it needs to drop FLAG_PRIVILEGED. 5908 if (locationIsPrivileged(scanFile)) { 5909 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5910 } else { 5911 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5912 } 5913 5914 if (ps != null && !ps.codePath.equals(scanFile)) { 5915 // The path has changed from what was last scanned... check the 5916 // version of the new path against what we have stored to determine 5917 // what to do. 5918 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5919 if (pkg.mVersionCode <= ps.versionCode) { 5920 // The system package has been updated and the code path does not match 5921 // Ignore entry. Skip it. 5922 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5923 + " ignored: updated version " + ps.versionCode 5924 + " better than this " + pkg.mVersionCode); 5925 if (!updatedPkg.codePath.equals(scanFile)) { 5926 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5927 + ps.name + " changing from " + updatedPkg.codePathString 5928 + " to " + scanFile); 5929 updatedPkg.codePath = scanFile; 5930 updatedPkg.codePathString = scanFile.toString(); 5931 updatedPkg.resourcePath = scanFile; 5932 updatedPkg.resourcePathString = scanFile.toString(); 5933 } 5934 updatedPkg.pkg = pkg; 5935 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5936 "Package " + ps.name + " at " + scanFile 5937 + " ignored: updated version " + ps.versionCode 5938 + " better than this " + pkg.mVersionCode); 5939 } else { 5940 // The current app on the system partition is better than 5941 // what we have updated to on the data partition; switch 5942 // back to the system partition version. 5943 // At this point, its safely assumed that package installation for 5944 // apps in system partition will go through. If not there won't be a working 5945 // version of the app 5946 // writer 5947 synchronized (mPackages) { 5948 // Just remove the loaded entries from package lists. 5949 mPackages.remove(ps.name); 5950 } 5951 5952 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5953 + " reverting from " + ps.codePathString 5954 + ": new version " + pkg.mVersionCode 5955 + " better than installed " + ps.versionCode); 5956 5957 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5958 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5959 synchronized (mInstallLock) { 5960 args.cleanUpResourcesLI(); 5961 } 5962 synchronized (mPackages) { 5963 mSettings.enableSystemPackageLPw(ps.name); 5964 } 5965 updatedPkgBetter = true; 5966 } 5967 } 5968 } 5969 5970 if (updatedPkg != null) { 5971 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5972 // initially 5973 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5974 5975 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5976 // flag set initially 5977 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5978 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5979 } 5980 } 5981 5982 // Verify certificates against what was last scanned 5983 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5984 5985 /* 5986 * A new system app appeared, but we already had a non-system one of the 5987 * same name installed earlier. 5988 */ 5989 boolean shouldHideSystemApp = false; 5990 if (updatedPkg == null && ps != null 5991 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5992 /* 5993 * Check to make sure the signatures match first. If they don't, 5994 * wipe the installed application and its data. 5995 */ 5996 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5997 != PackageManager.SIGNATURE_MATCH) { 5998 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5999 + " signatures don't match existing userdata copy; removing"); 6000 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6001 ps = null; 6002 } else { 6003 /* 6004 * If the newly-added system app is an older version than the 6005 * already installed version, hide it. It will be scanned later 6006 * and re-added like an update. 6007 */ 6008 if (pkg.mVersionCode <= ps.versionCode) { 6009 shouldHideSystemApp = true; 6010 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6011 + " but new version " + pkg.mVersionCode + " better than installed " 6012 + ps.versionCode + "; hiding system"); 6013 } else { 6014 /* 6015 * The newly found system app is a newer version that the 6016 * one previously installed. Simply remove the 6017 * already-installed application and replace it with our own 6018 * while keeping the application data. 6019 */ 6020 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6021 + " reverting from " + ps.codePathString + ": new version " 6022 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6023 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6024 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6025 synchronized (mInstallLock) { 6026 args.cleanUpResourcesLI(); 6027 } 6028 } 6029 } 6030 } 6031 6032 // The apk is forward locked (not public) if its code and resources 6033 // are kept in different files. (except for app in either system or 6034 // vendor path). 6035 // TODO grab this value from PackageSettings 6036 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6037 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6038 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6039 } 6040 } 6041 6042 // TODO: extend to support forward-locked splits 6043 String resourcePath = null; 6044 String baseResourcePath = null; 6045 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6046 if (ps != null && ps.resourcePathString != null) { 6047 resourcePath = ps.resourcePathString; 6048 baseResourcePath = ps.resourcePathString; 6049 } else { 6050 // Should not happen at all. Just log an error. 6051 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6052 } 6053 } else { 6054 resourcePath = pkg.codePath; 6055 baseResourcePath = pkg.baseCodePath; 6056 } 6057 6058 // Set application objects path explicitly. 6059 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6060 pkg.applicationInfo.setCodePath(pkg.codePath); 6061 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6062 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6063 pkg.applicationInfo.setResourcePath(resourcePath); 6064 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6065 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6066 6067 // Note that we invoke the following method only if we are about to unpack an application 6068 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6069 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6070 6071 /* 6072 * If the system app should be overridden by a previously installed 6073 * data, hide the system app now and let the /data/app scan pick it up 6074 * again. 6075 */ 6076 if (shouldHideSystemApp) { 6077 synchronized (mPackages) { 6078 mSettings.disableSystemPackageLPw(pkg.packageName); 6079 } 6080 } 6081 6082 return scannedPkg; 6083 } 6084 6085 private static String fixProcessName(String defProcessName, 6086 String processName, int uid) { 6087 if (processName == null) { 6088 return defProcessName; 6089 } 6090 return processName; 6091 } 6092 6093 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6094 throws PackageManagerException { 6095 if (pkgSetting.signatures.mSignatures != null) { 6096 // Already existing package. Make sure signatures match 6097 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6098 == PackageManager.SIGNATURE_MATCH; 6099 if (!match) { 6100 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6101 == PackageManager.SIGNATURE_MATCH; 6102 } 6103 if (!match) { 6104 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6105 == PackageManager.SIGNATURE_MATCH; 6106 } 6107 if (!match) { 6108 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6109 + pkg.packageName + " signatures do not match the " 6110 + "previously installed version; ignoring!"); 6111 } 6112 } 6113 6114 // Check for shared user signatures 6115 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6116 // Already existing package. Make sure signatures match 6117 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6118 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6119 if (!match) { 6120 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6121 == PackageManager.SIGNATURE_MATCH; 6122 } 6123 if (!match) { 6124 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6125 == PackageManager.SIGNATURE_MATCH; 6126 } 6127 if (!match) { 6128 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6129 "Package " + pkg.packageName 6130 + " has no signatures that match those in shared user " 6131 + pkgSetting.sharedUser.name + "; ignoring!"); 6132 } 6133 } 6134 } 6135 6136 /** 6137 * Enforces that only the system UID or root's UID can call a method exposed 6138 * via Binder. 6139 * 6140 * @param message used as message if SecurityException is thrown 6141 * @throws SecurityException if the caller is not system or root 6142 */ 6143 private static final void enforceSystemOrRoot(String message) { 6144 final int uid = Binder.getCallingUid(); 6145 if (uid != Process.SYSTEM_UID && uid != 0) { 6146 throw new SecurityException(message); 6147 } 6148 } 6149 6150 @Override 6151 public void performBootDexOpt() { 6152 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6153 6154 // Before everything else, see whether we need to fstrim. 6155 try { 6156 IMountService ms = PackageHelper.getMountService(); 6157 if (ms != null) { 6158 final boolean isUpgrade = isUpgrade(); 6159 boolean doTrim = isUpgrade; 6160 if (doTrim) { 6161 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6162 } else { 6163 final long interval = android.provider.Settings.Global.getLong( 6164 mContext.getContentResolver(), 6165 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6166 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6167 if (interval > 0) { 6168 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6169 if (timeSinceLast > interval) { 6170 doTrim = true; 6171 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6172 + "; running immediately"); 6173 } 6174 } 6175 } 6176 if (doTrim) { 6177 if (!isFirstBoot()) { 6178 try { 6179 ActivityManagerNative.getDefault().showBootMessage( 6180 mContext.getResources().getString( 6181 R.string.android_upgrading_fstrim), true); 6182 } catch (RemoteException e) { 6183 } 6184 } 6185 ms.runMaintenance(); 6186 } 6187 } else { 6188 Slog.e(TAG, "Mount service unavailable!"); 6189 } 6190 } catch (RemoteException e) { 6191 // Can't happen; MountService is local 6192 } 6193 6194 final ArraySet<PackageParser.Package> pkgs; 6195 synchronized (mPackages) { 6196 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6197 } 6198 6199 if (pkgs != null) { 6200 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6201 // in case the device runs out of space. 6202 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6203 // Give priority to core apps. 6204 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6205 PackageParser.Package pkg = it.next(); 6206 if (pkg.coreApp) { 6207 if (DEBUG_DEXOPT) { 6208 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6209 } 6210 sortedPkgs.add(pkg); 6211 it.remove(); 6212 } 6213 } 6214 // Give priority to system apps that listen for pre boot complete. 6215 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6216 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6217 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6218 PackageParser.Package pkg = it.next(); 6219 if (pkgNames.contains(pkg.packageName)) { 6220 if (DEBUG_DEXOPT) { 6221 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6222 } 6223 sortedPkgs.add(pkg); 6224 it.remove(); 6225 } 6226 } 6227 // Filter out packages that aren't recently used. 6228 filterRecentlyUsedApps(pkgs); 6229 // Add all remaining apps. 6230 for (PackageParser.Package pkg : pkgs) { 6231 if (DEBUG_DEXOPT) { 6232 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6233 } 6234 sortedPkgs.add(pkg); 6235 } 6236 6237 // If we want to be lazy, filter everything that wasn't recently used. 6238 if (mLazyDexOpt) { 6239 filterRecentlyUsedApps(sortedPkgs); 6240 } 6241 6242 int i = 0; 6243 int total = sortedPkgs.size(); 6244 File dataDir = Environment.getDataDirectory(); 6245 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6246 if (lowThreshold == 0) { 6247 throw new IllegalStateException("Invalid low memory threshold"); 6248 } 6249 for (PackageParser.Package pkg : sortedPkgs) { 6250 long usableSpace = dataDir.getUsableSpace(); 6251 if (usableSpace < lowThreshold) { 6252 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6253 break; 6254 } 6255 performBootDexOpt(pkg, ++i, total); 6256 } 6257 } 6258 } 6259 6260 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6261 // Filter out packages that aren't recently used. 6262 // 6263 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6264 // should do a full dexopt. 6265 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6266 int total = pkgs.size(); 6267 int skipped = 0; 6268 long now = System.currentTimeMillis(); 6269 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6270 PackageParser.Package pkg = i.next(); 6271 long then = pkg.mLastPackageUsageTimeInMills; 6272 if (then + mDexOptLRUThresholdInMills < now) { 6273 if (DEBUG_DEXOPT) { 6274 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6275 ((then == 0) ? "never" : new Date(then))); 6276 } 6277 i.remove(); 6278 skipped++; 6279 } 6280 } 6281 if (DEBUG_DEXOPT) { 6282 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6283 } 6284 } 6285 } 6286 6287 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6288 List<ResolveInfo> ris = null; 6289 try { 6290 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6291 intent, null, 0, userId); 6292 } catch (RemoteException e) { 6293 } 6294 ArraySet<String> pkgNames = new ArraySet<String>(); 6295 if (ris != null) { 6296 for (ResolveInfo ri : ris) { 6297 pkgNames.add(ri.activityInfo.packageName); 6298 } 6299 } 6300 return pkgNames; 6301 } 6302 6303 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6304 if (DEBUG_DEXOPT) { 6305 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6306 } 6307 if (!isFirstBoot()) { 6308 try { 6309 ActivityManagerNative.getDefault().showBootMessage( 6310 mContext.getResources().getString(R.string.android_upgrading_apk, 6311 curr, total), true); 6312 } catch (RemoteException e) { 6313 } 6314 } 6315 PackageParser.Package p = pkg; 6316 synchronized (mInstallLock) { 6317 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6318 false /* force dex */, false /* defer */, true /* include dependencies */, 6319 false /* boot complete */, false /*useJit*/); 6320 } 6321 } 6322 6323 @Override 6324 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6325 return performDexOptTraced(packageName, instructionSet, false); 6326 } 6327 6328 public boolean performDexOpt( 6329 String packageName, String instructionSet, boolean backgroundDexopt) { 6330 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6331 } 6332 6333 private boolean performDexOptTraced( 6334 String packageName, String instructionSet, boolean backgroundDexopt) { 6335 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6336 try { 6337 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6338 } finally { 6339 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6340 } 6341 } 6342 6343 private boolean performDexOptInternal( 6344 String packageName, String instructionSet, boolean backgroundDexopt) { 6345 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6346 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6347 if (!dexopt && !updateUsage) { 6348 // We aren't going to dexopt or update usage, so bail early. 6349 return false; 6350 } 6351 PackageParser.Package p; 6352 final String targetInstructionSet; 6353 synchronized (mPackages) { 6354 p = mPackages.get(packageName); 6355 if (p == null) { 6356 return false; 6357 } 6358 if (updateUsage) { 6359 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6360 } 6361 mPackageUsage.write(false); 6362 if (!dexopt) { 6363 // We aren't going to dexopt, so bail early. 6364 return false; 6365 } 6366 6367 targetInstructionSet = instructionSet != null ? instructionSet : 6368 getPrimaryInstructionSet(p.applicationInfo); 6369 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6370 return false; 6371 } 6372 } 6373 long callingId = Binder.clearCallingIdentity(); 6374 try { 6375 synchronized (mInstallLock) { 6376 final String[] instructionSets = new String[] { targetInstructionSet }; 6377 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6378 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6379 true /* boot complete */, false /*useJit*/); 6380 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6381 } 6382 } finally { 6383 Binder.restoreCallingIdentity(callingId); 6384 } 6385 } 6386 6387 public ArraySet<String> getPackagesThatNeedDexOpt() { 6388 ArraySet<String> pkgs = null; 6389 synchronized (mPackages) { 6390 for (PackageParser.Package p : mPackages.values()) { 6391 if (DEBUG_DEXOPT) { 6392 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6393 } 6394 if (!p.mDexOptPerformed.isEmpty()) { 6395 continue; 6396 } 6397 if (pkgs == null) { 6398 pkgs = new ArraySet<String>(); 6399 } 6400 pkgs.add(p.packageName); 6401 } 6402 } 6403 return pkgs; 6404 } 6405 6406 public void shutdown() { 6407 mPackageUsage.write(true); 6408 } 6409 6410 @Override 6411 public void forceDexOpt(String packageName) { 6412 enforceSystemOrRoot("forceDexOpt"); 6413 6414 PackageParser.Package pkg; 6415 synchronized (mPackages) { 6416 pkg = mPackages.get(packageName); 6417 if (pkg == null) { 6418 throw new IllegalArgumentException("Missing package: " + packageName); 6419 } 6420 } 6421 6422 synchronized (mInstallLock) { 6423 final String[] instructionSets = new String[] { 6424 getPrimaryInstructionSet(pkg.applicationInfo) }; 6425 6426 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6427 6428 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6429 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6430 true /* boot complete */, false /*useJit*/); 6431 6432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6433 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6434 throw new IllegalStateException("Failed to dexopt: " + res); 6435 } 6436 } 6437 } 6438 6439 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6440 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6441 Slog.w(TAG, "Unable to update from " + oldPkg.name 6442 + " to " + newPkg.packageName 6443 + ": old package not in system partition"); 6444 return false; 6445 } else if (mPackages.get(oldPkg.name) != null) { 6446 Slog.w(TAG, "Unable to update from " + oldPkg.name 6447 + " to " + newPkg.packageName 6448 + ": old package still exists"); 6449 return false; 6450 } 6451 return true; 6452 } 6453 6454 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6455 int[] users = sUserManager.getUserIds(); 6456 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6457 if (res < 0) { 6458 return res; 6459 } 6460 for (int user : users) { 6461 if (user != 0) { 6462 res = mInstaller.createUserData(volumeUuid, packageName, 6463 UserHandle.getUid(user, uid), user, seinfo); 6464 if (res < 0) { 6465 return res; 6466 } 6467 } 6468 } 6469 return res; 6470 } 6471 6472 private int removeDataDirsLI(String volumeUuid, String packageName) { 6473 int[] users = sUserManager.getUserIds(); 6474 int res = 0; 6475 for (int user : users) { 6476 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6477 if (resInner < 0) { 6478 res = resInner; 6479 } 6480 } 6481 6482 return res; 6483 } 6484 6485 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6486 int[] users = sUserManager.getUserIds(); 6487 int res = 0; 6488 for (int user : users) { 6489 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6490 if (resInner < 0) { 6491 res = resInner; 6492 } 6493 } 6494 return res; 6495 } 6496 6497 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6498 PackageParser.Package changingLib) { 6499 if (file.path != null) { 6500 usesLibraryFiles.add(file.path); 6501 return; 6502 } 6503 PackageParser.Package p = mPackages.get(file.apk); 6504 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6505 // If we are doing this while in the middle of updating a library apk, 6506 // then we need to make sure to use that new apk for determining the 6507 // dependencies here. (We haven't yet finished committing the new apk 6508 // to the package manager state.) 6509 if (p == null || p.packageName.equals(changingLib.packageName)) { 6510 p = changingLib; 6511 } 6512 } 6513 if (p != null) { 6514 usesLibraryFiles.addAll(p.getAllCodePaths()); 6515 } 6516 } 6517 6518 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6519 PackageParser.Package changingLib) throws PackageManagerException { 6520 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6521 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6522 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6523 for (int i=0; i<N; i++) { 6524 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6525 if (file == null) { 6526 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6527 "Package " + pkg.packageName + " requires unavailable shared library " 6528 + pkg.usesLibraries.get(i) + "; failing!"); 6529 } 6530 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6531 } 6532 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6533 for (int i=0; i<N; i++) { 6534 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6535 if (file == null) { 6536 Slog.w(TAG, "Package " + pkg.packageName 6537 + " desires unavailable shared library " 6538 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6539 } else { 6540 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6541 } 6542 } 6543 N = usesLibraryFiles.size(); 6544 if (N > 0) { 6545 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6546 } else { 6547 pkg.usesLibraryFiles = null; 6548 } 6549 } 6550 } 6551 6552 private static boolean hasString(List<String> list, List<String> which) { 6553 if (list == null) { 6554 return false; 6555 } 6556 for (int i=list.size()-1; i>=0; i--) { 6557 for (int j=which.size()-1; j>=0; j--) { 6558 if (which.get(j).equals(list.get(i))) { 6559 return true; 6560 } 6561 } 6562 } 6563 return false; 6564 } 6565 6566 private void updateAllSharedLibrariesLPw() { 6567 for (PackageParser.Package pkg : mPackages.values()) { 6568 try { 6569 updateSharedLibrariesLPw(pkg, null); 6570 } catch (PackageManagerException e) { 6571 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6572 } 6573 } 6574 } 6575 6576 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6577 PackageParser.Package changingPkg) { 6578 ArrayList<PackageParser.Package> res = null; 6579 for (PackageParser.Package pkg : mPackages.values()) { 6580 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6581 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6582 if (res == null) { 6583 res = new ArrayList<PackageParser.Package>(); 6584 } 6585 res.add(pkg); 6586 try { 6587 updateSharedLibrariesLPw(pkg, changingPkg); 6588 } catch (PackageManagerException e) { 6589 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6590 } 6591 } 6592 } 6593 return res; 6594 } 6595 6596 /** 6597 * Derive the value of the {@code cpuAbiOverride} based on the provided 6598 * value and an optional stored value from the package settings. 6599 */ 6600 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6601 String cpuAbiOverride = null; 6602 6603 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6604 cpuAbiOverride = null; 6605 } else if (abiOverride != null) { 6606 cpuAbiOverride = abiOverride; 6607 } else if (settings != null) { 6608 cpuAbiOverride = settings.cpuAbiOverrideString; 6609 } 6610 6611 return cpuAbiOverride; 6612 } 6613 6614 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6615 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6616 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6617 try { 6618 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6619 } finally { 6620 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6621 } 6622 } 6623 6624 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6625 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6626 boolean success = false; 6627 try { 6628 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6629 currentTime, user); 6630 success = true; 6631 return res; 6632 } finally { 6633 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6634 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6635 } 6636 } 6637 } 6638 6639 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6640 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6641 final File scanFile = new File(pkg.codePath); 6642 if (pkg.applicationInfo.getCodePath() == null || 6643 pkg.applicationInfo.getResourcePath() == null) { 6644 // Bail out. The resource and code paths haven't been set. 6645 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6646 "Code and resource paths haven't been set correctly"); 6647 } 6648 6649 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6650 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6651 } else { 6652 // Only allow system apps to be flagged as core apps. 6653 pkg.coreApp = false; 6654 } 6655 6656 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6657 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6658 } 6659 6660 if (mCustomResolverComponentName != null && 6661 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6662 setUpCustomResolverActivity(pkg); 6663 } 6664 6665 if (pkg.packageName.equals("android")) { 6666 synchronized (mPackages) { 6667 if (mAndroidApplication != null) { 6668 Slog.w(TAG, "*************************************************"); 6669 Slog.w(TAG, "Core android package being redefined. Skipping."); 6670 Slog.w(TAG, " file=" + scanFile); 6671 Slog.w(TAG, "*************************************************"); 6672 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6673 "Core android package being redefined. Skipping."); 6674 } 6675 6676 // Set up information for our fall-back user intent resolution activity. 6677 mPlatformPackage = pkg; 6678 pkg.mVersionCode = mSdkVersion; 6679 mAndroidApplication = pkg.applicationInfo; 6680 6681 if (!mResolverReplaced) { 6682 mResolveActivity.applicationInfo = mAndroidApplication; 6683 mResolveActivity.name = ResolverActivity.class.getName(); 6684 mResolveActivity.packageName = mAndroidApplication.packageName; 6685 mResolveActivity.processName = "system:ui"; 6686 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6687 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6688 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6689 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6690 mResolveActivity.exported = true; 6691 mResolveActivity.enabled = true; 6692 mResolveInfo.activityInfo = mResolveActivity; 6693 mResolveInfo.priority = 0; 6694 mResolveInfo.preferredOrder = 0; 6695 mResolveInfo.match = 0; 6696 mResolveComponentName = new ComponentName( 6697 mAndroidApplication.packageName, mResolveActivity.name); 6698 } 6699 } 6700 } 6701 6702 if (DEBUG_PACKAGE_SCANNING) { 6703 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6704 Log.d(TAG, "Scanning package " + pkg.packageName); 6705 } 6706 6707 if (mPackages.containsKey(pkg.packageName) 6708 || mSharedLibraries.containsKey(pkg.packageName)) { 6709 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6710 "Application package " + pkg.packageName 6711 + " already installed. Skipping duplicate."); 6712 } 6713 6714 // If we're only installing presumed-existing packages, require that the 6715 // scanned APK is both already known and at the path previously established 6716 // for it. Previously unknown packages we pick up normally, but if we have an 6717 // a priori expectation about this package's install presence, enforce it. 6718 // With a singular exception for new system packages. When an OTA contains 6719 // a new system package, we allow the codepath to change from a system location 6720 // to the user-installed location. If we don't allow this change, any newer, 6721 // user-installed version of the application will be ignored. 6722 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6723 if (mExpectingBetter.containsKey(pkg.packageName)) { 6724 logCriticalInfo(Log.WARN, 6725 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6726 } else { 6727 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6728 if (known != null) { 6729 if (DEBUG_PACKAGE_SCANNING) { 6730 Log.d(TAG, "Examining " + pkg.codePath 6731 + " and requiring known paths " + known.codePathString 6732 + " & " + known.resourcePathString); 6733 } 6734 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6735 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6736 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6737 "Application package " + pkg.packageName 6738 + " found at " + pkg.applicationInfo.getCodePath() 6739 + " but expected at " + known.codePathString + "; ignoring."); 6740 } 6741 } 6742 } 6743 } 6744 6745 // Initialize package source and resource directories 6746 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6747 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6748 6749 SharedUserSetting suid = null; 6750 PackageSetting pkgSetting = null; 6751 6752 if (!isSystemApp(pkg)) { 6753 // Only system apps can use these features. 6754 pkg.mOriginalPackages = null; 6755 pkg.mRealPackage = null; 6756 pkg.mAdoptPermissions = null; 6757 } 6758 6759 // writer 6760 synchronized (mPackages) { 6761 if (pkg.mSharedUserId != null) { 6762 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6763 if (suid == null) { 6764 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6765 "Creating application package " + pkg.packageName 6766 + " for shared user failed"); 6767 } 6768 if (DEBUG_PACKAGE_SCANNING) { 6769 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6770 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6771 + "): packages=" + suid.packages); 6772 } 6773 } 6774 6775 // Check if we are renaming from an original package name. 6776 PackageSetting origPackage = null; 6777 String realName = null; 6778 if (pkg.mOriginalPackages != null) { 6779 // This package may need to be renamed to a previously 6780 // installed name. Let's check on that... 6781 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6782 if (pkg.mOriginalPackages.contains(renamed)) { 6783 // This package had originally been installed as the 6784 // original name, and we have already taken care of 6785 // transitioning to the new one. Just update the new 6786 // one to continue using the old name. 6787 realName = pkg.mRealPackage; 6788 if (!pkg.packageName.equals(renamed)) { 6789 // Callers into this function may have already taken 6790 // care of renaming the package; only do it here if 6791 // it is not already done. 6792 pkg.setPackageName(renamed); 6793 } 6794 6795 } else { 6796 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6797 if ((origPackage = mSettings.peekPackageLPr( 6798 pkg.mOriginalPackages.get(i))) != null) { 6799 // We do have the package already installed under its 6800 // original name... should we use it? 6801 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6802 // New package is not compatible with original. 6803 origPackage = null; 6804 continue; 6805 } else if (origPackage.sharedUser != null) { 6806 // Make sure uid is compatible between packages. 6807 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6808 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6809 + " to " + pkg.packageName + ": old uid " 6810 + origPackage.sharedUser.name 6811 + " differs from " + pkg.mSharedUserId); 6812 origPackage = null; 6813 continue; 6814 } 6815 } else { 6816 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6817 + pkg.packageName + " to old name " + origPackage.name); 6818 } 6819 break; 6820 } 6821 } 6822 } 6823 } 6824 6825 if (mTransferedPackages.contains(pkg.packageName)) { 6826 Slog.w(TAG, "Package " + pkg.packageName 6827 + " was transferred to another, but its .apk remains"); 6828 } 6829 6830 // Just create the setting, don't add it yet. For already existing packages 6831 // the PkgSetting exists already and doesn't have to be created. 6832 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6833 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6834 pkg.applicationInfo.primaryCpuAbi, 6835 pkg.applicationInfo.secondaryCpuAbi, 6836 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6837 user, false); 6838 if (pkgSetting == null) { 6839 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6840 "Creating application package " + pkg.packageName + " failed"); 6841 } 6842 6843 if (pkgSetting.origPackage != null) { 6844 // If we are first transitioning from an original package, 6845 // fix up the new package's name now. We need to do this after 6846 // looking up the package under its new name, so getPackageLP 6847 // can take care of fiddling things correctly. 6848 pkg.setPackageName(origPackage.name); 6849 6850 // File a report about this. 6851 String msg = "New package " + pkgSetting.realName 6852 + " renamed to replace old package " + pkgSetting.name; 6853 reportSettingsProblem(Log.WARN, msg); 6854 6855 // Make a note of it. 6856 mTransferedPackages.add(origPackage.name); 6857 6858 // No longer need to retain this. 6859 pkgSetting.origPackage = null; 6860 } 6861 6862 if (realName != null) { 6863 // Make a note of it. 6864 mTransferedPackages.add(pkg.packageName); 6865 } 6866 6867 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6868 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6869 } 6870 6871 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6872 // Check all shared libraries and map to their actual file path. 6873 // We only do this here for apps not on a system dir, because those 6874 // are the only ones that can fail an install due to this. We 6875 // will take care of the system apps by updating all of their 6876 // library paths after the scan is done. 6877 updateSharedLibrariesLPw(pkg, null); 6878 } 6879 6880 if (mFoundPolicyFile) { 6881 SELinuxMMAC.assignSeinfoValue(pkg); 6882 } 6883 6884 pkg.applicationInfo.uid = pkgSetting.appId; 6885 pkg.mExtras = pkgSetting; 6886 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6887 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6888 // We just determined the app is signed correctly, so bring 6889 // over the latest parsed certs. 6890 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6891 } else { 6892 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6893 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6894 "Package " + pkg.packageName + " upgrade keys do not match the " 6895 + "previously installed version"); 6896 } else { 6897 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6898 String msg = "System package " + pkg.packageName 6899 + " signature changed; retaining data."; 6900 reportSettingsProblem(Log.WARN, msg); 6901 } 6902 } 6903 } else { 6904 try { 6905 verifySignaturesLP(pkgSetting, pkg); 6906 // We just determined the app is signed correctly, so bring 6907 // over the latest parsed certs. 6908 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6909 } catch (PackageManagerException e) { 6910 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6911 throw e; 6912 } 6913 // The signature has changed, but this package is in the system 6914 // image... let's recover! 6915 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6916 // However... if this package is part of a shared user, but it 6917 // doesn't match the signature of the shared user, let's fail. 6918 // What this means is that you can't change the signatures 6919 // associated with an overall shared user, which doesn't seem all 6920 // that unreasonable. 6921 if (pkgSetting.sharedUser != null) { 6922 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6923 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6924 throw new PackageManagerException( 6925 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6926 "Signature mismatch for shared user : " 6927 + pkgSetting.sharedUser); 6928 } 6929 } 6930 // File a report about this. 6931 String msg = "System package " + pkg.packageName 6932 + " signature changed; retaining data."; 6933 reportSettingsProblem(Log.WARN, msg); 6934 } 6935 } 6936 // Verify that this new package doesn't have any content providers 6937 // that conflict with existing packages. Only do this if the 6938 // package isn't already installed, since we don't want to break 6939 // things that are installed. 6940 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6941 final int N = pkg.providers.size(); 6942 int i; 6943 for (i=0; i<N; i++) { 6944 PackageParser.Provider p = pkg.providers.get(i); 6945 if (p.info.authority != null) { 6946 String names[] = p.info.authority.split(";"); 6947 for (int j = 0; j < names.length; j++) { 6948 if (mProvidersByAuthority.containsKey(names[j])) { 6949 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6950 final String otherPackageName = 6951 ((other != null && other.getComponentName() != null) ? 6952 other.getComponentName().getPackageName() : "?"); 6953 throw new PackageManagerException( 6954 INSTALL_FAILED_CONFLICTING_PROVIDER, 6955 "Can't install because provider name " + names[j] 6956 + " (in package " + pkg.applicationInfo.packageName 6957 + ") is already used by " + otherPackageName); 6958 } 6959 } 6960 } 6961 } 6962 } 6963 6964 if (pkg.mAdoptPermissions != null) { 6965 // This package wants to adopt ownership of permissions from 6966 // another package. 6967 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6968 final String origName = pkg.mAdoptPermissions.get(i); 6969 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6970 if (orig != null) { 6971 if (verifyPackageUpdateLPr(orig, pkg)) { 6972 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6973 + pkg.packageName); 6974 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6975 } 6976 } 6977 } 6978 } 6979 } 6980 6981 final String pkgName = pkg.packageName; 6982 6983 final long scanFileTime = scanFile.lastModified(); 6984 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6985 pkg.applicationInfo.processName = fixProcessName( 6986 pkg.applicationInfo.packageName, 6987 pkg.applicationInfo.processName, 6988 pkg.applicationInfo.uid); 6989 6990 if (pkg != mPlatformPackage) { 6991 // This is a normal package, need to make its data directory. 6992 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 6993 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 6994 6995 boolean uidError = false; 6996 if (dataPath.exists()) { 6997 int currentUid = 0; 6998 try { 6999 StructStat stat = Os.stat(dataPath.getPath()); 7000 currentUid = stat.st_uid; 7001 } catch (ErrnoException e) { 7002 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7003 } 7004 7005 // If we have mismatched owners for the data path, we have a problem. 7006 if (currentUid != pkg.applicationInfo.uid) { 7007 boolean recovered = false; 7008 if (currentUid == 0) { 7009 // The directory somehow became owned by root. Wow. 7010 // This is probably because the system was stopped while 7011 // installd was in the middle of messing with its libs 7012 // directory. Ask installd to fix that. 7013 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7014 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7015 if (ret >= 0) { 7016 recovered = true; 7017 String msg = "Package " + pkg.packageName 7018 + " unexpectedly changed to uid 0; recovered to " + 7019 + pkg.applicationInfo.uid; 7020 reportSettingsProblem(Log.WARN, msg); 7021 } 7022 } 7023 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7024 || (scanFlags&SCAN_BOOTING) != 0)) { 7025 // If this is a system app, we can at least delete its 7026 // current data so the application will still work. 7027 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7028 if (ret >= 0) { 7029 // TODO: Kill the processes first 7030 // Old data gone! 7031 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7032 ? "System package " : "Third party package "; 7033 String msg = prefix + pkg.packageName 7034 + " has changed from uid: " 7035 + currentUid + " to " 7036 + pkg.applicationInfo.uid + "; old data erased"; 7037 reportSettingsProblem(Log.WARN, msg); 7038 recovered = true; 7039 7040 // And now re-install the app. 7041 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7042 pkg.applicationInfo.seinfo); 7043 if (ret == -1) { 7044 // Ack should not happen! 7045 msg = prefix + pkg.packageName 7046 + " could not have data directory re-created after delete."; 7047 reportSettingsProblem(Log.WARN, msg); 7048 throw new PackageManagerException( 7049 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 7050 } 7051 } 7052 if (!recovered) { 7053 mHasSystemUidErrors = true; 7054 } 7055 } else if (!recovered) { 7056 // If we allow this install to proceed, we will be broken. 7057 // Abort, abort! 7058 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7059 "scanPackageLI"); 7060 } 7061 if (!recovered) { 7062 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7063 + pkg.applicationInfo.uid + "/fs_" 7064 + currentUid; 7065 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7066 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7067 String msg = "Package " + pkg.packageName 7068 + " has mismatched uid: " 7069 + currentUid + " on disk, " 7070 + pkg.applicationInfo.uid + " in settings"; 7071 // writer 7072 synchronized (mPackages) { 7073 mSettings.mReadMessages.append(msg); 7074 mSettings.mReadMessages.append('\n'); 7075 uidError = true; 7076 if (!pkgSetting.uidError) { 7077 reportSettingsProblem(Log.ERROR, msg); 7078 } 7079 } 7080 } 7081 } 7082 7083 if (mShouldRestoreconData) { 7084 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7085 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7086 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7087 } 7088 } else { 7089 if (DEBUG_PACKAGE_SCANNING) { 7090 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7091 Log.v(TAG, "Want this data dir: " + dataPath); 7092 } 7093 //invoke installer to do the actual installation 7094 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7095 pkg.applicationInfo.seinfo); 7096 if (ret < 0) { 7097 // Error from installer 7098 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7099 "Unable to create data dirs [errorCode=" + ret + "]"); 7100 } 7101 } 7102 7103 // Get all of our default paths setup 7104 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7105 7106 pkgSetting.uidError = uidError; 7107 } 7108 7109 final String path = scanFile.getPath(); 7110 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7111 7112 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7113 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7114 7115 // Some system apps still use directory structure for native libraries 7116 // in which case we might end up not detecting abi solely based on apk 7117 // structure. Try to detect abi based on directory structure. 7118 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7119 pkg.applicationInfo.primaryCpuAbi == null) { 7120 setBundledAppAbisAndRoots(pkg, pkgSetting); 7121 setNativeLibraryPaths(pkg); 7122 } 7123 7124 } else { 7125 if ((scanFlags & SCAN_MOVE) != 0) { 7126 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7127 // but we already have this packages package info in the PackageSetting. We just 7128 // use that and derive the native library path based on the new codepath. 7129 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7130 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7131 } 7132 7133 // Set native library paths again. For moves, the path will be updated based on the 7134 // ABIs we've determined above. For non-moves, the path will be updated based on the 7135 // ABIs we determined during compilation, but the path will depend on the final 7136 // package path (after the rename away from the stage path). 7137 setNativeLibraryPaths(pkg); 7138 } 7139 7140 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7141 final int[] userIds = sUserManager.getUserIds(); 7142 synchronized (mInstallLock) { 7143 // Make sure all user data directories are ready to roll; we're okay 7144 // if they already exist 7145 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7146 for (int userId : userIds) { 7147 if (userId != UserHandle.USER_SYSTEM) { 7148 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7149 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7150 pkg.applicationInfo.seinfo); 7151 } 7152 } 7153 } 7154 7155 // Create a native library symlink only if we have native libraries 7156 // and if the native libraries are 32 bit libraries. We do not provide 7157 // this symlink for 64 bit libraries. 7158 if (pkg.applicationInfo.primaryCpuAbi != null && 7159 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7160 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7161 try { 7162 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7163 for (int userId : userIds) { 7164 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7165 nativeLibPath, userId) < 0) { 7166 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7167 "Failed linking native library dir (user=" + userId + ")"); 7168 } 7169 } 7170 } finally { 7171 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7172 } 7173 } 7174 } 7175 7176 // This is a special case for the "system" package, where the ABI is 7177 // dictated by the zygote configuration (and init.rc). We should keep track 7178 // of this ABI so that we can deal with "normal" applications that run under 7179 // the same UID correctly. 7180 if (mPlatformPackage == pkg) { 7181 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7182 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7183 } 7184 7185 // If there's a mismatch between the abi-override in the package setting 7186 // and the abiOverride specified for the install. Warn about this because we 7187 // would've already compiled the app without taking the package setting into 7188 // account. 7189 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7190 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7191 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7192 " for package: " + pkg.packageName); 7193 } 7194 } 7195 7196 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7197 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7198 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7199 7200 // Copy the derived override back to the parsed package, so that we can 7201 // update the package settings accordingly. 7202 pkg.cpuAbiOverride = cpuAbiOverride; 7203 7204 if (DEBUG_ABI_SELECTION) { 7205 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7206 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7207 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7208 } 7209 7210 // Push the derived path down into PackageSettings so we know what to 7211 // clean up at uninstall time. 7212 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7213 7214 if (DEBUG_ABI_SELECTION) { 7215 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7216 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7217 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7218 } 7219 7220 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7221 // We don't do this here during boot because we can do it all 7222 // at once after scanning all existing packages. 7223 // 7224 // We also do this *before* we perform dexopt on this package, so that 7225 // we can avoid redundant dexopts, and also to make sure we've got the 7226 // code and package path correct. 7227 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7228 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7229 } 7230 7231 if ((scanFlags & SCAN_NO_DEX) == 0) { 7232 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7233 7234 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7235 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7236 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7237 7238 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7239 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7240 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7241 } 7242 } 7243 if (mFactoryTest && pkg.requestedPermissions.contains( 7244 android.Manifest.permission.FACTORY_TEST)) { 7245 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7246 } 7247 7248 ArrayList<PackageParser.Package> clientLibPkgs = null; 7249 7250 // writer 7251 synchronized (mPackages) { 7252 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7253 // Only system apps can add new shared libraries. 7254 if (pkg.libraryNames != null) { 7255 for (int i=0; i<pkg.libraryNames.size(); i++) { 7256 String name = pkg.libraryNames.get(i); 7257 boolean allowed = false; 7258 if (pkg.isUpdatedSystemApp()) { 7259 // New library entries can only be added through the 7260 // system image. This is important to get rid of a lot 7261 // of nasty edge cases: for example if we allowed a non- 7262 // system update of the app to add a library, then uninstalling 7263 // the update would make the library go away, and assumptions 7264 // we made such as through app install filtering would now 7265 // have allowed apps on the device which aren't compatible 7266 // with it. Better to just have the restriction here, be 7267 // conservative, and create many fewer cases that can negatively 7268 // impact the user experience. 7269 final PackageSetting sysPs = mSettings 7270 .getDisabledSystemPkgLPr(pkg.packageName); 7271 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7272 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7273 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7274 allowed = true; 7275 break; 7276 } 7277 } 7278 } 7279 } else { 7280 allowed = true; 7281 } 7282 if (allowed) { 7283 if (!mSharedLibraries.containsKey(name)) { 7284 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7285 } else if (!name.equals(pkg.packageName)) { 7286 Slog.w(TAG, "Package " + pkg.packageName + " library " 7287 + name + " already exists; skipping"); 7288 } 7289 } else { 7290 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7291 + name + " that is not declared on system image; skipping"); 7292 } 7293 } 7294 if ((scanFlags&SCAN_BOOTING) == 0) { 7295 // If we are not booting, we need to update any applications 7296 // that are clients of our shared library. If we are booting, 7297 // this will all be done once the scan is complete. 7298 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7299 } 7300 } 7301 } 7302 } 7303 7304 // We also need to dexopt any apps that are dependent on this library. Note that 7305 // if these fail, we should abort the install since installing the library will 7306 // result in some apps being broken. 7307 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7308 try { 7309 if (clientLibPkgs != null) { 7310 if ((scanFlags & SCAN_NO_DEX) == 0) { 7311 for (int i = 0; i < clientLibPkgs.size(); i++) { 7312 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7313 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7314 null /* instruction sets */, forceDex, 7315 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7316 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7317 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7318 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7319 "scanPackageLI failed to dexopt clientLibPkgs"); 7320 } 7321 } 7322 } 7323 } 7324 } finally { 7325 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7326 } 7327 7328 // Request the ActivityManager to kill the process(only for existing packages) 7329 // so that we do not end up in a confused state while the user is still using the older 7330 // version of the application while the new one gets installed. 7331 if ((scanFlags & SCAN_REPLACING) != 0) { 7332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7333 7334 killApplication(pkg.applicationInfo.packageName, 7335 pkg.applicationInfo.uid, "replace pkg"); 7336 7337 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7338 } 7339 7340 // Also need to kill any apps that are dependent on the library. 7341 if (clientLibPkgs != null) { 7342 for (int i=0; i<clientLibPkgs.size(); i++) { 7343 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7344 killApplication(clientPkg.applicationInfo.packageName, 7345 clientPkg.applicationInfo.uid, "update lib"); 7346 } 7347 } 7348 7349 // Make sure we're not adding any bogus keyset info 7350 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7351 ksms.assertScannedPackageValid(pkg); 7352 7353 // writer 7354 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7355 7356 boolean createIdmapFailed = false; 7357 synchronized (mPackages) { 7358 // We don't expect installation to fail beyond this point 7359 7360 // Add the new setting to mSettings 7361 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7362 // Add the new setting to mPackages 7363 mPackages.put(pkg.applicationInfo.packageName, pkg); 7364 // Make sure we don't accidentally delete its data. 7365 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7366 while (iter.hasNext()) { 7367 PackageCleanItem item = iter.next(); 7368 if (pkgName.equals(item.packageName)) { 7369 iter.remove(); 7370 } 7371 } 7372 7373 // Take care of first install / last update times. 7374 if (currentTime != 0) { 7375 if (pkgSetting.firstInstallTime == 0) { 7376 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7377 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7378 pkgSetting.lastUpdateTime = currentTime; 7379 } 7380 } else if (pkgSetting.firstInstallTime == 0) { 7381 // We need *something*. Take time time stamp of the file. 7382 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7383 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7384 if (scanFileTime != pkgSetting.timeStamp) { 7385 // A package on the system image has changed; consider this 7386 // to be an update. 7387 pkgSetting.lastUpdateTime = scanFileTime; 7388 } 7389 } 7390 7391 // Add the package's KeySets to the global KeySetManagerService 7392 ksms.addScannedPackageLPw(pkg); 7393 7394 int N = pkg.providers.size(); 7395 StringBuilder r = null; 7396 int i; 7397 for (i=0; i<N; i++) { 7398 PackageParser.Provider p = pkg.providers.get(i); 7399 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7400 p.info.processName, pkg.applicationInfo.uid); 7401 mProviders.addProvider(p); 7402 p.syncable = p.info.isSyncable; 7403 if (p.info.authority != null) { 7404 String names[] = p.info.authority.split(";"); 7405 p.info.authority = null; 7406 for (int j = 0; j < names.length; j++) { 7407 if (j == 1 && p.syncable) { 7408 // We only want the first authority for a provider to possibly be 7409 // syncable, so if we already added this provider using a different 7410 // authority clear the syncable flag. We copy the provider before 7411 // changing it because the mProviders object contains a reference 7412 // to a provider that we don't want to change. 7413 // Only do this for the second authority since the resulting provider 7414 // object can be the same for all future authorities for this provider. 7415 p = new PackageParser.Provider(p); 7416 p.syncable = false; 7417 } 7418 if (!mProvidersByAuthority.containsKey(names[j])) { 7419 mProvidersByAuthority.put(names[j], p); 7420 if (p.info.authority == null) { 7421 p.info.authority = names[j]; 7422 } else { 7423 p.info.authority = p.info.authority + ";" + names[j]; 7424 } 7425 if (DEBUG_PACKAGE_SCANNING) { 7426 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7427 Log.d(TAG, "Registered content provider: " + names[j] 7428 + ", className = " + p.info.name + ", isSyncable = " 7429 + p.info.isSyncable); 7430 } 7431 } else { 7432 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7433 Slog.w(TAG, "Skipping provider name " + names[j] + 7434 " (in package " + pkg.applicationInfo.packageName + 7435 "): name already used by " 7436 + ((other != null && other.getComponentName() != null) 7437 ? other.getComponentName().getPackageName() : "?")); 7438 } 7439 } 7440 } 7441 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7442 if (r == null) { 7443 r = new StringBuilder(256); 7444 } else { 7445 r.append(' '); 7446 } 7447 r.append(p.info.name); 7448 } 7449 } 7450 if (r != null) { 7451 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7452 } 7453 7454 N = pkg.services.size(); 7455 r = null; 7456 for (i=0; i<N; i++) { 7457 PackageParser.Service s = pkg.services.get(i); 7458 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7459 s.info.processName, pkg.applicationInfo.uid); 7460 mServices.addService(s); 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(s.info.name); 7468 } 7469 } 7470 if (r != null) { 7471 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7472 } 7473 7474 N = pkg.receivers.size(); 7475 r = null; 7476 for (i=0; i<N; i++) { 7477 PackageParser.Activity a = pkg.receivers.get(i); 7478 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7479 a.info.processName, pkg.applicationInfo.uid); 7480 mReceivers.addActivity(a, "receiver"); 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(a.info.name); 7488 } 7489 } 7490 if (r != null) { 7491 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7492 } 7493 7494 N = pkg.activities.size(); 7495 r = null; 7496 for (i=0; i<N; i++) { 7497 PackageParser.Activity a = pkg.activities.get(i); 7498 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7499 a.info.processName, pkg.applicationInfo.uid); 7500 mActivities.addActivity(a, "activity"); 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, " Activities: " + r); 7512 } 7513 7514 N = pkg.permissionGroups.size(); 7515 r = null; 7516 for (i=0; i<N; i++) { 7517 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7518 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7519 if (cur == null) { 7520 mPermissionGroups.put(pg.info.name, pg); 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(pg.info.name); 7528 } 7529 } else { 7530 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7531 + pg.info.packageName + " ignored: original from " 7532 + cur.info.packageName); 7533 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7534 if (r == null) { 7535 r = new StringBuilder(256); 7536 } else { 7537 r.append(' '); 7538 } 7539 r.append("DUP:"); 7540 r.append(pg.info.name); 7541 } 7542 } 7543 } 7544 if (r != null) { 7545 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7546 } 7547 7548 N = pkg.permissions.size(); 7549 r = null; 7550 for (i=0; i<N; i++) { 7551 PackageParser.Permission p = pkg.permissions.get(i); 7552 7553 // Assume by default that we did not install this permission into the system. 7554 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7555 7556 // Now that permission groups have a special meaning, we ignore permission 7557 // groups for legacy apps to prevent unexpected behavior. In particular, 7558 // permissions for one app being granted to someone just becuase they happen 7559 // to be in a group defined by another app (before this had no implications). 7560 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7561 p.group = mPermissionGroups.get(p.info.group); 7562 // Warn for a permission in an unknown group. 7563 if (p.info.group != null && p.group == null) { 7564 Slog.w(TAG, "Permission " + p.info.name + " from package " 7565 + p.info.packageName + " in an unknown group " + p.info.group); 7566 } 7567 } 7568 7569 ArrayMap<String, BasePermission> permissionMap = 7570 p.tree ? mSettings.mPermissionTrees 7571 : mSettings.mPermissions; 7572 BasePermission bp = permissionMap.get(p.info.name); 7573 7574 // Allow system apps to redefine non-system permissions 7575 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7576 final boolean currentOwnerIsSystem = (bp.perm != null 7577 && isSystemApp(bp.perm.owner)); 7578 if (isSystemApp(p.owner)) { 7579 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7580 // It's a built-in permission and no owner, take ownership now 7581 bp.packageSetting = pkgSetting; 7582 bp.perm = p; 7583 bp.uid = pkg.applicationInfo.uid; 7584 bp.sourcePackage = p.info.packageName; 7585 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7586 } else if (!currentOwnerIsSystem) { 7587 String msg = "New decl " + p.owner + " of permission " 7588 + p.info.name + " is system; overriding " + bp.sourcePackage; 7589 reportSettingsProblem(Log.WARN, msg); 7590 bp = null; 7591 } 7592 } 7593 } 7594 7595 if (bp == null) { 7596 bp = new BasePermission(p.info.name, p.info.packageName, 7597 BasePermission.TYPE_NORMAL); 7598 permissionMap.put(p.info.name, bp); 7599 } 7600 7601 if (bp.perm == null) { 7602 if (bp.sourcePackage == null 7603 || bp.sourcePackage.equals(p.info.packageName)) { 7604 BasePermission tree = findPermissionTreeLP(p.info.name); 7605 if (tree == null 7606 || tree.sourcePackage.equals(p.info.packageName)) { 7607 bp.packageSetting = pkgSetting; 7608 bp.perm = p; 7609 bp.uid = pkg.applicationInfo.uid; 7610 bp.sourcePackage = p.info.packageName; 7611 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7612 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7613 if (r == null) { 7614 r = new StringBuilder(256); 7615 } else { 7616 r.append(' '); 7617 } 7618 r.append(p.info.name); 7619 } 7620 } else { 7621 Slog.w(TAG, "Permission " + p.info.name + " from package " 7622 + p.info.packageName + " ignored: base tree " 7623 + tree.name + " is from package " 7624 + tree.sourcePackage); 7625 } 7626 } else { 7627 Slog.w(TAG, "Permission " + p.info.name + " from package " 7628 + p.info.packageName + " ignored: original from " 7629 + bp.sourcePackage); 7630 } 7631 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7632 if (r == null) { 7633 r = new StringBuilder(256); 7634 } else { 7635 r.append(' '); 7636 } 7637 r.append("DUP:"); 7638 r.append(p.info.name); 7639 } 7640 if (bp.perm == p) { 7641 bp.protectionLevel = p.info.protectionLevel; 7642 } 7643 } 7644 7645 if (r != null) { 7646 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7647 } 7648 7649 N = pkg.instrumentation.size(); 7650 r = null; 7651 for (i=0; i<N; i++) { 7652 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7653 a.info.packageName = pkg.applicationInfo.packageName; 7654 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7655 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7656 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7657 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7658 a.info.dataDir = pkg.applicationInfo.dataDir; 7659 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7660 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7661 7662 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7663 // need other information about the application, like the ABI and what not ? 7664 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7665 mInstrumentation.put(a.getComponentName(), a); 7666 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7667 if (r == null) { 7668 r = new StringBuilder(256); 7669 } else { 7670 r.append(' '); 7671 } 7672 r.append(a.info.name); 7673 } 7674 } 7675 if (r != null) { 7676 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7677 } 7678 7679 if (pkg.protectedBroadcasts != null) { 7680 N = pkg.protectedBroadcasts.size(); 7681 for (i=0; i<N; i++) { 7682 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7683 } 7684 } 7685 7686 pkgSetting.setTimeStamp(scanFileTime); 7687 7688 // Create idmap files for pairs of (packages, overlay packages). 7689 // Note: "android", ie framework-res.apk, is handled by native layers. 7690 if (pkg.mOverlayTarget != null) { 7691 // This is an overlay package. 7692 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7693 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7694 mOverlays.put(pkg.mOverlayTarget, 7695 new ArrayMap<String, PackageParser.Package>()); 7696 } 7697 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7698 map.put(pkg.packageName, pkg); 7699 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7700 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7701 createIdmapFailed = true; 7702 } 7703 } 7704 } else if (mOverlays.containsKey(pkg.packageName) && 7705 !pkg.packageName.equals("android")) { 7706 // This is a regular package, with one or more known overlay packages. 7707 createIdmapsForPackageLI(pkg); 7708 } 7709 } 7710 7711 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7712 7713 if (createIdmapFailed) { 7714 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7715 "scanPackageLI failed to createIdmap"); 7716 } 7717 return pkg; 7718 } 7719 7720 /** 7721 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7722 * is derived purely on the basis of the contents of {@code scanFile} and 7723 * {@code cpuAbiOverride}. 7724 * 7725 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7726 */ 7727 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7728 String cpuAbiOverride, boolean extractLibs) 7729 throws PackageManagerException { 7730 // TODO: We can probably be smarter about this stuff. For installed apps, 7731 // we can calculate this information at install time once and for all. For 7732 // system apps, we can probably assume that this information doesn't change 7733 // after the first boot scan. As things stand, we do lots of unnecessary work. 7734 7735 // Give ourselves some initial paths; we'll come back for another 7736 // pass once we've determined ABI below. 7737 setNativeLibraryPaths(pkg); 7738 7739 // We would never need to extract libs for forward-locked and external packages, 7740 // since the container service will do it for us. We shouldn't attempt to 7741 // extract libs from system app when it was not updated. 7742 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7743 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7744 extractLibs = false; 7745 } 7746 7747 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7748 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7749 7750 NativeLibraryHelper.Handle handle = null; 7751 try { 7752 handle = NativeLibraryHelper.Handle.create(pkg); 7753 // TODO(multiArch): This can be null for apps that didn't go through the 7754 // usual installation process. We can calculate it again, like we 7755 // do during install time. 7756 // 7757 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7758 // unnecessary. 7759 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7760 7761 // Null out the abis so that they can be recalculated. 7762 pkg.applicationInfo.primaryCpuAbi = null; 7763 pkg.applicationInfo.secondaryCpuAbi = null; 7764 if (isMultiArch(pkg.applicationInfo)) { 7765 // Warn if we've set an abiOverride for multi-lib packages.. 7766 // By definition, we need to copy both 32 and 64 bit libraries for 7767 // such packages. 7768 if (pkg.cpuAbiOverride != null 7769 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7770 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7771 } 7772 7773 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7774 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7775 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7776 if (extractLibs) { 7777 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7778 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7779 useIsaSpecificSubdirs); 7780 } else { 7781 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7782 } 7783 } 7784 7785 maybeThrowExceptionForMultiArchCopy( 7786 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7787 7788 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7789 if (extractLibs) { 7790 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7791 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7792 useIsaSpecificSubdirs); 7793 } else { 7794 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7795 } 7796 } 7797 7798 maybeThrowExceptionForMultiArchCopy( 7799 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7800 7801 if (abi64 >= 0) { 7802 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7803 } 7804 7805 if (abi32 >= 0) { 7806 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7807 if (abi64 >= 0) { 7808 pkg.applicationInfo.secondaryCpuAbi = abi; 7809 } else { 7810 pkg.applicationInfo.primaryCpuAbi = abi; 7811 } 7812 } 7813 } else { 7814 String[] abiList = (cpuAbiOverride != null) ? 7815 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7816 7817 // Enable gross and lame hacks for apps that are built with old 7818 // SDK tools. We must scan their APKs for renderscript bitcode and 7819 // not launch them if it's present. Don't bother checking on devices 7820 // that don't have 64 bit support. 7821 boolean needsRenderScriptOverride = false; 7822 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7823 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7824 abiList = Build.SUPPORTED_32_BIT_ABIS; 7825 needsRenderScriptOverride = true; 7826 } 7827 7828 final int copyRet; 7829 if (extractLibs) { 7830 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7831 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7832 } else { 7833 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7834 } 7835 7836 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7837 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7838 "Error unpackaging native libs for app, errorCode=" + copyRet); 7839 } 7840 7841 if (copyRet >= 0) { 7842 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7843 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7844 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7845 } else if (needsRenderScriptOverride) { 7846 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7847 } 7848 } 7849 } catch (IOException ioe) { 7850 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7851 } finally { 7852 IoUtils.closeQuietly(handle); 7853 } 7854 7855 // Now that we've calculated the ABIs and determined if it's an internal app, 7856 // we will go ahead and populate the nativeLibraryPath. 7857 setNativeLibraryPaths(pkg); 7858 } 7859 7860 /** 7861 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7862 * i.e, so that all packages can be run inside a single process if required. 7863 * 7864 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7865 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7866 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7867 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7868 * updating a package that belongs to a shared user. 7869 * 7870 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7871 * adds unnecessary complexity. 7872 */ 7873 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7874 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7875 boolean bootComplete) { 7876 String requiredInstructionSet = null; 7877 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7878 requiredInstructionSet = VMRuntime.getInstructionSet( 7879 scannedPackage.applicationInfo.primaryCpuAbi); 7880 } 7881 7882 PackageSetting requirer = null; 7883 for (PackageSetting ps : packagesForUser) { 7884 // If packagesForUser contains scannedPackage, we skip it. This will happen 7885 // when scannedPackage is an update of an existing package. Without this check, 7886 // we will never be able to change the ABI of any package belonging to a shared 7887 // user, even if it's compatible with other packages. 7888 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7889 if (ps.primaryCpuAbiString == null) { 7890 continue; 7891 } 7892 7893 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7894 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7895 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7896 // this but there's not much we can do. 7897 String errorMessage = "Instruction set mismatch, " 7898 + ((requirer == null) ? "[caller]" : requirer) 7899 + " requires " + requiredInstructionSet + " whereas " + ps 7900 + " requires " + instructionSet; 7901 Slog.w(TAG, errorMessage); 7902 } 7903 7904 if (requiredInstructionSet == null) { 7905 requiredInstructionSet = instructionSet; 7906 requirer = ps; 7907 } 7908 } 7909 } 7910 7911 if (requiredInstructionSet != null) { 7912 String adjustedAbi; 7913 if (requirer != null) { 7914 // requirer != null implies that either scannedPackage was null or that scannedPackage 7915 // did not require an ABI, in which case we have to adjust scannedPackage to match 7916 // the ABI of the set (which is the same as requirer's ABI) 7917 adjustedAbi = requirer.primaryCpuAbiString; 7918 if (scannedPackage != null) { 7919 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7920 } 7921 } else { 7922 // requirer == null implies that we're updating all ABIs in the set to 7923 // match scannedPackage. 7924 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7925 } 7926 7927 for (PackageSetting ps : packagesForUser) { 7928 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7929 if (ps.primaryCpuAbiString != null) { 7930 continue; 7931 } 7932 7933 ps.primaryCpuAbiString = adjustedAbi; 7934 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7935 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7936 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7937 7938 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7939 7940 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7941 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7942 bootComplete, false /*useJit*/); 7943 7944 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7945 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7946 ps.primaryCpuAbiString = null; 7947 ps.pkg.applicationInfo.primaryCpuAbi = null; 7948 return; 7949 } else { 7950 mInstaller.rmdex(ps.codePathString, 7951 getDexCodeInstructionSet(getPreferredInstructionSet())); 7952 } 7953 } 7954 } 7955 } 7956 } 7957 } 7958 7959 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7960 synchronized (mPackages) { 7961 mResolverReplaced = true; 7962 // Set up information for custom user intent resolution activity. 7963 mResolveActivity.applicationInfo = pkg.applicationInfo; 7964 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7965 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7966 mResolveActivity.processName = pkg.applicationInfo.packageName; 7967 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7968 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7969 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7970 mResolveActivity.theme = 0; 7971 mResolveActivity.exported = true; 7972 mResolveActivity.enabled = true; 7973 mResolveInfo.activityInfo = mResolveActivity; 7974 mResolveInfo.priority = 0; 7975 mResolveInfo.preferredOrder = 0; 7976 mResolveInfo.match = 0; 7977 mResolveComponentName = mCustomResolverComponentName; 7978 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7979 mResolveComponentName); 7980 } 7981 } 7982 7983 private static String calculateBundledApkRoot(final String codePathString) { 7984 final File codePath = new File(codePathString); 7985 final File codeRoot; 7986 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7987 codeRoot = Environment.getRootDirectory(); 7988 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7989 codeRoot = Environment.getOemDirectory(); 7990 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7991 codeRoot = Environment.getVendorDirectory(); 7992 } else { 7993 // Unrecognized code path; take its top real segment as the apk root: 7994 // e.g. /something/app/blah.apk => /something 7995 try { 7996 File f = codePath.getCanonicalFile(); 7997 File parent = f.getParentFile(); // non-null because codePath is a file 7998 File tmp; 7999 while ((tmp = parent.getParentFile()) != null) { 8000 f = parent; 8001 parent = tmp; 8002 } 8003 codeRoot = f; 8004 Slog.w(TAG, "Unrecognized code path " 8005 + codePath + " - using " + codeRoot); 8006 } catch (IOException e) { 8007 // Can't canonicalize the code path -- shenanigans? 8008 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8009 return Environment.getRootDirectory().getPath(); 8010 } 8011 } 8012 return codeRoot.getPath(); 8013 } 8014 8015 /** 8016 * Derive and set the location of native libraries for the given package, 8017 * which varies depending on where and how the package was installed. 8018 */ 8019 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8020 final ApplicationInfo info = pkg.applicationInfo; 8021 final String codePath = pkg.codePath; 8022 final File codeFile = new File(codePath); 8023 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8024 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8025 8026 info.nativeLibraryRootDir = null; 8027 info.nativeLibraryRootRequiresIsa = false; 8028 info.nativeLibraryDir = null; 8029 info.secondaryNativeLibraryDir = null; 8030 8031 if (isApkFile(codeFile)) { 8032 // Monolithic install 8033 if (bundledApp) { 8034 // If "/system/lib64/apkname" exists, assume that is the per-package 8035 // native library directory to use; otherwise use "/system/lib/apkname". 8036 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8037 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8038 getPrimaryInstructionSet(info)); 8039 8040 // This is a bundled system app so choose the path based on the ABI. 8041 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8042 // is just the default path. 8043 final String apkName = deriveCodePathName(codePath); 8044 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8045 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8046 apkName).getAbsolutePath(); 8047 8048 if (info.secondaryCpuAbi != null) { 8049 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8050 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8051 secondaryLibDir, apkName).getAbsolutePath(); 8052 } 8053 } else if (asecApp) { 8054 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8055 .getAbsolutePath(); 8056 } else { 8057 final String apkName = deriveCodePathName(codePath); 8058 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8059 .getAbsolutePath(); 8060 } 8061 8062 info.nativeLibraryRootRequiresIsa = false; 8063 info.nativeLibraryDir = info.nativeLibraryRootDir; 8064 } else { 8065 // Cluster install 8066 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8067 info.nativeLibraryRootRequiresIsa = true; 8068 8069 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8070 getPrimaryInstructionSet(info)).getAbsolutePath(); 8071 8072 if (info.secondaryCpuAbi != null) { 8073 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8074 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8075 } 8076 } 8077 } 8078 8079 /** 8080 * Calculate the abis and roots for a bundled app. These can uniquely 8081 * be determined from the contents of the system partition, i.e whether 8082 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8083 * of this information, and instead assume that the system was built 8084 * sensibly. 8085 */ 8086 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8087 PackageSetting pkgSetting) { 8088 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8089 8090 // If "/system/lib64/apkname" exists, assume that is the per-package 8091 // native library directory to use; otherwise use "/system/lib/apkname". 8092 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8093 setBundledAppAbi(pkg, apkRoot, apkName); 8094 // pkgSetting might be null during rescan following uninstall of updates 8095 // to a bundled app, so accommodate that possibility. The settings in 8096 // that case will be established later from the parsed package. 8097 // 8098 // If the settings aren't null, sync them up with what we've just derived. 8099 // note that apkRoot isn't stored in the package settings. 8100 if (pkgSetting != null) { 8101 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8102 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8103 } 8104 } 8105 8106 /** 8107 * Deduces the ABI of a bundled app and sets the relevant fields on the 8108 * parsed pkg object. 8109 * 8110 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8111 * under which system libraries are installed. 8112 * @param apkName the name of the installed package. 8113 */ 8114 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8115 final File codeFile = new File(pkg.codePath); 8116 8117 final boolean has64BitLibs; 8118 final boolean has32BitLibs; 8119 if (isApkFile(codeFile)) { 8120 // Monolithic install 8121 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8122 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8123 } else { 8124 // Cluster install 8125 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8126 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8127 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8128 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8129 has64BitLibs = (new File(rootDir, isa)).exists(); 8130 } else { 8131 has64BitLibs = false; 8132 } 8133 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8134 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8135 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8136 has32BitLibs = (new File(rootDir, isa)).exists(); 8137 } else { 8138 has32BitLibs = false; 8139 } 8140 } 8141 8142 if (has64BitLibs && !has32BitLibs) { 8143 // The package has 64 bit libs, but not 32 bit libs. Its primary 8144 // ABI should be 64 bit. We can safely assume here that the bundled 8145 // native libraries correspond to the most preferred ABI in the list. 8146 8147 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8148 pkg.applicationInfo.secondaryCpuAbi = null; 8149 } else if (has32BitLibs && !has64BitLibs) { 8150 // The package has 32 bit libs but not 64 bit libs. Its primary 8151 // ABI should be 32 bit. 8152 8153 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8154 pkg.applicationInfo.secondaryCpuAbi = null; 8155 } else if (has32BitLibs && has64BitLibs) { 8156 // The application has both 64 and 32 bit bundled libraries. We check 8157 // here that the app declares multiArch support, and warn if it doesn't. 8158 // 8159 // We will be lenient here and record both ABIs. The primary will be the 8160 // ABI that's higher on the list, i.e, a device that's configured to prefer 8161 // 64 bit apps will see a 64 bit primary ABI, 8162 8163 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8164 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8165 } 8166 8167 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8168 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8169 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8170 } else { 8171 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8172 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8173 } 8174 } else { 8175 pkg.applicationInfo.primaryCpuAbi = null; 8176 pkg.applicationInfo.secondaryCpuAbi = null; 8177 } 8178 } 8179 8180 private void killApplication(String pkgName, int appId, String reason) { 8181 // Request the ActivityManager to kill the process(only for existing packages) 8182 // so that we do not end up in a confused state while the user is still using the older 8183 // version of the application while the new one gets installed. 8184 IActivityManager am = ActivityManagerNative.getDefault(); 8185 if (am != null) { 8186 try { 8187 am.killApplicationWithAppId(pkgName, appId, reason); 8188 } catch (RemoteException e) { 8189 } 8190 } 8191 } 8192 8193 void removePackageLI(PackageSetting ps, boolean chatty) { 8194 if (DEBUG_INSTALL) { 8195 if (chatty) 8196 Log.d(TAG, "Removing package " + ps.name); 8197 } 8198 8199 // writer 8200 synchronized (mPackages) { 8201 mPackages.remove(ps.name); 8202 final PackageParser.Package pkg = ps.pkg; 8203 if (pkg != null) { 8204 cleanPackageDataStructuresLILPw(pkg, chatty); 8205 } 8206 } 8207 } 8208 8209 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8210 if (DEBUG_INSTALL) { 8211 if (chatty) 8212 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8213 } 8214 8215 // writer 8216 synchronized (mPackages) { 8217 mPackages.remove(pkg.applicationInfo.packageName); 8218 cleanPackageDataStructuresLILPw(pkg, chatty); 8219 } 8220 } 8221 8222 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8223 int N = pkg.providers.size(); 8224 StringBuilder r = null; 8225 int i; 8226 for (i=0; i<N; i++) { 8227 PackageParser.Provider p = pkg.providers.get(i); 8228 mProviders.removeProvider(p); 8229 if (p.info.authority == null) { 8230 8231 /* There was another ContentProvider with this authority when 8232 * this app was installed so this authority is null, 8233 * Ignore it as we don't have to unregister the provider. 8234 */ 8235 continue; 8236 } 8237 String names[] = p.info.authority.split(";"); 8238 for (int j = 0; j < names.length; j++) { 8239 if (mProvidersByAuthority.get(names[j]) == p) { 8240 mProvidersByAuthority.remove(names[j]); 8241 if (DEBUG_REMOVE) { 8242 if (chatty) 8243 Log.d(TAG, "Unregistered content provider: " + names[j] 8244 + ", className = " + p.info.name + ", isSyncable = " 8245 + p.info.isSyncable); 8246 } 8247 } 8248 } 8249 if (DEBUG_REMOVE && chatty) { 8250 if (r == null) { 8251 r = new StringBuilder(256); 8252 } else { 8253 r.append(' '); 8254 } 8255 r.append(p.info.name); 8256 } 8257 } 8258 if (r != null) { 8259 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8260 } 8261 8262 N = pkg.services.size(); 8263 r = null; 8264 for (i=0; i<N; i++) { 8265 PackageParser.Service s = pkg.services.get(i); 8266 mServices.removeService(s); 8267 if (chatty) { 8268 if (r == null) { 8269 r = new StringBuilder(256); 8270 } else { 8271 r.append(' '); 8272 } 8273 r.append(s.info.name); 8274 } 8275 } 8276 if (r != null) { 8277 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8278 } 8279 8280 N = pkg.receivers.size(); 8281 r = null; 8282 for (i=0; i<N; i++) { 8283 PackageParser.Activity a = pkg.receivers.get(i); 8284 mReceivers.removeActivity(a, "receiver"); 8285 if (DEBUG_REMOVE && chatty) { 8286 if (r == null) { 8287 r = new StringBuilder(256); 8288 } else { 8289 r.append(' '); 8290 } 8291 r.append(a.info.name); 8292 } 8293 } 8294 if (r != null) { 8295 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8296 } 8297 8298 N = pkg.activities.size(); 8299 r = null; 8300 for (i=0; i<N; i++) { 8301 PackageParser.Activity a = pkg.activities.get(i); 8302 mActivities.removeActivity(a, "activity"); 8303 if (DEBUG_REMOVE && chatty) { 8304 if (r == null) { 8305 r = new StringBuilder(256); 8306 } else { 8307 r.append(' '); 8308 } 8309 r.append(a.info.name); 8310 } 8311 } 8312 if (r != null) { 8313 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8314 } 8315 8316 N = pkg.permissions.size(); 8317 r = null; 8318 for (i=0; i<N; i++) { 8319 PackageParser.Permission p = pkg.permissions.get(i); 8320 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8321 if (bp == null) { 8322 bp = mSettings.mPermissionTrees.get(p.info.name); 8323 } 8324 if (bp != null && bp.perm == p) { 8325 bp.perm = null; 8326 if (DEBUG_REMOVE && chatty) { 8327 if (r == null) { 8328 r = new StringBuilder(256); 8329 } else { 8330 r.append(' '); 8331 } 8332 r.append(p.info.name); 8333 } 8334 } 8335 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8336 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8337 if (appOpPerms != null) { 8338 appOpPerms.remove(pkg.packageName); 8339 } 8340 } 8341 } 8342 if (r != null) { 8343 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8344 } 8345 8346 N = pkg.requestedPermissions.size(); 8347 r = null; 8348 for (i=0; i<N; i++) { 8349 String perm = pkg.requestedPermissions.get(i); 8350 BasePermission bp = mSettings.mPermissions.get(perm); 8351 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8352 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8353 if (appOpPerms != null) { 8354 appOpPerms.remove(pkg.packageName); 8355 if (appOpPerms.isEmpty()) { 8356 mAppOpPermissionPackages.remove(perm); 8357 } 8358 } 8359 } 8360 } 8361 if (r != null) { 8362 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8363 } 8364 8365 N = pkg.instrumentation.size(); 8366 r = null; 8367 for (i=0; i<N; i++) { 8368 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8369 mInstrumentation.remove(a.getComponentName()); 8370 if (DEBUG_REMOVE && chatty) { 8371 if (r == null) { 8372 r = new StringBuilder(256); 8373 } else { 8374 r.append(' '); 8375 } 8376 r.append(a.info.name); 8377 } 8378 } 8379 if (r != null) { 8380 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8381 } 8382 8383 r = null; 8384 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8385 // Only system apps can hold shared libraries. 8386 if (pkg.libraryNames != null) { 8387 for (i=0; i<pkg.libraryNames.size(); i++) { 8388 String name = pkg.libraryNames.get(i); 8389 SharedLibraryEntry cur = mSharedLibraries.get(name); 8390 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8391 mSharedLibraries.remove(name); 8392 if (DEBUG_REMOVE && chatty) { 8393 if (r == null) { 8394 r = new StringBuilder(256); 8395 } else { 8396 r.append(' '); 8397 } 8398 r.append(name); 8399 } 8400 } 8401 } 8402 } 8403 } 8404 if (r != null) { 8405 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8406 } 8407 } 8408 8409 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8410 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8411 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8412 return true; 8413 } 8414 } 8415 return false; 8416 } 8417 8418 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8419 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8420 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8421 8422 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8423 int flags) { 8424 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8425 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8426 } 8427 8428 private void updatePermissionsLPw(String changingPkg, 8429 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8430 // Make sure there are no dangling permission trees. 8431 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8432 while (it.hasNext()) { 8433 final BasePermission bp = it.next(); 8434 if (bp.packageSetting == null) { 8435 // We may not yet have parsed the package, so just see if 8436 // we still know about its settings. 8437 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8438 } 8439 if (bp.packageSetting == null) { 8440 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8441 + " from package " + bp.sourcePackage); 8442 it.remove(); 8443 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8444 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8445 Slog.i(TAG, "Removing old permission tree: " + bp.name 8446 + " from package " + bp.sourcePackage); 8447 flags |= UPDATE_PERMISSIONS_ALL; 8448 it.remove(); 8449 } 8450 } 8451 } 8452 8453 // Make sure all dynamic permissions have been assigned to a package, 8454 // and make sure there are no dangling permissions. 8455 it = mSettings.mPermissions.values().iterator(); 8456 while (it.hasNext()) { 8457 final BasePermission bp = it.next(); 8458 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8459 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8460 + bp.name + " pkg=" + bp.sourcePackage 8461 + " info=" + bp.pendingInfo); 8462 if (bp.packageSetting == null && bp.pendingInfo != null) { 8463 final BasePermission tree = findPermissionTreeLP(bp.name); 8464 if (tree != null && tree.perm != null) { 8465 bp.packageSetting = tree.packageSetting; 8466 bp.perm = new PackageParser.Permission(tree.perm.owner, 8467 new PermissionInfo(bp.pendingInfo)); 8468 bp.perm.info.packageName = tree.perm.info.packageName; 8469 bp.perm.info.name = bp.name; 8470 bp.uid = tree.uid; 8471 } 8472 } 8473 } 8474 if (bp.packageSetting == null) { 8475 // We may not yet have parsed the package, so just see if 8476 // we still know about its settings. 8477 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8478 } 8479 if (bp.packageSetting == null) { 8480 Slog.w(TAG, "Removing dangling permission: " + bp.name 8481 + " from package " + bp.sourcePackage); 8482 it.remove(); 8483 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8484 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8485 Slog.i(TAG, "Removing old permission: " + bp.name 8486 + " from package " + bp.sourcePackage); 8487 flags |= UPDATE_PERMISSIONS_ALL; 8488 it.remove(); 8489 } 8490 } 8491 } 8492 8493 // Now update the permissions for all packages, in particular 8494 // replace the granted permissions of the system packages. 8495 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8496 for (PackageParser.Package pkg : mPackages.values()) { 8497 if (pkg != pkgInfo) { 8498 // Only replace for packages on requested volume 8499 final String volumeUuid = getVolumeUuidForPackage(pkg); 8500 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8501 && Objects.equals(replaceVolumeUuid, volumeUuid); 8502 grantPermissionsLPw(pkg, replace, changingPkg); 8503 } 8504 } 8505 } 8506 8507 if (pkgInfo != null) { 8508 // Only replace for packages on requested volume 8509 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8510 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8511 && Objects.equals(replaceVolumeUuid, volumeUuid); 8512 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8513 } 8514 } 8515 8516 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8517 String packageOfInterest) { 8518 // IMPORTANT: There are two types of permissions: install and runtime. 8519 // Install time permissions are granted when the app is installed to 8520 // all device users and users added in the future. Runtime permissions 8521 // are granted at runtime explicitly to specific users. Normal and signature 8522 // protected permissions are install time permissions. Dangerous permissions 8523 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8524 // otherwise they are runtime permissions. This function does not manage 8525 // runtime permissions except for the case an app targeting Lollipop MR1 8526 // being upgraded to target a newer SDK, in which case dangerous permissions 8527 // are transformed from install time to runtime ones. 8528 8529 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8530 if (ps == null) { 8531 return; 8532 } 8533 8534 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8535 8536 PermissionsState permissionsState = ps.getPermissionsState(); 8537 PermissionsState origPermissions = permissionsState; 8538 8539 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8540 8541 boolean runtimePermissionsRevoked = false; 8542 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8543 8544 boolean changedInstallPermission = false; 8545 8546 if (replace) { 8547 ps.installPermissionsFixed = false; 8548 if (!ps.isSharedUser()) { 8549 origPermissions = new PermissionsState(permissionsState); 8550 permissionsState.reset(); 8551 } else { 8552 // We need to know only about runtime permission changes since the 8553 // calling code always writes the install permissions state but 8554 // the runtime ones are written only if changed. The only cases of 8555 // changed runtime permissions here are promotion of an install to 8556 // runtime and revocation of a runtime from a shared user. 8557 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8558 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8559 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8560 runtimePermissionsRevoked = true; 8561 } 8562 } 8563 } 8564 8565 permissionsState.setGlobalGids(mGlobalGids); 8566 8567 final int N = pkg.requestedPermissions.size(); 8568 for (int i=0; i<N; i++) { 8569 final String name = pkg.requestedPermissions.get(i); 8570 final BasePermission bp = mSettings.mPermissions.get(name); 8571 8572 if (DEBUG_INSTALL) { 8573 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8574 } 8575 8576 if (bp == null || bp.packageSetting == null) { 8577 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8578 Slog.w(TAG, "Unknown permission " + name 8579 + " in package " + pkg.packageName); 8580 } 8581 continue; 8582 } 8583 8584 final String perm = bp.name; 8585 boolean allowedSig = false; 8586 int grant = GRANT_DENIED; 8587 8588 // Keep track of app op permissions. 8589 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8590 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8591 if (pkgs == null) { 8592 pkgs = new ArraySet<>(); 8593 mAppOpPermissionPackages.put(bp.name, pkgs); 8594 } 8595 pkgs.add(pkg.packageName); 8596 } 8597 8598 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8599 switch (level) { 8600 case PermissionInfo.PROTECTION_NORMAL: { 8601 // For all apps normal permissions are install time ones. 8602 grant = GRANT_INSTALL; 8603 } break; 8604 8605 case PermissionInfo.PROTECTION_DANGEROUS: { 8606 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8607 // For legacy apps dangerous permissions are install time ones. 8608 grant = GRANT_INSTALL_LEGACY; 8609 } else if (origPermissions.hasInstallPermission(bp.name)) { 8610 // For legacy apps that became modern, install becomes runtime. 8611 grant = GRANT_UPGRADE; 8612 } else if (mPromoteSystemApps 8613 && isSystemApp(ps) 8614 && mExistingSystemPackages.contains(ps.name)) { 8615 // For legacy system apps, install becomes runtime. 8616 // We cannot check hasInstallPermission() for system apps since those 8617 // permissions were granted implicitly and not persisted pre-M. 8618 grant = GRANT_UPGRADE; 8619 } else { 8620 // For modern apps keep runtime permissions unchanged. 8621 grant = GRANT_RUNTIME; 8622 } 8623 } break; 8624 8625 case PermissionInfo.PROTECTION_SIGNATURE: { 8626 // For all apps signature permissions are install time ones. 8627 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8628 if (allowedSig) { 8629 grant = GRANT_INSTALL; 8630 } 8631 } break; 8632 } 8633 8634 if (DEBUG_INSTALL) { 8635 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8636 } 8637 8638 if (grant != GRANT_DENIED) { 8639 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8640 // If this is an existing, non-system package, then 8641 // we can't add any new permissions to it. 8642 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8643 // Except... if this is a permission that was added 8644 // to the platform (note: need to only do this when 8645 // updating the platform). 8646 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8647 grant = GRANT_DENIED; 8648 } 8649 } 8650 } 8651 8652 switch (grant) { 8653 case GRANT_INSTALL: { 8654 // Revoke this as runtime permission to handle the case of 8655 // a runtime permission being downgraded to an install one. 8656 for (int userId : UserManagerService.getInstance().getUserIds()) { 8657 if (origPermissions.getRuntimePermissionState( 8658 bp.name, userId) != null) { 8659 // Revoke the runtime permission and clear the flags. 8660 origPermissions.revokeRuntimePermission(bp, userId); 8661 origPermissions.updatePermissionFlags(bp, userId, 8662 PackageManager.MASK_PERMISSION_FLAGS, 0); 8663 // If we revoked a permission permission, we have to write. 8664 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8665 changedRuntimePermissionUserIds, userId); 8666 } 8667 } 8668 // Grant an install permission. 8669 if (permissionsState.grantInstallPermission(bp) != 8670 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8671 changedInstallPermission = true; 8672 } 8673 } break; 8674 8675 case GRANT_INSTALL_LEGACY: { 8676 // Grant an install permission. 8677 if (permissionsState.grantInstallPermission(bp) != 8678 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8679 changedInstallPermission = true; 8680 } 8681 } break; 8682 8683 case GRANT_RUNTIME: { 8684 // Grant previously granted runtime permissions. 8685 for (int userId : UserManagerService.getInstance().getUserIds()) { 8686 PermissionState permissionState = origPermissions 8687 .getRuntimePermissionState(bp.name, userId); 8688 final int flags = permissionState != null 8689 ? permissionState.getFlags() : 0; 8690 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8691 if (permissionsState.grantRuntimePermission(bp, userId) == 8692 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8693 // If we cannot put the permission as it was, we have to write. 8694 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8695 changedRuntimePermissionUserIds, userId); 8696 } 8697 } 8698 // Propagate the permission flags. 8699 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8700 } 8701 } break; 8702 8703 case GRANT_UPGRADE: { 8704 // Grant runtime permissions for a previously held install permission. 8705 PermissionState permissionState = origPermissions 8706 .getInstallPermissionState(bp.name); 8707 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8708 8709 if (origPermissions.revokeInstallPermission(bp) 8710 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8711 // We will be transferring the permission flags, so clear them. 8712 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8713 PackageManager.MASK_PERMISSION_FLAGS, 0); 8714 changedInstallPermission = true; 8715 } 8716 8717 // If the permission is not to be promoted to runtime we ignore it and 8718 // also its other flags as they are not applicable to install permissions. 8719 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8720 for (int userId : currentUserIds) { 8721 if (permissionsState.grantRuntimePermission(bp, userId) != 8722 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8723 // Transfer the permission flags. 8724 permissionsState.updatePermissionFlags(bp, userId, 8725 flags, flags); 8726 // If we granted the permission, we have to write. 8727 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8728 changedRuntimePermissionUserIds, userId); 8729 } 8730 } 8731 } 8732 } break; 8733 8734 default: { 8735 if (packageOfInterest == null 8736 || packageOfInterest.equals(pkg.packageName)) { 8737 Slog.w(TAG, "Not granting permission " + perm 8738 + " to package " + pkg.packageName 8739 + " because it was previously installed without"); 8740 } 8741 } break; 8742 } 8743 } else { 8744 if (permissionsState.revokeInstallPermission(bp) != 8745 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8746 // Also drop the permission flags. 8747 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8748 PackageManager.MASK_PERMISSION_FLAGS, 0); 8749 changedInstallPermission = true; 8750 Slog.i(TAG, "Un-granting permission " + perm 8751 + " from package " + pkg.packageName 8752 + " (protectionLevel=" + bp.protectionLevel 8753 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8754 + ")"); 8755 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8756 // Don't print warning for app op permissions, since it is fine for them 8757 // not to be granted, there is a UI for the user to decide. 8758 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8759 Slog.w(TAG, "Not granting permission " + perm 8760 + " to package " + pkg.packageName 8761 + " (protectionLevel=" + bp.protectionLevel 8762 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8763 + ")"); 8764 } 8765 } 8766 } 8767 } 8768 8769 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8770 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8771 // This is the first that we have heard about this package, so the 8772 // permissions we have now selected are fixed until explicitly 8773 // changed. 8774 ps.installPermissionsFixed = true; 8775 } 8776 8777 // Persist the runtime permissions state for users with changes. If permissions 8778 // were revoked because no app in the shared user declares them we have to 8779 // write synchronously to avoid losing runtime permissions state. 8780 for (int userId : changedRuntimePermissionUserIds) { 8781 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8782 } 8783 8784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8785 } 8786 8787 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8788 boolean allowed = false; 8789 final int NP = PackageParser.NEW_PERMISSIONS.length; 8790 for (int ip=0; ip<NP; ip++) { 8791 final PackageParser.NewPermissionInfo npi 8792 = PackageParser.NEW_PERMISSIONS[ip]; 8793 if (npi.name.equals(perm) 8794 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8795 allowed = true; 8796 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8797 + pkg.packageName); 8798 break; 8799 } 8800 } 8801 return allowed; 8802 } 8803 8804 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8805 BasePermission bp, PermissionsState origPermissions) { 8806 boolean allowed; 8807 allowed = (compareSignatures( 8808 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8809 == PackageManager.SIGNATURE_MATCH) 8810 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8811 == PackageManager.SIGNATURE_MATCH); 8812 if (!allowed && (bp.protectionLevel 8813 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8814 if (isSystemApp(pkg)) { 8815 // For updated system applications, a system permission 8816 // is granted only if it had been defined by the original application. 8817 if (pkg.isUpdatedSystemApp()) { 8818 final PackageSetting sysPs = mSettings 8819 .getDisabledSystemPkgLPr(pkg.packageName); 8820 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8821 // If the original was granted this permission, we take 8822 // that grant decision as read and propagate it to the 8823 // update. 8824 if (sysPs.isPrivileged()) { 8825 allowed = true; 8826 } 8827 } else { 8828 // The system apk may have been updated with an older 8829 // version of the one on the data partition, but which 8830 // granted a new system permission that it didn't have 8831 // before. In this case we do want to allow the app to 8832 // now get the new permission if the ancestral apk is 8833 // privileged to get it. 8834 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8835 for (int j=0; 8836 j<sysPs.pkg.requestedPermissions.size(); j++) { 8837 if (perm.equals( 8838 sysPs.pkg.requestedPermissions.get(j))) { 8839 allowed = true; 8840 break; 8841 } 8842 } 8843 } 8844 } 8845 } else { 8846 allowed = isPrivilegedApp(pkg); 8847 } 8848 } 8849 } 8850 if (!allowed) { 8851 if (!allowed && (bp.protectionLevel 8852 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8853 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8854 // If this was a previously normal/dangerous permission that got moved 8855 // to a system permission as part of the runtime permission redesign, then 8856 // we still want to blindly grant it to old apps. 8857 allowed = true; 8858 } 8859 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8860 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8861 // If this permission is to be granted to the system installer and 8862 // this app is an installer, then it gets the permission. 8863 allowed = true; 8864 } 8865 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8866 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8867 // If this permission is to be granted to the system verifier and 8868 // this app is a verifier, then it gets the permission. 8869 allowed = true; 8870 } 8871 if (!allowed && (bp.protectionLevel 8872 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8873 && isSystemApp(pkg)) { 8874 // Any pre-installed system app is allowed to get this permission. 8875 allowed = true; 8876 } 8877 if (!allowed && (bp.protectionLevel 8878 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8879 // For development permissions, a development permission 8880 // is granted only if it was already granted. 8881 allowed = origPermissions.hasInstallPermission(perm); 8882 } 8883 } 8884 return allowed; 8885 } 8886 8887 final class ActivityIntentResolver 8888 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8889 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8890 boolean defaultOnly, int userId) { 8891 if (!sUserManager.exists(userId)) return null; 8892 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8893 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8894 } 8895 8896 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8897 int userId) { 8898 if (!sUserManager.exists(userId)) return null; 8899 mFlags = flags; 8900 return super.queryIntent(intent, resolvedType, 8901 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8902 } 8903 8904 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8905 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8906 if (!sUserManager.exists(userId)) return null; 8907 if (packageActivities == null) { 8908 return null; 8909 } 8910 mFlags = flags; 8911 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8912 final int N = packageActivities.size(); 8913 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8914 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8915 8916 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8917 for (int i = 0; i < N; ++i) { 8918 intentFilters = packageActivities.get(i).intents; 8919 if (intentFilters != null && intentFilters.size() > 0) { 8920 PackageParser.ActivityIntentInfo[] array = 8921 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8922 intentFilters.toArray(array); 8923 listCut.add(array); 8924 } 8925 } 8926 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8927 } 8928 8929 public final void addActivity(PackageParser.Activity a, String type) { 8930 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8931 mActivities.put(a.getComponentName(), a); 8932 if (DEBUG_SHOW_INFO) 8933 Log.v( 8934 TAG, " " + type + " " + 8935 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8936 if (DEBUG_SHOW_INFO) 8937 Log.v(TAG, " Class=" + a.info.name); 8938 final int NI = a.intents.size(); 8939 for (int j=0; j<NI; j++) { 8940 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8941 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8942 intent.setPriority(0); 8943 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8944 + a.className + " with priority > 0, forcing to 0"); 8945 } 8946 if (DEBUG_SHOW_INFO) { 8947 Log.v(TAG, " IntentFilter:"); 8948 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8949 } 8950 if (!intent.debugCheck()) { 8951 Log.w(TAG, "==> For Activity " + a.info.name); 8952 } 8953 addFilter(intent); 8954 } 8955 } 8956 8957 public final void removeActivity(PackageParser.Activity a, String type) { 8958 mActivities.remove(a.getComponentName()); 8959 if (DEBUG_SHOW_INFO) { 8960 Log.v(TAG, " " + type + " " 8961 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8962 : a.info.name) + ":"); 8963 Log.v(TAG, " Class=" + a.info.name); 8964 } 8965 final int NI = a.intents.size(); 8966 for (int j=0; j<NI; j++) { 8967 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8968 if (DEBUG_SHOW_INFO) { 8969 Log.v(TAG, " IntentFilter:"); 8970 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8971 } 8972 removeFilter(intent); 8973 } 8974 } 8975 8976 @Override 8977 protected boolean allowFilterResult( 8978 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8979 ActivityInfo filterAi = filter.activity.info; 8980 for (int i=dest.size()-1; i>=0; i--) { 8981 ActivityInfo destAi = dest.get(i).activityInfo; 8982 if (destAi.name == filterAi.name 8983 && destAi.packageName == filterAi.packageName) { 8984 return false; 8985 } 8986 } 8987 return true; 8988 } 8989 8990 @Override 8991 protected ActivityIntentInfo[] newArray(int size) { 8992 return new ActivityIntentInfo[size]; 8993 } 8994 8995 @Override 8996 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8997 if (!sUserManager.exists(userId)) return true; 8998 PackageParser.Package p = filter.activity.owner; 8999 if (p != null) { 9000 PackageSetting ps = (PackageSetting)p.mExtras; 9001 if (ps != null) { 9002 // System apps are never considered stopped for purposes of 9003 // filtering, because there may be no way for the user to 9004 // actually re-launch them. 9005 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9006 && ps.getStopped(userId); 9007 } 9008 } 9009 return false; 9010 } 9011 9012 @Override 9013 protected boolean isPackageForFilter(String packageName, 9014 PackageParser.ActivityIntentInfo info) { 9015 return packageName.equals(info.activity.owner.packageName); 9016 } 9017 9018 @Override 9019 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9020 int match, int userId) { 9021 if (!sUserManager.exists(userId)) return null; 9022 if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) { 9023 return null; 9024 } 9025 final PackageParser.Activity activity = info.activity; 9026 if (mSafeMode && (activity.info.applicationInfo.flags 9027 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9028 return null; 9029 } 9030 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9031 if (ps == null) { 9032 return null; 9033 } 9034 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9035 ps.readUserState(userId), userId); 9036 if (ai == null) { 9037 return null; 9038 } 9039 final ResolveInfo res = new ResolveInfo(); 9040 res.activityInfo = ai; 9041 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9042 res.filter = info; 9043 } 9044 if (info != null) { 9045 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9046 } 9047 res.priority = info.getPriority(); 9048 res.preferredOrder = activity.owner.mPreferredOrder; 9049 //System.out.println("Result: " + res.activityInfo.className + 9050 // " = " + res.priority); 9051 res.match = match; 9052 res.isDefault = info.hasDefault; 9053 res.labelRes = info.labelRes; 9054 res.nonLocalizedLabel = info.nonLocalizedLabel; 9055 if (userNeedsBadging(userId)) { 9056 res.noResourceId = true; 9057 } else { 9058 res.icon = info.icon; 9059 } 9060 res.iconResourceId = info.icon; 9061 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9062 return res; 9063 } 9064 9065 @Override 9066 protected void sortResults(List<ResolveInfo> results) { 9067 Collections.sort(results, mResolvePrioritySorter); 9068 } 9069 9070 @Override 9071 protected void dumpFilter(PrintWriter out, String prefix, 9072 PackageParser.ActivityIntentInfo filter) { 9073 out.print(prefix); out.print( 9074 Integer.toHexString(System.identityHashCode(filter.activity))); 9075 out.print(' '); 9076 filter.activity.printComponentShortName(out); 9077 out.print(" filter "); 9078 out.println(Integer.toHexString(System.identityHashCode(filter))); 9079 } 9080 9081 @Override 9082 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9083 return filter.activity; 9084 } 9085 9086 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9087 PackageParser.Activity activity = (PackageParser.Activity)label; 9088 out.print(prefix); out.print( 9089 Integer.toHexString(System.identityHashCode(activity))); 9090 out.print(' '); 9091 activity.printComponentShortName(out); 9092 if (count > 1) { 9093 out.print(" ("); out.print(count); out.print(" filters)"); 9094 } 9095 out.println(); 9096 } 9097 9098// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9099// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9100// final List<ResolveInfo> retList = Lists.newArrayList(); 9101// while (i.hasNext()) { 9102// final ResolveInfo resolveInfo = i.next(); 9103// if (isEnabledLP(resolveInfo.activityInfo)) { 9104// retList.add(resolveInfo); 9105// } 9106// } 9107// return retList; 9108// } 9109 9110 // Keys are String (activity class name), values are Activity. 9111 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9112 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9113 private int mFlags; 9114 } 9115 9116 private final class ServiceIntentResolver 9117 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9118 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9119 boolean defaultOnly, int userId) { 9120 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9121 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9122 } 9123 9124 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9125 int userId) { 9126 if (!sUserManager.exists(userId)) return null; 9127 mFlags = flags; 9128 return super.queryIntent(intent, resolvedType, 9129 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9130 } 9131 9132 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9133 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9134 if (!sUserManager.exists(userId)) return null; 9135 if (packageServices == null) { 9136 return null; 9137 } 9138 mFlags = flags; 9139 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9140 final int N = packageServices.size(); 9141 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9142 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9143 9144 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9145 for (int i = 0; i < N; ++i) { 9146 intentFilters = packageServices.get(i).intents; 9147 if (intentFilters != null && intentFilters.size() > 0) { 9148 PackageParser.ServiceIntentInfo[] array = 9149 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9150 intentFilters.toArray(array); 9151 listCut.add(array); 9152 } 9153 } 9154 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9155 } 9156 9157 public final void addService(PackageParser.Service s) { 9158 mServices.put(s.getComponentName(), s); 9159 if (DEBUG_SHOW_INFO) { 9160 Log.v(TAG, " " 9161 + (s.info.nonLocalizedLabel != null 9162 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9163 Log.v(TAG, " Class=" + s.info.name); 9164 } 9165 final int NI = s.intents.size(); 9166 int j; 9167 for (j=0; j<NI; j++) { 9168 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9169 if (DEBUG_SHOW_INFO) { 9170 Log.v(TAG, " IntentFilter:"); 9171 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9172 } 9173 if (!intent.debugCheck()) { 9174 Log.w(TAG, "==> For Service " + s.info.name); 9175 } 9176 addFilter(intent); 9177 } 9178 } 9179 9180 public final void removeService(PackageParser.Service s) { 9181 mServices.remove(s.getComponentName()); 9182 if (DEBUG_SHOW_INFO) { 9183 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9184 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9185 Log.v(TAG, " Class=" + s.info.name); 9186 } 9187 final int NI = s.intents.size(); 9188 int j; 9189 for (j=0; j<NI; j++) { 9190 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9191 if (DEBUG_SHOW_INFO) { 9192 Log.v(TAG, " IntentFilter:"); 9193 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9194 } 9195 removeFilter(intent); 9196 } 9197 } 9198 9199 @Override 9200 protected boolean allowFilterResult( 9201 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9202 ServiceInfo filterSi = filter.service.info; 9203 for (int i=dest.size()-1; i>=0; i--) { 9204 ServiceInfo destAi = dest.get(i).serviceInfo; 9205 if (destAi.name == filterSi.name 9206 && destAi.packageName == filterSi.packageName) { 9207 return false; 9208 } 9209 } 9210 return true; 9211 } 9212 9213 @Override 9214 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9215 return new PackageParser.ServiceIntentInfo[size]; 9216 } 9217 9218 @Override 9219 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9220 if (!sUserManager.exists(userId)) return true; 9221 PackageParser.Package p = filter.service.owner; 9222 if (p != null) { 9223 PackageSetting ps = (PackageSetting)p.mExtras; 9224 if (ps != null) { 9225 // System apps are never considered stopped for purposes of 9226 // filtering, because there may be no way for the user to 9227 // actually re-launch them. 9228 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9229 && ps.getStopped(userId); 9230 } 9231 } 9232 return false; 9233 } 9234 9235 @Override 9236 protected boolean isPackageForFilter(String packageName, 9237 PackageParser.ServiceIntentInfo info) { 9238 return packageName.equals(info.service.owner.packageName); 9239 } 9240 9241 @Override 9242 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9243 int match, int userId) { 9244 if (!sUserManager.exists(userId)) return null; 9245 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9246 if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) { 9247 return null; 9248 } 9249 final PackageParser.Service service = info.service; 9250 if (mSafeMode && (service.info.applicationInfo.flags 9251 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9252 return null; 9253 } 9254 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9255 if (ps == null) { 9256 return null; 9257 } 9258 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9259 ps.readUserState(userId), userId); 9260 if (si == null) { 9261 return null; 9262 } 9263 final ResolveInfo res = new ResolveInfo(); 9264 res.serviceInfo = si; 9265 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9266 res.filter = filter; 9267 } 9268 res.priority = info.getPriority(); 9269 res.preferredOrder = service.owner.mPreferredOrder; 9270 res.match = match; 9271 res.isDefault = info.hasDefault; 9272 res.labelRes = info.labelRes; 9273 res.nonLocalizedLabel = info.nonLocalizedLabel; 9274 res.icon = info.icon; 9275 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9276 return res; 9277 } 9278 9279 @Override 9280 protected void sortResults(List<ResolveInfo> results) { 9281 Collections.sort(results, mResolvePrioritySorter); 9282 } 9283 9284 @Override 9285 protected void dumpFilter(PrintWriter out, String prefix, 9286 PackageParser.ServiceIntentInfo filter) { 9287 out.print(prefix); out.print( 9288 Integer.toHexString(System.identityHashCode(filter.service))); 9289 out.print(' '); 9290 filter.service.printComponentShortName(out); 9291 out.print(" filter "); 9292 out.println(Integer.toHexString(System.identityHashCode(filter))); 9293 } 9294 9295 @Override 9296 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9297 return filter.service; 9298 } 9299 9300 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9301 PackageParser.Service service = (PackageParser.Service)label; 9302 out.print(prefix); out.print( 9303 Integer.toHexString(System.identityHashCode(service))); 9304 out.print(' '); 9305 service.printComponentShortName(out); 9306 if (count > 1) { 9307 out.print(" ("); out.print(count); out.print(" filters)"); 9308 } 9309 out.println(); 9310 } 9311 9312// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9313// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9314// final List<ResolveInfo> retList = Lists.newArrayList(); 9315// while (i.hasNext()) { 9316// final ResolveInfo resolveInfo = (ResolveInfo) i; 9317// if (isEnabledLP(resolveInfo.serviceInfo)) { 9318// retList.add(resolveInfo); 9319// } 9320// } 9321// return retList; 9322// } 9323 9324 // Keys are String (activity class name), values are Activity. 9325 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9326 = new ArrayMap<ComponentName, PackageParser.Service>(); 9327 private int mFlags; 9328 }; 9329 9330 private final class ProviderIntentResolver 9331 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9332 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9333 boolean defaultOnly, int userId) { 9334 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9335 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9336 } 9337 9338 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9339 int userId) { 9340 if (!sUserManager.exists(userId)) 9341 return null; 9342 mFlags = flags; 9343 return super.queryIntent(intent, resolvedType, 9344 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9345 } 9346 9347 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9348 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9349 if (!sUserManager.exists(userId)) 9350 return null; 9351 if (packageProviders == null) { 9352 return null; 9353 } 9354 mFlags = flags; 9355 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9356 final int N = packageProviders.size(); 9357 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9358 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9359 9360 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9361 for (int i = 0; i < N; ++i) { 9362 intentFilters = packageProviders.get(i).intents; 9363 if (intentFilters != null && intentFilters.size() > 0) { 9364 PackageParser.ProviderIntentInfo[] array = 9365 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9366 intentFilters.toArray(array); 9367 listCut.add(array); 9368 } 9369 } 9370 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9371 } 9372 9373 public final void addProvider(PackageParser.Provider p) { 9374 if (mProviders.containsKey(p.getComponentName())) { 9375 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9376 return; 9377 } 9378 9379 mProviders.put(p.getComponentName(), p); 9380 if (DEBUG_SHOW_INFO) { 9381 Log.v(TAG, " " 9382 + (p.info.nonLocalizedLabel != null 9383 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9384 Log.v(TAG, " Class=" + p.info.name); 9385 } 9386 final int NI = p.intents.size(); 9387 int j; 9388 for (j = 0; j < NI; j++) { 9389 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9390 if (DEBUG_SHOW_INFO) { 9391 Log.v(TAG, " IntentFilter:"); 9392 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9393 } 9394 if (!intent.debugCheck()) { 9395 Log.w(TAG, "==> For Provider " + p.info.name); 9396 } 9397 addFilter(intent); 9398 } 9399 } 9400 9401 public final void removeProvider(PackageParser.Provider p) { 9402 mProviders.remove(p.getComponentName()); 9403 if (DEBUG_SHOW_INFO) { 9404 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9405 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9406 Log.v(TAG, " Class=" + p.info.name); 9407 } 9408 final int NI = p.intents.size(); 9409 int j; 9410 for (j = 0; j < NI; j++) { 9411 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9412 if (DEBUG_SHOW_INFO) { 9413 Log.v(TAG, " IntentFilter:"); 9414 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9415 } 9416 removeFilter(intent); 9417 } 9418 } 9419 9420 @Override 9421 protected boolean allowFilterResult( 9422 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9423 ProviderInfo filterPi = filter.provider.info; 9424 for (int i = dest.size() - 1; i >= 0; i--) { 9425 ProviderInfo destPi = dest.get(i).providerInfo; 9426 if (destPi.name == filterPi.name 9427 && destPi.packageName == filterPi.packageName) { 9428 return false; 9429 } 9430 } 9431 return true; 9432 } 9433 9434 @Override 9435 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9436 return new PackageParser.ProviderIntentInfo[size]; 9437 } 9438 9439 @Override 9440 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9441 if (!sUserManager.exists(userId)) 9442 return true; 9443 PackageParser.Package p = filter.provider.owner; 9444 if (p != null) { 9445 PackageSetting ps = (PackageSetting) p.mExtras; 9446 if (ps != null) { 9447 // System apps are never considered stopped for purposes of 9448 // filtering, because there may be no way for the user to 9449 // actually re-launch them. 9450 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9451 && ps.getStopped(userId); 9452 } 9453 } 9454 return false; 9455 } 9456 9457 @Override 9458 protected boolean isPackageForFilter(String packageName, 9459 PackageParser.ProviderIntentInfo info) { 9460 return packageName.equals(info.provider.owner.packageName); 9461 } 9462 9463 @Override 9464 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9465 int match, int userId) { 9466 if (!sUserManager.exists(userId)) 9467 return null; 9468 final PackageParser.ProviderIntentInfo info = filter; 9469 if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) { 9470 return null; 9471 } 9472 final PackageParser.Provider provider = info.provider; 9473 if (mSafeMode && (provider.info.applicationInfo.flags 9474 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9475 return null; 9476 } 9477 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9478 if (ps == null) { 9479 return null; 9480 } 9481 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9482 ps.readUserState(userId), userId); 9483 if (pi == null) { 9484 return null; 9485 } 9486 final ResolveInfo res = new ResolveInfo(); 9487 res.providerInfo = pi; 9488 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9489 res.filter = filter; 9490 } 9491 res.priority = info.getPriority(); 9492 res.preferredOrder = provider.owner.mPreferredOrder; 9493 res.match = match; 9494 res.isDefault = info.hasDefault; 9495 res.labelRes = info.labelRes; 9496 res.nonLocalizedLabel = info.nonLocalizedLabel; 9497 res.icon = info.icon; 9498 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9499 return res; 9500 } 9501 9502 @Override 9503 protected void sortResults(List<ResolveInfo> results) { 9504 Collections.sort(results, mResolvePrioritySorter); 9505 } 9506 9507 @Override 9508 protected void dumpFilter(PrintWriter out, String prefix, 9509 PackageParser.ProviderIntentInfo filter) { 9510 out.print(prefix); 9511 out.print( 9512 Integer.toHexString(System.identityHashCode(filter.provider))); 9513 out.print(' '); 9514 filter.provider.printComponentShortName(out); 9515 out.print(" filter "); 9516 out.println(Integer.toHexString(System.identityHashCode(filter))); 9517 } 9518 9519 @Override 9520 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9521 return filter.provider; 9522 } 9523 9524 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9525 PackageParser.Provider provider = (PackageParser.Provider)label; 9526 out.print(prefix); out.print( 9527 Integer.toHexString(System.identityHashCode(provider))); 9528 out.print(' '); 9529 provider.printComponentShortName(out); 9530 if (count > 1) { 9531 out.print(" ("); out.print(count); out.print(" filters)"); 9532 } 9533 out.println(); 9534 } 9535 9536 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9537 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9538 private int mFlags; 9539 }; 9540 9541 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9542 new Comparator<ResolveInfo>() { 9543 public int compare(ResolveInfo r1, ResolveInfo r2) { 9544 int v1 = r1.priority; 9545 int v2 = r2.priority; 9546 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9547 if (v1 != v2) { 9548 return (v1 > v2) ? -1 : 1; 9549 } 9550 v1 = r1.preferredOrder; 9551 v2 = r2.preferredOrder; 9552 if (v1 != v2) { 9553 return (v1 > v2) ? -1 : 1; 9554 } 9555 if (r1.isDefault != r2.isDefault) { 9556 return r1.isDefault ? -1 : 1; 9557 } 9558 v1 = r1.match; 9559 v2 = r2.match; 9560 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9561 if (v1 != v2) { 9562 return (v1 > v2) ? -1 : 1; 9563 } 9564 if (r1.system != r2.system) { 9565 return r1.system ? -1 : 1; 9566 } 9567 return 0; 9568 } 9569 }; 9570 9571 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9572 new Comparator<ProviderInfo>() { 9573 public int compare(ProviderInfo p1, ProviderInfo p2) { 9574 final int v1 = p1.initOrder; 9575 final int v2 = p2.initOrder; 9576 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9577 } 9578 }; 9579 9580 final void sendPackageBroadcast(final String action, final String pkg, 9581 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9582 final int[] userIds) { 9583 mHandler.post(new Runnable() { 9584 @Override 9585 public void run() { 9586 try { 9587 final IActivityManager am = ActivityManagerNative.getDefault(); 9588 if (am == null) return; 9589 final int[] resolvedUserIds; 9590 if (userIds == null) { 9591 resolvedUserIds = am.getRunningUserIds(); 9592 } else { 9593 resolvedUserIds = userIds; 9594 } 9595 for (int id : resolvedUserIds) { 9596 final Intent intent = new Intent(action, 9597 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9598 if (extras != null) { 9599 intent.putExtras(extras); 9600 } 9601 if (targetPkg != null) { 9602 intent.setPackage(targetPkg); 9603 } 9604 // Modify the UID when posting to other users 9605 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9606 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9607 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9608 intent.putExtra(Intent.EXTRA_UID, uid); 9609 } 9610 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9611 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9612 if (DEBUG_BROADCASTS) { 9613 RuntimeException here = new RuntimeException("here"); 9614 here.fillInStackTrace(); 9615 Slog.d(TAG, "Sending to user " + id + ": " 9616 + intent.toShortString(false, true, false, false) 9617 + " " + intent.getExtras(), here); 9618 } 9619 am.broadcastIntent(null, intent, null, finishedReceiver, 9620 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9621 null, finishedReceiver != null, false, id); 9622 } 9623 } catch (RemoteException ex) { 9624 } 9625 } 9626 }); 9627 } 9628 9629 /** 9630 * Check if the external storage media is available. This is true if there 9631 * is a mounted external storage medium or if the external storage is 9632 * emulated. 9633 */ 9634 private boolean isExternalMediaAvailable() { 9635 return mMediaMounted || Environment.isExternalStorageEmulated(); 9636 } 9637 9638 @Override 9639 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9640 // writer 9641 synchronized (mPackages) { 9642 if (!isExternalMediaAvailable()) { 9643 // If the external storage is no longer mounted at this point, 9644 // the caller may not have been able to delete all of this 9645 // packages files and can not delete any more. Bail. 9646 return null; 9647 } 9648 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9649 if (lastPackage != null) { 9650 pkgs.remove(lastPackage); 9651 } 9652 if (pkgs.size() > 0) { 9653 return pkgs.get(0); 9654 } 9655 } 9656 return null; 9657 } 9658 9659 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9660 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9661 userId, andCode ? 1 : 0, packageName); 9662 if (mSystemReady) { 9663 msg.sendToTarget(); 9664 } else { 9665 if (mPostSystemReadyMessages == null) { 9666 mPostSystemReadyMessages = new ArrayList<>(); 9667 } 9668 mPostSystemReadyMessages.add(msg); 9669 } 9670 } 9671 9672 void startCleaningPackages() { 9673 // reader 9674 synchronized (mPackages) { 9675 if (!isExternalMediaAvailable()) { 9676 return; 9677 } 9678 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9679 return; 9680 } 9681 } 9682 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9683 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9684 IActivityManager am = ActivityManagerNative.getDefault(); 9685 if (am != null) { 9686 try { 9687 am.startService(null, intent, null, mContext.getOpPackageName(), 9688 UserHandle.USER_SYSTEM); 9689 } catch (RemoteException e) { 9690 } 9691 } 9692 } 9693 9694 @Override 9695 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9696 int installFlags, String installerPackageName, VerificationParams verificationParams, 9697 String packageAbiOverride) { 9698 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9699 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9700 } 9701 9702 @Override 9703 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9704 int installFlags, String installerPackageName, VerificationParams verificationParams, 9705 String packageAbiOverride, int userId) { 9706 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9707 9708 final int callingUid = Binder.getCallingUid(); 9709 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9710 9711 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9712 try { 9713 if (observer != null) { 9714 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9715 } 9716 } catch (RemoteException re) { 9717 } 9718 return; 9719 } 9720 9721 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9722 installFlags |= PackageManager.INSTALL_FROM_ADB; 9723 9724 } else { 9725 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9726 // about installerPackageName. 9727 9728 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9729 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9730 } 9731 9732 UserHandle user; 9733 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9734 user = UserHandle.ALL; 9735 } else { 9736 user = new UserHandle(userId); 9737 } 9738 9739 // Only system components can circumvent runtime permissions when installing. 9740 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9741 && mContext.checkCallingOrSelfPermission(Manifest.permission 9742 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9743 throw new SecurityException("You need the " 9744 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9745 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9746 } 9747 9748 verificationParams.setInstallerUid(callingUid); 9749 9750 final File originFile = new File(originPath); 9751 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9752 9753 final Message msg = mHandler.obtainMessage(INIT_COPY); 9754 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9755 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9756 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9757 msg.obj = params; 9758 9759 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9760 System.identityHashCode(msg.obj)); 9761 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9762 System.identityHashCode(msg.obj)); 9763 9764 mHandler.sendMessage(msg); 9765 } 9766 9767 void installStage(String packageName, File stagedDir, String stagedCid, 9768 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9769 String installerPackageName, int installerUid, UserHandle user) { 9770 final VerificationParams verifParams = new VerificationParams( 9771 null, sessionParams.originatingUri, sessionParams.referrerUri, 9772 sessionParams.originatingUid, null); 9773 verifParams.setInstallerUid(installerUid); 9774 9775 final OriginInfo origin; 9776 if (stagedDir != null) { 9777 origin = OriginInfo.fromStagedFile(stagedDir); 9778 } else { 9779 origin = OriginInfo.fromStagedContainer(stagedCid); 9780 } 9781 9782 final Message msg = mHandler.obtainMessage(INIT_COPY); 9783 final InstallParams params = new InstallParams(origin, null, observer, 9784 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9785 verifParams, user, sessionParams.abiOverride, 9786 sessionParams.grantedRuntimePermissions); 9787 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9788 msg.obj = params; 9789 9790 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9791 System.identityHashCode(msg.obj)); 9792 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9793 System.identityHashCode(msg.obj)); 9794 9795 mHandler.sendMessage(msg); 9796 } 9797 9798 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9799 Bundle extras = new Bundle(1); 9800 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9801 9802 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9803 packageName, extras, null, null, new int[] {userId}); 9804 try { 9805 IActivityManager am = ActivityManagerNative.getDefault(); 9806 final boolean isSystem = 9807 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9808 if (isSystem && am.isUserRunning(userId, 0)) { 9809 // The just-installed/enabled app is bundled on the system, so presumed 9810 // to be able to run automatically without needing an explicit launch. 9811 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9812 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9813 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9814 .setPackage(packageName); 9815 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9816 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9817 } 9818 } catch (RemoteException e) { 9819 // shouldn't happen 9820 Slog.w(TAG, "Unable to bootstrap installed package", e); 9821 } 9822 } 9823 9824 @Override 9825 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9826 int userId) { 9827 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9828 PackageSetting pkgSetting; 9829 final int uid = Binder.getCallingUid(); 9830 enforceCrossUserPermission(uid, userId, true, true, 9831 "setApplicationHiddenSetting for user " + userId); 9832 9833 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9834 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9835 return false; 9836 } 9837 9838 long callingId = Binder.clearCallingIdentity(); 9839 try { 9840 boolean sendAdded = false; 9841 boolean sendRemoved = false; 9842 // writer 9843 synchronized (mPackages) { 9844 pkgSetting = mSettings.mPackages.get(packageName); 9845 if (pkgSetting == null) { 9846 return false; 9847 } 9848 if (pkgSetting.getHidden(userId) != hidden) { 9849 pkgSetting.setHidden(hidden, userId); 9850 mSettings.writePackageRestrictionsLPr(userId); 9851 if (hidden) { 9852 sendRemoved = true; 9853 } else { 9854 sendAdded = true; 9855 } 9856 } 9857 } 9858 if (sendAdded) { 9859 sendPackageAddedForUser(packageName, pkgSetting, userId); 9860 return true; 9861 } 9862 if (sendRemoved) { 9863 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9864 "hiding pkg"); 9865 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9866 return true; 9867 } 9868 } finally { 9869 Binder.restoreCallingIdentity(callingId); 9870 } 9871 return false; 9872 } 9873 9874 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9875 int userId) { 9876 final PackageRemovedInfo info = new PackageRemovedInfo(); 9877 info.removedPackage = packageName; 9878 info.removedUsers = new int[] {userId}; 9879 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9880 info.sendBroadcast(false, false, false); 9881 } 9882 9883 /** 9884 * Returns true if application is not found or there was an error. Otherwise it returns 9885 * the hidden state of the package for the given user. 9886 */ 9887 @Override 9888 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9889 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9890 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9891 false, "getApplicationHidden for user " + userId); 9892 PackageSetting pkgSetting; 9893 long callingId = Binder.clearCallingIdentity(); 9894 try { 9895 // writer 9896 synchronized (mPackages) { 9897 pkgSetting = mSettings.mPackages.get(packageName); 9898 if (pkgSetting == null) { 9899 return true; 9900 } 9901 return pkgSetting.getHidden(userId); 9902 } 9903 } finally { 9904 Binder.restoreCallingIdentity(callingId); 9905 } 9906 } 9907 9908 /** 9909 * @hide 9910 */ 9911 @Override 9912 public int installExistingPackageAsUser(String packageName, int userId) { 9913 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9914 null); 9915 PackageSetting pkgSetting; 9916 final int uid = Binder.getCallingUid(); 9917 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9918 + userId); 9919 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9920 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9921 } 9922 9923 long callingId = Binder.clearCallingIdentity(); 9924 try { 9925 boolean sendAdded = false; 9926 9927 // writer 9928 synchronized (mPackages) { 9929 pkgSetting = mSettings.mPackages.get(packageName); 9930 if (pkgSetting == null) { 9931 return PackageManager.INSTALL_FAILED_INVALID_URI; 9932 } 9933 if (!pkgSetting.getInstalled(userId)) { 9934 pkgSetting.setInstalled(true, userId); 9935 pkgSetting.setHidden(false, userId); 9936 mSettings.writePackageRestrictionsLPr(userId); 9937 sendAdded = true; 9938 } 9939 } 9940 9941 if (sendAdded) { 9942 sendPackageAddedForUser(packageName, pkgSetting, userId); 9943 } 9944 } finally { 9945 Binder.restoreCallingIdentity(callingId); 9946 } 9947 9948 return PackageManager.INSTALL_SUCCEEDED; 9949 } 9950 9951 boolean isUserRestricted(int userId, String restrictionKey) { 9952 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9953 if (restrictions.getBoolean(restrictionKey, false)) { 9954 Log.w(TAG, "User is restricted: " + restrictionKey); 9955 return true; 9956 } 9957 return false; 9958 } 9959 9960 @Override 9961 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9962 mContext.enforceCallingOrSelfPermission( 9963 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9964 "Only package verification agents can verify applications"); 9965 9966 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9967 final PackageVerificationResponse response = new PackageVerificationResponse( 9968 verificationCode, Binder.getCallingUid()); 9969 msg.arg1 = id; 9970 msg.obj = response; 9971 mHandler.sendMessage(msg); 9972 } 9973 9974 @Override 9975 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9976 long millisecondsToDelay) { 9977 mContext.enforceCallingOrSelfPermission( 9978 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9979 "Only package verification agents can extend verification timeouts"); 9980 9981 final PackageVerificationState state = mPendingVerification.get(id); 9982 final PackageVerificationResponse response = new PackageVerificationResponse( 9983 verificationCodeAtTimeout, Binder.getCallingUid()); 9984 9985 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9986 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9987 } 9988 if (millisecondsToDelay < 0) { 9989 millisecondsToDelay = 0; 9990 } 9991 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9992 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9993 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9994 } 9995 9996 if ((state != null) && !state.timeoutExtended()) { 9997 state.extendTimeout(); 9998 9999 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10000 msg.arg1 = id; 10001 msg.obj = response; 10002 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10003 } 10004 } 10005 10006 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10007 int verificationCode, UserHandle user) { 10008 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10009 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10010 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10011 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10012 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10013 10014 mContext.sendBroadcastAsUser(intent, user, 10015 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10016 } 10017 10018 private ComponentName matchComponentForVerifier(String packageName, 10019 List<ResolveInfo> receivers) { 10020 ActivityInfo targetReceiver = null; 10021 10022 final int NR = receivers.size(); 10023 for (int i = 0; i < NR; i++) { 10024 final ResolveInfo info = receivers.get(i); 10025 if (info.activityInfo == null) { 10026 continue; 10027 } 10028 10029 if (packageName.equals(info.activityInfo.packageName)) { 10030 targetReceiver = info.activityInfo; 10031 break; 10032 } 10033 } 10034 10035 if (targetReceiver == null) { 10036 return null; 10037 } 10038 10039 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10040 } 10041 10042 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10043 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10044 if (pkgInfo.verifiers.length == 0) { 10045 return null; 10046 } 10047 10048 final int N = pkgInfo.verifiers.length; 10049 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10050 for (int i = 0; i < N; i++) { 10051 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10052 10053 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10054 receivers); 10055 if (comp == null) { 10056 continue; 10057 } 10058 10059 final int verifierUid = getUidForVerifier(verifierInfo); 10060 if (verifierUid == -1) { 10061 continue; 10062 } 10063 10064 if (DEBUG_VERIFY) { 10065 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10066 + " with the correct signature"); 10067 } 10068 sufficientVerifiers.add(comp); 10069 verificationState.addSufficientVerifier(verifierUid); 10070 } 10071 10072 return sufficientVerifiers; 10073 } 10074 10075 private int getUidForVerifier(VerifierInfo verifierInfo) { 10076 synchronized (mPackages) { 10077 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10078 if (pkg == null) { 10079 return -1; 10080 } else if (pkg.mSignatures.length != 1) { 10081 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10082 + " has more than one signature; ignoring"); 10083 return -1; 10084 } 10085 10086 /* 10087 * If the public key of the package's signature does not match 10088 * our expected public key, then this is a different package and 10089 * we should skip. 10090 */ 10091 10092 final byte[] expectedPublicKey; 10093 try { 10094 final Signature verifierSig = pkg.mSignatures[0]; 10095 final PublicKey publicKey = verifierSig.getPublicKey(); 10096 expectedPublicKey = publicKey.getEncoded(); 10097 } catch (CertificateException e) { 10098 return -1; 10099 } 10100 10101 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10102 10103 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10104 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10105 + " does not have the expected public key; ignoring"); 10106 return -1; 10107 } 10108 10109 return pkg.applicationInfo.uid; 10110 } 10111 } 10112 10113 @Override 10114 public void finishPackageInstall(int token) { 10115 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10116 10117 if (DEBUG_INSTALL) { 10118 Slog.v(TAG, "BM finishing package install for " + token); 10119 } 10120 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10121 10122 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10123 mHandler.sendMessage(msg); 10124 } 10125 10126 /** 10127 * Get the verification agent timeout. 10128 * 10129 * @return verification timeout in milliseconds 10130 */ 10131 private long getVerificationTimeout() { 10132 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10133 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10134 DEFAULT_VERIFICATION_TIMEOUT); 10135 } 10136 10137 /** 10138 * Get the default verification agent response code. 10139 * 10140 * @return default verification response code 10141 */ 10142 private int getDefaultVerificationResponse() { 10143 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10144 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10145 DEFAULT_VERIFICATION_RESPONSE); 10146 } 10147 10148 /** 10149 * Check whether or not package verification has been enabled. 10150 * 10151 * @return true if verification should be performed 10152 */ 10153 private boolean isVerificationEnabled(int userId, int installFlags) { 10154 if (!DEFAULT_VERIFY_ENABLE) { 10155 return false; 10156 } 10157 // TODO: fix b/25118622; don't bypass verification 10158 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10159 return false; 10160 } 10161 10162 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10163 10164 // Check if installing from ADB 10165 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10166 // Do not run verification in a test harness environment 10167 if (ActivityManager.isRunningInTestHarness()) { 10168 return false; 10169 } 10170 if (ensureVerifyAppsEnabled) { 10171 return true; 10172 } 10173 // Check if the developer does not want package verification for ADB installs 10174 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10175 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10176 return false; 10177 } 10178 } 10179 10180 if (ensureVerifyAppsEnabled) { 10181 return true; 10182 } 10183 10184 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10185 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10186 } 10187 10188 @Override 10189 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10190 throws RemoteException { 10191 mContext.enforceCallingOrSelfPermission( 10192 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10193 "Only intentfilter verification agents can verify applications"); 10194 10195 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10196 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10197 Binder.getCallingUid(), verificationCode, failedDomains); 10198 msg.arg1 = id; 10199 msg.obj = response; 10200 mHandler.sendMessage(msg); 10201 } 10202 10203 @Override 10204 public int getIntentVerificationStatus(String packageName, int userId) { 10205 synchronized (mPackages) { 10206 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10207 } 10208 } 10209 10210 @Override 10211 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10212 mContext.enforceCallingOrSelfPermission( 10213 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10214 10215 boolean result = false; 10216 synchronized (mPackages) { 10217 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10218 } 10219 if (result) { 10220 scheduleWritePackageRestrictionsLocked(userId); 10221 } 10222 return result; 10223 } 10224 10225 @Override 10226 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10227 synchronized (mPackages) { 10228 return mSettings.getIntentFilterVerificationsLPr(packageName); 10229 } 10230 } 10231 10232 @Override 10233 public List<IntentFilter> getAllIntentFilters(String packageName) { 10234 if (TextUtils.isEmpty(packageName)) { 10235 return Collections.<IntentFilter>emptyList(); 10236 } 10237 synchronized (mPackages) { 10238 PackageParser.Package pkg = mPackages.get(packageName); 10239 if (pkg == null || pkg.activities == null) { 10240 return Collections.<IntentFilter>emptyList(); 10241 } 10242 final int count = pkg.activities.size(); 10243 ArrayList<IntentFilter> result = new ArrayList<>(); 10244 for (int n=0; n<count; n++) { 10245 PackageParser.Activity activity = pkg.activities.get(n); 10246 if (activity.intents != null || activity.intents.size() > 0) { 10247 result.addAll(activity.intents); 10248 } 10249 } 10250 return result; 10251 } 10252 } 10253 10254 @Override 10255 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10256 mContext.enforceCallingOrSelfPermission( 10257 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10258 10259 synchronized (mPackages) { 10260 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10261 if (packageName != null) { 10262 result |= updateIntentVerificationStatus(packageName, 10263 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10264 userId); 10265 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10266 packageName, userId); 10267 } 10268 return result; 10269 } 10270 } 10271 10272 @Override 10273 public String getDefaultBrowserPackageName(int userId) { 10274 synchronized (mPackages) { 10275 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10276 } 10277 } 10278 10279 /** 10280 * Get the "allow unknown sources" setting. 10281 * 10282 * @return the current "allow unknown sources" setting 10283 */ 10284 private int getUnknownSourcesSettings() { 10285 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10286 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10287 -1); 10288 } 10289 10290 @Override 10291 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10292 final int uid = Binder.getCallingUid(); 10293 // writer 10294 synchronized (mPackages) { 10295 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10296 if (targetPackageSetting == null) { 10297 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10298 } 10299 10300 PackageSetting installerPackageSetting; 10301 if (installerPackageName != null) { 10302 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10303 if (installerPackageSetting == null) { 10304 throw new IllegalArgumentException("Unknown installer package: " 10305 + installerPackageName); 10306 } 10307 } else { 10308 installerPackageSetting = null; 10309 } 10310 10311 Signature[] callerSignature; 10312 Object obj = mSettings.getUserIdLPr(uid); 10313 if (obj != null) { 10314 if (obj instanceof SharedUserSetting) { 10315 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10316 } else if (obj instanceof PackageSetting) { 10317 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10318 } else { 10319 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10320 } 10321 } else { 10322 throw new SecurityException("Unknown calling uid " + uid); 10323 } 10324 10325 // Verify: can't set installerPackageName to a package that is 10326 // not signed with the same cert as the caller. 10327 if (installerPackageSetting != null) { 10328 if (compareSignatures(callerSignature, 10329 installerPackageSetting.signatures.mSignatures) 10330 != PackageManager.SIGNATURE_MATCH) { 10331 throw new SecurityException( 10332 "Caller does not have same cert as new installer package " 10333 + installerPackageName); 10334 } 10335 } 10336 10337 // Verify: if target already has an installer package, it must 10338 // be signed with the same cert as the caller. 10339 if (targetPackageSetting.installerPackageName != null) { 10340 PackageSetting setting = mSettings.mPackages.get( 10341 targetPackageSetting.installerPackageName); 10342 // If the currently set package isn't valid, then it's always 10343 // okay to change it. 10344 if (setting != null) { 10345 if (compareSignatures(callerSignature, 10346 setting.signatures.mSignatures) 10347 != PackageManager.SIGNATURE_MATCH) { 10348 throw new SecurityException( 10349 "Caller does not have same cert as old installer package " 10350 + targetPackageSetting.installerPackageName); 10351 } 10352 } 10353 } 10354 10355 // Okay! 10356 targetPackageSetting.installerPackageName = installerPackageName; 10357 scheduleWriteSettingsLocked(); 10358 } 10359 } 10360 10361 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10362 // Queue up an async operation since the package installation may take a little while. 10363 mHandler.post(new Runnable() { 10364 public void run() { 10365 mHandler.removeCallbacks(this); 10366 // Result object to be returned 10367 PackageInstalledInfo res = new PackageInstalledInfo(); 10368 res.returnCode = currentStatus; 10369 res.uid = -1; 10370 res.pkg = null; 10371 res.removedInfo = new PackageRemovedInfo(); 10372 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10373 args.doPreInstall(res.returnCode); 10374 synchronized (mInstallLock) { 10375 installPackageTracedLI(args, res); 10376 } 10377 args.doPostInstall(res.returnCode, res.uid); 10378 } 10379 10380 // A restore should be performed at this point if (a) the install 10381 // succeeded, (b) the operation is not an update, and (c) the new 10382 // package has not opted out of backup participation. 10383 final boolean update = res.removedInfo.removedPackage != null; 10384 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10385 boolean doRestore = !update 10386 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10387 10388 // Set up the post-install work request bookkeeping. This will be used 10389 // and cleaned up by the post-install event handling regardless of whether 10390 // there's a restore pass performed. Token values are >= 1. 10391 int token; 10392 if (mNextInstallToken < 0) mNextInstallToken = 1; 10393 token = mNextInstallToken++; 10394 10395 PostInstallData data = new PostInstallData(args, res); 10396 mRunningInstalls.put(token, data); 10397 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10398 10399 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10400 // Pass responsibility to the Backup Manager. It will perform a 10401 // restore if appropriate, then pass responsibility back to the 10402 // Package Manager to run the post-install observer callbacks 10403 // and broadcasts. 10404 IBackupManager bm = IBackupManager.Stub.asInterface( 10405 ServiceManager.getService(Context.BACKUP_SERVICE)); 10406 if (bm != null) { 10407 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10408 + " to BM for possible restore"); 10409 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10410 try { 10411 // TODO: http://b/22388012 10412 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10413 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10414 } else { 10415 doRestore = false; 10416 } 10417 } catch (RemoteException e) { 10418 // can't happen; the backup manager is local 10419 } catch (Exception e) { 10420 Slog.e(TAG, "Exception trying to enqueue restore", e); 10421 doRestore = false; 10422 } 10423 } else { 10424 Slog.e(TAG, "Backup Manager not found!"); 10425 doRestore = false; 10426 } 10427 } 10428 10429 if (!doRestore) { 10430 // No restore possible, or the Backup Manager was mysteriously not 10431 // available -- just fire the post-install work request directly. 10432 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10433 10434 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10435 10436 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10437 mHandler.sendMessage(msg); 10438 } 10439 } 10440 }); 10441 } 10442 10443 private abstract class HandlerParams { 10444 private static final int MAX_RETRIES = 4; 10445 10446 /** 10447 * Number of times startCopy() has been attempted and had a non-fatal 10448 * error. 10449 */ 10450 private int mRetries = 0; 10451 10452 /** User handle for the user requesting the information or installation. */ 10453 private final UserHandle mUser; 10454 String traceMethod; 10455 int traceCookie; 10456 10457 HandlerParams(UserHandle user) { 10458 mUser = user; 10459 } 10460 10461 UserHandle getUser() { 10462 return mUser; 10463 } 10464 10465 HandlerParams setTraceMethod(String traceMethod) { 10466 this.traceMethod = traceMethod; 10467 return this; 10468 } 10469 10470 HandlerParams setTraceCookie(int traceCookie) { 10471 this.traceCookie = traceCookie; 10472 return this; 10473 } 10474 10475 final boolean startCopy() { 10476 boolean res; 10477 try { 10478 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10479 10480 if (++mRetries > MAX_RETRIES) { 10481 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10482 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10483 handleServiceError(); 10484 return false; 10485 } else { 10486 handleStartCopy(); 10487 res = true; 10488 } 10489 } catch (RemoteException e) { 10490 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10491 mHandler.sendEmptyMessage(MCS_RECONNECT); 10492 res = false; 10493 } 10494 handleReturnCode(); 10495 return res; 10496 } 10497 10498 final void serviceError() { 10499 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10500 handleServiceError(); 10501 handleReturnCode(); 10502 } 10503 10504 abstract void handleStartCopy() throws RemoteException; 10505 abstract void handleServiceError(); 10506 abstract void handleReturnCode(); 10507 } 10508 10509 class MeasureParams extends HandlerParams { 10510 private final PackageStats mStats; 10511 private boolean mSuccess; 10512 10513 private final IPackageStatsObserver mObserver; 10514 10515 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10516 super(new UserHandle(stats.userHandle)); 10517 mObserver = observer; 10518 mStats = stats; 10519 } 10520 10521 @Override 10522 public String toString() { 10523 return "MeasureParams{" 10524 + Integer.toHexString(System.identityHashCode(this)) 10525 + " " + mStats.packageName + "}"; 10526 } 10527 10528 @Override 10529 void handleStartCopy() throws RemoteException { 10530 synchronized (mInstallLock) { 10531 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10532 } 10533 10534 if (mSuccess) { 10535 final boolean mounted; 10536 if (Environment.isExternalStorageEmulated()) { 10537 mounted = true; 10538 } else { 10539 final String status = Environment.getExternalStorageState(); 10540 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10541 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10542 } 10543 10544 if (mounted) { 10545 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10546 10547 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10548 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10549 10550 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10551 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10552 10553 // Always subtract cache size, since it's a subdirectory 10554 mStats.externalDataSize -= mStats.externalCacheSize; 10555 10556 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10557 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10558 10559 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10560 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10561 } 10562 } 10563 } 10564 10565 @Override 10566 void handleReturnCode() { 10567 if (mObserver != null) { 10568 try { 10569 mObserver.onGetStatsCompleted(mStats, mSuccess); 10570 } catch (RemoteException e) { 10571 Slog.i(TAG, "Observer no longer exists."); 10572 } 10573 } 10574 } 10575 10576 @Override 10577 void handleServiceError() { 10578 Slog.e(TAG, "Could not measure application " + mStats.packageName 10579 + " external storage"); 10580 } 10581 } 10582 10583 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10584 throws RemoteException { 10585 long result = 0; 10586 for (File path : paths) { 10587 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10588 } 10589 return result; 10590 } 10591 10592 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10593 for (File path : paths) { 10594 try { 10595 mcs.clearDirectory(path.getAbsolutePath()); 10596 } catch (RemoteException e) { 10597 } 10598 } 10599 } 10600 10601 static class OriginInfo { 10602 /** 10603 * Location where install is coming from, before it has been 10604 * copied/renamed into place. This could be a single monolithic APK 10605 * file, or a cluster directory. This location may be untrusted. 10606 */ 10607 final File file; 10608 final String cid; 10609 10610 /** 10611 * Flag indicating that {@link #file} or {@link #cid} has already been 10612 * staged, meaning downstream users don't need to defensively copy the 10613 * contents. 10614 */ 10615 final boolean staged; 10616 10617 /** 10618 * Flag indicating that {@link #file} or {@link #cid} is an already 10619 * installed app that is being moved. 10620 */ 10621 final boolean existing; 10622 10623 final String resolvedPath; 10624 final File resolvedFile; 10625 10626 static OriginInfo fromNothing() { 10627 return new OriginInfo(null, null, false, false); 10628 } 10629 10630 static OriginInfo fromUntrustedFile(File file) { 10631 return new OriginInfo(file, null, false, false); 10632 } 10633 10634 static OriginInfo fromExistingFile(File file) { 10635 return new OriginInfo(file, null, false, true); 10636 } 10637 10638 static OriginInfo fromStagedFile(File file) { 10639 return new OriginInfo(file, null, true, false); 10640 } 10641 10642 static OriginInfo fromStagedContainer(String cid) { 10643 return new OriginInfo(null, cid, true, false); 10644 } 10645 10646 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10647 this.file = file; 10648 this.cid = cid; 10649 this.staged = staged; 10650 this.existing = existing; 10651 10652 if (cid != null) { 10653 resolvedPath = PackageHelper.getSdDir(cid); 10654 resolvedFile = new File(resolvedPath); 10655 } else if (file != null) { 10656 resolvedPath = file.getAbsolutePath(); 10657 resolvedFile = file; 10658 } else { 10659 resolvedPath = null; 10660 resolvedFile = null; 10661 } 10662 } 10663 } 10664 10665 class MoveInfo { 10666 final int moveId; 10667 final String fromUuid; 10668 final String toUuid; 10669 final String packageName; 10670 final String dataAppName; 10671 final int appId; 10672 final String seinfo; 10673 10674 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10675 String dataAppName, int appId, String seinfo) { 10676 this.moveId = moveId; 10677 this.fromUuid = fromUuid; 10678 this.toUuid = toUuid; 10679 this.packageName = packageName; 10680 this.dataAppName = dataAppName; 10681 this.appId = appId; 10682 this.seinfo = seinfo; 10683 } 10684 } 10685 10686 class InstallParams extends HandlerParams { 10687 final OriginInfo origin; 10688 final MoveInfo move; 10689 final IPackageInstallObserver2 observer; 10690 int installFlags; 10691 final String installerPackageName; 10692 final String volumeUuid; 10693 final VerificationParams verificationParams; 10694 private InstallArgs mArgs; 10695 private int mRet; 10696 final String packageAbiOverride; 10697 final String[] grantedRuntimePermissions; 10698 10699 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10700 int installFlags, String installerPackageName, String volumeUuid, 10701 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10702 String[] grantedPermissions) { 10703 super(user); 10704 this.origin = origin; 10705 this.move = move; 10706 this.observer = observer; 10707 this.installFlags = installFlags; 10708 this.installerPackageName = installerPackageName; 10709 this.volumeUuid = volumeUuid; 10710 this.verificationParams = verificationParams; 10711 this.packageAbiOverride = packageAbiOverride; 10712 this.grantedRuntimePermissions = grantedPermissions; 10713 } 10714 10715 @Override 10716 public String toString() { 10717 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10718 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10719 } 10720 10721 public ManifestDigest getManifestDigest() { 10722 if (verificationParams == null) { 10723 return null; 10724 } 10725 return verificationParams.getManifestDigest(); 10726 } 10727 10728 private int installLocationPolicy(PackageInfoLite pkgLite) { 10729 String packageName = pkgLite.packageName; 10730 int installLocation = pkgLite.installLocation; 10731 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10732 // reader 10733 synchronized (mPackages) { 10734 PackageParser.Package pkg = mPackages.get(packageName); 10735 if (pkg != null) { 10736 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10737 // Check for downgrading. 10738 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10739 try { 10740 checkDowngrade(pkg, pkgLite); 10741 } catch (PackageManagerException e) { 10742 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10743 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10744 } 10745 } 10746 // Check for updated system application. 10747 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10748 if (onSd) { 10749 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10750 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10751 } 10752 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10753 } else { 10754 if (onSd) { 10755 // Install flag overrides everything. 10756 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10757 } 10758 // If current upgrade specifies particular preference 10759 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10760 // Application explicitly specified internal. 10761 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10762 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10763 // App explictly prefers external. Let policy decide 10764 } else { 10765 // Prefer previous location 10766 if (isExternal(pkg)) { 10767 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10768 } 10769 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10770 } 10771 } 10772 } else { 10773 // Invalid install. Return error code 10774 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10775 } 10776 } 10777 } 10778 // All the special cases have been taken care of. 10779 // Return result based on recommended install location. 10780 if (onSd) { 10781 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10782 } 10783 return pkgLite.recommendedInstallLocation; 10784 } 10785 10786 /* 10787 * Invoke remote method to get package information and install 10788 * location values. Override install location based on default 10789 * policy if needed and then create install arguments based 10790 * on the install location. 10791 */ 10792 public void handleStartCopy() throws RemoteException { 10793 int ret = PackageManager.INSTALL_SUCCEEDED; 10794 10795 // If we're already staged, we've firmly committed to an install location 10796 if (origin.staged) { 10797 if (origin.file != null) { 10798 installFlags |= PackageManager.INSTALL_INTERNAL; 10799 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10800 } else if (origin.cid != null) { 10801 installFlags |= PackageManager.INSTALL_EXTERNAL; 10802 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10803 } else { 10804 throw new IllegalStateException("Invalid stage location"); 10805 } 10806 } 10807 10808 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10809 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10810 PackageInfoLite pkgLite = null; 10811 10812 if (onInt && onSd) { 10813 // Check if both bits are set. 10814 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10815 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10816 } else { 10817 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10818 packageAbiOverride); 10819 10820 /* 10821 * If we have too little free space, try to free cache 10822 * before giving up. 10823 */ 10824 if (!origin.staged && pkgLite.recommendedInstallLocation 10825 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10826 // TODO: focus freeing disk space on the target device 10827 final StorageManager storage = StorageManager.from(mContext); 10828 final long lowThreshold = storage.getStorageLowBytes( 10829 Environment.getDataDirectory()); 10830 10831 final long sizeBytes = mContainerService.calculateInstalledSize( 10832 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10833 10834 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10835 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10836 installFlags, packageAbiOverride); 10837 } 10838 10839 /* 10840 * The cache free must have deleted the file we 10841 * downloaded to install. 10842 * 10843 * TODO: fix the "freeCache" call to not delete 10844 * the file we care about. 10845 */ 10846 if (pkgLite.recommendedInstallLocation 10847 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10848 pkgLite.recommendedInstallLocation 10849 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10850 } 10851 } 10852 } 10853 10854 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10855 int loc = pkgLite.recommendedInstallLocation; 10856 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10857 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10858 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10859 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10860 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10861 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10862 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10863 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10864 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10865 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10866 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10867 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10868 } else { 10869 // Override with defaults if needed. 10870 loc = installLocationPolicy(pkgLite); 10871 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10872 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10873 } else if (!onSd && !onInt) { 10874 // Override install location with flags 10875 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10876 // Set the flag to install on external media. 10877 installFlags |= PackageManager.INSTALL_EXTERNAL; 10878 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10879 } else { 10880 // Make sure the flag for installing on external 10881 // media is unset 10882 installFlags |= PackageManager.INSTALL_INTERNAL; 10883 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10884 } 10885 } 10886 } 10887 } 10888 10889 final InstallArgs args = createInstallArgs(this); 10890 mArgs = args; 10891 10892 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10893 // TODO: http://b/22976637 10894 // Apps installed for "all" users use the device owner to verify the app 10895 UserHandle verifierUser = getUser(); 10896 if (verifierUser == UserHandle.ALL) { 10897 verifierUser = UserHandle.SYSTEM; 10898 } 10899 10900 /* 10901 * Determine if we have any installed package verifiers. If we 10902 * do, then we'll defer to them to verify the packages. 10903 */ 10904 final int requiredUid = mRequiredVerifierPackage == null ? -1 10905 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10906 if (!origin.existing && requiredUid != -1 10907 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10908 final Intent verification = new Intent( 10909 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10910 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10911 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10912 PACKAGE_MIME_TYPE); 10913 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10914 10915 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10916 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10917 verifierUser.getIdentifier()); 10918 10919 if (DEBUG_VERIFY) { 10920 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10921 + verification.toString() + " with " + pkgLite.verifiers.length 10922 + " optional verifiers"); 10923 } 10924 10925 final int verificationId = mPendingVerificationToken++; 10926 10927 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10928 10929 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10930 installerPackageName); 10931 10932 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10933 installFlags); 10934 10935 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10936 pkgLite.packageName); 10937 10938 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10939 pkgLite.versionCode); 10940 10941 if (verificationParams != null) { 10942 if (verificationParams.getVerificationURI() != null) { 10943 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10944 verificationParams.getVerificationURI()); 10945 } 10946 if (verificationParams.getOriginatingURI() != null) { 10947 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10948 verificationParams.getOriginatingURI()); 10949 } 10950 if (verificationParams.getReferrer() != null) { 10951 verification.putExtra(Intent.EXTRA_REFERRER, 10952 verificationParams.getReferrer()); 10953 } 10954 if (verificationParams.getOriginatingUid() >= 0) { 10955 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10956 verificationParams.getOriginatingUid()); 10957 } 10958 if (verificationParams.getInstallerUid() >= 0) { 10959 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10960 verificationParams.getInstallerUid()); 10961 } 10962 } 10963 10964 final PackageVerificationState verificationState = new PackageVerificationState( 10965 requiredUid, args); 10966 10967 mPendingVerification.append(verificationId, verificationState); 10968 10969 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10970 receivers, verificationState); 10971 10972 /* 10973 * If any sufficient verifiers were listed in the package 10974 * manifest, attempt to ask them. 10975 */ 10976 if (sufficientVerifiers != null) { 10977 final int N = sufficientVerifiers.size(); 10978 if (N == 0) { 10979 Slog.i(TAG, "Additional verifiers required, but none installed."); 10980 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10981 } else { 10982 for (int i = 0; i < N; i++) { 10983 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10984 10985 final Intent sufficientIntent = new Intent(verification); 10986 sufficientIntent.setComponent(verifierComponent); 10987 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10988 } 10989 } 10990 } 10991 10992 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10993 mRequiredVerifierPackage, receivers); 10994 if (ret == PackageManager.INSTALL_SUCCEEDED 10995 && mRequiredVerifierPackage != null) { 10996 Trace.asyncTraceBegin( 10997 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10998 /* 10999 * Send the intent to the required verification agent, 11000 * but only start the verification timeout after the 11001 * target BroadcastReceivers have run. 11002 */ 11003 verification.setComponent(requiredVerifierComponent); 11004 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11005 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11006 new BroadcastReceiver() { 11007 @Override 11008 public void onReceive(Context context, Intent intent) { 11009 final Message msg = mHandler 11010 .obtainMessage(CHECK_PENDING_VERIFICATION); 11011 msg.arg1 = verificationId; 11012 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11013 } 11014 }, null, 0, null, null); 11015 11016 /* 11017 * We don't want the copy to proceed until verification 11018 * succeeds, so null out this field. 11019 */ 11020 mArgs = null; 11021 } 11022 } else { 11023 /* 11024 * No package verification is enabled, so immediately start 11025 * the remote call to initiate copy using temporary file. 11026 */ 11027 ret = args.copyApk(mContainerService, true); 11028 } 11029 } 11030 11031 mRet = ret; 11032 } 11033 11034 @Override 11035 void handleReturnCode() { 11036 // If mArgs is null, then MCS couldn't be reached. When it 11037 // reconnects, it will try again to install. At that point, this 11038 // will succeed. 11039 if (mArgs != null) { 11040 processPendingInstall(mArgs, mRet); 11041 } 11042 } 11043 11044 @Override 11045 void handleServiceError() { 11046 mArgs = createInstallArgs(this); 11047 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11048 } 11049 11050 public boolean isForwardLocked() { 11051 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11052 } 11053 } 11054 11055 /** 11056 * Used during creation of InstallArgs 11057 * 11058 * @param installFlags package installation flags 11059 * @return true if should be installed on external storage 11060 */ 11061 private static boolean installOnExternalAsec(int installFlags) { 11062 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11063 return false; 11064 } 11065 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11066 return true; 11067 } 11068 return false; 11069 } 11070 11071 /** 11072 * Used during creation of InstallArgs 11073 * 11074 * @param installFlags package installation flags 11075 * @return true if should be installed as forward locked 11076 */ 11077 private static boolean installForwardLocked(int installFlags) { 11078 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11079 } 11080 11081 private InstallArgs createInstallArgs(InstallParams params) { 11082 if (params.move != null) { 11083 return new MoveInstallArgs(params); 11084 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11085 return new AsecInstallArgs(params); 11086 } else { 11087 return new FileInstallArgs(params); 11088 } 11089 } 11090 11091 /** 11092 * Create args that describe an existing installed package. Typically used 11093 * when cleaning up old installs, or used as a move source. 11094 */ 11095 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11096 String resourcePath, String[] instructionSets) { 11097 final boolean isInAsec; 11098 if (installOnExternalAsec(installFlags)) { 11099 /* Apps on SD card are always in ASEC containers. */ 11100 isInAsec = true; 11101 } else if (installForwardLocked(installFlags) 11102 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11103 /* 11104 * Forward-locked apps are only in ASEC containers if they're the 11105 * new style 11106 */ 11107 isInAsec = true; 11108 } else { 11109 isInAsec = false; 11110 } 11111 11112 if (isInAsec) { 11113 return new AsecInstallArgs(codePath, instructionSets, 11114 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11115 } else { 11116 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11117 } 11118 } 11119 11120 static abstract class InstallArgs { 11121 /** @see InstallParams#origin */ 11122 final OriginInfo origin; 11123 /** @see InstallParams#move */ 11124 final MoveInfo move; 11125 11126 final IPackageInstallObserver2 observer; 11127 // Always refers to PackageManager flags only 11128 final int installFlags; 11129 final String installerPackageName; 11130 final String volumeUuid; 11131 final ManifestDigest manifestDigest; 11132 final UserHandle user; 11133 final String abiOverride; 11134 final String[] installGrantPermissions; 11135 /** If non-null, drop an async trace when the install completes */ 11136 final String traceMethod; 11137 final int traceCookie; 11138 11139 // The list of instruction sets supported by this app. This is currently 11140 // only used during the rmdex() phase to clean up resources. We can get rid of this 11141 // if we move dex files under the common app path. 11142 /* nullable */ String[] instructionSets; 11143 11144 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11145 int installFlags, String installerPackageName, String volumeUuid, 11146 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11147 String abiOverride, String[] installGrantPermissions, 11148 String traceMethod, int traceCookie) { 11149 this.origin = origin; 11150 this.move = move; 11151 this.installFlags = installFlags; 11152 this.observer = observer; 11153 this.installerPackageName = installerPackageName; 11154 this.volumeUuid = volumeUuid; 11155 this.manifestDigest = manifestDigest; 11156 this.user = user; 11157 this.instructionSets = instructionSets; 11158 this.abiOverride = abiOverride; 11159 this.installGrantPermissions = installGrantPermissions; 11160 this.traceMethod = traceMethod; 11161 this.traceCookie = traceCookie; 11162 } 11163 11164 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11165 abstract int doPreInstall(int status); 11166 11167 /** 11168 * Rename package into final resting place. All paths on the given 11169 * scanned package should be updated to reflect the rename. 11170 */ 11171 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11172 abstract int doPostInstall(int status, int uid); 11173 11174 /** @see PackageSettingBase#codePathString */ 11175 abstract String getCodePath(); 11176 /** @see PackageSettingBase#resourcePathString */ 11177 abstract String getResourcePath(); 11178 11179 // Need installer lock especially for dex file removal. 11180 abstract void cleanUpResourcesLI(); 11181 abstract boolean doPostDeleteLI(boolean delete); 11182 11183 /** 11184 * Called before the source arguments are copied. This is used mostly 11185 * for MoveParams when it needs to read the source file to put it in the 11186 * destination. 11187 */ 11188 int doPreCopy() { 11189 return PackageManager.INSTALL_SUCCEEDED; 11190 } 11191 11192 /** 11193 * Called after the source arguments are copied. This is used mostly for 11194 * MoveParams when it needs to read the source file to put it in the 11195 * destination. 11196 * 11197 * @return 11198 */ 11199 int doPostCopy(int uid) { 11200 return PackageManager.INSTALL_SUCCEEDED; 11201 } 11202 11203 protected boolean isFwdLocked() { 11204 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11205 } 11206 11207 protected boolean isExternalAsec() { 11208 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11209 } 11210 11211 UserHandle getUser() { 11212 return user; 11213 } 11214 } 11215 11216 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11217 if (!allCodePaths.isEmpty()) { 11218 if (instructionSets == null) { 11219 throw new IllegalStateException("instructionSet == null"); 11220 } 11221 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11222 for (String codePath : allCodePaths) { 11223 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11224 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11225 if (retCode < 0) { 11226 Slog.w(TAG, "Couldn't remove dex file for package: " 11227 + " at location " + codePath + ", retcode=" + retCode); 11228 // we don't consider this to be a failure of the core package deletion 11229 } 11230 } 11231 } 11232 } 11233 } 11234 11235 /** 11236 * Logic to handle installation of non-ASEC applications, including copying 11237 * and renaming logic. 11238 */ 11239 class FileInstallArgs extends InstallArgs { 11240 private File codeFile; 11241 private File resourceFile; 11242 11243 // Example topology: 11244 // /data/app/com.example/base.apk 11245 // /data/app/com.example/split_foo.apk 11246 // /data/app/com.example/lib/arm/libfoo.so 11247 // /data/app/com.example/lib/arm64/libfoo.so 11248 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11249 11250 /** New install */ 11251 FileInstallArgs(InstallParams params) { 11252 super(params.origin, params.move, params.observer, params.installFlags, 11253 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11254 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11255 params.grantedRuntimePermissions, 11256 params.traceMethod, params.traceCookie); 11257 if (isFwdLocked()) { 11258 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11259 } 11260 } 11261 11262 /** Existing install */ 11263 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11264 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11265 null, null, null, 0); 11266 this.codeFile = (codePath != null) ? new File(codePath) : null; 11267 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11268 } 11269 11270 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11271 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11272 try { 11273 return doCopyApk(imcs, temp); 11274 } finally { 11275 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11276 } 11277 } 11278 11279 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11280 if (origin.staged) { 11281 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11282 codeFile = origin.file; 11283 resourceFile = origin.file; 11284 return PackageManager.INSTALL_SUCCEEDED; 11285 } 11286 11287 try { 11288 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11289 codeFile = tempDir; 11290 resourceFile = tempDir; 11291 } catch (IOException e) { 11292 Slog.w(TAG, "Failed to create copy file: " + e); 11293 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11294 } 11295 11296 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11297 @Override 11298 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11299 if (!FileUtils.isValidExtFilename(name)) { 11300 throw new IllegalArgumentException("Invalid filename: " + name); 11301 } 11302 try { 11303 final File file = new File(codeFile, name); 11304 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11305 O_RDWR | O_CREAT, 0644); 11306 Os.chmod(file.getAbsolutePath(), 0644); 11307 return new ParcelFileDescriptor(fd); 11308 } catch (ErrnoException e) { 11309 throw new RemoteException("Failed to open: " + e.getMessage()); 11310 } 11311 } 11312 }; 11313 11314 int ret = PackageManager.INSTALL_SUCCEEDED; 11315 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11316 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11317 Slog.e(TAG, "Failed to copy package"); 11318 return ret; 11319 } 11320 11321 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11322 NativeLibraryHelper.Handle handle = null; 11323 try { 11324 handle = NativeLibraryHelper.Handle.create(codeFile); 11325 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11326 abiOverride); 11327 } catch (IOException e) { 11328 Slog.e(TAG, "Copying native libraries failed", e); 11329 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11330 } finally { 11331 IoUtils.closeQuietly(handle); 11332 } 11333 11334 return ret; 11335 } 11336 11337 int doPreInstall(int status) { 11338 if (status != PackageManager.INSTALL_SUCCEEDED) { 11339 cleanUp(); 11340 } 11341 return status; 11342 } 11343 11344 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11345 if (status != PackageManager.INSTALL_SUCCEEDED) { 11346 cleanUp(); 11347 return false; 11348 } 11349 11350 final File targetDir = codeFile.getParentFile(); 11351 final File beforeCodeFile = codeFile; 11352 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11353 11354 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11355 try { 11356 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11357 } catch (ErrnoException e) { 11358 Slog.w(TAG, "Failed to rename", e); 11359 return false; 11360 } 11361 11362 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11363 Slog.w(TAG, "Failed to restorecon"); 11364 return false; 11365 } 11366 11367 // Reflect the rename internally 11368 codeFile = afterCodeFile; 11369 resourceFile = afterCodeFile; 11370 11371 // Reflect the rename in scanned details 11372 pkg.codePath = afterCodeFile.getAbsolutePath(); 11373 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11374 pkg.baseCodePath); 11375 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11376 pkg.splitCodePaths); 11377 11378 // Reflect the rename in app info 11379 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11380 pkg.applicationInfo.setCodePath(pkg.codePath); 11381 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11382 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11383 pkg.applicationInfo.setResourcePath(pkg.codePath); 11384 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11385 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11386 11387 return true; 11388 } 11389 11390 int doPostInstall(int status, int uid) { 11391 if (status != PackageManager.INSTALL_SUCCEEDED) { 11392 cleanUp(); 11393 } 11394 return status; 11395 } 11396 11397 @Override 11398 String getCodePath() { 11399 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11400 } 11401 11402 @Override 11403 String getResourcePath() { 11404 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11405 } 11406 11407 private boolean cleanUp() { 11408 if (codeFile == null || !codeFile.exists()) { 11409 return false; 11410 } 11411 11412 if (codeFile.isDirectory()) { 11413 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11414 } else { 11415 codeFile.delete(); 11416 } 11417 11418 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11419 resourceFile.delete(); 11420 } 11421 11422 return true; 11423 } 11424 11425 void cleanUpResourcesLI() { 11426 // Try enumerating all code paths before deleting 11427 List<String> allCodePaths = Collections.EMPTY_LIST; 11428 if (codeFile != null && codeFile.exists()) { 11429 try { 11430 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11431 allCodePaths = pkg.getAllCodePaths(); 11432 } catch (PackageParserException e) { 11433 // Ignored; we tried our best 11434 } 11435 } 11436 11437 cleanUp(); 11438 removeDexFiles(allCodePaths, instructionSets); 11439 } 11440 11441 boolean doPostDeleteLI(boolean delete) { 11442 // XXX err, shouldn't we respect the delete flag? 11443 cleanUpResourcesLI(); 11444 return true; 11445 } 11446 } 11447 11448 private boolean isAsecExternal(String cid) { 11449 final String asecPath = PackageHelper.getSdFilesystem(cid); 11450 return !asecPath.startsWith(mAsecInternalPath); 11451 } 11452 11453 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11454 PackageManagerException { 11455 if (copyRet < 0) { 11456 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11457 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11458 throw new PackageManagerException(copyRet, message); 11459 } 11460 } 11461 } 11462 11463 /** 11464 * Extract the MountService "container ID" from the full code path of an 11465 * .apk. 11466 */ 11467 static String cidFromCodePath(String fullCodePath) { 11468 int eidx = fullCodePath.lastIndexOf("/"); 11469 String subStr1 = fullCodePath.substring(0, eidx); 11470 int sidx = subStr1.lastIndexOf("/"); 11471 return subStr1.substring(sidx+1, eidx); 11472 } 11473 11474 /** 11475 * Logic to handle installation of ASEC applications, including copying and 11476 * renaming logic. 11477 */ 11478 class AsecInstallArgs extends InstallArgs { 11479 static final String RES_FILE_NAME = "pkg.apk"; 11480 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11481 11482 String cid; 11483 String packagePath; 11484 String resourcePath; 11485 11486 /** New install */ 11487 AsecInstallArgs(InstallParams params) { 11488 super(params.origin, params.move, params.observer, params.installFlags, 11489 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11490 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11491 params.grantedRuntimePermissions, 11492 params.traceMethod, params.traceCookie); 11493 } 11494 11495 /** Existing install */ 11496 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11497 boolean isExternal, boolean isForwardLocked) { 11498 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11499 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11500 instructionSets, null, null, null, 0); 11501 // Hackily pretend we're still looking at a full code path 11502 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11503 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11504 } 11505 11506 // Extract cid from fullCodePath 11507 int eidx = fullCodePath.lastIndexOf("/"); 11508 String subStr1 = fullCodePath.substring(0, eidx); 11509 int sidx = subStr1.lastIndexOf("/"); 11510 cid = subStr1.substring(sidx+1, eidx); 11511 setMountPath(subStr1); 11512 } 11513 11514 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11515 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11516 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11517 instructionSets, null, null, null, 0); 11518 this.cid = cid; 11519 setMountPath(PackageHelper.getSdDir(cid)); 11520 } 11521 11522 void createCopyFile() { 11523 cid = mInstallerService.allocateExternalStageCidLegacy(); 11524 } 11525 11526 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11527 if (origin.staged) { 11528 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11529 cid = origin.cid; 11530 setMountPath(PackageHelper.getSdDir(cid)); 11531 return PackageManager.INSTALL_SUCCEEDED; 11532 } 11533 11534 if (temp) { 11535 createCopyFile(); 11536 } else { 11537 /* 11538 * Pre-emptively destroy the container since it's destroyed if 11539 * copying fails due to it existing anyway. 11540 */ 11541 PackageHelper.destroySdDir(cid); 11542 } 11543 11544 final String newMountPath = imcs.copyPackageToContainer( 11545 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11546 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11547 11548 if (newMountPath != null) { 11549 setMountPath(newMountPath); 11550 return PackageManager.INSTALL_SUCCEEDED; 11551 } else { 11552 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11553 } 11554 } 11555 11556 @Override 11557 String getCodePath() { 11558 return packagePath; 11559 } 11560 11561 @Override 11562 String getResourcePath() { 11563 return resourcePath; 11564 } 11565 11566 int doPreInstall(int status) { 11567 if (status != PackageManager.INSTALL_SUCCEEDED) { 11568 // Destroy container 11569 PackageHelper.destroySdDir(cid); 11570 } else { 11571 boolean mounted = PackageHelper.isContainerMounted(cid); 11572 if (!mounted) { 11573 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11574 Process.SYSTEM_UID); 11575 if (newMountPath != null) { 11576 setMountPath(newMountPath); 11577 } else { 11578 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11579 } 11580 } 11581 } 11582 return status; 11583 } 11584 11585 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11586 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11587 String newMountPath = null; 11588 if (PackageHelper.isContainerMounted(cid)) { 11589 // Unmount the container 11590 if (!PackageHelper.unMountSdDir(cid)) { 11591 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11592 return false; 11593 } 11594 } 11595 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11596 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11597 " which might be stale. Will try to clean up."); 11598 // Clean up the stale container and proceed to recreate. 11599 if (!PackageHelper.destroySdDir(newCacheId)) { 11600 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11601 return false; 11602 } 11603 // Successfully cleaned up stale container. Try to rename again. 11604 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11605 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11606 + " inspite of cleaning it up."); 11607 return false; 11608 } 11609 } 11610 if (!PackageHelper.isContainerMounted(newCacheId)) { 11611 Slog.w(TAG, "Mounting container " + newCacheId); 11612 newMountPath = PackageHelper.mountSdDir(newCacheId, 11613 getEncryptKey(), Process.SYSTEM_UID); 11614 } else { 11615 newMountPath = PackageHelper.getSdDir(newCacheId); 11616 } 11617 if (newMountPath == null) { 11618 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11619 return false; 11620 } 11621 Log.i(TAG, "Succesfully renamed " + cid + 11622 " to " + newCacheId + 11623 " at new path: " + newMountPath); 11624 cid = newCacheId; 11625 11626 final File beforeCodeFile = new File(packagePath); 11627 setMountPath(newMountPath); 11628 final File afterCodeFile = new File(packagePath); 11629 11630 // Reflect the rename in scanned details 11631 pkg.codePath = afterCodeFile.getAbsolutePath(); 11632 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11633 pkg.baseCodePath); 11634 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11635 pkg.splitCodePaths); 11636 11637 // Reflect the rename in app info 11638 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11639 pkg.applicationInfo.setCodePath(pkg.codePath); 11640 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11641 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11642 pkg.applicationInfo.setResourcePath(pkg.codePath); 11643 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11644 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11645 11646 return true; 11647 } 11648 11649 private void setMountPath(String mountPath) { 11650 final File mountFile = new File(mountPath); 11651 11652 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11653 if (monolithicFile.exists()) { 11654 packagePath = monolithicFile.getAbsolutePath(); 11655 if (isFwdLocked()) { 11656 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11657 } else { 11658 resourcePath = packagePath; 11659 } 11660 } else { 11661 packagePath = mountFile.getAbsolutePath(); 11662 resourcePath = packagePath; 11663 } 11664 } 11665 11666 int doPostInstall(int status, int uid) { 11667 if (status != PackageManager.INSTALL_SUCCEEDED) { 11668 cleanUp(); 11669 } else { 11670 final int groupOwner; 11671 final String protectedFile; 11672 if (isFwdLocked()) { 11673 groupOwner = UserHandle.getSharedAppGid(uid); 11674 protectedFile = RES_FILE_NAME; 11675 } else { 11676 groupOwner = -1; 11677 protectedFile = null; 11678 } 11679 11680 if (uid < Process.FIRST_APPLICATION_UID 11681 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11682 Slog.e(TAG, "Failed to finalize " + cid); 11683 PackageHelper.destroySdDir(cid); 11684 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11685 } 11686 11687 boolean mounted = PackageHelper.isContainerMounted(cid); 11688 if (!mounted) { 11689 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11690 } 11691 } 11692 return status; 11693 } 11694 11695 private void cleanUp() { 11696 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11697 11698 // Destroy secure container 11699 PackageHelper.destroySdDir(cid); 11700 } 11701 11702 private List<String> getAllCodePaths() { 11703 final File codeFile = new File(getCodePath()); 11704 if (codeFile != null && codeFile.exists()) { 11705 try { 11706 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11707 return pkg.getAllCodePaths(); 11708 } catch (PackageParserException e) { 11709 // Ignored; we tried our best 11710 } 11711 } 11712 return Collections.EMPTY_LIST; 11713 } 11714 11715 void cleanUpResourcesLI() { 11716 // Enumerate all code paths before deleting 11717 cleanUpResourcesLI(getAllCodePaths()); 11718 } 11719 11720 private void cleanUpResourcesLI(List<String> allCodePaths) { 11721 cleanUp(); 11722 removeDexFiles(allCodePaths, instructionSets); 11723 } 11724 11725 String getPackageName() { 11726 return getAsecPackageName(cid); 11727 } 11728 11729 boolean doPostDeleteLI(boolean delete) { 11730 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11731 final List<String> allCodePaths = getAllCodePaths(); 11732 boolean mounted = PackageHelper.isContainerMounted(cid); 11733 if (mounted) { 11734 // Unmount first 11735 if (PackageHelper.unMountSdDir(cid)) { 11736 mounted = false; 11737 } 11738 } 11739 if (!mounted && delete) { 11740 cleanUpResourcesLI(allCodePaths); 11741 } 11742 return !mounted; 11743 } 11744 11745 @Override 11746 int doPreCopy() { 11747 if (isFwdLocked()) { 11748 if (!PackageHelper.fixSdPermissions(cid, 11749 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11750 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11751 } 11752 } 11753 11754 return PackageManager.INSTALL_SUCCEEDED; 11755 } 11756 11757 @Override 11758 int doPostCopy(int uid) { 11759 if (isFwdLocked()) { 11760 if (uid < Process.FIRST_APPLICATION_UID 11761 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11762 RES_FILE_NAME)) { 11763 Slog.e(TAG, "Failed to finalize " + cid); 11764 PackageHelper.destroySdDir(cid); 11765 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11766 } 11767 } 11768 11769 return PackageManager.INSTALL_SUCCEEDED; 11770 } 11771 } 11772 11773 /** 11774 * Logic to handle movement of existing installed applications. 11775 */ 11776 class MoveInstallArgs extends InstallArgs { 11777 private File codeFile; 11778 private File resourceFile; 11779 11780 /** New install */ 11781 MoveInstallArgs(InstallParams params) { 11782 super(params.origin, params.move, params.observer, params.installFlags, 11783 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11784 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11785 params.grantedRuntimePermissions, 11786 params.traceMethod, params.traceCookie); 11787 } 11788 11789 int copyApk(IMediaContainerService imcs, boolean temp) { 11790 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11791 + move.fromUuid + " to " + move.toUuid); 11792 synchronized (mInstaller) { 11793 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11794 move.dataAppName, move.appId, move.seinfo) != 0) { 11795 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11796 } 11797 } 11798 11799 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11800 resourceFile = codeFile; 11801 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11802 11803 return PackageManager.INSTALL_SUCCEEDED; 11804 } 11805 11806 int doPreInstall(int status) { 11807 if (status != PackageManager.INSTALL_SUCCEEDED) { 11808 cleanUp(move.toUuid); 11809 } 11810 return status; 11811 } 11812 11813 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11814 if (status != PackageManager.INSTALL_SUCCEEDED) { 11815 cleanUp(move.toUuid); 11816 return false; 11817 } 11818 11819 // Reflect the move in app info 11820 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11821 pkg.applicationInfo.setCodePath(pkg.codePath); 11822 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11823 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11824 pkg.applicationInfo.setResourcePath(pkg.codePath); 11825 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11826 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11827 11828 return true; 11829 } 11830 11831 int doPostInstall(int status, int uid) { 11832 if (status == PackageManager.INSTALL_SUCCEEDED) { 11833 cleanUp(move.fromUuid); 11834 } else { 11835 cleanUp(move.toUuid); 11836 } 11837 return status; 11838 } 11839 11840 @Override 11841 String getCodePath() { 11842 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11843 } 11844 11845 @Override 11846 String getResourcePath() { 11847 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11848 } 11849 11850 private boolean cleanUp(String volumeUuid) { 11851 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11852 move.dataAppName); 11853 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11854 synchronized (mInstallLock) { 11855 // Clean up both app data and code 11856 removeDataDirsLI(volumeUuid, move.packageName); 11857 if (codeFile.isDirectory()) { 11858 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11859 } else { 11860 codeFile.delete(); 11861 } 11862 } 11863 return true; 11864 } 11865 11866 void cleanUpResourcesLI() { 11867 throw new UnsupportedOperationException(); 11868 } 11869 11870 boolean doPostDeleteLI(boolean delete) { 11871 throw new UnsupportedOperationException(); 11872 } 11873 } 11874 11875 static String getAsecPackageName(String packageCid) { 11876 int idx = packageCid.lastIndexOf("-"); 11877 if (idx == -1) { 11878 return packageCid; 11879 } 11880 return packageCid.substring(0, idx); 11881 } 11882 11883 // Utility method used to create code paths based on package name and available index. 11884 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11885 String idxStr = ""; 11886 int idx = 1; 11887 // Fall back to default value of idx=1 if prefix is not 11888 // part of oldCodePath 11889 if (oldCodePath != null) { 11890 String subStr = oldCodePath; 11891 // Drop the suffix right away 11892 if (suffix != null && subStr.endsWith(suffix)) { 11893 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11894 } 11895 // If oldCodePath already contains prefix find out the 11896 // ending index to either increment or decrement. 11897 int sidx = subStr.lastIndexOf(prefix); 11898 if (sidx != -1) { 11899 subStr = subStr.substring(sidx + prefix.length()); 11900 if (subStr != null) { 11901 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11902 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11903 } 11904 try { 11905 idx = Integer.parseInt(subStr); 11906 if (idx <= 1) { 11907 idx++; 11908 } else { 11909 idx--; 11910 } 11911 } catch(NumberFormatException e) { 11912 } 11913 } 11914 } 11915 } 11916 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11917 return prefix + idxStr; 11918 } 11919 11920 private File getNextCodePath(File targetDir, String packageName) { 11921 int suffix = 1; 11922 File result; 11923 do { 11924 result = new File(targetDir, packageName + "-" + suffix); 11925 suffix++; 11926 } while (result.exists()); 11927 return result; 11928 } 11929 11930 // Utility method that returns the relative package path with respect 11931 // to the installation directory. Like say for /data/data/com.test-1.apk 11932 // string com.test-1 is returned. 11933 static String deriveCodePathName(String codePath) { 11934 if (codePath == null) { 11935 return null; 11936 } 11937 final File codeFile = new File(codePath); 11938 final String name = codeFile.getName(); 11939 if (codeFile.isDirectory()) { 11940 return name; 11941 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11942 final int lastDot = name.lastIndexOf('.'); 11943 return name.substring(0, lastDot); 11944 } else { 11945 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11946 return null; 11947 } 11948 } 11949 11950 class PackageInstalledInfo { 11951 String name; 11952 int uid; 11953 // The set of users that originally had this package installed. 11954 int[] origUsers; 11955 // The set of users that now have this package installed. 11956 int[] newUsers; 11957 PackageParser.Package pkg; 11958 int returnCode; 11959 String returnMsg; 11960 PackageRemovedInfo removedInfo; 11961 11962 public void setError(int code, String msg) { 11963 returnCode = code; 11964 returnMsg = msg; 11965 Slog.w(TAG, msg); 11966 } 11967 11968 public void setError(String msg, PackageParserException e) { 11969 returnCode = e.error; 11970 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11971 Slog.w(TAG, msg, e); 11972 } 11973 11974 public void setError(String msg, PackageManagerException e) { 11975 returnCode = e.error; 11976 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11977 Slog.w(TAG, msg, e); 11978 } 11979 11980 // In some error cases we want to convey more info back to the observer 11981 String origPackage; 11982 String origPermission; 11983 } 11984 11985 /* 11986 * Install a non-existing package. 11987 */ 11988 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11989 UserHandle user, String installerPackageName, String volumeUuid, 11990 PackageInstalledInfo res) { 11991 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11992 11993 // Remember this for later, in case we need to rollback this install 11994 String pkgName = pkg.packageName; 11995 11996 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11997 // TODO: b/23350563 11998 final boolean dataDirExists = Environment 11999 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12000 12001 synchronized(mPackages) { 12002 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12003 // A package with the same name is already installed, though 12004 // it has been renamed to an older name. The package we 12005 // are trying to install should be installed as an update to 12006 // the existing one, but that has not been requested, so bail. 12007 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12008 + " without first uninstalling package running as " 12009 + mSettings.mRenamedPackages.get(pkgName)); 12010 return; 12011 } 12012 if (mPackages.containsKey(pkgName)) { 12013 // Don't allow installation over an existing package with the same name. 12014 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12015 + " without first uninstalling."); 12016 return; 12017 } 12018 } 12019 12020 try { 12021 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12022 System.currentTimeMillis(), user); 12023 12024 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12025 // delete the partially installed application. the data directory will have to be 12026 // restored if it was already existing 12027 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12028 // remove package from internal structures. Note that we want deletePackageX to 12029 // delete the package data and cache directories that it created in 12030 // scanPackageLocked, unless those directories existed before we even tried to 12031 // install. 12032 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12033 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12034 res.removedInfo, true); 12035 } 12036 12037 } catch (PackageManagerException e) { 12038 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12039 } 12040 12041 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12042 } 12043 12044 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12045 // Can't rotate keys during boot or if sharedUser. 12046 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12047 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12048 return false; 12049 } 12050 // app is using upgradeKeySets; make sure all are valid 12051 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12052 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12053 for (int i = 0; i < upgradeKeySets.length; i++) { 12054 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12055 Slog.wtf(TAG, "Package " 12056 + (oldPs.name != null ? oldPs.name : "<null>") 12057 + " contains upgrade-key-set reference to unknown key-set: " 12058 + upgradeKeySets[i] 12059 + " reverting to signatures check."); 12060 return false; 12061 } 12062 } 12063 return true; 12064 } 12065 12066 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12067 // Upgrade keysets are being used. Determine if new package has a superset of the 12068 // required keys. 12069 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12070 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12071 for (int i = 0; i < upgradeKeySets.length; i++) { 12072 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12073 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12074 return true; 12075 } 12076 } 12077 return false; 12078 } 12079 12080 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12081 UserHandle user, String installerPackageName, String volumeUuid, 12082 PackageInstalledInfo res) { 12083 final PackageParser.Package oldPackage; 12084 final String pkgName = pkg.packageName; 12085 final int[] allUsers; 12086 final boolean[] perUserInstalled; 12087 12088 // First find the old package info and check signatures 12089 synchronized(mPackages) { 12090 oldPackage = mPackages.get(pkgName); 12091 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12092 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12093 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12094 if(!checkUpgradeKeySetLP(ps, pkg)) { 12095 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12096 "New package not signed by keys specified by upgrade-keysets: " 12097 + pkgName); 12098 return; 12099 } 12100 } else { 12101 // default to original signature matching 12102 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12103 != PackageManager.SIGNATURE_MATCH) { 12104 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12105 "New package has a different signature: " + pkgName); 12106 return; 12107 } 12108 } 12109 12110 // In case of rollback, remember per-user/profile install state 12111 allUsers = sUserManager.getUserIds(); 12112 perUserInstalled = new boolean[allUsers.length]; 12113 for (int i = 0; i < allUsers.length; i++) { 12114 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12115 } 12116 } 12117 12118 boolean sysPkg = (isSystemApp(oldPackage)); 12119 if (sysPkg) { 12120 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12121 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12122 } else { 12123 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12124 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12125 } 12126 } 12127 12128 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12129 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12130 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12131 String volumeUuid, PackageInstalledInfo res) { 12132 String pkgName = deletedPackage.packageName; 12133 boolean deletedPkg = true; 12134 boolean updatedSettings = false; 12135 12136 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12137 + deletedPackage); 12138 long origUpdateTime; 12139 if (pkg.mExtras != null) { 12140 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12141 } else { 12142 origUpdateTime = 0; 12143 } 12144 12145 // First delete the existing package while retaining the data directory 12146 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12147 res.removedInfo, true)) { 12148 // If the existing package wasn't successfully deleted 12149 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12150 deletedPkg = false; 12151 } else { 12152 // Successfully deleted the old package; proceed with replace. 12153 12154 // If deleted package lived in a container, give users a chance to 12155 // relinquish resources before killing. 12156 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12157 if (DEBUG_INSTALL) { 12158 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12159 } 12160 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12161 final ArrayList<String> pkgList = new ArrayList<String>(1); 12162 pkgList.add(deletedPackage.applicationInfo.packageName); 12163 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12164 } 12165 12166 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12167 try { 12168 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12169 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12170 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12171 perUserInstalled, res, user); 12172 updatedSettings = true; 12173 } catch (PackageManagerException e) { 12174 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12175 } 12176 } 12177 12178 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12179 // remove package from internal structures. Note that we want deletePackageX to 12180 // delete the package data and cache directories that it created in 12181 // scanPackageLocked, unless those directories existed before we even tried to 12182 // install. 12183 if(updatedSettings) { 12184 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12185 deletePackageLI( 12186 pkgName, null, true, allUsers, perUserInstalled, 12187 PackageManager.DELETE_KEEP_DATA, 12188 res.removedInfo, true); 12189 } 12190 // Since we failed to install the new package we need to restore the old 12191 // package that we deleted. 12192 if (deletedPkg) { 12193 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12194 File restoreFile = new File(deletedPackage.codePath); 12195 // Parse old package 12196 boolean oldExternal = isExternal(deletedPackage); 12197 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12198 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12199 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12200 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12201 try { 12202 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12203 null); 12204 } catch (PackageManagerException e) { 12205 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12206 + e.getMessage()); 12207 return; 12208 } 12209 // Restore of old package succeeded. Update permissions. 12210 // writer 12211 synchronized (mPackages) { 12212 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12213 UPDATE_PERMISSIONS_ALL); 12214 // can downgrade to reader 12215 mSettings.writeLPr(); 12216 } 12217 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12218 } 12219 } 12220 } 12221 12222 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12223 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12224 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12225 String volumeUuid, PackageInstalledInfo res) { 12226 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12227 + ", old=" + deletedPackage); 12228 boolean disabledSystem = false; 12229 boolean updatedSettings = false; 12230 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12231 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12232 != 0) { 12233 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12234 } 12235 String packageName = deletedPackage.packageName; 12236 if (packageName == null) { 12237 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12238 "Attempt to delete null packageName."); 12239 return; 12240 } 12241 PackageParser.Package oldPkg; 12242 PackageSetting oldPkgSetting; 12243 // reader 12244 synchronized (mPackages) { 12245 oldPkg = mPackages.get(packageName); 12246 oldPkgSetting = mSettings.mPackages.get(packageName); 12247 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12248 (oldPkgSetting == null)) { 12249 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12250 "Couldn't find package:" + packageName + " information"); 12251 return; 12252 } 12253 } 12254 12255 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12256 12257 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12258 res.removedInfo.removedPackage = packageName; 12259 // Remove existing system package 12260 removePackageLI(oldPkgSetting, true); 12261 // writer 12262 synchronized (mPackages) { 12263 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12264 if (!disabledSystem && deletedPackage != null) { 12265 // We didn't need to disable the .apk as a current system package, 12266 // which means we are replacing another update that is already 12267 // installed. We need to make sure to delete the older one's .apk. 12268 res.removedInfo.args = createInstallArgsForExisting(0, 12269 deletedPackage.applicationInfo.getCodePath(), 12270 deletedPackage.applicationInfo.getResourcePath(), 12271 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12272 } else { 12273 res.removedInfo.args = null; 12274 } 12275 } 12276 12277 // Successfully disabled the old package. Now proceed with re-installation 12278 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12279 12280 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12281 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12282 12283 PackageParser.Package newPackage = null; 12284 try { 12285 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12286 if (newPackage.mExtras != null) { 12287 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12288 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12289 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12290 12291 // is the update attempting to change shared user? that isn't going to work... 12292 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12293 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12294 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12295 + " to " + newPkgSetting.sharedUser); 12296 updatedSettings = true; 12297 } 12298 } 12299 12300 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12301 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12302 perUserInstalled, res, user); 12303 updatedSettings = true; 12304 } 12305 12306 } catch (PackageManagerException e) { 12307 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12308 } 12309 12310 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12311 // Re installation failed. Restore old information 12312 // Remove new pkg information 12313 if (newPackage != null) { 12314 removeInstalledPackageLI(newPackage, true); 12315 } 12316 // Add back the old system package 12317 try { 12318 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12319 } catch (PackageManagerException e) { 12320 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12321 } 12322 // Restore the old system information in Settings 12323 synchronized (mPackages) { 12324 if (disabledSystem) { 12325 mSettings.enableSystemPackageLPw(packageName); 12326 } 12327 if (updatedSettings) { 12328 mSettings.setInstallerPackageName(packageName, 12329 oldPkgSetting.installerPackageName); 12330 } 12331 mSettings.writeLPr(); 12332 } 12333 } 12334 } 12335 12336 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12337 // Collect all used permissions in the UID 12338 ArraySet<String> usedPermissions = new ArraySet<>(); 12339 final int packageCount = su.packages.size(); 12340 for (int i = 0; i < packageCount; i++) { 12341 PackageSetting ps = su.packages.valueAt(i); 12342 if (ps.pkg == null) { 12343 continue; 12344 } 12345 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12346 for (int j = 0; j < requestedPermCount; j++) { 12347 String permission = ps.pkg.requestedPermissions.get(j); 12348 BasePermission bp = mSettings.mPermissions.get(permission); 12349 if (bp != null) { 12350 usedPermissions.add(permission); 12351 } 12352 } 12353 } 12354 12355 PermissionsState permissionsState = su.getPermissionsState(); 12356 // Prune install permissions 12357 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12358 final int installPermCount = installPermStates.size(); 12359 for (int i = installPermCount - 1; i >= 0; i--) { 12360 PermissionState permissionState = installPermStates.get(i); 12361 if (!usedPermissions.contains(permissionState.getName())) { 12362 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12363 if (bp != null) { 12364 permissionsState.revokeInstallPermission(bp); 12365 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12366 PackageManager.MASK_PERMISSION_FLAGS, 0); 12367 } 12368 } 12369 } 12370 12371 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12372 12373 // Prune runtime permissions 12374 for (int userId : allUserIds) { 12375 List<PermissionState> runtimePermStates = permissionsState 12376 .getRuntimePermissionStates(userId); 12377 final int runtimePermCount = runtimePermStates.size(); 12378 for (int i = runtimePermCount - 1; i >= 0; i--) { 12379 PermissionState permissionState = runtimePermStates.get(i); 12380 if (!usedPermissions.contains(permissionState.getName())) { 12381 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12382 if (bp != null) { 12383 permissionsState.revokeRuntimePermission(bp, userId); 12384 permissionsState.updatePermissionFlags(bp, userId, 12385 PackageManager.MASK_PERMISSION_FLAGS, 0); 12386 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12387 runtimePermissionChangedUserIds, userId); 12388 } 12389 } 12390 } 12391 } 12392 12393 return runtimePermissionChangedUserIds; 12394 } 12395 12396 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12397 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12398 UserHandle user) { 12399 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12400 12401 String pkgName = newPackage.packageName; 12402 synchronized (mPackages) { 12403 //write settings. the installStatus will be incomplete at this stage. 12404 //note that the new package setting would have already been 12405 //added to mPackages. It hasn't been persisted yet. 12406 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12407 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12408 mSettings.writeLPr(); 12409 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12410 } 12411 12412 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12413 synchronized (mPackages) { 12414 updatePermissionsLPw(newPackage.packageName, newPackage, 12415 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12416 ? UPDATE_PERMISSIONS_ALL : 0)); 12417 // For system-bundled packages, we assume that installing an upgraded version 12418 // of the package implies that the user actually wants to run that new code, 12419 // so we enable the package. 12420 PackageSetting ps = mSettings.mPackages.get(pkgName); 12421 if (ps != null) { 12422 if (isSystemApp(newPackage)) { 12423 // NB: implicit assumption that system package upgrades apply to all users 12424 if (DEBUG_INSTALL) { 12425 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12426 } 12427 if (res.origUsers != null) { 12428 for (int userHandle : res.origUsers) { 12429 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12430 userHandle, installerPackageName); 12431 } 12432 } 12433 // Also convey the prior install/uninstall state 12434 if (allUsers != null && perUserInstalled != null) { 12435 for (int i = 0; i < allUsers.length; i++) { 12436 if (DEBUG_INSTALL) { 12437 Slog.d(TAG, " user " + allUsers[i] 12438 + " => " + perUserInstalled[i]); 12439 } 12440 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12441 } 12442 // these install state changes will be persisted in the 12443 // upcoming call to mSettings.writeLPr(). 12444 } 12445 } 12446 // It's implied that when a user requests installation, they want the app to be 12447 // installed and enabled. 12448 int userId = user.getIdentifier(); 12449 if (userId != UserHandle.USER_ALL) { 12450 ps.setInstalled(true, userId); 12451 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12452 } 12453 } 12454 res.name = pkgName; 12455 res.uid = newPackage.applicationInfo.uid; 12456 res.pkg = newPackage; 12457 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12458 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12459 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12460 //to update install status 12461 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12462 mSettings.writeLPr(); 12463 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12464 } 12465 12466 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12467 } 12468 12469 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12470 try { 12471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12472 installPackageLI(args, res); 12473 } finally { 12474 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12475 } 12476 } 12477 12478 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12479 final int installFlags = args.installFlags; 12480 final String installerPackageName = args.installerPackageName; 12481 final String volumeUuid = args.volumeUuid; 12482 final File tmpPackageFile = new File(args.getCodePath()); 12483 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12484 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12485 || (args.volumeUuid != null)); 12486 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12487 boolean replace = false; 12488 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12489 if (args.move != null) { 12490 // moving a complete application; perfom an initial scan on the new install location 12491 scanFlags |= SCAN_INITIAL; 12492 } 12493 // Result object to be returned 12494 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12495 12496 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12497 12498 // Retrieve PackageSettings and parse package 12499 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12500 | PackageParser.PARSE_ENFORCE_CODE 12501 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12502 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12503 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12504 PackageParser pp = new PackageParser(); 12505 pp.setSeparateProcesses(mSeparateProcesses); 12506 pp.setDisplayMetrics(mMetrics); 12507 12508 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12509 final PackageParser.Package pkg; 12510 try { 12511 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12512 } catch (PackageParserException e) { 12513 res.setError("Failed parse during installPackageLI", e); 12514 return; 12515 } finally { 12516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12517 } 12518 12519 // Mark that we have an install time CPU ABI override. 12520 pkg.cpuAbiOverride = args.abiOverride; 12521 12522 String pkgName = res.name = pkg.packageName; 12523 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12524 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12525 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12526 return; 12527 } 12528 } 12529 12530 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12531 try { 12532 pp.collectCertificates(pkg, parseFlags); 12533 } catch (PackageParserException e) { 12534 res.setError("Failed collect during installPackageLI", e); 12535 return; 12536 } finally { 12537 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12538 } 12539 12540 /* If the installer passed in a manifest digest, compare it now. */ 12541 if (args.manifestDigest != null) { 12542 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12543 try { 12544 pp.collectManifestDigest(pkg); 12545 } catch (PackageParserException e) { 12546 res.setError("Failed collect during installPackageLI", e); 12547 return; 12548 } finally { 12549 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12550 } 12551 12552 if (DEBUG_INSTALL) { 12553 final String parsedManifest = pkg.manifestDigest == null ? "null" 12554 : pkg.manifestDigest.toString(); 12555 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12556 + parsedManifest); 12557 } 12558 12559 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12560 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12561 return; 12562 } 12563 } else if (DEBUG_INSTALL) { 12564 final String parsedManifest = pkg.manifestDigest == null 12565 ? "null" : pkg.manifestDigest.toString(); 12566 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12567 } 12568 12569 // Get rid of all references to package scan path via parser. 12570 pp = null; 12571 String oldCodePath = null; 12572 boolean systemApp = false; 12573 synchronized (mPackages) { 12574 // Check if installing already existing package 12575 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12576 String oldName = mSettings.mRenamedPackages.get(pkgName); 12577 if (pkg.mOriginalPackages != null 12578 && pkg.mOriginalPackages.contains(oldName) 12579 && mPackages.containsKey(oldName)) { 12580 // This package is derived from an original package, 12581 // and this device has been updating from that original 12582 // name. We must continue using the original name, so 12583 // rename the new package here. 12584 pkg.setPackageName(oldName); 12585 pkgName = pkg.packageName; 12586 replace = true; 12587 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12588 + oldName + " pkgName=" + pkgName); 12589 } else if (mPackages.containsKey(pkgName)) { 12590 // This package, under its official name, already exists 12591 // on the device; we should replace it. 12592 replace = true; 12593 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12594 } 12595 12596 // Prevent apps opting out from runtime permissions 12597 if (replace) { 12598 PackageParser.Package oldPackage = mPackages.get(pkgName); 12599 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12600 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12601 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12602 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12603 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12604 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12605 + " doesn't support runtime permissions but the old" 12606 + " target SDK " + oldTargetSdk + " does."); 12607 return; 12608 } 12609 } 12610 } 12611 12612 PackageSetting ps = mSettings.mPackages.get(pkgName); 12613 if (ps != null) { 12614 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12615 12616 // Quick sanity check that we're signed correctly if updating; 12617 // we'll check this again later when scanning, but we want to 12618 // bail early here before tripping over redefined permissions. 12619 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12620 if (!checkUpgradeKeySetLP(ps, pkg)) { 12621 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12622 + pkg.packageName + " upgrade keys do not match the " 12623 + "previously installed version"); 12624 return; 12625 } 12626 } else { 12627 try { 12628 verifySignaturesLP(ps, pkg); 12629 } catch (PackageManagerException e) { 12630 res.setError(e.error, e.getMessage()); 12631 return; 12632 } 12633 } 12634 12635 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12636 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12637 systemApp = (ps.pkg.applicationInfo.flags & 12638 ApplicationInfo.FLAG_SYSTEM) != 0; 12639 } 12640 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12641 } 12642 12643 // Check whether the newly-scanned package wants to define an already-defined perm 12644 int N = pkg.permissions.size(); 12645 for (int i = N-1; i >= 0; i--) { 12646 PackageParser.Permission perm = pkg.permissions.get(i); 12647 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12648 if (bp != null) { 12649 // If the defining package is signed with our cert, it's okay. This 12650 // also includes the "updating the same package" case, of course. 12651 // "updating same package" could also involve key-rotation. 12652 final boolean sigsOk; 12653 if (bp.sourcePackage.equals(pkg.packageName) 12654 && (bp.packageSetting instanceof PackageSetting) 12655 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12656 scanFlags))) { 12657 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12658 } else { 12659 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12660 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12661 } 12662 if (!sigsOk) { 12663 // If the owning package is the system itself, we log but allow 12664 // install to proceed; we fail the install on all other permission 12665 // redefinitions. 12666 if (!bp.sourcePackage.equals("android")) { 12667 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12668 + pkg.packageName + " attempting to redeclare permission " 12669 + perm.info.name + " already owned by " + bp.sourcePackage); 12670 res.origPermission = perm.info.name; 12671 res.origPackage = bp.sourcePackage; 12672 return; 12673 } else { 12674 Slog.w(TAG, "Package " + pkg.packageName 12675 + " attempting to redeclare system permission " 12676 + perm.info.name + "; ignoring new declaration"); 12677 pkg.permissions.remove(i); 12678 } 12679 } 12680 } 12681 } 12682 12683 } 12684 12685 if (systemApp && onExternal) { 12686 // Disable updates to system apps on sdcard 12687 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12688 "Cannot install updates to system apps on sdcard"); 12689 return; 12690 } 12691 12692 if (args.move != null) { 12693 // We did an in-place move, so dex is ready to roll 12694 scanFlags |= SCAN_NO_DEX; 12695 scanFlags |= SCAN_MOVE; 12696 12697 synchronized (mPackages) { 12698 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12699 if (ps == null) { 12700 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12701 "Missing settings for moved package " + pkgName); 12702 } 12703 12704 // We moved the entire application as-is, so bring over the 12705 // previously derived ABI information. 12706 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12707 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12708 } 12709 12710 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12711 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12712 scanFlags |= SCAN_NO_DEX; 12713 12714 try { 12715 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12716 true /* extract libs */); 12717 } catch (PackageManagerException pme) { 12718 Slog.e(TAG, "Error deriving application ABI", pme); 12719 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12720 return; 12721 } 12722 12723 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12724 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12725 12726 int result = mPackageDexOptimizer 12727 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12728 false /* defer */, false /* inclDependencies */, 12729 true /*bootComplete*/, quickInstall /*useJit*/); 12730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12731 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12732 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12733 return; 12734 } 12735 } 12736 12737 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12738 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12739 return; 12740 } 12741 12742 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12743 12744 if (replace) { 12745 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12746 installerPackageName, volumeUuid, res); 12747 } else { 12748 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12749 args.user, installerPackageName, volumeUuid, res); 12750 } 12751 synchronized (mPackages) { 12752 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12753 if (ps != null) { 12754 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12755 } 12756 } 12757 } 12758 12759 private void startIntentFilterVerifications(int userId, boolean replacing, 12760 PackageParser.Package pkg) { 12761 if (mIntentFilterVerifierComponent == null) { 12762 Slog.w(TAG, "No IntentFilter verification will not be done as " 12763 + "there is no IntentFilterVerifier available!"); 12764 return; 12765 } 12766 12767 final int verifierUid = getPackageUid( 12768 mIntentFilterVerifierComponent.getPackageName(), 12769 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12770 12771 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12772 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12773 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12774 mHandler.sendMessage(msg); 12775 } 12776 12777 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12778 PackageParser.Package pkg) { 12779 int size = pkg.activities.size(); 12780 if (size == 0) { 12781 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12782 "No activity, so no need to verify any IntentFilter!"); 12783 return; 12784 } 12785 12786 final boolean hasDomainURLs = hasDomainURLs(pkg); 12787 if (!hasDomainURLs) { 12788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12789 "No domain URLs, so no need to verify any IntentFilter!"); 12790 return; 12791 } 12792 12793 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12794 + " if any IntentFilter from the " + size 12795 + " Activities needs verification ..."); 12796 12797 int count = 0; 12798 final String packageName = pkg.packageName; 12799 12800 synchronized (mPackages) { 12801 // If this is a new install and we see that we've already run verification for this 12802 // package, we have nothing to do: it means the state was restored from backup. 12803 if (!replacing) { 12804 IntentFilterVerificationInfo ivi = 12805 mSettings.getIntentFilterVerificationLPr(packageName); 12806 if (ivi != null) { 12807 if (DEBUG_DOMAIN_VERIFICATION) { 12808 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12809 + ivi.getStatusString()); 12810 } 12811 return; 12812 } 12813 } 12814 12815 // If any filters need to be verified, then all need to be. 12816 boolean needToVerify = false; 12817 for (PackageParser.Activity a : pkg.activities) { 12818 for (ActivityIntentInfo filter : a.intents) { 12819 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12820 if (DEBUG_DOMAIN_VERIFICATION) { 12821 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12822 } 12823 needToVerify = true; 12824 break; 12825 } 12826 } 12827 } 12828 12829 if (needToVerify) { 12830 final int verificationId = mIntentFilterVerificationToken++; 12831 for (PackageParser.Activity a : pkg.activities) { 12832 for (ActivityIntentInfo filter : a.intents) { 12833 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12834 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12835 "Verification needed for IntentFilter:" + filter.toString()); 12836 mIntentFilterVerifier.addOneIntentFilterVerification( 12837 verifierUid, userId, verificationId, filter, packageName); 12838 count++; 12839 } 12840 } 12841 } 12842 } 12843 } 12844 12845 if (count > 0) { 12846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12847 + " IntentFilter verification" + (count > 1 ? "s" : "") 12848 + " for userId:" + userId); 12849 mIntentFilterVerifier.startVerifications(userId); 12850 } else { 12851 if (DEBUG_DOMAIN_VERIFICATION) { 12852 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12853 } 12854 } 12855 } 12856 12857 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12858 final ComponentName cn = filter.activity.getComponentName(); 12859 final String packageName = cn.getPackageName(); 12860 12861 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12862 packageName); 12863 if (ivi == null) { 12864 return true; 12865 } 12866 int status = ivi.getStatus(); 12867 switch (status) { 12868 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12869 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12870 return true; 12871 12872 default: 12873 // Nothing to do 12874 return false; 12875 } 12876 } 12877 12878 private static boolean isMultiArch(PackageSetting ps) { 12879 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12880 } 12881 12882 private static boolean isMultiArch(ApplicationInfo info) { 12883 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12884 } 12885 12886 private static boolean isExternal(PackageParser.Package pkg) { 12887 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12888 } 12889 12890 private static boolean isExternal(PackageSetting ps) { 12891 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12892 } 12893 12894 private static boolean isExternal(ApplicationInfo info) { 12895 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12896 } 12897 12898 private static boolean isSystemApp(PackageParser.Package pkg) { 12899 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12900 } 12901 12902 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12903 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12904 } 12905 12906 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12907 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12908 } 12909 12910 private static boolean isSystemApp(PackageSetting ps) { 12911 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12912 } 12913 12914 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12915 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12916 } 12917 12918 private int packageFlagsToInstallFlags(PackageSetting ps) { 12919 int installFlags = 0; 12920 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12921 // This existing package was an external ASEC install when we have 12922 // the external flag without a UUID 12923 installFlags |= PackageManager.INSTALL_EXTERNAL; 12924 } 12925 if (ps.isForwardLocked()) { 12926 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12927 } 12928 return installFlags; 12929 } 12930 12931 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12932 if (isExternal(pkg)) { 12933 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12934 return StorageManager.UUID_PRIMARY_PHYSICAL; 12935 } else { 12936 return pkg.volumeUuid; 12937 } 12938 } else { 12939 return StorageManager.UUID_PRIVATE_INTERNAL; 12940 } 12941 } 12942 12943 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12944 if (isExternal(pkg)) { 12945 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12946 return mSettings.getExternalVersion(); 12947 } else { 12948 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12949 } 12950 } else { 12951 return mSettings.getInternalVersion(); 12952 } 12953 } 12954 12955 private void deleteTempPackageFiles() { 12956 final FilenameFilter filter = new FilenameFilter() { 12957 public boolean accept(File dir, String name) { 12958 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12959 } 12960 }; 12961 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12962 file.delete(); 12963 } 12964 } 12965 12966 @Override 12967 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12968 int flags) { 12969 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12970 flags); 12971 } 12972 12973 @Override 12974 public void deletePackage(final String packageName, 12975 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12976 mContext.enforceCallingOrSelfPermission( 12977 android.Manifest.permission.DELETE_PACKAGES, null); 12978 Preconditions.checkNotNull(packageName); 12979 Preconditions.checkNotNull(observer); 12980 final int uid = Binder.getCallingUid(); 12981 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12982 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12983 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12984 mContext.enforceCallingPermission( 12985 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12986 "deletePackage for user " + userId); 12987 } 12988 12989 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12990 try { 12991 observer.onPackageDeleted(packageName, 12992 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12993 } catch (RemoteException re) { 12994 } 12995 return; 12996 } 12997 12998 for (int currentUserId : users) { 12999 if (getBlockUninstallForUser(packageName, currentUserId)) { 13000 try { 13001 observer.onPackageDeleted(packageName, 13002 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13003 } catch (RemoteException re) { 13004 } 13005 return; 13006 } 13007 } 13008 13009 if (DEBUG_REMOVE) { 13010 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13011 } 13012 // Queue up an async operation since the package deletion may take a little while. 13013 mHandler.post(new Runnable() { 13014 public void run() { 13015 mHandler.removeCallbacks(this); 13016 final int returnCode = deletePackageX(packageName, userId, flags); 13017 try { 13018 observer.onPackageDeleted(packageName, returnCode, null); 13019 } catch (RemoteException e) { 13020 Log.i(TAG, "Observer no longer exists."); 13021 } //end catch 13022 } //end run 13023 }); 13024 } 13025 13026 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13027 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13028 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13029 try { 13030 if (dpm != null) { 13031 // Does the package contains the device owner? 13032 if (dpm.isDeviceOwnerPackage(packageName)) { 13033 return true; 13034 } 13035 // Does it contain a device admin for any user? 13036 int[] users; 13037 if (userId == UserHandle.USER_ALL) { 13038 users = sUserManager.getUserIds(); 13039 } else { 13040 users = new int[]{userId}; 13041 } 13042 for (int i = 0; i < users.length; ++i) { 13043 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13044 return true; 13045 } 13046 } 13047 } 13048 } catch (RemoteException e) { 13049 } 13050 return false; 13051 } 13052 13053 /** 13054 * This method is an internal method that could be get invoked either 13055 * to delete an installed package or to clean up a failed installation. 13056 * After deleting an installed package, a broadcast is sent to notify any 13057 * listeners that the package has been installed. For cleaning up a failed 13058 * installation, the broadcast is not necessary since the package's 13059 * installation wouldn't have sent the initial broadcast either 13060 * The key steps in deleting a package are 13061 * deleting the package information in internal structures like mPackages, 13062 * deleting the packages base directories through installd 13063 * updating mSettings to reflect current status 13064 * persisting settings for later use 13065 * sending a broadcast if necessary 13066 */ 13067 private int deletePackageX(String packageName, int userId, int flags) { 13068 final PackageRemovedInfo info = new PackageRemovedInfo(); 13069 final boolean res; 13070 13071 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13072 ? UserHandle.ALL : new UserHandle(userId); 13073 13074 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13075 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13076 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13077 } 13078 13079 boolean removedForAllUsers = false; 13080 boolean systemUpdate = false; 13081 13082 // for the uninstall-updates case and restricted profiles, remember the per- 13083 // userhandle installed state 13084 int[] allUsers; 13085 boolean[] perUserInstalled; 13086 synchronized (mPackages) { 13087 PackageSetting ps = mSettings.mPackages.get(packageName); 13088 allUsers = sUserManager.getUserIds(); 13089 perUserInstalled = new boolean[allUsers.length]; 13090 for (int i = 0; i < allUsers.length; i++) { 13091 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13092 } 13093 } 13094 13095 synchronized (mInstallLock) { 13096 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13097 res = deletePackageLI(packageName, removeForUser, 13098 true, allUsers, perUserInstalled, 13099 flags | REMOVE_CHATTY, info, true); 13100 systemUpdate = info.isRemovedPackageSystemUpdate; 13101 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13102 removedForAllUsers = true; 13103 } 13104 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13105 + " removedForAllUsers=" + removedForAllUsers); 13106 } 13107 13108 if (res) { 13109 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13110 13111 // If the removed package was a system update, the old system package 13112 // was re-enabled; we need to broadcast this information 13113 if (systemUpdate) { 13114 Bundle extras = new Bundle(1); 13115 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13116 ? info.removedAppId : info.uid); 13117 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13118 13119 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13120 extras, null, null, null); 13121 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13122 extras, null, null, null); 13123 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13124 null, packageName, null, null); 13125 } 13126 } 13127 // Force a gc here. 13128 Runtime.getRuntime().gc(); 13129 // Delete the resources here after sending the broadcast to let 13130 // other processes clean up before deleting resources. 13131 if (info.args != null) { 13132 synchronized (mInstallLock) { 13133 info.args.doPostDeleteLI(true); 13134 } 13135 } 13136 13137 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13138 } 13139 13140 class PackageRemovedInfo { 13141 String removedPackage; 13142 int uid = -1; 13143 int removedAppId = -1; 13144 int[] removedUsers = null; 13145 boolean isRemovedPackageSystemUpdate = false; 13146 // Clean up resources deleted packages. 13147 InstallArgs args = null; 13148 13149 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13150 Bundle extras = new Bundle(1); 13151 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13152 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13153 if (replacing) { 13154 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13155 } 13156 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13157 if (removedPackage != null) { 13158 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13159 extras, null, null, removedUsers); 13160 if (fullRemove && !replacing) { 13161 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13162 extras, null, null, removedUsers); 13163 } 13164 } 13165 if (removedAppId >= 0) { 13166 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13167 removedUsers); 13168 } 13169 } 13170 } 13171 13172 /* 13173 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13174 * flag is not set, the data directory is removed as well. 13175 * make sure this flag is set for partially installed apps. If not its meaningless to 13176 * delete a partially installed application. 13177 */ 13178 private void removePackageDataLI(PackageSetting ps, 13179 int[] allUserHandles, boolean[] perUserInstalled, 13180 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13181 String packageName = ps.name; 13182 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13183 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13184 // Retrieve object to delete permissions for shared user later on 13185 final PackageSetting deletedPs; 13186 // reader 13187 synchronized (mPackages) { 13188 deletedPs = mSettings.mPackages.get(packageName); 13189 if (outInfo != null) { 13190 outInfo.removedPackage = packageName; 13191 outInfo.removedUsers = deletedPs != null 13192 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13193 : null; 13194 } 13195 } 13196 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13197 removeDataDirsLI(ps.volumeUuid, packageName); 13198 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13199 } 13200 // writer 13201 synchronized (mPackages) { 13202 if (deletedPs != null) { 13203 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13204 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13205 clearDefaultBrowserIfNeeded(packageName); 13206 if (outInfo != null) { 13207 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13208 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13209 } 13210 updatePermissionsLPw(deletedPs.name, null, 0); 13211 if (deletedPs.sharedUser != null) { 13212 // Remove permissions associated with package. Since runtime 13213 // permissions are per user we have to kill the removed package 13214 // or packages running under the shared user of the removed 13215 // package if revoking the permissions requested only by the removed 13216 // package is successful and this causes a change in gids. 13217 for (int userId : UserManagerService.getInstance().getUserIds()) { 13218 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13219 userId); 13220 if (userIdToKill == UserHandle.USER_ALL 13221 || userIdToKill >= UserHandle.USER_SYSTEM) { 13222 // If gids changed for this user, kill all affected packages. 13223 mHandler.post(new Runnable() { 13224 @Override 13225 public void run() { 13226 // This has to happen with no lock held. 13227 killApplication(deletedPs.name, deletedPs.appId, 13228 KILL_APP_REASON_GIDS_CHANGED); 13229 } 13230 }); 13231 break; 13232 } 13233 } 13234 } 13235 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13236 } 13237 // make sure to preserve per-user disabled state if this removal was just 13238 // a downgrade of a system app to the factory package 13239 if (allUserHandles != null && perUserInstalled != null) { 13240 if (DEBUG_REMOVE) { 13241 Slog.d(TAG, "Propagating install state across downgrade"); 13242 } 13243 for (int i = 0; i < allUserHandles.length; i++) { 13244 if (DEBUG_REMOVE) { 13245 Slog.d(TAG, " user " + allUserHandles[i] 13246 + " => " + perUserInstalled[i]); 13247 } 13248 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13249 } 13250 } 13251 } 13252 // can downgrade to reader 13253 if (writeSettings) { 13254 // Save settings now 13255 mSettings.writeLPr(); 13256 } 13257 } 13258 if (outInfo != null) { 13259 // A user ID was deleted here. Go through all users and remove it 13260 // from KeyStore. 13261 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13262 } 13263 } 13264 13265 static boolean locationIsPrivileged(File path) { 13266 try { 13267 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13268 .getCanonicalPath(); 13269 return path.getCanonicalPath().startsWith(privilegedAppDir); 13270 } catch (IOException e) { 13271 Slog.e(TAG, "Unable to access code path " + path); 13272 } 13273 return false; 13274 } 13275 13276 /* 13277 * Tries to delete system package. 13278 */ 13279 private boolean deleteSystemPackageLI(PackageSetting newPs, 13280 int[] allUserHandles, boolean[] perUserInstalled, 13281 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13282 final boolean applyUserRestrictions 13283 = (allUserHandles != null) && (perUserInstalled != null); 13284 PackageSetting disabledPs = null; 13285 // Confirm if the system package has been updated 13286 // An updated system app can be deleted. This will also have to restore 13287 // the system pkg from system partition 13288 // reader 13289 synchronized (mPackages) { 13290 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13291 } 13292 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13293 + " disabledPs=" + disabledPs); 13294 if (disabledPs == null) { 13295 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13296 return false; 13297 } else if (DEBUG_REMOVE) { 13298 Slog.d(TAG, "Deleting system pkg from data partition"); 13299 } 13300 if (DEBUG_REMOVE) { 13301 if (applyUserRestrictions) { 13302 Slog.d(TAG, "Remembering install states:"); 13303 for (int i = 0; i < allUserHandles.length; i++) { 13304 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13305 } 13306 } 13307 } 13308 // Delete the updated package 13309 outInfo.isRemovedPackageSystemUpdate = true; 13310 if (disabledPs.versionCode < newPs.versionCode) { 13311 // Delete data for downgrades 13312 flags &= ~PackageManager.DELETE_KEEP_DATA; 13313 } else { 13314 // Preserve data by setting flag 13315 flags |= PackageManager.DELETE_KEEP_DATA; 13316 } 13317 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13318 allUserHandles, perUserInstalled, outInfo, writeSettings); 13319 if (!ret) { 13320 return false; 13321 } 13322 // writer 13323 synchronized (mPackages) { 13324 // Reinstate the old system package 13325 mSettings.enableSystemPackageLPw(newPs.name); 13326 // Remove any native libraries from the upgraded package. 13327 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13328 } 13329 // Install the system package 13330 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13331 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13332 if (locationIsPrivileged(disabledPs.codePath)) { 13333 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13334 } 13335 13336 final PackageParser.Package newPkg; 13337 try { 13338 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13339 } catch (PackageManagerException e) { 13340 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13341 return false; 13342 } 13343 13344 // writer 13345 synchronized (mPackages) { 13346 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13347 13348 // Propagate the permissions state as we do not want to drop on the floor 13349 // runtime permissions. The update permissions method below will take 13350 // care of removing obsolete permissions and grant install permissions. 13351 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13352 updatePermissionsLPw(newPkg.packageName, newPkg, 13353 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13354 13355 if (applyUserRestrictions) { 13356 if (DEBUG_REMOVE) { 13357 Slog.d(TAG, "Propagating install state across reinstall"); 13358 } 13359 for (int i = 0; i < allUserHandles.length; i++) { 13360 if (DEBUG_REMOVE) { 13361 Slog.d(TAG, " user " + allUserHandles[i] 13362 + " => " + perUserInstalled[i]); 13363 } 13364 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13365 13366 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13367 } 13368 // Regardless of writeSettings we need to ensure that this restriction 13369 // state propagation is persisted 13370 mSettings.writeAllUsersPackageRestrictionsLPr(); 13371 } 13372 // can downgrade to reader here 13373 if (writeSettings) { 13374 mSettings.writeLPr(); 13375 } 13376 } 13377 return true; 13378 } 13379 13380 private boolean deleteInstalledPackageLI(PackageSetting ps, 13381 boolean deleteCodeAndResources, int flags, 13382 int[] allUserHandles, boolean[] perUserInstalled, 13383 PackageRemovedInfo outInfo, boolean writeSettings) { 13384 if (outInfo != null) { 13385 outInfo.uid = ps.appId; 13386 } 13387 13388 // Delete package data from internal structures and also remove data if flag is set 13389 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13390 13391 // Delete application code and resources 13392 if (deleteCodeAndResources && (outInfo != null)) { 13393 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13394 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13395 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13396 } 13397 return true; 13398 } 13399 13400 @Override 13401 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13402 int userId) { 13403 mContext.enforceCallingOrSelfPermission( 13404 android.Manifest.permission.DELETE_PACKAGES, null); 13405 synchronized (mPackages) { 13406 PackageSetting ps = mSettings.mPackages.get(packageName); 13407 if (ps == null) { 13408 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13409 return false; 13410 } 13411 if (!ps.getInstalled(userId)) { 13412 // Can't block uninstall for an app that is not installed or enabled. 13413 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13414 return false; 13415 } 13416 ps.setBlockUninstall(blockUninstall, userId); 13417 mSettings.writePackageRestrictionsLPr(userId); 13418 } 13419 return true; 13420 } 13421 13422 @Override 13423 public boolean getBlockUninstallForUser(String packageName, int userId) { 13424 synchronized (mPackages) { 13425 PackageSetting ps = mSettings.mPackages.get(packageName); 13426 if (ps == null) { 13427 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13428 return false; 13429 } 13430 return ps.getBlockUninstall(userId); 13431 } 13432 } 13433 13434 /* 13435 * This method handles package deletion in general 13436 */ 13437 private boolean deletePackageLI(String packageName, UserHandle user, 13438 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13439 int flags, PackageRemovedInfo outInfo, 13440 boolean writeSettings) { 13441 if (packageName == null) { 13442 Slog.w(TAG, "Attempt to delete null packageName."); 13443 return false; 13444 } 13445 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13446 PackageSetting ps; 13447 boolean dataOnly = false; 13448 int removeUser = -1; 13449 int appId = -1; 13450 synchronized (mPackages) { 13451 ps = mSettings.mPackages.get(packageName); 13452 if (ps == null) { 13453 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13454 return false; 13455 } 13456 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13457 && user.getIdentifier() != UserHandle.USER_ALL) { 13458 // The caller is asking that the package only be deleted for a single 13459 // user. To do this, we just mark its uninstalled state and delete 13460 // its data. If this is a system app, we only allow this to happen if 13461 // they have set the special DELETE_SYSTEM_APP which requests different 13462 // semantics than normal for uninstalling system apps. 13463 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13464 final int userId = user.getIdentifier(); 13465 ps.setUserState(userId, 13466 COMPONENT_ENABLED_STATE_DEFAULT, 13467 false, //installed 13468 true, //stopped 13469 true, //notLaunched 13470 false, //hidden 13471 null, null, null, 13472 false, // blockUninstall 13473 ps.readUserState(userId).domainVerificationStatus, 0); 13474 if (!isSystemApp(ps)) { 13475 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13476 // Other user still have this package installed, so all 13477 // we need to do is clear this user's data and save that 13478 // it is uninstalled. 13479 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13480 removeUser = user.getIdentifier(); 13481 appId = ps.appId; 13482 scheduleWritePackageRestrictionsLocked(removeUser); 13483 } else { 13484 // We need to set it back to 'installed' so the uninstall 13485 // broadcasts will be sent correctly. 13486 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13487 ps.setInstalled(true, user.getIdentifier()); 13488 } 13489 } else { 13490 // This is a system app, so we assume that the 13491 // other users still have this package installed, so all 13492 // we need to do is clear this user's data and save that 13493 // it is uninstalled. 13494 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13495 removeUser = user.getIdentifier(); 13496 appId = ps.appId; 13497 scheduleWritePackageRestrictionsLocked(removeUser); 13498 } 13499 } 13500 } 13501 13502 if (removeUser >= 0) { 13503 // From above, we determined that we are deleting this only 13504 // for a single user. Continue the work here. 13505 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13506 if (outInfo != null) { 13507 outInfo.removedPackage = packageName; 13508 outInfo.removedAppId = appId; 13509 outInfo.removedUsers = new int[] {removeUser}; 13510 } 13511 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13512 removeKeystoreDataIfNeeded(removeUser, appId); 13513 schedulePackageCleaning(packageName, removeUser, false); 13514 synchronized (mPackages) { 13515 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13516 scheduleWritePackageRestrictionsLocked(removeUser); 13517 } 13518 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13519 } 13520 return true; 13521 } 13522 13523 if (dataOnly) { 13524 // Delete application data first 13525 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13526 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13527 return true; 13528 } 13529 13530 boolean ret = false; 13531 if (isSystemApp(ps)) { 13532 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13533 // When an updated system application is deleted we delete the existing resources as well and 13534 // fall back to existing code in system partition 13535 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13536 flags, outInfo, writeSettings); 13537 } else { 13538 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13539 // Kill application pre-emptively especially for apps on sd. 13540 killApplication(packageName, ps.appId, "uninstall pkg"); 13541 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13542 allUserHandles, perUserInstalled, 13543 outInfo, writeSettings); 13544 } 13545 13546 return ret; 13547 } 13548 13549 private final class ClearStorageConnection implements ServiceConnection { 13550 IMediaContainerService mContainerService; 13551 13552 @Override 13553 public void onServiceConnected(ComponentName name, IBinder service) { 13554 synchronized (this) { 13555 mContainerService = IMediaContainerService.Stub.asInterface(service); 13556 notifyAll(); 13557 } 13558 } 13559 13560 @Override 13561 public void onServiceDisconnected(ComponentName name) { 13562 } 13563 } 13564 13565 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13566 final boolean mounted; 13567 if (Environment.isExternalStorageEmulated()) { 13568 mounted = true; 13569 } else { 13570 final String status = Environment.getExternalStorageState(); 13571 13572 mounted = status.equals(Environment.MEDIA_MOUNTED) 13573 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13574 } 13575 13576 if (!mounted) { 13577 return; 13578 } 13579 13580 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13581 int[] users; 13582 if (userId == UserHandle.USER_ALL) { 13583 users = sUserManager.getUserIds(); 13584 } else { 13585 users = new int[] { userId }; 13586 } 13587 final ClearStorageConnection conn = new ClearStorageConnection(); 13588 if (mContext.bindServiceAsUser( 13589 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13590 try { 13591 for (int curUser : users) { 13592 long timeout = SystemClock.uptimeMillis() + 5000; 13593 synchronized (conn) { 13594 long now = SystemClock.uptimeMillis(); 13595 while (conn.mContainerService == null && now < timeout) { 13596 try { 13597 conn.wait(timeout - now); 13598 } catch (InterruptedException e) { 13599 } 13600 } 13601 } 13602 if (conn.mContainerService == null) { 13603 return; 13604 } 13605 13606 final UserEnvironment userEnv = new UserEnvironment(curUser); 13607 clearDirectory(conn.mContainerService, 13608 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13609 if (allData) { 13610 clearDirectory(conn.mContainerService, 13611 userEnv.buildExternalStorageAppDataDirs(packageName)); 13612 clearDirectory(conn.mContainerService, 13613 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13614 } 13615 } 13616 } finally { 13617 mContext.unbindService(conn); 13618 } 13619 } 13620 } 13621 13622 @Override 13623 public void clearApplicationUserData(final String packageName, 13624 final IPackageDataObserver observer, final int userId) { 13625 mContext.enforceCallingOrSelfPermission( 13626 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13627 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13628 // Queue up an async operation since the package deletion may take a little while. 13629 mHandler.post(new Runnable() { 13630 public void run() { 13631 mHandler.removeCallbacks(this); 13632 final boolean succeeded; 13633 synchronized (mInstallLock) { 13634 succeeded = clearApplicationUserDataLI(packageName, userId); 13635 } 13636 clearExternalStorageDataSync(packageName, userId, true); 13637 if (succeeded) { 13638 // invoke DeviceStorageMonitor's update method to clear any notifications 13639 DeviceStorageMonitorInternal 13640 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13641 if (dsm != null) { 13642 dsm.checkMemory(); 13643 } 13644 } 13645 if(observer != null) { 13646 try { 13647 observer.onRemoveCompleted(packageName, succeeded); 13648 } catch (RemoteException e) { 13649 Log.i(TAG, "Observer no longer exists."); 13650 } 13651 } //end if observer 13652 } //end run 13653 }); 13654 } 13655 13656 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13657 if (packageName == null) { 13658 Slog.w(TAG, "Attempt to delete null packageName."); 13659 return false; 13660 } 13661 13662 // Try finding details about the requested package 13663 PackageParser.Package pkg; 13664 synchronized (mPackages) { 13665 pkg = mPackages.get(packageName); 13666 if (pkg == null) { 13667 final PackageSetting ps = mSettings.mPackages.get(packageName); 13668 if (ps != null) { 13669 pkg = ps.pkg; 13670 } 13671 } 13672 13673 if (pkg == null) { 13674 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13675 return false; 13676 } 13677 13678 PackageSetting ps = (PackageSetting) pkg.mExtras; 13679 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13680 } 13681 13682 // Always delete data directories for package, even if we found no other 13683 // record of app. This helps users recover from UID mismatches without 13684 // resorting to a full data wipe. 13685 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13686 if (retCode < 0) { 13687 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13688 return false; 13689 } 13690 13691 final int appId = pkg.applicationInfo.uid; 13692 removeKeystoreDataIfNeeded(userId, appId); 13693 13694 // Create a native library symlink only if we have native libraries 13695 // and if the native libraries are 32 bit libraries. We do not provide 13696 // this symlink for 64 bit libraries. 13697 if (pkg.applicationInfo.primaryCpuAbi != null && 13698 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13699 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13700 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13701 nativeLibPath, userId) < 0) { 13702 Slog.w(TAG, "Failed linking native library dir"); 13703 return false; 13704 } 13705 } 13706 13707 return true; 13708 } 13709 13710 /** 13711 * Reverts user permission state changes (permissions and flags) in 13712 * all packages for a given user. 13713 * 13714 * @param userId The device user for which to do a reset. 13715 */ 13716 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13717 final int packageCount = mPackages.size(); 13718 for (int i = 0; i < packageCount; i++) { 13719 PackageParser.Package pkg = mPackages.valueAt(i); 13720 PackageSetting ps = (PackageSetting) pkg.mExtras; 13721 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13722 } 13723 } 13724 13725 /** 13726 * Reverts user permission state changes (permissions and flags). 13727 * 13728 * @param ps The package for which to reset. 13729 * @param userId The device user for which to do a reset. 13730 */ 13731 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13732 final PackageSetting ps, final int userId) { 13733 if (ps.pkg == null) { 13734 return; 13735 } 13736 13737 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13738 | FLAG_PERMISSION_USER_FIXED 13739 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13740 13741 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13742 | FLAG_PERMISSION_POLICY_FIXED; 13743 13744 boolean writeInstallPermissions = false; 13745 boolean writeRuntimePermissions = false; 13746 13747 final int permissionCount = ps.pkg.requestedPermissions.size(); 13748 for (int i = 0; i < permissionCount; i++) { 13749 String permission = ps.pkg.requestedPermissions.get(i); 13750 13751 BasePermission bp = mSettings.mPermissions.get(permission); 13752 if (bp == null) { 13753 continue; 13754 } 13755 13756 // If shared user we just reset the state to which only this app contributed. 13757 if (ps.sharedUser != null) { 13758 boolean used = false; 13759 final int packageCount = ps.sharedUser.packages.size(); 13760 for (int j = 0; j < packageCount; j++) { 13761 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13762 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13763 && pkg.pkg.requestedPermissions.contains(permission)) { 13764 used = true; 13765 break; 13766 } 13767 } 13768 if (used) { 13769 continue; 13770 } 13771 } 13772 13773 PermissionsState permissionsState = ps.getPermissionsState(); 13774 13775 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13776 13777 // Always clear the user settable flags. 13778 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13779 bp.name) != null; 13780 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13781 if (hasInstallState) { 13782 writeInstallPermissions = true; 13783 } else { 13784 writeRuntimePermissions = true; 13785 } 13786 } 13787 13788 // Below is only runtime permission handling. 13789 if (!bp.isRuntime()) { 13790 continue; 13791 } 13792 13793 // Never clobber system or policy. 13794 if ((oldFlags & policyOrSystemFlags) != 0) { 13795 continue; 13796 } 13797 13798 // If this permission was granted by default, make sure it is. 13799 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13800 if (permissionsState.grantRuntimePermission(bp, userId) 13801 != PERMISSION_OPERATION_FAILURE) { 13802 writeRuntimePermissions = true; 13803 } 13804 } else { 13805 // Otherwise, reset the permission. 13806 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13807 switch (revokeResult) { 13808 case PERMISSION_OPERATION_SUCCESS: { 13809 writeRuntimePermissions = true; 13810 } break; 13811 13812 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13813 writeRuntimePermissions = true; 13814 final int appId = ps.appId; 13815 mHandler.post(new Runnable() { 13816 @Override 13817 public void run() { 13818 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13819 } 13820 }); 13821 } break; 13822 } 13823 } 13824 } 13825 13826 // Synchronously write as we are taking permissions away. 13827 if (writeRuntimePermissions) { 13828 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13829 } 13830 13831 // Synchronously write as we are taking permissions away. 13832 if (writeInstallPermissions) { 13833 mSettings.writeLPr(); 13834 } 13835 } 13836 13837 /** 13838 * Remove entries from the keystore daemon. Will only remove it if the 13839 * {@code appId} is valid. 13840 */ 13841 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13842 if (appId < 0) { 13843 return; 13844 } 13845 13846 final KeyStore keyStore = KeyStore.getInstance(); 13847 if (keyStore != null) { 13848 if (userId == UserHandle.USER_ALL) { 13849 for (final int individual : sUserManager.getUserIds()) { 13850 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13851 } 13852 } else { 13853 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13854 } 13855 } else { 13856 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13857 } 13858 } 13859 13860 @Override 13861 public void deleteApplicationCacheFiles(final String packageName, 13862 final IPackageDataObserver observer) { 13863 mContext.enforceCallingOrSelfPermission( 13864 android.Manifest.permission.DELETE_CACHE_FILES, null); 13865 // Queue up an async operation since the package deletion may take a little while. 13866 final int userId = UserHandle.getCallingUserId(); 13867 mHandler.post(new Runnable() { 13868 public void run() { 13869 mHandler.removeCallbacks(this); 13870 final boolean succeded; 13871 synchronized (mInstallLock) { 13872 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13873 } 13874 clearExternalStorageDataSync(packageName, userId, false); 13875 if (observer != null) { 13876 try { 13877 observer.onRemoveCompleted(packageName, succeded); 13878 } catch (RemoteException e) { 13879 Log.i(TAG, "Observer no longer exists."); 13880 } 13881 } //end if observer 13882 } //end run 13883 }); 13884 } 13885 13886 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13887 if (packageName == null) { 13888 Slog.w(TAG, "Attempt to delete null packageName."); 13889 return false; 13890 } 13891 PackageParser.Package p; 13892 synchronized (mPackages) { 13893 p = mPackages.get(packageName); 13894 } 13895 if (p == null) { 13896 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13897 return false; 13898 } 13899 final ApplicationInfo applicationInfo = p.applicationInfo; 13900 if (applicationInfo == null) { 13901 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13902 return false; 13903 } 13904 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13905 if (retCode < 0) { 13906 Slog.w(TAG, "Couldn't remove cache files for package: " 13907 + packageName + " u" + userId); 13908 return false; 13909 } 13910 return true; 13911 } 13912 13913 @Override 13914 public void getPackageSizeInfo(final String packageName, int userHandle, 13915 final IPackageStatsObserver observer) { 13916 mContext.enforceCallingOrSelfPermission( 13917 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13918 if (packageName == null) { 13919 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13920 } 13921 13922 PackageStats stats = new PackageStats(packageName, userHandle); 13923 13924 /* 13925 * Queue up an async operation since the package measurement may take a 13926 * little while. 13927 */ 13928 Message msg = mHandler.obtainMessage(INIT_COPY); 13929 msg.obj = new MeasureParams(stats, observer); 13930 mHandler.sendMessage(msg); 13931 } 13932 13933 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13934 PackageStats pStats) { 13935 if (packageName == null) { 13936 Slog.w(TAG, "Attempt to get size of null packageName."); 13937 return false; 13938 } 13939 PackageParser.Package p; 13940 boolean dataOnly = false; 13941 String libDirRoot = null; 13942 String asecPath = null; 13943 PackageSetting ps = null; 13944 synchronized (mPackages) { 13945 p = mPackages.get(packageName); 13946 ps = mSettings.mPackages.get(packageName); 13947 if(p == null) { 13948 dataOnly = true; 13949 if((ps == null) || (ps.pkg == null)) { 13950 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13951 return false; 13952 } 13953 p = ps.pkg; 13954 } 13955 if (ps != null) { 13956 libDirRoot = ps.legacyNativeLibraryPathString; 13957 } 13958 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13959 final long token = Binder.clearCallingIdentity(); 13960 try { 13961 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13962 if (secureContainerId != null) { 13963 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13964 } 13965 } finally { 13966 Binder.restoreCallingIdentity(token); 13967 } 13968 } 13969 } 13970 String publicSrcDir = null; 13971 if(!dataOnly) { 13972 final ApplicationInfo applicationInfo = p.applicationInfo; 13973 if (applicationInfo == null) { 13974 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13975 return false; 13976 } 13977 if (p.isForwardLocked()) { 13978 publicSrcDir = applicationInfo.getBaseResourcePath(); 13979 } 13980 } 13981 // TODO: extend to measure size of split APKs 13982 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13983 // not just the first level. 13984 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13985 // just the primary. 13986 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13987 13988 String apkPath; 13989 File packageDir = new File(p.codePath); 13990 13991 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13992 apkPath = packageDir.getAbsolutePath(); 13993 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13994 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13995 libDirRoot = null; 13996 } 13997 } else { 13998 apkPath = p.baseCodePath; 13999 } 14000 14001 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14002 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14003 if (res < 0) { 14004 return false; 14005 } 14006 14007 // Fix-up for forward-locked applications in ASEC containers. 14008 if (!isExternal(p)) { 14009 pStats.codeSize += pStats.externalCodeSize; 14010 pStats.externalCodeSize = 0L; 14011 } 14012 14013 return true; 14014 } 14015 14016 14017 @Override 14018 public void addPackageToPreferred(String packageName) { 14019 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14020 } 14021 14022 @Override 14023 public void removePackageFromPreferred(String packageName) { 14024 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14025 } 14026 14027 @Override 14028 public List<PackageInfo> getPreferredPackages(int flags) { 14029 return new ArrayList<PackageInfo>(); 14030 } 14031 14032 private int getUidTargetSdkVersionLockedLPr(int uid) { 14033 Object obj = mSettings.getUserIdLPr(uid); 14034 if (obj instanceof SharedUserSetting) { 14035 final SharedUserSetting sus = (SharedUserSetting) obj; 14036 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14037 final Iterator<PackageSetting> it = sus.packages.iterator(); 14038 while (it.hasNext()) { 14039 final PackageSetting ps = it.next(); 14040 if (ps.pkg != null) { 14041 int v = ps.pkg.applicationInfo.targetSdkVersion; 14042 if (v < vers) vers = v; 14043 } 14044 } 14045 return vers; 14046 } else if (obj instanceof PackageSetting) { 14047 final PackageSetting ps = (PackageSetting) obj; 14048 if (ps.pkg != null) { 14049 return ps.pkg.applicationInfo.targetSdkVersion; 14050 } 14051 } 14052 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14053 } 14054 14055 @Override 14056 public void addPreferredActivity(IntentFilter filter, int match, 14057 ComponentName[] set, ComponentName activity, int userId) { 14058 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14059 "Adding preferred"); 14060 } 14061 14062 private void addPreferredActivityInternal(IntentFilter filter, int match, 14063 ComponentName[] set, ComponentName activity, boolean always, int userId, 14064 String opname) { 14065 // writer 14066 int callingUid = Binder.getCallingUid(); 14067 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14068 if (filter.countActions() == 0) { 14069 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14070 return; 14071 } 14072 synchronized (mPackages) { 14073 if (mContext.checkCallingOrSelfPermission( 14074 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14075 != PackageManager.PERMISSION_GRANTED) { 14076 if (getUidTargetSdkVersionLockedLPr(callingUid) 14077 < Build.VERSION_CODES.FROYO) { 14078 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14079 + callingUid); 14080 return; 14081 } 14082 mContext.enforceCallingOrSelfPermission( 14083 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14084 } 14085 14086 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14087 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14088 + userId + ":"); 14089 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14090 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14091 scheduleWritePackageRestrictionsLocked(userId); 14092 } 14093 } 14094 14095 @Override 14096 public void replacePreferredActivity(IntentFilter filter, int match, 14097 ComponentName[] set, ComponentName activity, int userId) { 14098 if (filter.countActions() != 1) { 14099 throw new IllegalArgumentException( 14100 "replacePreferredActivity expects filter to have only 1 action."); 14101 } 14102 if (filter.countDataAuthorities() != 0 14103 || filter.countDataPaths() != 0 14104 || filter.countDataSchemes() > 1 14105 || filter.countDataTypes() != 0) { 14106 throw new IllegalArgumentException( 14107 "replacePreferredActivity expects filter to have no data authorities, " + 14108 "paths, or types; and at most one scheme."); 14109 } 14110 14111 final int callingUid = Binder.getCallingUid(); 14112 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14113 synchronized (mPackages) { 14114 if (mContext.checkCallingOrSelfPermission( 14115 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14116 != PackageManager.PERMISSION_GRANTED) { 14117 if (getUidTargetSdkVersionLockedLPr(callingUid) 14118 < Build.VERSION_CODES.FROYO) { 14119 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14120 + Binder.getCallingUid()); 14121 return; 14122 } 14123 mContext.enforceCallingOrSelfPermission( 14124 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14125 } 14126 14127 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14128 if (pir != null) { 14129 // Get all of the existing entries that exactly match this filter. 14130 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14131 if (existing != null && existing.size() == 1) { 14132 PreferredActivity cur = existing.get(0); 14133 if (DEBUG_PREFERRED) { 14134 Slog.i(TAG, "Checking replace of preferred:"); 14135 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14136 if (!cur.mPref.mAlways) { 14137 Slog.i(TAG, " -- CUR; not mAlways!"); 14138 } else { 14139 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14140 Slog.i(TAG, " -- CUR: mSet=" 14141 + Arrays.toString(cur.mPref.mSetComponents)); 14142 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14143 Slog.i(TAG, " -- NEW: mMatch=" 14144 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14145 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14146 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14147 } 14148 } 14149 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14150 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14151 && cur.mPref.sameSet(set)) { 14152 // Setting the preferred activity to what it happens to be already 14153 if (DEBUG_PREFERRED) { 14154 Slog.i(TAG, "Replacing with same preferred activity " 14155 + cur.mPref.mShortComponent + " for user " 14156 + userId + ":"); 14157 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14158 } 14159 return; 14160 } 14161 } 14162 14163 if (existing != null) { 14164 if (DEBUG_PREFERRED) { 14165 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14166 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14167 } 14168 for (int i = 0; i < existing.size(); i++) { 14169 PreferredActivity pa = existing.get(i); 14170 if (DEBUG_PREFERRED) { 14171 Slog.i(TAG, "Removing existing preferred activity " 14172 + pa.mPref.mComponent + ":"); 14173 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14174 } 14175 pir.removeFilter(pa); 14176 } 14177 } 14178 } 14179 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14180 "Replacing preferred"); 14181 } 14182 } 14183 14184 @Override 14185 public void clearPackagePreferredActivities(String packageName) { 14186 final int uid = Binder.getCallingUid(); 14187 // writer 14188 synchronized (mPackages) { 14189 PackageParser.Package pkg = mPackages.get(packageName); 14190 if (pkg == null || pkg.applicationInfo.uid != uid) { 14191 if (mContext.checkCallingOrSelfPermission( 14192 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14193 != PackageManager.PERMISSION_GRANTED) { 14194 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14195 < Build.VERSION_CODES.FROYO) { 14196 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14197 + Binder.getCallingUid()); 14198 return; 14199 } 14200 mContext.enforceCallingOrSelfPermission( 14201 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14202 } 14203 } 14204 14205 int user = UserHandle.getCallingUserId(); 14206 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14207 scheduleWritePackageRestrictionsLocked(user); 14208 } 14209 } 14210 } 14211 14212 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14213 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14214 ArrayList<PreferredActivity> removed = null; 14215 boolean changed = false; 14216 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14217 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14218 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14219 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14220 continue; 14221 } 14222 Iterator<PreferredActivity> it = pir.filterIterator(); 14223 while (it.hasNext()) { 14224 PreferredActivity pa = it.next(); 14225 // Mark entry for removal only if it matches the package name 14226 // and the entry is of type "always". 14227 if (packageName == null || 14228 (pa.mPref.mComponent.getPackageName().equals(packageName) 14229 && pa.mPref.mAlways)) { 14230 if (removed == null) { 14231 removed = new ArrayList<PreferredActivity>(); 14232 } 14233 removed.add(pa); 14234 } 14235 } 14236 if (removed != null) { 14237 for (int j=0; j<removed.size(); j++) { 14238 PreferredActivity pa = removed.get(j); 14239 pir.removeFilter(pa); 14240 } 14241 changed = true; 14242 } 14243 } 14244 return changed; 14245 } 14246 14247 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14248 private void clearIntentFilterVerificationsLPw(int userId) { 14249 final int packageCount = mPackages.size(); 14250 for (int i = 0; i < packageCount; i++) { 14251 PackageParser.Package pkg = mPackages.valueAt(i); 14252 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14253 } 14254 } 14255 14256 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14257 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14258 if (userId == UserHandle.USER_ALL) { 14259 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14260 sUserManager.getUserIds())) { 14261 for (int oneUserId : sUserManager.getUserIds()) { 14262 scheduleWritePackageRestrictionsLocked(oneUserId); 14263 } 14264 } 14265 } else { 14266 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14267 scheduleWritePackageRestrictionsLocked(userId); 14268 } 14269 } 14270 } 14271 14272 void clearDefaultBrowserIfNeeded(String packageName) { 14273 for (int oneUserId : sUserManager.getUserIds()) { 14274 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14275 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14276 if (packageName.equals(defaultBrowserPackageName)) { 14277 setDefaultBrowserPackageName(null, oneUserId); 14278 } 14279 } 14280 } 14281 14282 @Override 14283 public void resetApplicationPreferences(int userId) { 14284 mContext.enforceCallingOrSelfPermission( 14285 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14286 // writer 14287 synchronized (mPackages) { 14288 final long identity = Binder.clearCallingIdentity(); 14289 try { 14290 clearPackagePreferredActivitiesLPw(null, userId); 14291 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14292 // TODO: We have to reset the default SMS and Phone. This requires 14293 // significant refactoring to keep all default apps in the package 14294 // manager (cleaner but more work) or have the services provide 14295 // callbacks to the package manager to request a default app reset. 14296 applyFactoryDefaultBrowserLPw(userId); 14297 clearIntentFilterVerificationsLPw(userId); 14298 primeDomainVerificationsLPw(userId); 14299 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14300 scheduleWritePackageRestrictionsLocked(userId); 14301 } finally { 14302 Binder.restoreCallingIdentity(identity); 14303 } 14304 } 14305 } 14306 14307 @Override 14308 public int getPreferredActivities(List<IntentFilter> outFilters, 14309 List<ComponentName> outActivities, String packageName) { 14310 14311 int num = 0; 14312 final int userId = UserHandle.getCallingUserId(); 14313 // reader 14314 synchronized (mPackages) { 14315 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14316 if (pir != null) { 14317 final Iterator<PreferredActivity> it = pir.filterIterator(); 14318 while (it.hasNext()) { 14319 final PreferredActivity pa = it.next(); 14320 if (packageName == null 14321 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14322 && pa.mPref.mAlways)) { 14323 if (outFilters != null) { 14324 outFilters.add(new IntentFilter(pa)); 14325 } 14326 if (outActivities != null) { 14327 outActivities.add(pa.mPref.mComponent); 14328 } 14329 } 14330 } 14331 } 14332 } 14333 14334 return num; 14335 } 14336 14337 @Override 14338 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14339 int userId) { 14340 int callingUid = Binder.getCallingUid(); 14341 if (callingUid != Process.SYSTEM_UID) { 14342 throw new SecurityException( 14343 "addPersistentPreferredActivity can only be run by the system"); 14344 } 14345 if (filter.countActions() == 0) { 14346 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14347 return; 14348 } 14349 synchronized (mPackages) { 14350 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14351 " :"); 14352 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14353 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14354 new PersistentPreferredActivity(filter, activity)); 14355 scheduleWritePackageRestrictionsLocked(userId); 14356 } 14357 } 14358 14359 @Override 14360 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14361 int callingUid = Binder.getCallingUid(); 14362 if (callingUid != Process.SYSTEM_UID) { 14363 throw new SecurityException( 14364 "clearPackagePersistentPreferredActivities can only be run by the system"); 14365 } 14366 ArrayList<PersistentPreferredActivity> removed = null; 14367 boolean changed = false; 14368 synchronized (mPackages) { 14369 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14370 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14371 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14372 .valueAt(i); 14373 if (userId != thisUserId) { 14374 continue; 14375 } 14376 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14377 while (it.hasNext()) { 14378 PersistentPreferredActivity ppa = it.next(); 14379 // Mark entry for removal only if it matches the package name. 14380 if (ppa.mComponent.getPackageName().equals(packageName)) { 14381 if (removed == null) { 14382 removed = new ArrayList<PersistentPreferredActivity>(); 14383 } 14384 removed.add(ppa); 14385 } 14386 } 14387 if (removed != null) { 14388 for (int j=0; j<removed.size(); j++) { 14389 PersistentPreferredActivity ppa = removed.get(j); 14390 ppir.removeFilter(ppa); 14391 } 14392 changed = true; 14393 } 14394 } 14395 14396 if (changed) { 14397 scheduleWritePackageRestrictionsLocked(userId); 14398 } 14399 } 14400 } 14401 14402 /** 14403 * Common machinery for picking apart a restored XML blob and passing 14404 * it to a caller-supplied functor to be applied to the running system. 14405 */ 14406 private void restoreFromXml(XmlPullParser parser, int userId, 14407 String expectedStartTag, BlobXmlRestorer functor) 14408 throws IOException, XmlPullParserException { 14409 int type; 14410 while ((type = parser.next()) != XmlPullParser.START_TAG 14411 && type != XmlPullParser.END_DOCUMENT) { 14412 } 14413 if (type != XmlPullParser.START_TAG) { 14414 // oops didn't find a start tag?! 14415 if (DEBUG_BACKUP) { 14416 Slog.e(TAG, "Didn't find start tag during restore"); 14417 } 14418 return; 14419 } 14420 14421 // this is supposed to be TAG_PREFERRED_BACKUP 14422 if (!expectedStartTag.equals(parser.getName())) { 14423 if (DEBUG_BACKUP) { 14424 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14425 } 14426 return; 14427 } 14428 14429 // skip interfering stuff, then we're aligned with the backing implementation 14430 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14431 functor.apply(parser, userId); 14432 } 14433 14434 private interface BlobXmlRestorer { 14435 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14436 } 14437 14438 /** 14439 * Non-Binder method, support for the backup/restore mechanism: write the 14440 * full set of preferred activities in its canonical XML format. Returns the 14441 * XML output as a byte array, or null if there is none. 14442 */ 14443 @Override 14444 public byte[] getPreferredActivityBackup(int userId) { 14445 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14446 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14447 } 14448 14449 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14450 try { 14451 final XmlSerializer serializer = new FastXmlSerializer(); 14452 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14453 serializer.startDocument(null, true); 14454 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14455 14456 synchronized (mPackages) { 14457 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14458 } 14459 14460 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14461 serializer.endDocument(); 14462 serializer.flush(); 14463 } catch (Exception e) { 14464 if (DEBUG_BACKUP) { 14465 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14466 } 14467 return null; 14468 } 14469 14470 return dataStream.toByteArray(); 14471 } 14472 14473 @Override 14474 public void restorePreferredActivities(byte[] backup, int userId) { 14475 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14476 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14477 } 14478 14479 try { 14480 final XmlPullParser parser = Xml.newPullParser(); 14481 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14482 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14483 new BlobXmlRestorer() { 14484 @Override 14485 public void apply(XmlPullParser parser, int userId) 14486 throws XmlPullParserException, IOException { 14487 synchronized (mPackages) { 14488 mSettings.readPreferredActivitiesLPw(parser, userId); 14489 } 14490 } 14491 } ); 14492 } catch (Exception e) { 14493 if (DEBUG_BACKUP) { 14494 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14495 } 14496 } 14497 } 14498 14499 /** 14500 * Non-Binder method, support for the backup/restore mechanism: write the 14501 * default browser (etc) settings in its canonical XML format. Returns the default 14502 * browser XML representation as a byte array, or null if there is none. 14503 */ 14504 @Override 14505 public byte[] getDefaultAppsBackup(int userId) { 14506 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14507 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14508 } 14509 14510 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14511 try { 14512 final XmlSerializer serializer = new FastXmlSerializer(); 14513 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14514 serializer.startDocument(null, true); 14515 serializer.startTag(null, TAG_DEFAULT_APPS); 14516 14517 synchronized (mPackages) { 14518 mSettings.writeDefaultAppsLPr(serializer, userId); 14519 } 14520 14521 serializer.endTag(null, TAG_DEFAULT_APPS); 14522 serializer.endDocument(); 14523 serializer.flush(); 14524 } catch (Exception e) { 14525 if (DEBUG_BACKUP) { 14526 Slog.e(TAG, "Unable to write default apps for backup", e); 14527 } 14528 return null; 14529 } 14530 14531 return dataStream.toByteArray(); 14532 } 14533 14534 @Override 14535 public void restoreDefaultApps(byte[] backup, int userId) { 14536 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14537 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14538 } 14539 14540 try { 14541 final XmlPullParser parser = Xml.newPullParser(); 14542 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14543 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14544 new BlobXmlRestorer() { 14545 @Override 14546 public void apply(XmlPullParser parser, int userId) 14547 throws XmlPullParserException, IOException { 14548 synchronized (mPackages) { 14549 mSettings.readDefaultAppsLPw(parser, userId); 14550 } 14551 } 14552 } ); 14553 } catch (Exception e) { 14554 if (DEBUG_BACKUP) { 14555 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14556 } 14557 } 14558 } 14559 14560 @Override 14561 public byte[] getIntentFilterVerificationBackup(int userId) { 14562 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14563 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14564 } 14565 14566 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14567 try { 14568 final XmlSerializer serializer = new FastXmlSerializer(); 14569 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14570 serializer.startDocument(null, true); 14571 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14572 14573 synchronized (mPackages) { 14574 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14575 } 14576 14577 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14578 serializer.endDocument(); 14579 serializer.flush(); 14580 } catch (Exception e) { 14581 if (DEBUG_BACKUP) { 14582 Slog.e(TAG, "Unable to write default apps for backup", e); 14583 } 14584 return null; 14585 } 14586 14587 return dataStream.toByteArray(); 14588 } 14589 14590 @Override 14591 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14592 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14593 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14594 } 14595 14596 try { 14597 final XmlPullParser parser = Xml.newPullParser(); 14598 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14599 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14600 new BlobXmlRestorer() { 14601 @Override 14602 public void apply(XmlPullParser parser, int userId) 14603 throws XmlPullParserException, IOException { 14604 synchronized (mPackages) { 14605 mSettings.readAllDomainVerificationsLPr(parser, userId); 14606 mSettings.writeLPr(); 14607 } 14608 } 14609 } ); 14610 } catch (Exception e) { 14611 if (DEBUG_BACKUP) { 14612 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14613 } 14614 } 14615 } 14616 14617 @Override 14618 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14619 int sourceUserId, int targetUserId, int flags) { 14620 mContext.enforceCallingOrSelfPermission( 14621 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14622 int callingUid = Binder.getCallingUid(); 14623 enforceOwnerRights(ownerPackage, callingUid); 14624 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14625 if (intentFilter.countActions() == 0) { 14626 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14627 return; 14628 } 14629 synchronized (mPackages) { 14630 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14631 ownerPackage, targetUserId, flags); 14632 CrossProfileIntentResolver resolver = 14633 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14634 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14635 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14636 if (existing != null) { 14637 int size = existing.size(); 14638 for (int i = 0; i < size; i++) { 14639 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14640 return; 14641 } 14642 } 14643 } 14644 resolver.addFilter(newFilter); 14645 scheduleWritePackageRestrictionsLocked(sourceUserId); 14646 } 14647 } 14648 14649 @Override 14650 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14651 mContext.enforceCallingOrSelfPermission( 14652 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14653 int callingUid = Binder.getCallingUid(); 14654 enforceOwnerRights(ownerPackage, callingUid); 14655 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14656 synchronized (mPackages) { 14657 CrossProfileIntentResolver resolver = 14658 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14659 ArraySet<CrossProfileIntentFilter> set = 14660 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14661 for (CrossProfileIntentFilter filter : set) { 14662 if (filter.getOwnerPackage().equals(ownerPackage)) { 14663 resolver.removeFilter(filter); 14664 } 14665 } 14666 scheduleWritePackageRestrictionsLocked(sourceUserId); 14667 } 14668 } 14669 14670 // Enforcing that callingUid is owning pkg on userId 14671 private void enforceOwnerRights(String pkg, int callingUid) { 14672 // The system owns everything. 14673 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14674 return; 14675 } 14676 int callingUserId = UserHandle.getUserId(callingUid); 14677 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14678 if (pi == null) { 14679 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14680 + callingUserId); 14681 } 14682 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14683 throw new SecurityException("Calling uid " + callingUid 14684 + " does not own package " + pkg); 14685 } 14686 } 14687 14688 @Override 14689 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14690 Intent intent = new Intent(Intent.ACTION_MAIN); 14691 intent.addCategory(Intent.CATEGORY_HOME); 14692 14693 final int callingUserId = UserHandle.getCallingUserId(); 14694 List<ResolveInfo> list = queryIntentActivities(intent, null, 14695 PackageManager.GET_META_DATA, callingUserId); 14696 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14697 true, false, false, callingUserId); 14698 14699 allHomeCandidates.clear(); 14700 if (list != null) { 14701 for (ResolveInfo ri : list) { 14702 allHomeCandidates.add(ri); 14703 } 14704 } 14705 return (preferred == null || preferred.activityInfo == null) 14706 ? null 14707 : new ComponentName(preferred.activityInfo.packageName, 14708 preferred.activityInfo.name); 14709 } 14710 14711 @Override 14712 public void setApplicationEnabledSetting(String appPackageName, 14713 int newState, int flags, int userId, String callingPackage) { 14714 if (!sUserManager.exists(userId)) return; 14715 if (callingPackage == null) { 14716 callingPackage = Integer.toString(Binder.getCallingUid()); 14717 } 14718 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14719 } 14720 14721 @Override 14722 public void setComponentEnabledSetting(ComponentName componentName, 14723 int newState, int flags, int userId) { 14724 if (!sUserManager.exists(userId)) return; 14725 setEnabledSetting(componentName.getPackageName(), 14726 componentName.getClassName(), newState, flags, userId, null); 14727 } 14728 14729 private void setEnabledSetting(final String packageName, String className, int newState, 14730 final int flags, int userId, String callingPackage) { 14731 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14732 || newState == COMPONENT_ENABLED_STATE_ENABLED 14733 || newState == COMPONENT_ENABLED_STATE_DISABLED 14734 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14735 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14736 throw new IllegalArgumentException("Invalid new component state: " 14737 + newState); 14738 } 14739 PackageSetting pkgSetting; 14740 final int uid = Binder.getCallingUid(); 14741 final int permission = mContext.checkCallingOrSelfPermission( 14742 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14743 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14744 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14745 boolean sendNow = false; 14746 boolean isApp = (className == null); 14747 String componentName = isApp ? packageName : className; 14748 int packageUid = -1; 14749 ArrayList<String> components; 14750 14751 // writer 14752 synchronized (mPackages) { 14753 pkgSetting = mSettings.mPackages.get(packageName); 14754 if (pkgSetting == null) { 14755 if (className == null) { 14756 throw new IllegalArgumentException( 14757 "Unknown package: " + packageName); 14758 } 14759 throw new IllegalArgumentException( 14760 "Unknown component: " + packageName 14761 + "/" + className); 14762 } 14763 // Allow root and verify that userId is not being specified by a different user 14764 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14765 throw new SecurityException( 14766 "Permission Denial: attempt to change component state from pid=" 14767 + Binder.getCallingPid() 14768 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14769 } 14770 if (className == null) { 14771 // We're dealing with an application/package level state change 14772 if (pkgSetting.getEnabled(userId) == newState) { 14773 // Nothing to do 14774 return; 14775 } 14776 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14777 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14778 // Don't care about who enables an app. 14779 callingPackage = null; 14780 } 14781 pkgSetting.setEnabled(newState, userId, callingPackage); 14782 // pkgSetting.pkg.mSetEnabled = newState; 14783 } else { 14784 // We're dealing with a component level state change 14785 // First, verify that this is a valid class name. 14786 PackageParser.Package pkg = pkgSetting.pkg; 14787 if (pkg == null || !pkg.hasComponentClassName(className)) { 14788 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14789 throw new IllegalArgumentException("Component class " + className 14790 + " does not exist in " + packageName); 14791 } else { 14792 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14793 + className + " does not exist in " + packageName); 14794 } 14795 } 14796 switch (newState) { 14797 case COMPONENT_ENABLED_STATE_ENABLED: 14798 if (!pkgSetting.enableComponentLPw(className, userId)) { 14799 return; 14800 } 14801 break; 14802 case COMPONENT_ENABLED_STATE_DISABLED: 14803 if (!pkgSetting.disableComponentLPw(className, userId)) { 14804 return; 14805 } 14806 break; 14807 case COMPONENT_ENABLED_STATE_DEFAULT: 14808 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14809 return; 14810 } 14811 break; 14812 default: 14813 Slog.e(TAG, "Invalid new component state: " + newState); 14814 return; 14815 } 14816 } 14817 scheduleWritePackageRestrictionsLocked(userId); 14818 components = mPendingBroadcasts.get(userId, packageName); 14819 final boolean newPackage = components == null; 14820 if (newPackage) { 14821 components = new ArrayList<String>(); 14822 } 14823 if (!components.contains(componentName)) { 14824 components.add(componentName); 14825 } 14826 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14827 sendNow = true; 14828 // Purge entry from pending broadcast list if another one exists already 14829 // since we are sending one right away. 14830 mPendingBroadcasts.remove(userId, packageName); 14831 } else { 14832 if (newPackage) { 14833 mPendingBroadcasts.put(userId, packageName, components); 14834 } 14835 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14836 // Schedule a message 14837 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14838 } 14839 } 14840 } 14841 14842 long callingId = Binder.clearCallingIdentity(); 14843 try { 14844 if (sendNow) { 14845 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14846 sendPackageChangedBroadcast(packageName, 14847 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14848 } 14849 } finally { 14850 Binder.restoreCallingIdentity(callingId); 14851 } 14852 } 14853 14854 private void sendPackageChangedBroadcast(String packageName, 14855 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14856 if (DEBUG_INSTALL) 14857 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14858 + componentNames); 14859 Bundle extras = new Bundle(4); 14860 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14861 String nameList[] = new String[componentNames.size()]; 14862 componentNames.toArray(nameList); 14863 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14864 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14865 extras.putInt(Intent.EXTRA_UID, packageUid); 14866 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14867 new int[] {UserHandle.getUserId(packageUid)}); 14868 } 14869 14870 @Override 14871 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14872 if (!sUserManager.exists(userId)) return; 14873 final int uid = Binder.getCallingUid(); 14874 final int permission = mContext.checkCallingOrSelfPermission( 14875 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14876 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14877 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14878 // writer 14879 synchronized (mPackages) { 14880 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14881 allowedByPermission, uid, userId)) { 14882 scheduleWritePackageRestrictionsLocked(userId); 14883 } 14884 } 14885 } 14886 14887 @Override 14888 public String getInstallerPackageName(String packageName) { 14889 // reader 14890 synchronized (mPackages) { 14891 return mSettings.getInstallerPackageNameLPr(packageName); 14892 } 14893 } 14894 14895 @Override 14896 public int getApplicationEnabledSetting(String packageName, int userId) { 14897 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14898 int uid = Binder.getCallingUid(); 14899 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14900 // reader 14901 synchronized (mPackages) { 14902 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14903 } 14904 } 14905 14906 @Override 14907 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14908 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14909 int uid = Binder.getCallingUid(); 14910 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14911 // reader 14912 synchronized (mPackages) { 14913 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14914 } 14915 } 14916 14917 @Override 14918 public void enterSafeMode() { 14919 enforceSystemOrRoot("Only the system can request entering safe mode"); 14920 14921 if (!mSystemReady) { 14922 mSafeMode = true; 14923 } 14924 } 14925 14926 @Override 14927 public void systemReady() { 14928 mSystemReady = true; 14929 14930 // Read the compatibilty setting when the system is ready. 14931 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14932 mContext.getContentResolver(), 14933 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14934 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14935 if (DEBUG_SETTINGS) { 14936 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14937 } 14938 14939 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14940 14941 synchronized (mPackages) { 14942 // Verify that all of the preferred activity components actually 14943 // exist. It is possible for applications to be updated and at 14944 // that point remove a previously declared activity component that 14945 // had been set as a preferred activity. We try to clean this up 14946 // the next time we encounter that preferred activity, but it is 14947 // possible for the user flow to never be able to return to that 14948 // situation so here we do a sanity check to make sure we haven't 14949 // left any junk around. 14950 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14951 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14952 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14953 removed.clear(); 14954 for (PreferredActivity pa : pir.filterSet()) { 14955 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14956 removed.add(pa); 14957 } 14958 } 14959 if (removed.size() > 0) { 14960 for (int r=0; r<removed.size(); r++) { 14961 PreferredActivity pa = removed.get(r); 14962 Slog.w(TAG, "Removing dangling preferred activity: " 14963 + pa.mPref.mComponent); 14964 pir.removeFilter(pa); 14965 } 14966 mSettings.writePackageRestrictionsLPr( 14967 mSettings.mPreferredActivities.keyAt(i)); 14968 } 14969 } 14970 14971 for (int userId : UserManagerService.getInstance().getUserIds()) { 14972 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14973 grantPermissionsUserIds = ArrayUtils.appendInt( 14974 grantPermissionsUserIds, userId); 14975 } 14976 } 14977 } 14978 sUserManager.systemReady(); 14979 14980 // If we upgraded grant all default permissions before kicking off. 14981 for (int userId : grantPermissionsUserIds) { 14982 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14983 } 14984 14985 // Kick off any messages waiting for system ready 14986 if (mPostSystemReadyMessages != null) { 14987 for (Message msg : mPostSystemReadyMessages) { 14988 msg.sendToTarget(); 14989 } 14990 mPostSystemReadyMessages = null; 14991 } 14992 14993 // Watch for external volumes that come and go over time 14994 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14995 storage.registerListener(mStorageListener); 14996 14997 mInstallerService.systemReady(); 14998 mPackageDexOptimizer.systemReady(); 14999 15000 MountServiceInternal mountServiceInternal = LocalServices.getService( 15001 MountServiceInternal.class); 15002 mountServiceInternal.addExternalStoragePolicy( 15003 new MountServiceInternal.ExternalStorageMountPolicy() { 15004 @Override 15005 public int getMountMode(int uid, String packageName) { 15006 if (Process.isIsolated(uid)) { 15007 return Zygote.MOUNT_EXTERNAL_NONE; 15008 } 15009 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15010 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15011 } 15012 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15013 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15014 } 15015 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15016 return Zygote.MOUNT_EXTERNAL_READ; 15017 } 15018 return Zygote.MOUNT_EXTERNAL_WRITE; 15019 } 15020 15021 @Override 15022 public boolean hasExternalStorage(int uid, String packageName) { 15023 return true; 15024 } 15025 }); 15026 } 15027 15028 @Override 15029 public boolean isSafeMode() { 15030 return mSafeMode; 15031 } 15032 15033 @Override 15034 public boolean hasSystemUidErrors() { 15035 return mHasSystemUidErrors; 15036 } 15037 15038 static String arrayToString(int[] array) { 15039 StringBuffer buf = new StringBuffer(128); 15040 buf.append('['); 15041 if (array != null) { 15042 for (int i=0; i<array.length; i++) { 15043 if (i > 0) buf.append(", "); 15044 buf.append(array[i]); 15045 } 15046 } 15047 buf.append(']'); 15048 return buf.toString(); 15049 } 15050 15051 static class DumpState { 15052 public static final int DUMP_LIBS = 1 << 0; 15053 public static final int DUMP_FEATURES = 1 << 1; 15054 public static final int DUMP_RESOLVERS = 1 << 2; 15055 public static final int DUMP_PERMISSIONS = 1 << 3; 15056 public static final int DUMP_PACKAGES = 1 << 4; 15057 public static final int DUMP_SHARED_USERS = 1 << 5; 15058 public static final int DUMP_MESSAGES = 1 << 6; 15059 public static final int DUMP_PROVIDERS = 1 << 7; 15060 public static final int DUMP_VERIFIERS = 1 << 8; 15061 public static final int DUMP_PREFERRED = 1 << 9; 15062 public static final int DUMP_PREFERRED_XML = 1 << 10; 15063 public static final int DUMP_KEYSETS = 1 << 11; 15064 public static final int DUMP_VERSION = 1 << 12; 15065 public static final int DUMP_INSTALLS = 1 << 13; 15066 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 15067 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 15068 15069 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15070 15071 private int mTypes; 15072 15073 private int mOptions; 15074 15075 private boolean mTitlePrinted; 15076 15077 private SharedUserSetting mSharedUser; 15078 15079 public boolean isDumping(int type) { 15080 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15081 return true; 15082 } 15083 15084 return (mTypes & type) != 0; 15085 } 15086 15087 public void setDump(int type) { 15088 mTypes |= type; 15089 } 15090 15091 public boolean isOptionEnabled(int option) { 15092 return (mOptions & option) != 0; 15093 } 15094 15095 public void setOptionEnabled(int option) { 15096 mOptions |= option; 15097 } 15098 15099 public boolean onTitlePrinted() { 15100 final boolean printed = mTitlePrinted; 15101 mTitlePrinted = true; 15102 return printed; 15103 } 15104 15105 public boolean getTitlePrinted() { 15106 return mTitlePrinted; 15107 } 15108 15109 public void setTitlePrinted(boolean enabled) { 15110 mTitlePrinted = enabled; 15111 } 15112 15113 public SharedUserSetting getSharedUser() { 15114 return mSharedUser; 15115 } 15116 15117 public void setSharedUser(SharedUserSetting user) { 15118 mSharedUser = user; 15119 } 15120 } 15121 15122 @Override 15123 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15124 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15125 (new PackageManagerShellCommand(this)).exec( 15126 this, in, out, err, args, resultReceiver); 15127 } 15128 15129 @Override 15130 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15131 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15132 != PackageManager.PERMISSION_GRANTED) { 15133 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15134 + Binder.getCallingPid() 15135 + ", uid=" + Binder.getCallingUid() 15136 + " without permission " 15137 + android.Manifest.permission.DUMP); 15138 return; 15139 } 15140 15141 DumpState dumpState = new DumpState(); 15142 boolean fullPreferred = false; 15143 boolean checkin = false; 15144 15145 String packageName = null; 15146 ArraySet<String> permissionNames = null; 15147 15148 int opti = 0; 15149 while (opti < args.length) { 15150 String opt = args[opti]; 15151 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15152 break; 15153 } 15154 opti++; 15155 15156 if ("-a".equals(opt)) { 15157 // Right now we only know how to print all. 15158 } else if ("-h".equals(opt)) { 15159 pw.println("Package manager dump options:"); 15160 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15161 pw.println(" --checkin: dump for a checkin"); 15162 pw.println(" -f: print details of intent filters"); 15163 pw.println(" -h: print this help"); 15164 pw.println(" cmd may be one of:"); 15165 pw.println(" l[ibraries]: list known shared libraries"); 15166 pw.println(" f[ibraries]: list device features"); 15167 pw.println(" k[eysets]: print known keysets"); 15168 pw.println(" r[esolvers]: dump intent resolvers"); 15169 pw.println(" perm[issions]: dump permissions"); 15170 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15171 pw.println(" pref[erred]: print preferred package settings"); 15172 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15173 pw.println(" prov[iders]: dump content providers"); 15174 pw.println(" p[ackages]: dump installed packages"); 15175 pw.println(" s[hared-users]: dump shared user IDs"); 15176 pw.println(" m[essages]: print collected runtime messages"); 15177 pw.println(" v[erifiers]: print package verifier info"); 15178 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15179 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15180 pw.println(" version: print database version info"); 15181 pw.println(" write: write current settings now"); 15182 pw.println(" installs: details about install sessions"); 15183 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15184 pw.println(" <package.name>: info about given package"); 15185 return; 15186 } else if ("--checkin".equals(opt)) { 15187 checkin = true; 15188 } else if ("-f".equals(opt)) { 15189 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15190 } else { 15191 pw.println("Unknown argument: " + opt + "; use -h for help"); 15192 } 15193 } 15194 15195 // Is the caller requesting to dump a particular piece of data? 15196 if (opti < args.length) { 15197 String cmd = args[opti]; 15198 opti++; 15199 // Is this a package name? 15200 if ("android".equals(cmd) || cmd.contains(".")) { 15201 packageName = cmd; 15202 // When dumping a single package, we always dump all of its 15203 // filter information since the amount of data will be reasonable. 15204 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15205 } else if ("check-permission".equals(cmd)) { 15206 if (opti >= args.length) { 15207 pw.println("Error: check-permission missing permission argument"); 15208 return; 15209 } 15210 String perm = args[opti]; 15211 opti++; 15212 if (opti >= args.length) { 15213 pw.println("Error: check-permission missing package argument"); 15214 return; 15215 } 15216 String pkg = args[opti]; 15217 opti++; 15218 int user = UserHandle.getUserId(Binder.getCallingUid()); 15219 if (opti < args.length) { 15220 try { 15221 user = Integer.parseInt(args[opti]); 15222 } catch (NumberFormatException e) { 15223 pw.println("Error: check-permission user argument is not a number: " 15224 + args[opti]); 15225 return; 15226 } 15227 } 15228 pw.println(checkPermission(perm, pkg, user)); 15229 return; 15230 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15231 dumpState.setDump(DumpState.DUMP_LIBS); 15232 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15233 dumpState.setDump(DumpState.DUMP_FEATURES); 15234 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15235 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15236 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15237 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15238 } else if ("permission".equals(cmd)) { 15239 if (opti >= args.length) { 15240 pw.println("Error: permission requires permission name"); 15241 return; 15242 } 15243 permissionNames = new ArraySet<>(); 15244 while (opti < args.length) { 15245 permissionNames.add(args[opti]); 15246 opti++; 15247 } 15248 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15249 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15250 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15251 dumpState.setDump(DumpState.DUMP_PREFERRED); 15252 } else if ("preferred-xml".equals(cmd)) { 15253 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15254 if (opti < args.length && "--full".equals(args[opti])) { 15255 fullPreferred = true; 15256 opti++; 15257 } 15258 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15259 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15260 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15261 dumpState.setDump(DumpState.DUMP_PACKAGES); 15262 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15263 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15264 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15265 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15266 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15267 dumpState.setDump(DumpState.DUMP_MESSAGES); 15268 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15269 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15270 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15271 || "intent-filter-verifiers".equals(cmd)) { 15272 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15273 } else if ("version".equals(cmd)) { 15274 dumpState.setDump(DumpState.DUMP_VERSION); 15275 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15276 dumpState.setDump(DumpState.DUMP_KEYSETS); 15277 } else if ("installs".equals(cmd)) { 15278 dumpState.setDump(DumpState.DUMP_INSTALLS); 15279 } else if ("write".equals(cmd)) { 15280 synchronized (mPackages) { 15281 mSettings.writeLPr(); 15282 pw.println("Settings written."); 15283 return; 15284 } 15285 } 15286 } 15287 15288 if (checkin) { 15289 pw.println("vers,1"); 15290 } 15291 15292 // reader 15293 synchronized (mPackages) { 15294 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15295 if (!checkin) { 15296 if (dumpState.onTitlePrinted()) 15297 pw.println(); 15298 pw.println("Database versions:"); 15299 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15300 } 15301 } 15302 15303 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15304 if (!checkin) { 15305 if (dumpState.onTitlePrinted()) 15306 pw.println(); 15307 pw.println("Verifiers:"); 15308 pw.print(" Required: "); 15309 pw.print(mRequiredVerifierPackage); 15310 pw.print(" (uid="); 15311 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15312 pw.println(")"); 15313 } else if (mRequiredVerifierPackage != null) { 15314 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15315 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15316 } 15317 } 15318 15319 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15320 packageName == null) { 15321 if (mIntentFilterVerifierComponent != null) { 15322 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15323 if (!checkin) { 15324 if (dumpState.onTitlePrinted()) 15325 pw.println(); 15326 pw.println("Intent Filter Verifier:"); 15327 pw.print(" Using: "); 15328 pw.print(verifierPackageName); 15329 pw.print(" (uid="); 15330 pw.print(getPackageUid(verifierPackageName, 0)); 15331 pw.println(")"); 15332 } else if (verifierPackageName != null) { 15333 pw.print("ifv,"); pw.print(verifierPackageName); 15334 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15335 } 15336 } else { 15337 pw.println(); 15338 pw.println("No Intent Filter Verifier available!"); 15339 } 15340 } 15341 15342 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15343 boolean printedHeader = false; 15344 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15345 while (it.hasNext()) { 15346 String name = it.next(); 15347 SharedLibraryEntry ent = mSharedLibraries.get(name); 15348 if (!checkin) { 15349 if (!printedHeader) { 15350 if (dumpState.onTitlePrinted()) 15351 pw.println(); 15352 pw.println("Libraries:"); 15353 printedHeader = true; 15354 } 15355 pw.print(" "); 15356 } else { 15357 pw.print("lib,"); 15358 } 15359 pw.print(name); 15360 if (!checkin) { 15361 pw.print(" -> "); 15362 } 15363 if (ent.path != null) { 15364 if (!checkin) { 15365 pw.print("(jar) "); 15366 pw.print(ent.path); 15367 } else { 15368 pw.print(",jar,"); 15369 pw.print(ent.path); 15370 } 15371 } else { 15372 if (!checkin) { 15373 pw.print("(apk) "); 15374 pw.print(ent.apk); 15375 } else { 15376 pw.print(",apk,"); 15377 pw.print(ent.apk); 15378 } 15379 } 15380 pw.println(); 15381 } 15382 } 15383 15384 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15385 if (dumpState.onTitlePrinted()) 15386 pw.println(); 15387 if (!checkin) { 15388 pw.println("Features:"); 15389 } 15390 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15391 while (it.hasNext()) { 15392 String name = it.next(); 15393 if (!checkin) { 15394 pw.print(" "); 15395 } else { 15396 pw.print("feat,"); 15397 } 15398 pw.println(name); 15399 } 15400 } 15401 15402 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15403 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15404 : "Activity Resolver Table:", " ", packageName, 15405 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15406 dumpState.setTitlePrinted(true); 15407 } 15408 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15409 : "Receiver Resolver Table:", " ", packageName, 15410 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15411 dumpState.setTitlePrinted(true); 15412 } 15413 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15414 : "Service Resolver Table:", " ", packageName, 15415 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15416 dumpState.setTitlePrinted(true); 15417 } 15418 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15419 : "Provider Resolver Table:", " ", packageName, 15420 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15421 dumpState.setTitlePrinted(true); 15422 } 15423 } 15424 15425 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15426 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15427 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15428 int user = mSettings.mPreferredActivities.keyAt(i); 15429 if (pir.dump(pw, 15430 dumpState.getTitlePrinted() 15431 ? "\nPreferred Activities User " + user + ":" 15432 : "Preferred Activities User " + user + ":", " ", 15433 packageName, true, false)) { 15434 dumpState.setTitlePrinted(true); 15435 } 15436 } 15437 } 15438 15439 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15440 pw.flush(); 15441 FileOutputStream fout = new FileOutputStream(fd); 15442 BufferedOutputStream str = new BufferedOutputStream(fout); 15443 XmlSerializer serializer = new FastXmlSerializer(); 15444 try { 15445 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15446 serializer.startDocument(null, true); 15447 serializer.setFeature( 15448 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15449 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15450 serializer.endDocument(); 15451 serializer.flush(); 15452 } catch (IllegalArgumentException e) { 15453 pw.println("Failed writing: " + e); 15454 } catch (IllegalStateException e) { 15455 pw.println("Failed writing: " + e); 15456 } catch (IOException e) { 15457 pw.println("Failed writing: " + e); 15458 } 15459 } 15460 15461 if (!checkin 15462 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15463 && packageName == null) { 15464 pw.println(); 15465 int count = mSettings.mPackages.size(); 15466 if (count == 0) { 15467 pw.println("No applications!"); 15468 pw.println(); 15469 } else { 15470 final String prefix = " "; 15471 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15472 if (allPackageSettings.size() == 0) { 15473 pw.println("No domain preferred apps!"); 15474 pw.println(); 15475 } else { 15476 pw.println("App verification status:"); 15477 pw.println(); 15478 count = 0; 15479 for (PackageSetting ps : allPackageSettings) { 15480 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15481 if (ivi == null || ivi.getPackageName() == null) continue; 15482 pw.println(prefix + "Package: " + ivi.getPackageName()); 15483 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15484 pw.println(prefix + "Status: " + ivi.getStatusString()); 15485 pw.println(); 15486 count++; 15487 } 15488 if (count == 0) { 15489 pw.println(prefix + "No app verification established."); 15490 pw.println(); 15491 } 15492 for (int userId : sUserManager.getUserIds()) { 15493 pw.println("App linkages for user " + userId + ":"); 15494 pw.println(); 15495 count = 0; 15496 for (PackageSetting ps : allPackageSettings) { 15497 final long status = ps.getDomainVerificationStatusForUser(userId); 15498 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15499 continue; 15500 } 15501 pw.println(prefix + "Package: " + ps.name); 15502 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15503 String statusStr = IntentFilterVerificationInfo. 15504 getStatusStringFromValue(status); 15505 pw.println(prefix + "Status: " + statusStr); 15506 pw.println(); 15507 count++; 15508 } 15509 if (count == 0) { 15510 pw.println(prefix + "No configured app linkages."); 15511 pw.println(); 15512 } 15513 } 15514 } 15515 } 15516 } 15517 15518 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15519 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15520 if (packageName == null && permissionNames == null) { 15521 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15522 if (iperm == 0) { 15523 if (dumpState.onTitlePrinted()) 15524 pw.println(); 15525 pw.println("AppOp Permissions:"); 15526 } 15527 pw.print(" AppOp Permission "); 15528 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15529 pw.println(":"); 15530 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15531 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15532 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15533 } 15534 } 15535 } 15536 } 15537 15538 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15539 boolean printedSomething = false; 15540 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15541 if (packageName != null && !packageName.equals(p.info.packageName)) { 15542 continue; 15543 } 15544 if (!printedSomething) { 15545 if (dumpState.onTitlePrinted()) 15546 pw.println(); 15547 pw.println("Registered ContentProviders:"); 15548 printedSomething = true; 15549 } 15550 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15551 pw.print(" "); pw.println(p.toString()); 15552 } 15553 printedSomething = false; 15554 for (Map.Entry<String, PackageParser.Provider> entry : 15555 mProvidersByAuthority.entrySet()) { 15556 PackageParser.Provider p = entry.getValue(); 15557 if (packageName != null && !packageName.equals(p.info.packageName)) { 15558 continue; 15559 } 15560 if (!printedSomething) { 15561 if (dumpState.onTitlePrinted()) 15562 pw.println(); 15563 pw.println("ContentProvider Authorities:"); 15564 printedSomething = true; 15565 } 15566 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15567 pw.print(" "); pw.println(p.toString()); 15568 if (p.info != null && p.info.applicationInfo != null) { 15569 final String appInfo = p.info.applicationInfo.toString(); 15570 pw.print(" applicationInfo="); pw.println(appInfo); 15571 } 15572 } 15573 } 15574 15575 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15576 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15577 } 15578 15579 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15580 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15581 } 15582 15583 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15584 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15585 } 15586 15587 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15588 // XXX should handle packageName != null by dumping only install data that 15589 // the given package is involved with. 15590 if (dumpState.onTitlePrinted()) pw.println(); 15591 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15592 } 15593 15594 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15595 if (dumpState.onTitlePrinted()) pw.println(); 15596 mSettings.dumpReadMessagesLPr(pw, dumpState); 15597 15598 pw.println(); 15599 pw.println("Package warning messages:"); 15600 BufferedReader in = null; 15601 String line = null; 15602 try { 15603 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15604 while ((line = in.readLine()) != null) { 15605 if (line.contains("ignored: updated version")) continue; 15606 pw.println(line); 15607 } 15608 } catch (IOException ignored) { 15609 } finally { 15610 IoUtils.closeQuietly(in); 15611 } 15612 } 15613 15614 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15615 BufferedReader in = null; 15616 String line = null; 15617 try { 15618 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15619 while ((line = in.readLine()) != null) { 15620 if (line.contains("ignored: updated version")) continue; 15621 pw.print("msg,"); 15622 pw.println(line); 15623 } 15624 } catch (IOException ignored) { 15625 } finally { 15626 IoUtils.closeQuietly(in); 15627 } 15628 } 15629 } 15630 } 15631 15632 private String dumpDomainString(String packageName) { 15633 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15634 List<IntentFilter> filters = getAllIntentFilters(packageName); 15635 15636 ArraySet<String> result = new ArraySet<>(); 15637 if (iviList.size() > 0) { 15638 for (IntentFilterVerificationInfo ivi : iviList) { 15639 for (String host : ivi.getDomains()) { 15640 result.add(host); 15641 } 15642 } 15643 } 15644 if (filters != null && filters.size() > 0) { 15645 for (IntentFilter filter : filters) { 15646 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15647 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15648 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15649 result.addAll(filter.getHostsList()); 15650 } 15651 } 15652 } 15653 15654 StringBuilder sb = new StringBuilder(result.size() * 16); 15655 for (String domain : result) { 15656 if (sb.length() > 0) sb.append(" "); 15657 sb.append(domain); 15658 } 15659 return sb.toString(); 15660 } 15661 15662 // ------- apps on sdcard specific code ------- 15663 static final boolean DEBUG_SD_INSTALL = false; 15664 15665 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15666 15667 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15668 15669 private boolean mMediaMounted = false; 15670 15671 static String getEncryptKey() { 15672 try { 15673 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15674 SD_ENCRYPTION_KEYSTORE_NAME); 15675 if (sdEncKey == null) { 15676 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15677 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15678 if (sdEncKey == null) { 15679 Slog.e(TAG, "Failed to create encryption keys"); 15680 return null; 15681 } 15682 } 15683 return sdEncKey; 15684 } catch (NoSuchAlgorithmException nsae) { 15685 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15686 return null; 15687 } catch (IOException ioe) { 15688 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15689 return null; 15690 } 15691 } 15692 15693 /* 15694 * Update media status on PackageManager. 15695 */ 15696 @Override 15697 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15698 int callingUid = Binder.getCallingUid(); 15699 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15700 throw new SecurityException("Media status can only be updated by the system"); 15701 } 15702 // reader; this apparently protects mMediaMounted, but should probably 15703 // be a different lock in that case. 15704 synchronized (mPackages) { 15705 Log.i(TAG, "Updating external media status from " 15706 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15707 + (mediaStatus ? "mounted" : "unmounted")); 15708 if (DEBUG_SD_INSTALL) 15709 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15710 + ", mMediaMounted=" + mMediaMounted); 15711 if (mediaStatus == mMediaMounted) { 15712 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15713 : 0, -1); 15714 mHandler.sendMessage(msg); 15715 return; 15716 } 15717 mMediaMounted = mediaStatus; 15718 } 15719 // Queue up an async operation since the package installation may take a 15720 // little while. 15721 mHandler.post(new Runnable() { 15722 public void run() { 15723 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15724 } 15725 }); 15726 } 15727 15728 /** 15729 * Called by MountService when the initial ASECs to scan are available. 15730 * Should block until all the ASEC containers are finished being scanned. 15731 */ 15732 public void scanAvailableAsecs() { 15733 updateExternalMediaStatusInner(true, false, false); 15734 if (mShouldRestoreconData) { 15735 SELinuxMMAC.setRestoreconDone(); 15736 mShouldRestoreconData = false; 15737 } 15738 } 15739 15740 /* 15741 * Collect information of applications on external media, map them against 15742 * existing containers and update information based on current mount status. 15743 * Please note that we always have to report status if reportStatus has been 15744 * set to true especially when unloading packages. 15745 */ 15746 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15747 boolean externalStorage) { 15748 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15749 int[] uidArr = EmptyArray.INT; 15750 15751 final String[] list = PackageHelper.getSecureContainerList(); 15752 if (ArrayUtils.isEmpty(list)) { 15753 Log.i(TAG, "No secure containers found"); 15754 } else { 15755 // Process list of secure containers and categorize them 15756 // as active or stale based on their package internal state. 15757 15758 // reader 15759 synchronized (mPackages) { 15760 for (String cid : list) { 15761 // Leave stages untouched for now; installer service owns them 15762 if (PackageInstallerService.isStageName(cid)) continue; 15763 15764 if (DEBUG_SD_INSTALL) 15765 Log.i(TAG, "Processing container " + cid); 15766 String pkgName = getAsecPackageName(cid); 15767 if (pkgName == null) { 15768 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15769 continue; 15770 } 15771 if (DEBUG_SD_INSTALL) 15772 Log.i(TAG, "Looking for pkg : " + pkgName); 15773 15774 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15775 if (ps == null) { 15776 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15777 continue; 15778 } 15779 15780 /* 15781 * Skip packages that are not external if we're unmounting 15782 * external storage. 15783 */ 15784 if (externalStorage && !isMounted && !isExternal(ps)) { 15785 continue; 15786 } 15787 15788 final AsecInstallArgs args = new AsecInstallArgs(cid, 15789 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15790 // The package status is changed only if the code path 15791 // matches between settings and the container id. 15792 if (ps.codePathString != null 15793 && ps.codePathString.startsWith(args.getCodePath())) { 15794 if (DEBUG_SD_INSTALL) { 15795 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15796 + " at code path: " + ps.codePathString); 15797 } 15798 15799 // We do have a valid package installed on sdcard 15800 processCids.put(args, ps.codePathString); 15801 final int uid = ps.appId; 15802 if (uid != -1) { 15803 uidArr = ArrayUtils.appendInt(uidArr, uid); 15804 } 15805 } else { 15806 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15807 + ps.codePathString); 15808 } 15809 } 15810 } 15811 15812 Arrays.sort(uidArr); 15813 } 15814 15815 // Process packages with valid entries. 15816 if (isMounted) { 15817 if (DEBUG_SD_INSTALL) 15818 Log.i(TAG, "Loading packages"); 15819 loadMediaPackages(processCids, uidArr, externalStorage); 15820 startCleaningPackages(); 15821 mInstallerService.onSecureContainersAvailable(); 15822 } else { 15823 if (DEBUG_SD_INSTALL) 15824 Log.i(TAG, "Unloading packages"); 15825 unloadMediaPackages(processCids, uidArr, reportStatus); 15826 } 15827 } 15828 15829 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15830 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15831 final int size = infos.size(); 15832 final String[] packageNames = new String[size]; 15833 final int[] packageUids = new int[size]; 15834 for (int i = 0; i < size; i++) { 15835 final ApplicationInfo info = infos.get(i); 15836 packageNames[i] = info.packageName; 15837 packageUids[i] = info.uid; 15838 } 15839 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15840 finishedReceiver); 15841 } 15842 15843 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15844 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15845 sendResourcesChangedBroadcast(mediaStatus, replacing, 15846 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15847 } 15848 15849 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15850 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15851 int size = pkgList.length; 15852 if (size > 0) { 15853 // Send broadcasts here 15854 Bundle extras = new Bundle(); 15855 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15856 if (uidArr != null) { 15857 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15858 } 15859 if (replacing) { 15860 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15861 } 15862 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15863 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15864 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15865 } 15866 } 15867 15868 /* 15869 * Look at potentially valid container ids from processCids If package 15870 * information doesn't match the one on record or package scanning fails, 15871 * the cid is added to list of removeCids. We currently don't delete stale 15872 * containers. 15873 */ 15874 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15875 boolean externalStorage) { 15876 ArrayList<String> pkgList = new ArrayList<String>(); 15877 Set<AsecInstallArgs> keys = processCids.keySet(); 15878 15879 for (AsecInstallArgs args : keys) { 15880 String codePath = processCids.get(args); 15881 if (DEBUG_SD_INSTALL) 15882 Log.i(TAG, "Loading container : " + args.cid); 15883 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15884 try { 15885 // Make sure there are no container errors first. 15886 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15887 Slog.e(TAG, "Failed to mount cid : " + args.cid 15888 + " when installing from sdcard"); 15889 continue; 15890 } 15891 // Check code path here. 15892 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15893 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15894 + " does not match one in settings " + codePath); 15895 continue; 15896 } 15897 // Parse package 15898 int parseFlags = mDefParseFlags; 15899 if (args.isExternalAsec()) { 15900 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15901 } 15902 if (args.isFwdLocked()) { 15903 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15904 } 15905 15906 synchronized (mInstallLock) { 15907 PackageParser.Package pkg = null; 15908 try { 15909 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15910 } catch (PackageManagerException e) { 15911 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15912 } 15913 // Scan the package 15914 if (pkg != null) { 15915 /* 15916 * TODO why is the lock being held? doPostInstall is 15917 * called in other places without the lock. This needs 15918 * to be straightened out. 15919 */ 15920 // writer 15921 synchronized (mPackages) { 15922 retCode = PackageManager.INSTALL_SUCCEEDED; 15923 pkgList.add(pkg.packageName); 15924 // Post process args 15925 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15926 pkg.applicationInfo.uid); 15927 } 15928 } else { 15929 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15930 } 15931 } 15932 15933 } finally { 15934 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15935 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15936 } 15937 } 15938 } 15939 // writer 15940 synchronized (mPackages) { 15941 // If the platform SDK has changed since the last time we booted, 15942 // we need to re-grant app permission to catch any new ones that 15943 // appear. This is really a hack, and means that apps can in some 15944 // cases get permissions that the user didn't initially explicitly 15945 // allow... it would be nice to have some better way to handle 15946 // this situation. 15947 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15948 : mSettings.getInternalVersion(); 15949 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15950 : StorageManager.UUID_PRIVATE_INTERNAL; 15951 15952 int updateFlags = UPDATE_PERMISSIONS_ALL; 15953 if (ver.sdkVersion != mSdkVersion) { 15954 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15955 + mSdkVersion + "; regranting permissions for external"); 15956 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15957 } 15958 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15959 15960 // Yay, everything is now upgraded 15961 ver.forceCurrent(); 15962 15963 // can downgrade to reader 15964 // Persist settings 15965 mSettings.writeLPr(); 15966 } 15967 // Send a broadcast to let everyone know we are done processing 15968 if (pkgList.size() > 0) { 15969 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15970 } 15971 } 15972 15973 /* 15974 * Utility method to unload a list of specified containers 15975 */ 15976 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15977 // Just unmount all valid containers. 15978 for (AsecInstallArgs arg : cidArgs) { 15979 synchronized (mInstallLock) { 15980 arg.doPostDeleteLI(false); 15981 } 15982 } 15983 } 15984 15985 /* 15986 * Unload packages mounted on external media. This involves deleting package 15987 * data from internal structures, sending broadcasts about diabled packages, 15988 * gc'ing to free up references, unmounting all secure containers 15989 * corresponding to packages on external media, and posting a 15990 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15991 * that we always have to post this message if status has been requested no 15992 * matter what. 15993 */ 15994 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15995 final boolean reportStatus) { 15996 if (DEBUG_SD_INSTALL) 15997 Log.i(TAG, "unloading media packages"); 15998 ArrayList<String> pkgList = new ArrayList<String>(); 15999 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16000 final Set<AsecInstallArgs> keys = processCids.keySet(); 16001 for (AsecInstallArgs args : keys) { 16002 String pkgName = args.getPackageName(); 16003 if (DEBUG_SD_INSTALL) 16004 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16005 // Delete package internally 16006 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16007 synchronized (mInstallLock) { 16008 boolean res = deletePackageLI(pkgName, null, false, null, null, 16009 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16010 if (res) { 16011 pkgList.add(pkgName); 16012 } else { 16013 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16014 failedList.add(args); 16015 } 16016 } 16017 } 16018 16019 // reader 16020 synchronized (mPackages) { 16021 // We didn't update the settings after removing each package; 16022 // write them now for all packages. 16023 mSettings.writeLPr(); 16024 } 16025 16026 // We have to absolutely send UPDATED_MEDIA_STATUS only 16027 // after confirming that all the receivers processed the ordered 16028 // broadcast when packages get disabled, force a gc to clean things up. 16029 // and unload all the containers. 16030 if (pkgList.size() > 0) { 16031 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16032 new IIntentReceiver.Stub() { 16033 public void performReceive(Intent intent, int resultCode, String data, 16034 Bundle extras, boolean ordered, boolean sticky, 16035 int sendingUser) throws RemoteException { 16036 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16037 reportStatus ? 1 : 0, 1, keys); 16038 mHandler.sendMessage(msg); 16039 } 16040 }); 16041 } else { 16042 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16043 keys); 16044 mHandler.sendMessage(msg); 16045 } 16046 } 16047 16048 private void loadPrivatePackages(final VolumeInfo vol) { 16049 mHandler.post(new Runnable() { 16050 @Override 16051 public void run() { 16052 loadPrivatePackagesInner(vol); 16053 } 16054 }); 16055 } 16056 16057 private void loadPrivatePackagesInner(VolumeInfo vol) { 16058 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16059 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16060 16061 final VersionInfo ver; 16062 final List<PackageSetting> packages; 16063 synchronized (mPackages) { 16064 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16065 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16066 } 16067 16068 for (PackageSetting ps : packages) { 16069 synchronized (mInstallLock) { 16070 final PackageParser.Package pkg; 16071 try { 16072 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16073 loaded.add(pkg.applicationInfo); 16074 } catch (PackageManagerException e) { 16075 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16076 } 16077 16078 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16079 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16080 } 16081 } 16082 } 16083 16084 synchronized (mPackages) { 16085 int updateFlags = UPDATE_PERMISSIONS_ALL; 16086 if (ver.sdkVersion != mSdkVersion) { 16087 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16088 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16089 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16090 } 16091 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16092 16093 // Yay, everything is now upgraded 16094 ver.forceCurrent(); 16095 16096 mSettings.writeLPr(); 16097 } 16098 16099 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16100 sendResourcesChangedBroadcast(true, false, loaded, null); 16101 } 16102 16103 private void unloadPrivatePackages(final VolumeInfo vol) { 16104 mHandler.post(new Runnable() { 16105 @Override 16106 public void run() { 16107 unloadPrivatePackagesInner(vol); 16108 } 16109 }); 16110 } 16111 16112 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16113 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16114 synchronized (mInstallLock) { 16115 synchronized (mPackages) { 16116 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16117 for (PackageSetting ps : packages) { 16118 if (ps.pkg == null) continue; 16119 16120 final ApplicationInfo info = ps.pkg.applicationInfo; 16121 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16122 if (deletePackageLI(ps.name, null, false, null, null, 16123 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16124 unloaded.add(info); 16125 } else { 16126 Slog.w(TAG, "Failed to unload " + ps.codePath); 16127 } 16128 } 16129 16130 mSettings.writeLPr(); 16131 } 16132 } 16133 16134 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16135 sendResourcesChangedBroadcast(false, false, unloaded, null); 16136 } 16137 16138 /** 16139 * Examine all users present on given mounted volume, and destroy data 16140 * belonging to users that are no longer valid, or whose user ID has been 16141 * recycled. 16142 */ 16143 private void reconcileUsers(String volumeUuid) { 16144 final File[] files = FileUtils 16145 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16146 for (File file : files) { 16147 if (!file.isDirectory()) continue; 16148 16149 final int userId; 16150 final UserInfo info; 16151 try { 16152 userId = Integer.parseInt(file.getName()); 16153 info = sUserManager.getUserInfo(userId); 16154 } catch (NumberFormatException e) { 16155 Slog.w(TAG, "Invalid user directory " + file); 16156 continue; 16157 } 16158 16159 boolean destroyUser = false; 16160 if (info == null) { 16161 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16162 + " because no matching user was found"); 16163 destroyUser = true; 16164 } else { 16165 try { 16166 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16167 } catch (IOException e) { 16168 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16169 + " because we failed to enforce serial number: " + e); 16170 destroyUser = true; 16171 } 16172 } 16173 16174 if (destroyUser) { 16175 synchronized (mInstallLock) { 16176 mInstaller.removeUserDataDirs(volumeUuid, userId); 16177 } 16178 } 16179 } 16180 16181 final UserManager um = mContext.getSystemService(UserManager.class); 16182 for (UserInfo user : um.getUsers()) { 16183 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16184 if (userDir.exists()) continue; 16185 16186 try { 16187 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16188 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16189 } catch (IOException e) { 16190 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16191 } 16192 } 16193 } 16194 16195 /** 16196 * Examine all apps present on given mounted volume, and destroy apps that 16197 * aren't expected, either due to uninstallation or reinstallation on 16198 * another volume. 16199 */ 16200 private void reconcileApps(String volumeUuid) { 16201 final File[] files = FileUtils 16202 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16203 for (File file : files) { 16204 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16205 && !PackageInstallerService.isStageName(file.getName()); 16206 if (!isPackage) { 16207 // Ignore entries which are not packages 16208 continue; 16209 } 16210 16211 boolean destroyApp = false; 16212 String packageName = null; 16213 try { 16214 final PackageLite pkg = PackageParser.parsePackageLite(file, 16215 PackageParser.PARSE_MUST_BE_APK); 16216 packageName = pkg.packageName; 16217 16218 synchronized (mPackages) { 16219 final PackageSetting ps = mSettings.mPackages.get(packageName); 16220 if (ps == null) { 16221 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16222 + volumeUuid + " because we found no install record"); 16223 destroyApp = true; 16224 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16225 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16226 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16227 destroyApp = true; 16228 } 16229 } 16230 16231 } catch (PackageParserException e) { 16232 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16233 destroyApp = true; 16234 } 16235 16236 if (destroyApp) { 16237 synchronized (mInstallLock) { 16238 if (packageName != null) { 16239 removeDataDirsLI(volumeUuid, packageName); 16240 } 16241 if (file.isDirectory()) { 16242 mInstaller.rmPackageDir(file.getAbsolutePath()); 16243 } else { 16244 file.delete(); 16245 } 16246 } 16247 } 16248 } 16249 } 16250 16251 private void unfreezePackage(String packageName) { 16252 synchronized (mPackages) { 16253 final PackageSetting ps = mSettings.mPackages.get(packageName); 16254 if (ps != null) { 16255 ps.frozen = false; 16256 } 16257 } 16258 } 16259 16260 @Override 16261 public int movePackage(final String packageName, final String volumeUuid) { 16262 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16263 16264 final int moveId = mNextMoveId.getAndIncrement(); 16265 mHandler.post(new Runnable() { 16266 @Override 16267 public void run() { 16268 try { 16269 movePackageInternal(packageName, volumeUuid, moveId); 16270 } catch (PackageManagerException e) { 16271 Slog.w(TAG, "Failed to move " + packageName, e); 16272 mMoveCallbacks.notifyStatusChanged(moveId, 16273 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16274 } 16275 } 16276 }); 16277 return moveId; 16278 } 16279 16280 private void movePackageInternal(final String packageName, final String volumeUuid, 16281 final int moveId) throws PackageManagerException { 16282 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16283 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16284 final PackageManager pm = mContext.getPackageManager(); 16285 16286 final boolean currentAsec; 16287 final String currentVolumeUuid; 16288 final File codeFile; 16289 final String installerPackageName; 16290 final String packageAbiOverride; 16291 final int appId; 16292 final String seinfo; 16293 final String label; 16294 16295 // reader 16296 synchronized (mPackages) { 16297 final PackageParser.Package pkg = mPackages.get(packageName); 16298 final PackageSetting ps = mSettings.mPackages.get(packageName); 16299 if (pkg == null || ps == null) { 16300 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16301 } 16302 16303 if (pkg.applicationInfo.isSystemApp()) { 16304 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16305 "Cannot move system application"); 16306 } 16307 16308 if (pkg.applicationInfo.isExternalAsec()) { 16309 currentAsec = true; 16310 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16311 } else if (pkg.applicationInfo.isForwardLocked()) { 16312 currentAsec = true; 16313 currentVolumeUuid = "forward_locked"; 16314 } else { 16315 currentAsec = false; 16316 currentVolumeUuid = ps.volumeUuid; 16317 16318 final File probe = new File(pkg.codePath); 16319 final File probeOat = new File(probe, "oat"); 16320 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16321 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16322 "Move only supported for modern cluster style installs"); 16323 } 16324 } 16325 16326 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16327 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16328 "Package already moved to " + volumeUuid); 16329 } 16330 16331 if (ps.frozen) { 16332 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16333 "Failed to move already frozen package"); 16334 } 16335 ps.frozen = true; 16336 16337 codeFile = new File(pkg.codePath); 16338 installerPackageName = ps.installerPackageName; 16339 packageAbiOverride = ps.cpuAbiOverrideString; 16340 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16341 seinfo = pkg.applicationInfo.seinfo; 16342 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16343 } 16344 16345 // Now that we're guarded by frozen state, kill app during move 16346 final long token = Binder.clearCallingIdentity(); 16347 try { 16348 killApplication(packageName, appId, "move pkg"); 16349 } finally { 16350 Binder.restoreCallingIdentity(token); 16351 } 16352 16353 final Bundle extras = new Bundle(); 16354 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16355 extras.putString(Intent.EXTRA_TITLE, label); 16356 mMoveCallbacks.notifyCreated(moveId, extras); 16357 16358 int installFlags; 16359 final boolean moveCompleteApp; 16360 final File measurePath; 16361 16362 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16363 installFlags = INSTALL_INTERNAL; 16364 moveCompleteApp = !currentAsec; 16365 measurePath = Environment.getDataAppDirectory(volumeUuid); 16366 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16367 installFlags = INSTALL_EXTERNAL; 16368 moveCompleteApp = false; 16369 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16370 } else { 16371 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16372 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16373 || !volume.isMountedWritable()) { 16374 unfreezePackage(packageName); 16375 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16376 "Move location not mounted private volume"); 16377 } 16378 16379 Preconditions.checkState(!currentAsec); 16380 16381 installFlags = INSTALL_INTERNAL; 16382 moveCompleteApp = true; 16383 measurePath = Environment.getDataAppDirectory(volumeUuid); 16384 } 16385 16386 final PackageStats stats = new PackageStats(null, -1); 16387 synchronized (mInstaller) { 16388 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16389 unfreezePackage(packageName); 16390 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16391 "Failed to measure package size"); 16392 } 16393 } 16394 16395 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16396 + stats.dataSize); 16397 16398 final long startFreeBytes = measurePath.getFreeSpace(); 16399 final long sizeBytes; 16400 if (moveCompleteApp) { 16401 sizeBytes = stats.codeSize + stats.dataSize; 16402 } else { 16403 sizeBytes = stats.codeSize; 16404 } 16405 16406 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16407 unfreezePackage(packageName); 16408 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16409 "Not enough free space to move"); 16410 } 16411 16412 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16413 16414 final CountDownLatch installedLatch = new CountDownLatch(1); 16415 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16416 @Override 16417 public void onUserActionRequired(Intent intent) throws RemoteException { 16418 throw new IllegalStateException(); 16419 } 16420 16421 @Override 16422 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16423 Bundle extras) throws RemoteException { 16424 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16425 + PackageManager.installStatusToString(returnCode, msg)); 16426 16427 installedLatch.countDown(); 16428 16429 // Regardless of success or failure of the move operation, 16430 // always unfreeze the package 16431 unfreezePackage(packageName); 16432 16433 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16434 switch (status) { 16435 case PackageInstaller.STATUS_SUCCESS: 16436 mMoveCallbacks.notifyStatusChanged(moveId, 16437 PackageManager.MOVE_SUCCEEDED); 16438 break; 16439 case PackageInstaller.STATUS_FAILURE_STORAGE: 16440 mMoveCallbacks.notifyStatusChanged(moveId, 16441 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16442 break; 16443 default: 16444 mMoveCallbacks.notifyStatusChanged(moveId, 16445 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16446 break; 16447 } 16448 } 16449 }; 16450 16451 final MoveInfo move; 16452 if (moveCompleteApp) { 16453 // Kick off a thread to report progress estimates 16454 new Thread() { 16455 @Override 16456 public void run() { 16457 while (true) { 16458 try { 16459 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16460 break; 16461 } 16462 } catch (InterruptedException ignored) { 16463 } 16464 16465 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16466 final int progress = 10 + (int) MathUtils.constrain( 16467 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16468 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16469 } 16470 } 16471 }.start(); 16472 16473 final String dataAppName = codeFile.getName(); 16474 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16475 dataAppName, appId, seinfo); 16476 } else { 16477 move = null; 16478 } 16479 16480 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16481 16482 final Message msg = mHandler.obtainMessage(INIT_COPY); 16483 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16484 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16485 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16486 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16487 msg.obj = params; 16488 16489 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16490 System.identityHashCode(msg.obj)); 16491 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16492 System.identityHashCode(msg.obj)); 16493 16494 mHandler.sendMessage(msg); 16495 } 16496 16497 @Override 16498 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16499 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16500 16501 final int realMoveId = mNextMoveId.getAndIncrement(); 16502 final Bundle extras = new Bundle(); 16503 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16504 mMoveCallbacks.notifyCreated(realMoveId, extras); 16505 16506 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16507 @Override 16508 public void onCreated(int moveId, Bundle extras) { 16509 // Ignored 16510 } 16511 16512 @Override 16513 public void onStatusChanged(int moveId, int status, long estMillis) { 16514 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16515 } 16516 }; 16517 16518 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16519 storage.setPrimaryStorageUuid(volumeUuid, callback); 16520 return realMoveId; 16521 } 16522 16523 @Override 16524 public int getMoveStatus(int moveId) { 16525 mContext.enforceCallingOrSelfPermission( 16526 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16527 return mMoveCallbacks.mLastStatus.get(moveId); 16528 } 16529 16530 @Override 16531 public void registerMoveCallback(IPackageMoveObserver callback) { 16532 mContext.enforceCallingOrSelfPermission( 16533 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16534 mMoveCallbacks.register(callback); 16535 } 16536 16537 @Override 16538 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16539 mContext.enforceCallingOrSelfPermission( 16540 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16541 mMoveCallbacks.unregister(callback); 16542 } 16543 16544 @Override 16545 public boolean setInstallLocation(int loc) { 16546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16547 null); 16548 if (getInstallLocation() == loc) { 16549 return true; 16550 } 16551 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16552 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16553 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16554 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16555 return true; 16556 } 16557 return false; 16558 } 16559 16560 @Override 16561 public int getInstallLocation() { 16562 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16563 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16564 PackageHelper.APP_INSTALL_AUTO); 16565 } 16566 16567 /** Called by UserManagerService */ 16568 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16569 mDirtyUsers.remove(userHandle); 16570 mSettings.removeUserLPw(userHandle); 16571 mPendingBroadcasts.remove(userHandle); 16572 if (mInstaller != null) { 16573 // Technically, we shouldn't be doing this with the package lock 16574 // held. However, this is very rare, and there is already so much 16575 // other disk I/O going on, that we'll let it slide for now. 16576 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16577 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16578 final String volumeUuid = vol.getFsUuid(); 16579 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16580 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16581 } 16582 } 16583 mUserNeedsBadging.delete(userHandle); 16584 removeUnusedPackagesLILPw(userManager, userHandle); 16585 } 16586 16587 /** 16588 * We're removing userHandle and would like to remove any downloaded packages 16589 * that are no longer in use by any other user. 16590 * @param userHandle the user being removed 16591 */ 16592 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16593 final boolean DEBUG_CLEAN_APKS = false; 16594 int [] users = userManager.getUserIds(); 16595 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16596 while (psit.hasNext()) { 16597 PackageSetting ps = psit.next(); 16598 if (ps.pkg == null) { 16599 continue; 16600 } 16601 final String packageName = ps.pkg.packageName; 16602 // Skip over if system app 16603 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16604 continue; 16605 } 16606 if (DEBUG_CLEAN_APKS) { 16607 Slog.i(TAG, "Checking package " + packageName); 16608 } 16609 boolean keep = false; 16610 for (int i = 0; i < users.length; i++) { 16611 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16612 keep = true; 16613 if (DEBUG_CLEAN_APKS) { 16614 Slog.i(TAG, " Keeping package " + packageName + " for user " 16615 + users[i]); 16616 } 16617 break; 16618 } 16619 } 16620 if (!keep) { 16621 if (DEBUG_CLEAN_APKS) { 16622 Slog.i(TAG, " Removing package " + packageName); 16623 } 16624 mHandler.post(new Runnable() { 16625 public void run() { 16626 deletePackageX(packageName, userHandle, 0); 16627 } //end run 16628 }); 16629 } 16630 } 16631 } 16632 16633 /** Called by UserManagerService */ 16634 void createNewUserLILPw(int userHandle) { 16635 if (mInstaller != null) { 16636 mInstaller.createUserConfig(userHandle); 16637 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16638 applyFactoryDefaultBrowserLPw(userHandle); 16639 primeDomainVerificationsLPw(userHandle); 16640 } 16641 } 16642 16643 void newUserCreated(final int userHandle) { 16644 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16645 } 16646 16647 @Override 16648 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16649 mContext.enforceCallingOrSelfPermission( 16650 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16651 "Only package verification agents can read the verifier device identity"); 16652 16653 synchronized (mPackages) { 16654 return mSettings.getVerifierDeviceIdentityLPw(); 16655 } 16656 } 16657 16658 @Override 16659 public void setPermissionEnforced(String permission, boolean enforced) { 16660 // TODO: Now that we no longer change GID for storage, this should to away. 16661 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16662 "setPermissionEnforced"); 16663 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16664 synchronized (mPackages) { 16665 if (mSettings.mReadExternalStorageEnforced == null 16666 || mSettings.mReadExternalStorageEnforced != enforced) { 16667 mSettings.mReadExternalStorageEnforced = enforced; 16668 mSettings.writeLPr(); 16669 } 16670 } 16671 // kill any non-foreground processes so we restart them and 16672 // grant/revoke the GID. 16673 final IActivityManager am = ActivityManagerNative.getDefault(); 16674 if (am != null) { 16675 final long token = Binder.clearCallingIdentity(); 16676 try { 16677 am.killProcessesBelowForeground("setPermissionEnforcement"); 16678 } catch (RemoteException e) { 16679 } finally { 16680 Binder.restoreCallingIdentity(token); 16681 } 16682 } 16683 } else { 16684 throw new IllegalArgumentException("No selective enforcement for " + permission); 16685 } 16686 } 16687 16688 @Override 16689 @Deprecated 16690 public boolean isPermissionEnforced(String permission) { 16691 return true; 16692 } 16693 16694 @Override 16695 public boolean isStorageLow() { 16696 final long token = Binder.clearCallingIdentity(); 16697 try { 16698 final DeviceStorageMonitorInternal 16699 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16700 if (dsm != null) { 16701 return dsm.isMemoryLow(); 16702 } else { 16703 return false; 16704 } 16705 } finally { 16706 Binder.restoreCallingIdentity(token); 16707 } 16708 } 16709 16710 @Override 16711 public IPackageInstaller getPackageInstaller() { 16712 return mInstallerService; 16713 } 16714 16715 private boolean userNeedsBadging(int userId) { 16716 int index = mUserNeedsBadging.indexOfKey(userId); 16717 if (index < 0) { 16718 final UserInfo userInfo; 16719 final long token = Binder.clearCallingIdentity(); 16720 try { 16721 userInfo = sUserManager.getUserInfo(userId); 16722 } finally { 16723 Binder.restoreCallingIdentity(token); 16724 } 16725 final boolean b; 16726 if (userInfo != null && userInfo.isManagedProfile()) { 16727 b = true; 16728 } else { 16729 b = false; 16730 } 16731 mUserNeedsBadging.put(userId, b); 16732 return b; 16733 } 16734 return mUserNeedsBadging.valueAt(index); 16735 } 16736 16737 @Override 16738 public KeySet getKeySetByAlias(String packageName, String alias) { 16739 if (packageName == null || alias == null) { 16740 return null; 16741 } 16742 synchronized(mPackages) { 16743 final PackageParser.Package pkg = mPackages.get(packageName); 16744 if (pkg == null) { 16745 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16746 throw new IllegalArgumentException("Unknown package: " + packageName); 16747 } 16748 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16749 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16750 } 16751 } 16752 16753 @Override 16754 public KeySet getSigningKeySet(String packageName) { 16755 if (packageName == null) { 16756 return null; 16757 } 16758 synchronized(mPackages) { 16759 final PackageParser.Package pkg = mPackages.get(packageName); 16760 if (pkg == null) { 16761 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16762 throw new IllegalArgumentException("Unknown package: " + packageName); 16763 } 16764 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16765 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16766 throw new SecurityException("May not access signing KeySet of other apps."); 16767 } 16768 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16769 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16770 } 16771 } 16772 16773 @Override 16774 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16775 if (packageName == null || ks == null) { 16776 return false; 16777 } 16778 synchronized(mPackages) { 16779 final PackageParser.Package pkg = mPackages.get(packageName); 16780 if (pkg == null) { 16781 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16782 throw new IllegalArgumentException("Unknown package: " + packageName); 16783 } 16784 IBinder ksh = ks.getToken(); 16785 if (ksh instanceof KeySetHandle) { 16786 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16787 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16788 } 16789 return false; 16790 } 16791 } 16792 16793 @Override 16794 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16795 if (packageName == null || ks == null) { 16796 return false; 16797 } 16798 synchronized(mPackages) { 16799 final PackageParser.Package pkg = mPackages.get(packageName); 16800 if (pkg == null) { 16801 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16802 throw new IllegalArgumentException("Unknown package: " + packageName); 16803 } 16804 IBinder ksh = ks.getToken(); 16805 if (ksh instanceof KeySetHandle) { 16806 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16807 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16808 } 16809 return false; 16810 } 16811 } 16812 16813 public void getUsageStatsIfNoPackageUsageInfo() { 16814 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16815 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16816 if (usm == null) { 16817 throw new IllegalStateException("UsageStatsManager must be initialized"); 16818 } 16819 long now = System.currentTimeMillis(); 16820 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16821 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16822 String packageName = entry.getKey(); 16823 PackageParser.Package pkg = mPackages.get(packageName); 16824 if (pkg == null) { 16825 continue; 16826 } 16827 UsageStats usage = entry.getValue(); 16828 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16829 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16830 } 16831 } 16832 } 16833 16834 /** 16835 * Check and throw if the given before/after packages would be considered a 16836 * downgrade. 16837 */ 16838 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16839 throws PackageManagerException { 16840 if (after.versionCode < before.mVersionCode) { 16841 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16842 "Update version code " + after.versionCode + " is older than current " 16843 + before.mVersionCode); 16844 } else if (after.versionCode == before.mVersionCode) { 16845 if (after.baseRevisionCode < before.baseRevisionCode) { 16846 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16847 "Update base revision code " + after.baseRevisionCode 16848 + " is older than current " + before.baseRevisionCode); 16849 } 16850 16851 if (!ArrayUtils.isEmpty(after.splitNames)) { 16852 for (int i = 0; i < after.splitNames.length; i++) { 16853 final String splitName = after.splitNames[i]; 16854 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16855 if (j != -1) { 16856 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16857 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16858 "Update split " + splitName + " revision code " 16859 + after.splitRevisionCodes[i] + " is older than current " 16860 + before.splitRevisionCodes[j]); 16861 } 16862 } 16863 } 16864 } 16865 } 16866 } 16867 16868 private static class MoveCallbacks extends Handler { 16869 private static final int MSG_CREATED = 1; 16870 private static final int MSG_STATUS_CHANGED = 2; 16871 16872 private final RemoteCallbackList<IPackageMoveObserver> 16873 mCallbacks = new RemoteCallbackList<>(); 16874 16875 private final SparseIntArray mLastStatus = new SparseIntArray(); 16876 16877 public MoveCallbacks(Looper looper) { 16878 super(looper); 16879 } 16880 16881 public void register(IPackageMoveObserver callback) { 16882 mCallbacks.register(callback); 16883 } 16884 16885 public void unregister(IPackageMoveObserver callback) { 16886 mCallbacks.unregister(callback); 16887 } 16888 16889 @Override 16890 public void handleMessage(Message msg) { 16891 final SomeArgs args = (SomeArgs) msg.obj; 16892 final int n = mCallbacks.beginBroadcast(); 16893 for (int i = 0; i < n; i++) { 16894 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16895 try { 16896 invokeCallback(callback, msg.what, args); 16897 } catch (RemoteException ignored) { 16898 } 16899 } 16900 mCallbacks.finishBroadcast(); 16901 args.recycle(); 16902 } 16903 16904 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16905 throws RemoteException { 16906 switch (what) { 16907 case MSG_CREATED: { 16908 callback.onCreated(args.argi1, (Bundle) args.arg2); 16909 break; 16910 } 16911 case MSG_STATUS_CHANGED: { 16912 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16913 break; 16914 } 16915 } 16916 } 16917 16918 private void notifyCreated(int moveId, Bundle extras) { 16919 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16920 16921 final SomeArgs args = SomeArgs.obtain(); 16922 args.argi1 = moveId; 16923 args.arg2 = extras; 16924 obtainMessage(MSG_CREATED, args).sendToTarget(); 16925 } 16926 16927 private void notifyStatusChanged(int moveId, int status) { 16928 notifyStatusChanged(moveId, status, -1); 16929 } 16930 16931 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16932 Slog.v(TAG, "Move " + moveId + " status " + status); 16933 16934 final SomeArgs args = SomeArgs.obtain(); 16935 args.argi1 = moveId; 16936 args.argi2 = status; 16937 args.arg3 = estMillis; 16938 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16939 16940 synchronized (mLastStatus) { 16941 mLastStatus.put(moveId, status); 16942 } 16943 } 16944 } 16945 16946 private final class OnPermissionChangeListeners extends Handler { 16947 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16948 16949 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16950 new RemoteCallbackList<>(); 16951 16952 public OnPermissionChangeListeners(Looper looper) { 16953 super(looper); 16954 } 16955 16956 @Override 16957 public void handleMessage(Message msg) { 16958 switch (msg.what) { 16959 case MSG_ON_PERMISSIONS_CHANGED: { 16960 final int uid = msg.arg1; 16961 handleOnPermissionsChanged(uid); 16962 } break; 16963 } 16964 } 16965 16966 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16967 mPermissionListeners.register(listener); 16968 16969 } 16970 16971 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16972 mPermissionListeners.unregister(listener); 16973 } 16974 16975 public void onPermissionsChanged(int uid) { 16976 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16977 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16978 } 16979 } 16980 16981 private void handleOnPermissionsChanged(int uid) { 16982 final int count = mPermissionListeners.beginBroadcast(); 16983 try { 16984 for (int i = 0; i < count; i++) { 16985 IOnPermissionsChangeListener callback = mPermissionListeners 16986 .getBroadcastItem(i); 16987 try { 16988 callback.onPermissionsChanged(uid); 16989 } catch (RemoteException e) { 16990 Log.e(TAG, "Permission listener is dead", e); 16991 } 16992 } 16993 } finally { 16994 mPermissionListeners.finishBroadcast(); 16995 } 16996 } 16997 } 16998 16999 private class PackageManagerInternalImpl extends PackageManagerInternal { 17000 @Override 17001 public void setLocationPackagesProvider(PackagesProvider provider) { 17002 synchronized (mPackages) { 17003 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17004 } 17005 } 17006 17007 @Override 17008 public void setImePackagesProvider(PackagesProvider provider) { 17009 synchronized (mPackages) { 17010 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17011 } 17012 } 17013 17014 @Override 17015 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17016 synchronized (mPackages) { 17017 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17018 } 17019 } 17020 17021 @Override 17022 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17023 synchronized (mPackages) { 17024 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17025 } 17026 } 17027 17028 @Override 17029 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17030 synchronized (mPackages) { 17031 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17032 } 17033 } 17034 17035 @Override 17036 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17037 synchronized (mPackages) { 17038 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17039 } 17040 } 17041 17042 @Override 17043 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17044 synchronized (mPackages) { 17045 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17046 } 17047 } 17048 17049 @Override 17050 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17051 synchronized (mPackages) { 17052 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17053 packageName, userId); 17054 } 17055 } 17056 17057 @Override 17058 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17059 synchronized (mPackages) { 17060 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17061 packageName, userId); 17062 } 17063 } 17064 @Override 17065 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17066 synchronized (mPackages) { 17067 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17068 packageName, userId); 17069 } 17070 } 17071 } 17072 17073 @Override 17074 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17075 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17076 synchronized (mPackages) { 17077 final long identity = Binder.clearCallingIdentity(); 17078 try { 17079 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17080 packageNames, userId); 17081 } finally { 17082 Binder.restoreCallingIdentity(identity); 17083 } 17084 } 17085 } 17086 17087 private static void enforceSystemOrPhoneCaller(String tag) { 17088 int callingUid = Binder.getCallingUid(); 17089 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17090 throw new SecurityException( 17091 "Cannot call " + tag + " from UID " + callingUid); 17092 } 17093 } 17094} 17095