PackageManagerService.java revision 82402753815ff4633cc572713ae490a17d9129e5
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.SELinux; 166import android.os.ServiceManager; 167import android.os.SystemClock; 168import android.os.SystemProperties; 169import android.os.Trace; 170import android.os.UserHandle; 171import android.os.UserManager; 172import android.os.storage.IMountService; 173import android.os.storage.MountServiceInternal; 174import android.os.storage.StorageEventListener; 175import android.os.storage.StorageManager; 176import android.os.storage.VolumeInfo; 177import android.os.storage.VolumeRecord; 178import android.security.KeyStore; 179import android.security.SystemKeyStore; 180import android.system.ErrnoException; 181import android.system.Os; 182import android.system.StructStat; 183import android.text.TextUtils; 184import android.text.format.DateUtils; 185import android.util.ArrayMap; 186import android.util.ArraySet; 187import android.util.AtomicFile; 188import android.util.DisplayMetrics; 189import android.util.EventLog; 190import android.util.ExceptionUtils; 191import android.util.Log; 192import android.util.LogPrinter; 193import android.util.MathUtils; 194import android.util.PrintStreamPrinter; 195import android.util.Slog; 196import android.util.SparseArray; 197import android.util.SparseBooleanArray; 198import android.util.SparseIntArray; 199import android.util.Xml; 200import android.view.Display; 201 202import dalvik.system.DexFile; 203import dalvik.system.VMRuntime; 204 205import libcore.io.IoUtils; 206import libcore.util.EmptyArray; 207 208import com.android.internal.R; 209import com.android.internal.annotations.GuardedBy; 210import com.android.internal.app.IMediaContainerService; 211import com.android.internal.app.ResolverActivity; 212import com.android.internal.content.NativeLibraryHelper; 213import com.android.internal.content.PackageHelper; 214import com.android.internal.os.IParcelFileDescriptorFactory; 215import com.android.internal.os.SomeArgs; 216import com.android.internal.os.Zygote; 217import com.android.internal.util.ArrayUtils; 218import com.android.internal.util.FastPrintWriter; 219import com.android.internal.util.FastXmlSerializer; 220import com.android.internal.util.IndentingPrintWriter; 221import com.android.internal.util.Preconditions; 222import com.android.server.EventLogTags; 223import com.android.server.FgThread; 224import com.android.server.IntentResolver; 225import com.android.server.LocalServices; 226import com.android.server.ServiceThread; 227import com.android.server.SystemConfig; 228import com.android.server.Watchdog; 229import com.android.server.pm.PermissionsState.PermissionState; 230import com.android.server.pm.Settings.DatabaseVersion; 231import com.android.server.pm.Settings.VersionInfo; 232import com.android.server.storage.DeviceStorageMonitorInternal; 233 234import org.xmlpull.v1.XmlPullParser; 235import org.xmlpull.v1.XmlPullParserException; 236import org.xmlpull.v1.XmlSerializer; 237 238import java.io.BufferedInputStream; 239import java.io.BufferedOutputStream; 240import java.io.BufferedReader; 241import java.io.ByteArrayInputStream; 242import java.io.ByteArrayOutputStream; 243import java.io.File; 244import java.io.FileDescriptor; 245import java.io.FileNotFoundException; 246import java.io.FileOutputStream; 247import java.io.FileReader; 248import java.io.FilenameFilter; 249import java.io.IOException; 250import java.io.InputStream; 251import java.io.PrintWriter; 252import java.nio.charset.StandardCharsets; 253import java.security.NoSuchAlgorithmException; 254import java.security.PublicKey; 255import java.security.cert.CertificateEncodingException; 256import java.security.cert.CertificateException; 257import java.text.SimpleDateFormat; 258import java.util.ArrayList; 259import java.util.Arrays; 260import java.util.Collection; 261import java.util.Collections; 262import java.util.Comparator; 263import java.util.Date; 264import java.util.Iterator; 265import java.util.List; 266import java.util.Map; 267import java.util.Objects; 268import java.util.Set; 269import java.util.concurrent.CountDownLatch; 270import java.util.concurrent.TimeUnit; 271import java.util.concurrent.atomic.AtomicBoolean; 272import java.util.concurrent.atomic.AtomicInteger; 273import java.util.concurrent.atomic.AtomicLong; 274 275/** 276 * Keep track of all those .apks everywhere. 277 * 278 * This is very central to the platform's security; please run the unit 279 * tests whenever making modifications here: 280 * 281runtest -c android.content.pm.PackageManagerTests frameworks-core 282 * 283 * {@hide} 284 */ 285public class PackageManagerService extends IPackageManager.Stub { 286 static final String TAG = "PackageManager"; 287 static final boolean DEBUG_SETTINGS = false; 288 static final boolean DEBUG_PREFERRED = false; 289 static final boolean DEBUG_UPGRADE = false; 290 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 291 private static final boolean DEBUG_BACKUP = false; 292 private static final boolean DEBUG_INSTALL = false; 293 private static final boolean DEBUG_REMOVE = false; 294 private static final boolean DEBUG_BROADCASTS = false; 295 private static final boolean DEBUG_SHOW_INFO = false; 296 private static final boolean DEBUG_PACKAGE_INFO = false; 297 private static final boolean DEBUG_INTENT_MATCHING = false; 298 private static final boolean DEBUG_PACKAGE_SCANNING = false; 299 private static final boolean DEBUG_VERIFY = false; 300 private static final boolean DEBUG_DEXOPT = false; 301 private static final boolean DEBUG_ABI_SELECTION = false; 302 303 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 304 305 private static final int RADIO_UID = Process.PHONE_UID; 306 private static final int LOG_UID = Process.LOG_UID; 307 private static final int NFC_UID = Process.NFC_UID; 308 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 309 private static final int SHELL_UID = Process.SHELL_UID; 310 311 // Cap the size of permission trees that 3rd party apps can define 312 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 313 314 // Suffix used during package installation when copying/moving 315 // package apks to install directory. 316 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 317 318 static final int SCAN_NO_DEX = 1<<1; 319 static final int SCAN_FORCE_DEX = 1<<2; 320 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 321 static final int SCAN_NEW_INSTALL = 1<<4; 322 static final int SCAN_NO_PATHS = 1<<5; 323 static final int SCAN_UPDATE_TIME = 1<<6; 324 static final int SCAN_DEFER_DEX = 1<<7; 325 static final int SCAN_BOOTING = 1<<8; 326 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 327 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 328 static final int SCAN_REPLACING = 1<<11; 329 static final int SCAN_REQUIRE_KNOWN = 1<<12; 330 static final int SCAN_MOVE = 1<<13; 331 static final int SCAN_INITIAL = 1<<14; 332 333 static final int REMOVE_CHATTY = 1<<16; 334 335 private static final int[] EMPTY_INT_ARRAY = new int[0]; 336 337 /** 338 * Timeout (in milliseconds) after which the watchdog should declare that 339 * our handler thread is wedged. The usual default for such things is one 340 * minute but we sometimes do very lengthy I/O operations on this thread, 341 * such as installing multi-gigabyte applications, so ours needs to be longer. 342 */ 343 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 344 345 /** 346 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 347 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 348 * settings entry if available, otherwise we use the hardcoded default. If it's been 349 * more than this long since the last fstrim, we force one during the boot sequence. 350 * 351 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 352 * one gets run at the next available charging+idle time. This final mandatory 353 * no-fstrim check kicks in only of the other scheduling criteria is never met. 354 */ 355 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 356 357 /** 358 * Whether verification is enabled by default. 359 */ 360 private static final boolean DEFAULT_VERIFY_ENABLE = true; 361 362 /** 363 * The default maximum time to wait for the verification agent to return in 364 * milliseconds. 365 */ 366 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 367 368 /** 369 * The default response for package verification timeout. 370 * 371 * This can be either PackageManager.VERIFICATION_ALLOW or 372 * PackageManager.VERIFICATION_REJECT. 373 */ 374 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 375 376 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 377 378 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 379 DEFAULT_CONTAINER_PACKAGE, 380 "com.android.defcontainer.DefaultContainerService"); 381 382 private static final String KILL_APP_REASON_GIDS_CHANGED = 383 "permission grant or revoke changed gids"; 384 385 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 386 "permissions revoked"; 387 388 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 389 390 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 391 392 /** Permission grant: not grant the permission. */ 393 private static final int GRANT_DENIED = 1; 394 395 /** Permission grant: grant the permission as an install permission. */ 396 private static final int GRANT_INSTALL = 2; 397 398 /** Permission grant: grant the permission as an install permission for a legacy app. */ 399 private static final int GRANT_INSTALL_LEGACY = 3; 400 401 /** Permission grant: grant the permission as a runtime one. */ 402 private static final int GRANT_RUNTIME = 4; 403 404 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 405 private static final int GRANT_UPGRADE = 5; 406 407 /** Canonical intent used to identify what counts as a "web browser" app */ 408 private static final Intent sBrowserIntent; 409 static { 410 sBrowserIntent = new Intent(); 411 sBrowserIntent.setAction(Intent.ACTION_VIEW); 412 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 413 sBrowserIntent.setData(Uri.parse("http:")); 414 } 415 416 final ServiceThread mHandlerThread; 417 418 final PackageHandler mHandler; 419 420 /** 421 * Messages for {@link #mHandler} that need to wait for system ready before 422 * being dispatched. 423 */ 424 private ArrayList<Message> mPostSystemReadyMessages; 425 426 final int mSdkVersion = Build.VERSION.SDK_INT; 427 428 final Context mContext; 429 final boolean mFactoryTest; 430 final boolean mOnlyCore; 431 final boolean mLazyDexOpt; 432 final long mDexOptLRUThresholdInMills; 433 final DisplayMetrics mMetrics; 434 final int mDefParseFlags; 435 final String[] mSeparateProcesses; 436 final boolean mIsUpgrade; 437 438 // This is where all application persistent data goes. 439 final File mAppDataDir; 440 441 // This is where all application persistent data goes for secondary users. 442 final File mUserAppDataDir; 443 444 /** The location for ASEC container files on internal storage. */ 445 final String mAsecInternalPath; 446 447 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 448 // LOCK HELD. Can be called with mInstallLock held. 449 @GuardedBy("mInstallLock") 450 final Installer mInstaller; 451 452 /** Directory where installed third-party apps stored */ 453 final File mAppInstallDir; 454 455 /** 456 * Directory to which applications installed internally have their 457 * 32 bit native libraries copied. 458 */ 459 private File mAppLib32InstallDir; 460 461 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 462 // apps. 463 final File mDrmAppPrivateInstallDir; 464 465 // ---------------------------------------------------------------- 466 467 // Lock for state used when installing and doing other long running 468 // operations. Methods that must be called with this lock held have 469 // the suffix "LI". 470 final Object mInstallLock = new Object(); 471 472 // ---------------------------------------------------------------- 473 474 // Keys are String (package name), values are Package. This also serves 475 // as the lock for the global state. Methods that must be called with 476 // this lock held have the prefix "LP". 477 @GuardedBy("mPackages") 478 final ArrayMap<String, PackageParser.Package> mPackages = 479 new ArrayMap<String, PackageParser.Package>(); 480 481 // Tracks available target package names -> overlay package paths. 482 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 483 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 484 485 /** 486 * Tracks new system packages [received in an OTA] that we expect to 487 * find updated user-installed versions. Keys are package name, values 488 * are package location. 489 */ 490 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 491 492 /** 493 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 494 */ 495 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 496 /** 497 * Whether or not system app permissions should be promoted from install to runtime. 498 */ 499 boolean mPromoteSystemApps; 500 501 final Settings mSettings; 502 boolean mRestoredSettings; 503 504 // System configuration read by SystemConfig. 505 final int[] mGlobalGids; 506 final SparseArray<ArraySet<String>> mSystemPermissions; 507 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 508 509 // If mac_permissions.xml was found for seinfo labeling. 510 boolean mFoundPolicyFile; 511 512 // If a recursive restorecon of /data/data/<pkg> is needed. 513 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 514 515 public static final class SharedLibraryEntry { 516 public final String path; 517 public final String apk; 518 519 SharedLibraryEntry(String _path, String _apk) { 520 path = _path; 521 apk = _apk; 522 } 523 } 524 525 // Currently known shared libraries. 526 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 527 new ArrayMap<String, SharedLibraryEntry>(); 528 529 // All available activities, for your resolving pleasure. 530 final ActivityIntentResolver mActivities = 531 new ActivityIntentResolver(); 532 533 // All available receivers, for your resolving pleasure. 534 final ActivityIntentResolver mReceivers = 535 new ActivityIntentResolver(); 536 537 // All available services, for your resolving pleasure. 538 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 539 540 // All available providers, for your resolving pleasure. 541 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 542 543 // Mapping from provider base names (first directory in content URI codePath) 544 // to the provider information. 545 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 546 new ArrayMap<String, PackageParser.Provider>(); 547 548 // Mapping from instrumentation class names to info about them. 549 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 550 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 551 552 // Mapping from permission names to info about them. 553 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 554 new ArrayMap<String, PackageParser.PermissionGroup>(); 555 556 // Packages whose data we have transfered into another package, thus 557 // should no longer exist. 558 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 559 560 // Broadcast actions that are only available to the system. 561 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 562 563 /** List of packages waiting for verification. */ 564 final SparseArray<PackageVerificationState> mPendingVerification 565 = new SparseArray<PackageVerificationState>(); 566 567 /** Set of packages associated with each app op permission. */ 568 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 569 570 final PackageInstallerService mInstallerService; 571 572 private final PackageDexOptimizer mPackageDexOptimizer; 573 574 private AtomicInteger mNextMoveId = new AtomicInteger(); 575 private final MoveCallbacks mMoveCallbacks; 576 577 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 578 579 // Cache of users who need badging. 580 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 581 582 /** Token for keys in mPendingVerification. */ 583 private int mPendingVerificationToken = 0; 584 585 volatile boolean mSystemReady; 586 volatile boolean mSafeMode; 587 volatile boolean mHasSystemUidErrors; 588 589 ApplicationInfo mAndroidApplication; 590 final ActivityInfo mResolveActivity = new ActivityInfo(); 591 final ResolveInfo mResolveInfo = new ResolveInfo(); 592 ComponentName mResolveComponentName; 593 PackageParser.Package mPlatformPackage; 594 ComponentName mCustomResolverComponentName; 595 596 boolean mResolverReplaced = false; 597 598 private final ComponentName mIntentFilterVerifierComponent; 599 private int mIntentFilterVerificationToken = 0; 600 601 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 602 = new SparseArray<IntentFilterVerificationState>(); 603 604 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 605 new DefaultPermissionGrantPolicy(this); 606 607 private static class IFVerificationParams { 608 PackageParser.Package pkg; 609 boolean replacing; 610 int userId; 611 int verifierUid; 612 613 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 614 int _userId, int _verifierUid) { 615 pkg = _pkg; 616 replacing = _replacing; 617 userId = _userId; 618 replacing = _replacing; 619 verifierUid = _verifierUid; 620 } 621 } 622 623 private interface IntentFilterVerifier<T extends IntentFilter> { 624 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 625 T filter, String packageName); 626 void startVerifications(int userId); 627 void receiveVerificationResponse(int verificationId); 628 } 629 630 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 631 private Context mContext; 632 private ComponentName mIntentFilterVerifierComponent; 633 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 634 635 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 636 mContext = context; 637 mIntentFilterVerifierComponent = verifierComponent; 638 } 639 640 private String getDefaultScheme() { 641 return IntentFilter.SCHEME_HTTPS; 642 } 643 644 @Override 645 public void startVerifications(int userId) { 646 // Launch verifications requests 647 int count = mCurrentIntentFilterVerifications.size(); 648 for (int n=0; n<count; n++) { 649 int verificationId = mCurrentIntentFilterVerifications.get(n); 650 final IntentFilterVerificationState ivs = 651 mIntentFilterVerificationStates.get(verificationId); 652 653 String packageName = ivs.getPackageName(); 654 655 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 656 final int filterCount = filters.size(); 657 ArraySet<String> domainsSet = new ArraySet<>(); 658 for (int m=0; m<filterCount; m++) { 659 PackageParser.ActivityIntentInfo filter = filters.get(m); 660 domainsSet.addAll(filter.getHostsList()); 661 } 662 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 663 synchronized (mPackages) { 664 if (mSettings.createIntentFilterVerificationIfNeededLPw( 665 packageName, domainsList) != null) { 666 scheduleWriteSettingsLocked(); 667 } 668 } 669 sendVerificationRequest(userId, verificationId, ivs); 670 } 671 mCurrentIntentFilterVerifications.clear(); 672 } 673 674 private void sendVerificationRequest(int userId, int verificationId, 675 IntentFilterVerificationState ivs) { 676 677 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 678 verificationIntent.putExtra( 679 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 680 verificationId); 681 verificationIntent.putExtra( 682 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 683 getDefaultScheme()); 684 verificationIntent.putExtra( 685 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 686 ivs.getHostsString()); 687 verificationIntent.putExtra( 688 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 689 ivs.getPackageName()); 690 verificationIntent.setComponent(mIntentFilterVerifierComponent); 691 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 692 693 UserHandle user = new UserHandle(userId); 694 mContext.sendBroadcastAsUser(verificationIntent, user); 695 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 696 "Sending IntentFilter verification broadcast"); 697 } 698 699 public void receiveVerificationResponse(int verificationId) { 700 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 701 702 final boolean verified = ivs.isVerified(); 703 704 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 705 final int count = filters.size(); 706 if (DEBUG_DOMAIN_VERIFICATION) { 707 Slog.i(TAG, "Received verification response " + verificationId 708 + " for " + count + " filters, verified=" + verified); 709 } 710 for (int n=0; n<count; n++) { 711 PackageParser.ActivityIntentInfo filter = filters.get(n); 712 filter.setVerified(verified); 713 714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 715 + " verified with result:" + verified + " and hosts:" 716 + ivs.getHostsString()); 717 } 718 719 mIntentFilterVerificationStates.remove(verificationId); 720 721 final String packageName = ivs.getPackageName(); 722 IntentFilterVerificationInfo ivi = null; 723 724 synchronized (mPackages) { 725 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 726 } 727 if (ivi == null) { 728 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 729 + verificationId + " packageName:" + packageName); 730 return; 731 } 732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 733 "Updating IntentFilterVerificationInfo for package " + packageName 734 +" verificationId:" + verificationId); 735 736 synchronized (mPackages) { 737 if (verified) { 738 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 739 } else { 740 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 741 } 742 scheduleWriteSettingsLocked(); 743 744 final int userId = ivs.getUserId(); 745 if (userId != UserHandle.USER_ALL) { 746 final int userStatus = 747 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 748 749 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 750 boolean needUpdate = false; 751 752 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 753 // already been set by the User thru the Disambiguation dialog 754 switch (userStatus) { 755 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 756 if (verified) { 757 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 758 } else { 759 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 760 } 761 needUpdate = true; 762 break; 763 764 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 765 if (verified) { 766 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 767 needUpdate = true; 768 } 769 break; 770 771 default: 772 // Nothing to do 773 } 774 775 if (needUpdate) { 776 mSettings.updateIntentFilterVerificationStatusLPw( 777 packageName, updatedStatus, userId); 778 scheduleWritePackageRestrictionsLocked(userId); 779 } 780 } 781 } 782 } 783 784 @Override 785 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 786 ActivityIntentInfo filter, String packageName) { 787 if (!hasValidDomains(filter)) { 788 return false; 789 } 790 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 791 if (ivs == null) { 792 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 793 packageName); 794 } 795 if (DEBUG_DOMAIN_VERIFICATION) { 796 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 797 } 798 ivs.addFilter(filter); 799 return true; 800 } 801 802 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 803 int userId, int verificationId, String packageName) { 804 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 805 verifierUid, userId, packageName); 806 ivs.setPendingState(); 807 synchronized (mPackages) { 808 mIntentFilterVerificationStates.append(verificationId, ivs); 809 mCurrentIntentFilterVerifications.add(verificationId); 810 } 811 return ivs; 812 } 813 } 814 815 private static boolean hasValidDomains(ActivityIntentInfo filter) { 816 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 817 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 818 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 819 } 820 821 private IntentFilterVerifier mIntentFilterVerifier; 822 823 // Set of pending broadcasts for aggregating enable/disable of components. 824 static class PendingPackageBroadcasts { 825 // for each user id, a map of <package name -> components within that package> 826 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 827 828 public PendingPackageBroadcasts() { 829 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 830 } 831 832 public ArrayList<String> get(int userId, String packageName) { 833 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 834 return packages.get(packageName); 835 } 836 837 public void put(int userId, String packageName, ArrayList<String> components) { 838 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 839 packages.put(packageName, components); 840 } 841 842 public void remove(int userId, String packageName) { 843 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 844 if (packages != null) { 845 packages.remove(packageName); 846 } 847 } 848 849 public void remove(int userId) { 850 mUidMap.remove(userId); 851 } 852 853 public int userIdCount() { 854 return mUidMap.size(); 855 } 856 857 public int userIdAt(int n) { 858 return mUidMap.keyAt(n); 859 } 860 861 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 862 return mUidMap.get(userId); 863 } 864 865 public int size() { 866 // total number of pending broadcast entries across all userIds 867 int num = 0; 868 for (int i = 0; i< mUidMap.size(); i++) { 869 num += mUidMap.valueAt(i).size(); 870 } 871 return num; 872 } 873 874 public void clear() { 875 mUidMap.clear(); 876 } 877 878 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 879 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 880 if (map == null) { 881 map = new ArrayMap<String, ArrayList<String>>(); 882 mUidMap.put(userId, map); 883 } 884 return map; 885 } 886 } 887 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 888 889 // Service Connection to remote media container service to copy 890 // package uri's from external media onto secure containers 891 // or internal storage. 892 private IMediaContainerService mContainerService = null; 893 894 static final int SEND_PENDING_BROADCAST = 1; 895 static final int MCS_BOUND = 3; 896 static final int END_COPY = 4; 897 static final int INIT_COPY = 5; 898 static final int MCS_UNBIND = 6; 899 static final int START_CLEANING_PACKAGE = 7; 900 static final int FIND_INSTALL_LOC = 8; 901 static final int POST_INSTALL = 9; 902 static final int MCS_RECONNECT = 10; 903 static final int MCS_GIVE_UP = 11; 904 static final int UPDATED_MEDIA_STATUS = 12; 905 static final int WRITE_SETTINGS = 13; 906 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 907 static final int PACKAGE_VERIFIED = 15; 908 static final int CHECK_PENDING_VERIFICATION = 16; 909 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 910 static final int INTENT_FILTER_VERIFIED = 18; 911 912 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 913 914 // Delay time in millisecs 915 static final int BROADCAST_DELAY = 10 * 1000; 916 917 static UserManagerService sUserManager; 918 919 // Stores a list of users whose package restrictions file needs to be updated 920 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 921 922 final private DefaultContainerConnection mDefContainerConn = 923 new DefaultContainerConnection(); 924 class DefaultContainerConnection implements ServiceConnection { 925 public void onServiceConnected(ComponentName name, IBinder service) { 926 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 927 IMediaContainerService imcs = 928 IMediaContainerService.Stub.asInterface(service); 929 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 930 } 931 932 public void onServiceDisconnected(ComponentName name) { 933 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 934 } 935 } 936 937 // Recordkeeping of restore-after-install operations that are currently in flight 938 // between the Package Manager and the Backup Manager 939 class PostInstallData { 940 public InstallArgs args; 941 public PackageInstalledInfo res; 942 943 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 944 args = _a; 945 res = _r; 946 } 947 } 948 949 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 950 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 951 952 // XML tags for backup/restore of various bits of state 953 private static final String TAG_PREFERRED_BACKUP = "pa"; 954 private static final String TAG_DEFAULT_APPS = "da"; 955 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 956 957 final String mRequiredVerifierPackage; 958 final String mRequiredInstallerPackage; 959 960 private final PackageUsage mPackageUsage = new PackageUsage(); 961 962 private class PackageUsage { 963 private static final int WRITE_INTERVAL 964 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 965 966 private final Object mFileLock = new Object(); 967 private final AtomicLong mLastWritten = new AtomicLong(0); 968 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 969 970 private boolean mIsHistoricalPackageUsageAvailable = true; 971 972 boolean isHistoricalPackageUsageAvailable() { 973 return mIsHistoricalPackageUsageAvailable; 974 } 975 976 void write(boolean force) { 977 if (force) { 978 writeInternal(); 979 return; 980 } 981 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 982 && !DEBUG_DEXOPT) { 983 return; 984 } 985 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 986 new Thread("PackageUsage_DiskWriter") { 987 @Override 988 public void run() { 989 try { 990 writeInternal(); 991 } finally { 992 mBackgroundWriteRunning.set(false); 993 } 994 } 995 }.start(); 996 } 997 } 998 999 private void writeInternal() { 1000 synchronized (mPackages) { 1001 synchronized (mFileLock) { 1002 AtomicFile file = getFile(); 1003 FileOutputStream f = null; 1004 try { 1005 f = file.startWrite(); 1006 BufferedOutputStream out = new BufferedOutputStream(f); 1007 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1008 StringBuilder sb = new StringBuilder(); 1009 for (PackageParser.Package pkg : mPackages.values()) { 1010 if (pkg.mLastPackageUsageTimeInMills == 0) { 1011 continue; 1012 } 1013 sb.setLength(0); 1014 sb.append(pkg.packageName); 1015 sb.append(' '); 1016 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1017 sb.append('\n'); 1018 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1019 } 1020 out.flush(); 1021 file.finishWrite(f); 1022 } catch (IOException e) { 1023 if (f != null) { 1024 file.failWrite(f); 1025 } 1026 Log.e(TAG, "Failed to write package usage times", e); 1027 } 1028 } 1029 } 1030 mLastWritten.set(SystemClock.elapsedRealtime()); 1031 } 1032 1033 void readLP() { 1034 synchronized (mFileLock) { 1035 AtomicFile file = getFile(); 1036 BufferedInputStream in = null; 1037 try { 1038 in = new BufferedInputStream(file.openRead()); 1039 StringBuffer sb = new StringBuffer(); 1040 while (true) { 1041 String packageName = readToken(in, sb, ' '); 1042 if (packageName == null) { 1043 break; 1044 } 1045 String timeInMillisString = readToken(in, sb, '\n'); 1046 if (timeInMillisString == null) { 1047 throw new IOException("Failed to find last usage time for package " 1048 + packageName); 1049 } 1050 PackageParser.Package pkg = mPackages.get(packageName); 1051 if (pkg == null) { 1052 continue; 1053 } 1054 long timeInMillis; 1055 try { 1056 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1057 } catch (NumberFormatException e) { 1058 throw new IOException("Failed to parse " + timeInMillisString 1059 + " as a long.", e); 1060 } 1061 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1062 } 1063 } catch (FileNotFoundException expected) { 1064 mIsHistoricalPackageUsageAvailable = false; 1065 } catch (IOException e) { 1066 Log.w(TAG, "Failed to read package usage times", e); 1067 } finally { 1068 IoUtils.closeQuietly(in); 1069 } 1070 } 1071 mLastWritten.set(SystemClock.elapsedRealtime()); 1072 } 1073 1074 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1075 throws IOException { 1076 sb.setLength(0); 1077 while (true) { 1078 int ch = in.read(); 1079 if (ch == -1) { 1080 if (sb.length() == 0) { 1081 return null; 1082 } 1083 throw new IOException("Unexpected EOF"); 1084 } 1085 if (ch == endOfToken) { 1086 return sb.toString(); 1087 } 1088 sb.append((char)ch); 1089 } 1090 } 1091 1092 private AtomicFile getFile() { 1093 File dataDir = Environment.getDataDirectory(); 1094 File systemDir = new File(dataDir, "system"); 1095 File fname = new File(systemDir, "package-usage.list"); 1096 return new AtomicFile(fname); 1097 } 1098 } 1099 1100 class PackageHandler extends Handler { 1101 private boolean mBound = false; 1102 final ArrayList<HandlerParams> mPendingInstalls = 1103 new ArrayList<HandlerParams>(); 1104 1105 private boolean connectToService() { 1106 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1107 " DefaultContainerService"); 1108 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1111 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1113 mBound = true; 1114 return true; 1115 } 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 return false; 1118 } 1119 1120 private void disconnectService() { 1121 mContainerService = null; 1122 mBound = false; 1123 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1124 mContext.unbindService(mDefContainerConn); 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } 1127 1128 PackageHandler(Looper looper) { 1129 super(looper); 1130 } 1131 1132 public void handleMessage(Message msg) { 1133 try { 1134 doHandleMessage(msg); 1135 } finally { 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } 1138 } 1139 1140 void doHandleMessage(Message msg) { 1141 switch (msg.what) { 1142 case INIT_COPY: { 1143 HandlerParams params = (HandlerParams) msg.obj; 1144 int idx = mPendingInstalls.size(); 1145 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1146 // If a bind was already initiated we dont really 1147 // need to do anything. The pending install 1148 // will be processed later on. 1149 if (!mBound) { 1150 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1151 System.identityHashCode(mHandler)); 1152 // If this is the only one pending we might 1153 // have to bind to the service again. 1154 if (!connectToService()) { 1155 Slog.e(TAG, "Failed to bind to media container service"); 1156 params.serviceError(); 1157 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1158 System.identityHashCode(mHandler)); 1159 if (params.traceMethod != null) { 1160 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1161 params.traceCookie); 1162 } 1163 return; 1164 } else { 1165 // Once we bind to the service, the first 1166 // pending request will be processed. 1167 mPendingInstalls.add(idx, params); 1168 } 1169 } else { 1170 mPendingInstalls.add(idx, params); 1171 // Already bound to the service. Just make 1172 // sure we trigger off processing the first request. 1173 if (idx == 0) { 1174 mHandler.sendEmptyMessage(MCS_BOUND); 1175 } 1176 } 1177 break; 1178 } 1179 case MCS_BOUND: { 1180 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1181 if (msg.obj != null) { 1182 mContainerService = (IMediaContainerService) msg.obj; 1183 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1184 System.identityHashCode(mHandler)); 1185 } 1186 if (mContainerService == null) { 1187 if (!mBound) { 1188 // Something seriously wrong since we are not bound and we are not 1189 // waiting for connection. Bail out. 1190 Slog.e(TAG, "Cannot bind to media container service"); 1191 for (HandlerParams params : mPendingInstalls) { 1192 // Indicate service bind error 1193 params.serviceError(); 1194 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1195 System.identityHashCode(params)); 1196 if (params.traceMethod != null) { 1197 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1198 params.traceMethod, params.traceCookie); 1199 } 1200 return; 1201 } 1202 mPendingInstalls.clear(); 1203 } else { 1204 Slog.w(TAG, "Waiting to connect to media container service"); 1205 } 1206 } else if (mPendingInstalls.size() > 0) { 1207 HandlerParams params = mPendingInstalls.get(0); 1208 if (params != null) { 1209 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1210 System.identityHashCode(params)); 1211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1212 if (params.startCopy()) { 1213 // We are done... look for more work or to 1214 // go idle. 1215 if (DEBUG_SD_INSTALL) Log.i(TAG, 1216 "Checking for more work or unbind..."); 1217 // Delete pending install 1218 if (mPendingInstalls.size() > 0) { 1219 mPendingInstalls.remove(0); 1220 } 1221 if (mPendingInstalls.size() == 0) { 1222 if (mBound) { 1223 if (DEBUG_SD_INSTALL) Log.i(TAG, 1224 "Posting delayed MCS_UNBIND"); 1225 removeMessages(MCS_UNBIND); 1226 Message ubmsg = obtainMessage(MCS_UNBIND); 1227 // Unbind after a little delay, to avoid 1228 // continual thrashing. 1229 sendMessageDelayed(ubmsg, 10000); 1230 } 1231 } else { 1232 // There are more pending requests in queue. 1233 // Just post MCS_BOUND message to trigger processing 1234 // of next pending install. 1235 if (DEBUG_SD_INSTALL) Log.i(TAG, 1236 "Posting MCS_BOUND for next work"); 1237 mHandler.sendEmptyMessage(MCS_BOUND); 1238 } 1239 } 1240 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1241 } 1242 } else { 1243 // Should never happen ideally. 1244 Slog.w(TAG, "Empty queue"); 1245 } 1246 break; 1247 } 1248 case MCS_RECONNECT: { 1249 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1250 if (mPendingInstalls.size() > 0) { 1251 if (mBound) { 1252 disconnectService(); 1253 } 1254 if (!connectToService()) { 1255 Slog.e(TAG, "Failed to bind to media container service"); 1256 for (HandlerParams params : mPendingInstalls) { 1257 // Indicate service bind error 1258 params.serviceError(); 1259 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1260 System.identityHashCode(params)); 1261 } 1262 mPendingInstalls.clear(); 1263 } 1264 } 1265 break; 1266 } 1267 case MCS_UNBIND: { 1268 // If there is no actual work left, then time to unbind. 1269 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1270 1271 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1272 if (mBound) { 1273 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1274 1275 disconnectService(); 1276 } 1277 } else if (mPendingInstalls.size() > 0) { 1278 // There are more pending requests in queue. 1279 // Just post MCS_BOUND message to trigger processing 1280 // of next pending install. 1281 mHandler.sendEmptyMessage(MCS_BOUND); 1282 } 1283 1284 break; 1285 } 1286 case MCS_GIVE_UP: { 1287 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1288 HandlerParams params = mPendingInstalls.remove(0); 1289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1290 System.identityHashCode(params)); 1291 break; 1292 } 1293 case SEND_PENDING_BROADCAST: { 1294 String packages[]; 1295 ArrayList<String> components[]; 1296 int size = 0; 1297 int uids[]; 1298 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1299 synchronized (mPackages) { 1300 if (mPendingBroadcasts == null) { 1301 return; 1302 } 1303 size = mPendingBroadcasts.size(); 1304 if (size <= 0) { 1305 // Nothing to be done. Just return 1306 return; 1307 } 1308 packages = new String[size]; 1309 components = new ArrayList[size]; 1310 uids = new int[size]; 1311 int i = 0; // filling out the above arrays 1312 1313 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1314 int packageUserId = mPendingBroadcasts.userIdAt(n); 1315 Iterator<Map.Entry<String, ArrayList<String>>> it 1316 = mPendingBroadcasts.packagesForUserId(packageUserId) 1317 .entrySet().iterator(); 1318 while (it.hasNext() && i < size) { 1319 Map.Entry<String, ArrayList<String>> ent = it.next(); 1320 packages[i] = ent.getKey(); 1321 components[i] = ent.getValue(); 1322 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1323 uids[i] = (ps != null) 1324 ? UserHandle.getUid(packageUserId, ps.appId) 1325 : -1; 1326 i++; 1327 } 1328 } 1329 size = i; 1330 mPendingBroadcasts.clear(); 1331 } 1332 // Send broadcasts 1333 for (int i = 0; i < size; i++) { 1334 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 break; 1338 } 1339 case START_CLEANING_PACKAGE: { 1340 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1341 final String packageName = (String)msg.obj; 1342 final int userId = msg.arg1; 1343 final boolean andCode = msg.arg2 != 0; 1344 synchronized (mPackages) { 1345 if (userId == UserHandle.USER_ALL) { 1346 int[] users = sUserManager.getUserIds(); 1347 for (int user : users) { 1348 mSettings.addPackageToCleanLPw( 1349 new PackageCleanItem(user, packageName, andCode)); 1350 } 1351 } else { 1352 mSettings.addPackageToCleanLPw( 1353 new PackageCleanItem(userId, packageName, andCode)); 1354 } 1355 } 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 startCleaningPackages(); 1358 } break; 1359 case POST_INSTALL: { 1360 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1361 PostInstallData data = mRunningInstalls.get(msg.arg1); 1362 mRunningInstalls.delete(msg.arg1); 1363 boolean deleteOld = false; 1364 1365 if (data != null) { 1366 InstallArgs args = data.args; 1367 PackageInstalledInfo res = data.res; 1368 1369 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1370 final String packageName = res.pkg.applicationInfo.packageName; 1371 res.removedInfo.sendBroadcast(false, true, false); 1372 Bundle extras = new Bundle(1); 1373 extras.putInt(Intent.EXTRA_UID, res.uid); 1374 1375 // Now that we successfully installed the package, grant runtime 1376 // permissions if requested before broadcasting the install. 1377 if ((args.installFlags 1378 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1379 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1380 args.installGrantPermissions); 1381 } 1382 1383 // Determine the set of users who are adding this 1384 // package for the first time vs. those who are seeing 1385 // an update. 1386 int[] firstUsers; 1387 int[] updateUsers = new int[0]; 1388 if (res.origUsers == null || res.origUsers.length == 0) { 1389 firstUsers = res.newUsers; 1390 } else { 1391 firstUsers = new int[0]; 1392 for (int i=0; i<res.newUsers.length; i++) { 1393 int user = res.newUsers[i]; 1394 boolean isNew = true; 1395 for (int j=0; j<res.origUsers.length; j++) { 1396 if (res.origUsers[j] == user) { 1397 isNew = false; 1398 break; 1399 } 1400 } 1401 if (isNew) { 1402 int[] newFirst = new int[firstUsers.length+1]; 1403 System.arraycopy(firstUsers, 0, newFirst, 0, 1404 firstUsers.length); 1405 newFirst[firstUsers.length] = user; 1406 firstUsers = newFirst; 1407 } else { 1408 int[] newUpdate = new int[updateUsers.length+1]; 1409 System.arraycopy(updateUsers, 0, newUpdate, 0, 1410 updateUsers.length); 1411 newUpdate[updateUsers.length] = user; 1412 updateUsers = newUpdate; 1413 } 1414 } 1415 } 1416 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1417 packageName, extras, null, null, firstUsers); 1418 final boolean update = res.removedInfo.removedPackage != null; 1419 if (update) { 1420 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1421 } 1422 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1423 packageName, extras, null, null, updateUsers); 1424 if (update) { 1425 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1426 packageName, extras, null, null, updateUsers); 1427 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1428 null, null, packageName, null, updateUsers); 1429 1430 // treat asec-hosted packages like removable media on upgrade 1431 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1432 if (DEBUG_INSTALL) { 1433 Slog.i(TAG, "upgrading pkg " + res.pkg 1434 + " is ASEC-hosted -> AVAILABLE"); 1435 } 1436 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1437 ArrayList<String> pkgList = new ArrayList<String>(1); 1438 pkgList.add(packageName); 1439 sendResourcesChangedBroadcast(true, true, 1440 pkgList,uidArray, null); 1441 } 1442 } 1443 if (res.removedInfo.args != null) { 1444 // Remove the replaced package's older resources safely now 1445 deleteOld = true; 1446 } 1447 1448 // If this app is a browser and it's newly-installed for some 1449 // users, clear any default-browser state in those users 1450 if (firstUsers.length > 0) { 1451 // the app's nature doesn't depend on the user, so we can just 1452 // check its browser nature in any user and generalize. 1453 if (packageIsBrowser(packageName, firstUsers[0])) { 1454 synchronized (mPackages) { 1455 for (int userId : firstUsers) { 1456 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1457 } 1458 } 1459 } 1460 } 1461 // Log current value of "unknown sources" setting 1462 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1463 getUnknownSourcesSettings()); 1464 } 1465 // Force a gc to clear up things 1466 Runtime.getRuntime().gc(); 1467 // We delete after a gc for applications on sdcard. 1468 if (deleteOld) { 1469 synchronized (mInstallLock) { 1470 res.removedInfo.args.doPostDeleteLI(true); 1471 } 1472 } 1473 if (args.observer != null) { 1474 try { 1475 Bundle extras = extrasForInstallResult(res); 1476 args.observer.onPackageInstalled(res.name, res.returnCode, 1477 res.returnMsg, extras); 1478 } catch (RemoteException e) { 1479 Slog.i(TAG, "Observer no longer exists."); 1480 } 1481 } 1482 if (args.traceMethod != null) { 1483 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1484 args.traceCookie); 1485 } 1486 return; 1487 } else { 1488 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1489 } 1490 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1492 } break; 1493 case UPDATED_MEDIA_STATUS: { 1494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1495 boolean reportStatus = msg.arg1 == 1; 1496 boolean doGc = msg.arg2 == 1; 1497 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1498 if (doGc) { 1499 // Force a gc to clear up stale containers. 1500 Runtime.getRuntime().gc(); 1501 } 1502 if (msg.obj != null) { 1503 @SuppressWarnings("unchecked") 1504 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1506 // Unload containers 1507 unloadAllContainers(args); 1508 } 1509 if (reportStatus) { 1510 try { 1511 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1512 PackageHelper.getMountService().finishMediaUpdate(); 1513 } catch (RemoteException e) { 1514 Log.e(TAG, "MountService not running?"); 1515 } 1516 } 1517 } break; 1518 case WRITE_SETTINGS: { 1519 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1520 synchronized (mPackages) { 1521 removeMessages(WRITE_SETTINGS); 1522 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1523 mSettings.writeLPr(); 1524 mDirtyUsers.clear(); 1525 } 1526 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1527 } break; 1528 case WRITE_PACKAGE_RESTRICTIONS: { 1529 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1530 synchronized (mPackages) { 1531 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1532 for (int userId : mDirtyUsers) { 1533 mSettings.writePackageRestrictionsLPr(userId); 1534 } 1535 mDirtyUsers.clear(); 1536 } 1537 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1538 } break; 1539 case CHECK_PENDING_VERIFICATION: { 1540 final int verificationId = msg.arg1; 1541 final PackageVerificationState state = mPendingVerification.get(verificationId); 1542 1543 if ((state != null) && !state.timeoutExtended()) { 1544 final InstallArgs args = state.getInstallArgs(); 1545 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1546 1547 Slog.i(TAG, "Verification timed out for " + originUri); 1548 mPendingVerification.remove(verificationId); 1549 1550 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1551 1552 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1553 Slog.i(TAG, "Continuing with installation of " + originUri); 1554 state.setVerifierResponse(Binder.getCallingUid(), 1555 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1556 broadcastPackageVerified(verificationId, originUri, 1557 PackageManager.VERIFICATION_ALLOW, 1558 state.getInstallArgs().getUser()); 1559 try { 1560 ret = args.copyApk(mContainerService, true); 1561 } catch (RemoteException e) { 1562 Slog.e(TAG, "Could not contact the ContainerService"); 1563 } 1564 } else { 1565 broadcastPackageVerified(verificationId, originUri, 1566 PackageManager.VERIFICATION_REJECT, 1567 state.getInstallArgs().getUser()); 1568 } 1569 1570 Trace.asyncTraceEnd( 1571 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1572 1573 processPendingInstall(args, ret); 1574 mHandler.sendEmptyMessage(MCS_UNBIND); 1575 } 1576 break; 1577 } 1578 case PACKAGE_VERIFIED: { 1579 final int verificationId = msg.arg1; 1580 1581 final PackageVerificationState state = mPendingVerification.get(verificationId); 1582 if (state == null) { 1583 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1584 break; 1585 } 1586 1587 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1588 1589 state.setVerifierResponse(response.callerUid, response.code); 1590 1591 if (state.isVerificationComplete()) { 1592 mPendingVerification.remove(verificationId); 1593 1594 final InstallArgs args = state.getInstallArgs(); 1595 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1596 1597 int ret; 1598 if (state.isInstallAllowed()) { 1599 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1600 broadcastPackageVerified(verificationId, originUri, 1601 response.code, state.getInstallArgs().getUser()); 1602 try { 1603 ret = args.copyApk(mContainerService, true); 1604 } catch (RemoteException e) { 1605 Slog.e(TAG, "Could not contact the ContainerService"); 1606 } 1607 } else { 1608 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1609 } 1610 1611 Trace.asyncTraceEnd( 1612 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1613 1614 processPendingInstall(args, ret); 1615 mHandler.sendEmptyMessage(MCS_UNBIND); 1616 } 1617 1618 break; 1619 } 1620 case START_INTENT_FILTER_VERIFICATIONS: { 1621 IFVerificationParams params = (IFVerificationParams) msg.obj; 1622 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1623 params.replacing, params.pkg); 1624 break; 1625 } 1626 case INTENT_FILTER_VERIFIED: { 1627 final int verificationId = msg.arg1; 1628 1629 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1630 verificationId); 1631 if (state == null) { 1632 Slog.w(TAG, "Invalid IntentFilter verification token " 1633 + verificationId + " received"); 1634 break; 1635 } 1636 1637 final int userId = state.getUserId(); 1638 1639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1640 "Processing IntentFilter verification with token:" 1641 + verificationId + " and userId:" + userId); 1642 1643 final IntentFilterVerificationResponse response = 1644 (IntentFilterVerificationResponse) msg.obj; 1645 1646 state.setVerifierResponse(response.callerUid, response.code); 1647 1648 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1649 "IntentFilter verification with token:" + verificationId 1650 + " and userId:" + userId 1651 + " is settings verifier response with response code:" 1652 + response.code); 1653 1654 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1655 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1656 + response.getFailedDomainsString()); 1657 } 1658 1659 if (state.isVerificationComplete()) { 1660 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1661 } else { 1662 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1663 "IntentFilter verification with token:" + verificationId 1664 + " was not said to be complete"); 1665 } 1666 1667 break; 1668 } 1669 } 1670 } 1671 } 1672 1673 private StorageEventListener mStorageListener = new StorageEventListener() { 1674 @Override 1675 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1676 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1677 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1678 final String volumeUuid = vol.getFsUuid(); 1679 1680 // Clean up any users or apps that were removed or recreated 1681 // while this volume was missing 1682 reconcileUsers(volumeUuid); 1683 reconcileApps(volumeUuid); 1684 1685 // Clean up any install sessions that expired or were 1686 // cancelled while this volume was missing 1687 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1688 1689 loadPrivatePackages(vol); 1690 1691 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1692 unloadPrivatePackages(vol); 1693 } 1694 } 1695 1696 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1697 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1698 updateExternalMediaStatus(true, false); 1699 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1700 updateExternalMediaStatus(false, false); 1701 } 1702 } 1703 } 1704 1705 @Override 1706 public void onVolumeForgotten(String fsUuid) { 1707 if (TextUtils.isEmpty(fsUuid)) { 1708 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1709 return; 1710 } 1711 1712 // Remove any apps installed on the forgotten volume 1713 synchronized (mPackages) { 1714 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1715 for (PackageSetting ps : packages) { 1716 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1717 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1718 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1719 } 1720 1721 mSettings.onVolumeForgotten(fsUuid); 1722 mSettings.writeLPr(); 1723 } 1724 } 1725 }; 1726 1727 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1728 String[] grantedPermissions) { 1729 if (userId >= UserHandle.USER_SYSTEM) { 1730 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1731 } else if (userId == UserHandle.USER_ALL) { 1732 final int[] userIds; 1733 synchronized (mPackages) { 1734 userIds = UserManagerService.getInstance().getUserIds(); 1735 } 1736 for (int someUserId : userIds) { 1737 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1738 } 1739 } 1740 1741 // We could have touched GID membership, so flush out packages.list 1742 synchronized (mPackages) { 1743 mSettings.writePackageListLPr(); 1744 } 1745 } 1746 1747 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1748 String[] grantedPermissions) { 1749 SettingBase sb = (SettingBase) pkg.mExtras; 1750 if (sb == null) { 1751 return; 1752 } 1753 1754 PermissionsState permissionsState = sb.getPermissionsState(); 1755 1756 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1757 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1758 1759 synchronized (mPackages) { 1760 for (String permission : pkg.requestedPermissions) { 1761 BasePermission bp = mSettings.mPermissions.get(permission); 1762 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1763 && (grantedPermissions == null 1764 || ArrayUtils.contains(grantedPermissions, permission))) { 1765 final int flags = permissionsState.getPermissionFlags(permission, userId); 1766 // Installer cannot change immutable permissions. 1767 if ((flags & immutableFlags) == 0) { 1768 grantRuntimePermission(pkg.packageName, permission, userId); 1769 } 1770 } 1771 } 1772 } 1773 } 1774 1775 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1776 Bundle extras = null; 1777 switch (res.returnCode) { 1778 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1779 extras = new Bundle(); 1780 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1781 res.origPermission); 1782 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1783 res.origPackage); 1784 break; 1785 } 1786 case PackageManager.INSTALL_SUCCEEDED: { 1787 extras = new Bundle(); 1788 extras.putBoolean(Intent.EXTRA_REPLACING, 1789 res.removedInfo != null && res.removedInfo.removedPackage != null); 1790 break; 1791 } 1792 } 1793 return extras; 1794 } 1795 1796 void scheduleWriteSettingsLocked() { 1797 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1798 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1799 } 1800 } 1801 1802 void scheduleWritePackageRestrictionsLocked(int userId) { 1803 if (!sUserManager.exists(userId)) return; 1804 mDirtyUsers.add(userId); 1805 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1806 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1807 } 1808 } 1809 1810 public static PackageManagerService main(Context context, Installer installer, 1811 boolean factoryTest, boolean onlyCore) { 1812 PackageManagerService m = new PackageManagerService(context, installer, 1813 factoryTest, onlyCore); 1814 ServiceManager.addService("package", m); 1815 return m; 1816 } 1817 1818 static String[] splitString(String str, char sep) { 1819 int count = 1; 1820 int i = 0; 1821 while ((i=str.indexOf(sep, i)) >= 0) { 1822 count++; 1823 i++; 1824 } 1825 1826 String[] res = new String[count]; 1827 i=0; 1828 count = 0; 1829 int lastI=0; 1830 while ((i=str.indexOf(sep, i)) >= 0) { 1831 res[count] = str.substring(lastI, i); 1832 count++; 1833 i++; 1834 lastI = i; 1835 } 1836 res[count] = str.substring(lastI, str.length()); 1837 return res; 1838 } 1839 1840 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1841 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1842 Context.DISPLAY_SERVICE); 1843 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1844 } 1845 1846 public PackageManagerService(Context context, Installer installer, 1847 boolean factoryTest, boolean onlyCore) { 1848 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1849 SystemClock.uptimeMillis()); 1850 1851 if (mSdkVersion <= 0) { 1852 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1853 } 1854 1855 mContext = context; 1856 mFactoryTest = factoryTest; 1857 mOnlyCore = onlyCore; 1858 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1859 mMetrics = new DisplayMetrics(); 1860 mSettings = new Settings(mPackages); 1861 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1862 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1863 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1864 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1865 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1866 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1867 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1868 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1869 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1870 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1871 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1872 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1873 1874 // TODO: add a property to control this? 1875 long dexOptLRUThresholdInMinutes; 1876 if (mLazyDexOpt) { 1877 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1878 } else { 1879 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1880 } 1881 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1882 1883 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1884 if (separateProcesses != null && separateProcesses.length() > 0) { 1885 if ("*".equals(separateProcesses)) { 1886 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1887 mSeparateProcesses = null; 1888 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1889 } else { 1890 mDefParseFlags = 0; 1891 mSeparateProcesses = separateProcesses.split(","); 1892 Slog.w(TAG, "Running with debug.separate_processes: " 1893 + separateProcesses); 1894 } 1895 } else { 1896 mDefParseFlags = 0; 1897 mSeparateProcesses = null; 1898 } 1899 1900 mInstaller = installer; 1901 mPackageDexOptimizer = new PackageDexOptimizer(this); 1902 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1903 1904 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1905 FgThread.get().getLooper()); 1906 1907 getDefaultDisplayMetrics(context, mMetrics); 1908 1909 SystemConfig systemConfig = SystemConfig.getInstance(); 1910 mGlobalGids = systemConfig.getGlobalGids(); 1911 mSystemPermissions = systemConfig.getSystemPermissions(); 1912 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1913 1914 synchronized (mInstallLock) { 1915 // writer 1916 synchronized (mPackages) { 1917 mHandlerThread = new ServiceThread(TAG, 1918 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1919 mHandlerThread.start(); 1920 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1921 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1922 1923 File dataDir = Environment.getDataDirectory(); 1924 mAppDataDir = new File(dataDir, "data"); 1925 mAppInstallDir = new File(dataDir, "app"); 1926 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1927 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1928 mUserAppDataDir = new File(dataDir, "user"); 1929 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1930 1931 sUserManager = new UserManagerService(context, this, 1932 mInstallLock, mPackages); 1933 1934 // Propagate permission configuration in to package manager. 1935 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1936 = systemConfig.getPermissions(); 1937 for (int i=0; i<permConfig.size(); i++) { 1938 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1939 BasePermission bp = mSettings.mPermissions.get(perm.name); 1940 if (bp == null) { 1941 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1942 mSettings.mPermissions.put(perm.name, bp); 1943 } 1944 if (perm.gids != null) { 1945 bp.setGids(perm.gids, perm.perUser); 1946 } 1947 } 1948 1949 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1950 for (int i=0; i<libConfig.size(); i++) { 1951 mSharedLibraries.put(libConfig.keyAt(i), 1952 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1953 } 1954 1955 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1956 1957 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1958 1959 String customResolverActivity = Resources.getSystem().getString( 1960 R.string.config_customResolverActivity); 1961 if (TextUtils.isEmpty(customResolverActivity)) { 1962 customResolverActivity = null; 1963 } else { 1964 mCustomResolverComponentName = ComponentName.unflattenFromString( 1965 customResolverActivity); 1966 } 1967 1968 long startTime = SystemClock.uptimeMillis(); 1969 1970 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1971 startTime); 1972 1973 // Set flag to monitor and not change apk file paths when 1974 // scanning install directories. 1975 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1976 1977 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1978 1979 /** 1980 * Add everything in the in the boot class path to the 1981 * list of process files because dexopt will have been run 1982 * if necessary during zygote startup. 1983 */ 1984 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1985 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1986 1987 if (bootClassPath != null) { 1988 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1989 for (String element : bootClassPathElements) { 1990 alreadyDexOpted.add(element); 1991 } 1992 } else { 1993 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1994 } 1995 1996 if (systemServerClassPath != null) { 1997 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1998 for (String element : systemServerClassPathElements) { 1999 alreadyDexOpted.add(element); 2000 } 2001 } else { 2002 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2003 } 2004 2005 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2006 final String[] dexCodeInstructionSets = 2007 getDexCodeInstructionSets( 2008 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2009 2010 /** 2011 * Ensure all external libraries have had dexopt run on them. 2012 */ 2013 if (mSharedLibraries.size() > 0) { 2014 // NOTE: For now, we're compiling these system "shared libraries" 2015 // (and framework jars) into all available architectures. It's possible 2016 // to compile them only when we come across an app that uses them (there's 2017 // already logic for that in scanPackageLI) but that adds some complexity. 2018 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2019 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2020 final String lib = libEntry.path; 2021 if (lib == null) { 2022 continue; 2023 } 2024 2025 try { 2026 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2027 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2028 alreadyDexOpted.add(lib); 2029 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2030 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2031 } 2032 } catch (FileNotFoundException e) { 2033 Slog.w(TAG, "Library not found: " + lib); 2034 } catch (IOException e) { 2035 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2036 + e.getMessage()); 2037 } 2038 } 2039 } 2040 } 2041 2042 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2043 2044 // Gross hack for now: we know this file doesn't contain any 2045 // code, so don't dexopt it to avoid the resulting log spew. 2046 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2047 2048 // Gross hack for now: we know this file is only part of 2049 // the boot class path for art, so don't dexopt it to 2050 // avoid the resulting log spew. 2051 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2052 2053 /** 2054 * There are a number of commands implemented in Java, which 2055 * we currently need to do the dexopt on so that they can be 2056 * run from a non-root shell. 2057 */ 2058 String[] frameworkFiles = frameworkDir.list(); 2059 if (frameworkFiles != null) { 2060 // TODO: We could compile these only for the most preferred ABI. We should 2061 // first double check that the dex files for these commands are not referenced 2062 // by other system apps. 2063 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2064 for (int i=0; i<frameworkFiles.length; i++) { 2065 File libPath = new File(frameworkDir, frameworkFiles[i]); 2066 String path = libPath.getPath(); 2067 // Skip the file if we already did it. 2068 if (alreadyDexOpted.contains(path)) { 2069 continue; 2070 } 2071 // Skip the file if it is not a type we want to dexopt. 2072 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2073 continue; 2074 } 2075 try { 2076 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2077 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2078 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2079 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2080 } 2081 } catch (FileNotFoundException e) { 2082 Slog.w(TAG, "Jar not found: " + path); 2083 } catch (IOException e) { 2084 Slog.w(TAG, "Exception reading jar: " + path, e); 2085 } 2086 } 2087 } 2088 } 2089 2090 final VersionInfo ver = mSettings.getInternalVersion(); 2091 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2092 // when upgrading from pre-M, promote system app permissions from install to runtime 2093 mPromoteSystemApps = 2094 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2095 2096 // save off the names of pre-existing system packages prior to scanning; we don't 2097 // want to automatically grant runtime permissions for new system apps 2098 if (mPromoteSystemApps) { 2099 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2100 while (pkgSettingIter.hasNext()) { 2101 PackageSetting ps = pkgSettingIter.next(); 2102 if (isSystemApp(ps)) { 2103 mExistingSystemPackages.add(ps.name); 2104 } 2105 } 2106 } 2107 2108 // Collect vendor overlay packages. 2109 // (Do this before scanning any apps.) 2110 // For security and version matching reason, only consider 2111 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2112 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2113 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2114 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2115 2116 // Find base frameworks (resource packages without code). 2117 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2118 | PackageParser.PARSE_IS_SYSTEM_DIR 2119 | PackageParser.PARSE_IS_PRIVILEGED, 2120 scanFlags | SCAN_NO_DEX, 0); 2121 2122 // Collected privileged system packages. 2123 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2124 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2125 | PackageParser.PARSE_IS_SYSTEM_DIR 2126 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2127 2128 // Collect ordinary system packages. 2129 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2130 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2131 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2132 2133 // Collect all vendor packages. 2134 File vendorAppDir = new File("/vendor/app"); 2135 try { 2136 vendorAppDir = vendorAppDir.getCanonicalFile(); 2137 } catch (IOException e) { 2138 // failed to look up canonical path, continue with original one 2139 } 2140 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2141 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2142 2143 // Collect all OEM packages. 2144 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2145 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2146 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2147 2148 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2149 mInstaller.moveFiles(); 2150 2151 // Prune any system packages that no longer exist. 2152 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2153 if (!mOnlyCore) { 2154 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2155 while (psit.hasNext()) { 2156 PackageSetting ps = psit.next(); 2157 2158 /* 2159 * If this is not a system app, it can't be a 2160 * disable system app. 2161 */ 2162 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2163 continue; 2164 } 2165 2166 /* 2167 * If the package is scanned, it's not erased. 2168 */ 2169 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2170 if (scannedPkg != null) { 2171 /* 2172 * If the system app is both scanned and in the 2173 * disabled packages list, then it must have been 2174 * added via OTA. Remove it from the currently 2175 * scanned package so the previously user-installed 2176 * application can be scanned. 2177 */ 2178 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2179 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2180 + ps.name + "; removing system app. Last known codePath=" 2181 + ps.codePathString + ", installStatus=" + ps.installStatus 2182 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2183 + scannedPkg.mVersionCode); 2184 removePackageLI(ps, true); 2185 mExpectingBetter.put(ps.name, ps.codePath); 2186 } 2187 2188 continue; 2189 } 2190 2191 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2192 psit.remove(); 2193 logCriticalInfo(Log.WARN, "System package " + ps.name 2194 + " no longer exists; wiping its data"); 2195 removeDataDirsLI(null, ps.name); 2196 } else { 2197 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2198 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2199 possiblyDeletedUpdatedSystemApps.add(ps.name); 2200 } 2201 } 2202 } 2203 } 2204 2205 //look for any incomplete package installations 2206 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2207 //clean up list 2208 for(int i = 0; i < deletePkgsList.size(); i++) { 2209 //clean up here 2210 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2211 } 2212 //delete tmp files 2213 deleteTempPackageFiles(); 2214 2215 // Remove any shared userIDs that have no associated packages 2216 mSettings.pruneSharedUsersLPw(); 2217 2218 if (!mOnlyCore) { 2219 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2220 SystemClock.uptimeMillis()); 2221 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2222 2223 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2224 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2225 2226 /** 2227 * Remove disable package settings for any updated system 2228 * apps that were removed via an OTA. If they're not a 2229 * previously-updated app, remove them completely. 2230 * Otherwise, just revoke their system-level permissions. 2231 */ 2232 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2233 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2234 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2235 2236 String msg; 2237 if (deletedPkg == null) { 2238 msg = "Updated system package " + deletedAppName 2239 + " no longer exists; wiping its data"; 2240 removeDataDirsLI(null, deletedAppName); 2241 } else { 2242 msg = "Updated system app + " + deletedAppName 2243 + " no longer present; removing system privileges for " 2244 + deletedAppName; 2245 2246 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2247 2248 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2249 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2250 } 2251 logCriticalInfo(Log.WARN, msg); 2252 } 2253 2254 /** 2255 * Make sure all system apps that we expected to appear on 2256 * the userdata partition actually showed up. If they never 2257 * appeared, crawl back and revive the system version. 2258 */ 2259 for (int i = 0; i < mExpectingBetter.size(); i++) { 2260 final String packageName = mExpectingBetter.keyAt(i); 2261 if (!mPackages.containsKey(packageName)) { 2262 final File scanFile = mExpectingBetter.valueAt(i); 2263 2264 logCriticalInfo(Log.WARN, "Expected better " + packageName 2265 + " but never showed up; reverting to system"); 2266 2267 final int reparseFlags; 2268 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2269 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2270 | PackageParser.PARSE_IS_SYSTEM_DIR 2271 | PackageParser.PARSE_IS_PRIVILEGED; 2272 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2273 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2274 | PackageParser.PARSE_IS_SYSTEM_DIR; 2275 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2276 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2277 | PackageParser.PARSE_IS_SYSTEM_DIR; 2278 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2279 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2280 | PackageParser.PARSE_IS_SYSTEM_DIR; 2281 } else { 2282 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2283 continue; 2284 } 2285 2286 mSettings.enableSystemPackageLPw(packageName); 2287 2288 try { 2289 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2290 } catch (PackageManagerException e) { 2291 Slog.e(TAG, "Failed to parse original system package: " 2292 + e.getMessage()); 2293 } 2294 } 2295 } 2296 } 2297 mExpectingBetter.clear(); 2298 2299 // Now that we know all of the shared libraries, update all clients to have 2300 // the correct library paths. 2301 updateAllSharedLibrariesLPw(); 2302 2303 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2304 // NOTE: We ignore potential failures here during a system scan (like 2305 // the rest of the commands above) because there's precious little we 2306 // can do about it. A settings error is reported, though. 2307 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2308 false /* force dexopt */, false /* defer dexopt */, 2309 false /* boot complete */); 2310 } 2311 2312 // Now that we know all the packages we are keeping, 2313 // read and update their last usage times. 2314 mPackageUsage.readLP(); 2315 2316 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2317 SystemClock.uptimeMillis()); 2318 Slog.i(TAG, "Time to scan packages: " 2319 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2320 + " seconds"); 2321 2322 // If the platform SDK has changed since the last time we booted, 2323 // we need to re-grant app permission to catch any new ones that 2324 // appear. This is really a hack, and means that apps can in some 2325 // cases get permissions that the user didn't initially explicitly 2326 // allow... it would be nice to have some better way to handle 2327 // this situation. 2328 int updateFlags = UPDATE_PERMISSIONS_ALL; 2329 if (ver.sdkVersion != mSdkVersion) { 2330 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2331 + mSdkVersion + "; regranting permissions for internal storage"); 2332 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2333 } 2334 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2335 ver.sdkVersion = mSdkVersion; 2336 2337 // If this is the first boot or an update from pre-M, and it is a normal 2338 // boot, then we need to initialize the default preferred apps across 2339 // all defined users. 2340 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2341 for (UserInfo user : sUserManager.getUsers(true)) { 2342 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2343 applyFactoryDefaultBrowserLPw(user.id); 2344 primeDomainVerificationsLPw(user.id); 2345 } 2346 } 2347 2348 // If this is first boot after an OTA, and a normal boot, then 2349 // we need to clear code cache directories. 2350 if (mIsUpgrade && !onlyCore) { 2351 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2352 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2353 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2354 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2355 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2356 } 2357 } 2358 ver.fingerprint = Build.FINGERPRINT; 2359 } 2360 2361 checkDefaultBrowser(); 2362 2363 // clear only after permissions and other defaults have been updated 2364 mExistingSystemPackages.clear(); 2365 mPromoteSystemApps = false; 2366 2367 // All the changes are done during package scanning. 2368 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2369 2370 // can downgrade to reader 2371 mSettings.writeLPr(); 2372 2373 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2374 SystemClock.uptimeMillis()); 2375 2376 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2377 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2378 2379 mInstallerService = new PackageInstallerService(context, this); 2380 2381 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2382 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2383 mIntentFilterVerifierComponent); 2384 2385 } // synchronized (mPackages) 2386 } // synchronized (mInstallLock) 2387 2388 // Now after opening every single application zip, make sure they 2389 // are all flushed. Not really needed, but keeps things nice and 2390 // tidy. 2391 Runtime.getRuntime().gc(); 2392 2393 // Expose private service for system components to use. 2394 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2395 } 2396 2397 @Override 2398 public boolean isFirstBoot() { 2399 return !mRestoredSettings; 2400 } 2401 2402 @Override 2403 public boolean isOnlyCoreApps() { 2404 return mOnlyCore; 2405 } 2406 2407 @Override 2408 public boolean isUpgrade() { 2409 return mIsUpgrade; 2410 } 2411 2412 private String getRequiredVerifierLPr() { 2413 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2414 // We only care about verifier that's installed under system user. 2415 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2416 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2417 2418 String requiredVerifier = null; 2419 2420 final int N = receivers.size(); 2421 for (int i = 0; i < N; i++) { 2422 final ResolveInfo info = receivers.get(i); 2423 2424 if (info.activityInfo == null) { 2425 continue; 2426 } 2427 2428 final String packageName = info.activityInfo.packageName; 2429 2430 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2431 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2432 continue; 2433 } 2434 2435 if (requiredVerifier != null) { 2436 throw new RuntimeException("There can be only one required verifier"); 2437 } 2438 2439 requiredVerifier = packageName; 2440 } 2441 2442 return requiredVerifier; 2443 } 2444 2445 private String getRequiredInstallerLPr() { 2446 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2447 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2448 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2449 2450 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2451 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2452 2453 String requiredInstaller = null; 2454 2455 final int N = installers.size(); 2456 for (int i = 0; i < N; i++) { 2457 final ResolveInfo info = installers.get(i); 2458 final String packageName = info.activityInfo.packageName; 2459 2460 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2461 continue; 2462 } 2463 2464 if (requiredInstaller != null) { 2465 throw new RuntimeException("There must be one required installer"); 2466 } 2467 2468 requiredInstaller = packageName; 2469 } 2470 2471 if (requiredInstaller == null) { 2472 throw new RuntimeException("There must be one required installer"); 2473 } 2474 2475 return requiredInstaller; 2476 } 2477 2478 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2479 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2480 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2481 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2482 2483 ComponentName verifierComponentName = null; 2484 2485 int priority = -1000; 2486 final int N = receivers.size(); 2487 for (int i = 0; i < N; i++) { 2488 final ResolveInfo info = receivers.get(i); 2489 2490 if (info.activityInfo == null) { 2491 continue; 2492 } 2493 2494 final String packageName = info.activityInfo.packageName; 2495 2496 final PackageSetting ps = mSettings.mPackages.get(packageName); 2497 if (ps == null) { 2498 continue; 2499 } 2500 2501 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2502 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2503 continue; 2504 } 2505 2506 // Select the IntentFilterVerifier with the highest priority 2507 if (priority < info.priority) { 2508 priority = info.priority; 2509 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2510 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2511 + verifierComponentName + " with priority: " + info.priority); 2512 } 2513 } 2514 2515 return verifierComponentName; 2516 } 2517 2518 private void primeDomainVerificationsLPw(int userId) { 2519 if (DEBUG_DOMAIN_VERIFICATION) { 2520 Slog.d(TAG, "Priming domain verifications in user " + userId); 2521 } 2522 2523 SystemConfig systemConfig = SystemConfig.getInstance(); 2524 ArraySet<String> packages = systemConfig.getLinkedApps(); 2525 ArraySet<String> domains = new ArraySet<String>(); 2526 2527 for (String packageName : packages) { 2528 PackageParser.Package pkg = mPackages.get(packageName); 2529 if (pkg != null) { 2530 if (!pkg.isSystemApp()) { 2531 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2532 continue; 2533 } 2534 2535 domains.clear(); 2536 for (PackageParser.Activity a : pkg.activities) { 2537 for (ActivityIntentInfo filter : a.intents) { 2538 if (hasValidDomains(filter)) { 2539 domains.addAll(filter.getHostsList()); 2540 } 2541 } 2542 } 2543 2544 if (domains.size() > 0) { 2545 if (DEBUG_DOMAIN_VERIFICATION) { 2546 Slog.v(TAG, " + " + packageName); 2547 } 2548 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2549 // state w.r.t. the formal app-linkage "no verification attempted" state; 2550 // and then 'always' in the per-user state actually used for intent resolution. 2551 final IntentFilterVerificationInfo ivi; 2552 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2553 new ArrayList<String>(domains)); 2554 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2555 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2556 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2557 } else { 2558 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2559 + "' does not handle web links"); 2560 } 2561 } else { 2562 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2563 } 2564 } 2565 2566 scheduleWritePackageRestrictionsLocked(userId); 2567 scheduleWriteSettingsLocked(); 2568 } 2569 2570 private void applyFactoryDefaultBrowserLPw(int userId) { 2571 // The default browser app's package name is stored in a string resource, 2572 // with a product-specific overlay used for vendor customization. 2573 String browserPkg = mContext.getResources().getString( 2574 com.android.internal.R.string.default_browser); 2575 if (!TextUtils.isEmpty(browserPkg)) { 2576 // non-empty string => required to be a known package 2577 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2578 if (ps == null) { 2579 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2580 browserPkg = null; 2581 } else { 2582 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2583 } 2584 } 2585 2586 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2587 // default. If there's more than one, just leave everything alone. 2588 if (browserPkg == null) { 2589 calculateDefaultBrowserLPw(userId); 2590 } 2591 } 2592 2593 private void calculateDefaultBrowserLPw(int userId) { 2594 List<String> allBrowsers = resolveAllBrowserApps(userId); 2595 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2596 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2597 } 2598 2599 private List<String> resolveAllBrowserApps(int userId) { 2600 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2601 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2602 PackageManager.MATCH_ALL, userId); 2603 2604 final int count = list.size(); 2605 List<String> result = new ArrayList<String>(count); 2606 for (int i=0; i<count; i++) { 2607 ResolveInfo info = list.get(i); 2608 if (info.activityInfo == null 2609 || !info.handleAllWebDataURI 2610 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2611 || result.contains(info.activityInfo.packageName)) { 2612 continue; 2613 } 2614 result.add(info.activityInfo.packageName); 2615 } 2616 2617 return result; 2618 } 2619 2620 private boolean packageIsBrowser(String packageName, int userId) { 2621 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2622 PackageManager.MATCH_ALL, userId); 2623 final int N = list.size(); 2624 for (int i = 0; i < N; i++) { 2625 ResolveInfo info = list.get(i); 2626 if (packageName.equals(info.activityInfo.packageName)) { 2627 return true; 2628 } 2629 } 2630 return false; 2631 } 2632 2633 private void checkDefaultBrowser() { 2634 final int myUserId = UserHandle.myUserId(); 2635 final String packageName = getDefaultBrowserPackageName(myUserId); 2636 if (packageName != null) { 2637 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2638 if (info == null) { 2639 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2640 synchronized (mPackages) { 2641 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2642 } 2643 } 2644 } 2645 } 2646 2647 @Override 2648 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2649 throws RemoteException { 2650 try { 2651 return super.onTransact(code, data, reply, flags); 2652 } catch (RuntimeException e) { 2653 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2654 Slog.wtf(TAG, "Package Manager Crash", e); 2655 } 2656 throw e; 2657 } 2658 } 2659 2660 void cleanupInstallFailedPackage(PackageSetting ps) { 2661 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2662 2663 removeDataDirsLI(ps.volumeUuid, ps.name); 2664 if (ps.codePath != null) { 2665 if (ps.codePath.isDirectory()) { 2666 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2667 } else { 2668 ps.codePath.delete(); 2669 } 2670 } 2671 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2672 if (ps.resourcePath.isDirectory()) { 2673 FileUtils.deleteContents(ps.resourcePath); 2674 } 2675 ps.resourcePath.delete(); 2676 } 2677 mSettings.removePackageLPw(ps.name); 2678 } 2679 2680 static int[] appendInts(int[] cur, int[] add) { 2681 if (add == null) return cur; 2682 if (cur == null) return add; 2683 final int N = add.length; 2684 for (int i=0; i<N; i++) { 2685 cur = appendInt(cur, add[i]); 2686 } 2687 return cur; 2688 } 2689 2690 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2691 if (!sUserManager.exists(userId)) return null; 2692 final PackageSetting ps = (PackageSetting) p.mExtras; 2693 if (ps == null) { 2694 return null; 2695 } 2696 2697 final PermissionsState permissionsState = ps.getPermissionsState(); 2698 2699 final int[] gids = permissionsState.computeGids(userId); 2700 final Set<String> permissions = permissionsState.getPermissions(userId); 2701 final PackageUserState state = ps.readUserState(userId); 2702 2703 return PackageParser.generatePackageInfo(p, gids, flags, 2704 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2705 } 2706 2707 @Override 2708 public boolean isPackageFrozen(String packageName) { 2709 synchronized (mPackages) { 2710 final PackageSetting ps = mSettings.mPackages.get(packageName); 2711 if (ps != null) { 2712 return ps.frozen; 2713 } 2714 } 2715 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2716 return true; 2717 } 2718 2719 @Override 2720 public boolean isPackageAvailable(String packageName, int userId) { 2721 if (!sUserManager.exists(userId)) return false; 2722 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2723 synchronized (mPackages) { 2724 PackageParser.Package p = mPackages.get(packageName); 2725 if (p != null) { 2726 final PackageSetting ps = (PackageSetting) p.mExtras; 2727 if (ps != null) { 2728 final PackageUserState state = ps.readUserState(userId); 2729 if (state != null) { 2730 return PackageParser.isAvailable(state); 2731 } 2732 } 2733 } 2734 } 2735 return false; 2736 } 2737 2738 @Override 2739 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2740 if (!sUserManager.exists(userId)) return null; 2741 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2742 // reader 2743 synchronized (mPackages) { 2744 PackageParser.Package p = mPackages.get(packageName); 2745 if (DEBUG_PACKAGE_INFO) 2746 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2747 if (p != null) { 2748 return generatePackageInfo(p, flags, userId); 2749 } 2750 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2751 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2752 } 2753 } 2754 return null; 2755 } 2756 2757 @Override 2758 public String[] currentToCanonicalPackageNames(String[] names) { 2759 String[] out = new String[names.length]; 2760 // reader 2761 synchronized (mPackages) { 2762 for (int i=names.length-1; i>=0; i--) { 2763 PackageSetting ps = mSettings.mPackages.get(names[i]); 2764 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2765 } 2766 } 2767 return out; 2768 } 2769 2770 @Override 2771 public String[] canonicalToCurrentPackageNames(String[] names) { 2772 String[] out = new String[names.length]; 2773 // reader 2774 synchronized (mPackages) { 2775 for (int i=names.length-1; i>=0; i--) { 2776 String cur = mSettings.mRenamedPackages.get(names[i]); 2777 out[i] = cur != null ? cur : names[i]; 2778 } 2779 } 2780 return out; 2781 } 2782 2783 @Override 2784 public int getPackageUid(String packageName, int userId) { 2785 return getPackageUidEtc(packageName, 0, userId); 2786 } 2787 2788 @Override 2789 public int getPackageUidEtc(String packageName, int flags, int userId) { 2790 if (!sUserManager.exists(userId)) return -1; 2791 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2792 2793 // reader 2794 synchronized (mPackages) { 2795 final PackageParser.Package p = mPackages.get(packageName); 2796 if (p != null) { 2797 return UserHandle.getUid(userId, p.applicationInfo.uid); 2798 } 2799 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2800 final PackageSetting ps = mSettings.mPackages.get(packageName); 2801 if (ps != null) { 2802 return UserHandle.getUid(userId, ps.appId); 2803 } 2804 } 2805 } 2806 2807 return -1; 2808 } 2809 2810 @Override 2811 public int[] getPackageGids(String packageName, int userId) { 2812 return getPackageGidsEtc(packageName, 0, userId); 2813 } 2814 2815 @Override 2816 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2817 if (!sUserManager.exists(userId)) { 2818 return null; 2819 } 2820 2821 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2822 "getPackageGids"); 2823 2824 // reader 2825 synchronized (mPackages) { 2826 final PackageParser.Package p = mPackages.get(packageName); 2827 if (p != null) { 2828 PackageSetting ps = (PackageSetting) p.mExtras; 2829 return ps.getPermissionsState().computeGids(userId); 2830 } 2831 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2832 final PackageSetting ps = mSettings.mPackages.get(packageName); 2833 if (ps != null) { 2834 return ps.getPermissionsState().computeGids(userId); 2835 } 2836 } 2837 } 2838 2839 return null; 2840 } 2841 2842 static PermissionInfo generatePermissionInfo( 2843 BasePermission bp, int flags) { 2844 if (bp.perm != null) { 2845 return PackageParser.generatePermissionInfo(bp.perm, flags); 2846 } 2847 PermissionInfo pi = new PermissionInfo(); 2848 pi.name = bp.name; 2849 pi.packageName = bp.sourcePackage; 2850 pi.nonLocalizedLabel = bp.name; 2851 pi.protectionLevel = bp.protectionLevel; 2852 return pi; 2853 } 2854 2855 @Override 2856 public PermissionInfo getPermissionInfo(String name, int flags) { 2857 // reader 2858 synchronized (mPackages) { 2859 final BasePermission p = mSettings.mPermissions.get(name); 2860 if (p != null) { 2861 return generatePermissionInfo(p, flags); 2862 } 2863 return null; 2864 } 2865 } 2866 2867 @Override 2868 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2869 // reader 2870 synchronized (mPackages) { 2871 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2872 for (BasePermission p : mSettings.mPermissions.values()) { 2873 if (group == null) { 2874 if (p.perm == null || p.perm.info.group == null) { 2875 out.add(generatePermissionInfo(p, flags)); 2876 } 2877 } else { 2878 if (p.perm != null && group.equals(p.perm.info.group)) { 2879 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2880 } 2881 } 2882 } 2883 2884 if (out.size() > 0) { 2885 return out; 2886 } 2887 return mPermissionGroups.containsKey(group) ? out : null; 2888 } 2889 } 2890 2891 @Override 2892 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2893 // reader 2894 synchronized (mPackages) { 2895 return PackageParser.generatePermissionGroupInfo( 2896 mPermissionGroups.get(name), flags); 2897 } 2898 } 2899 2900 @Override 2901 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2902 // reader 2903 synchronized (mPackages) { 2904 final int N = mPermissionGroups.size(); 2905 ArrayList<PermissionGroupInfo> out 2906 = new ArrayList<PermissionGroupInfo>(N); 2907 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2908 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2909 } 2910 return out; 2911 } 2912 } 2913 2914 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2915 int userId) { 2916 if (!sUserManager.exists(userId)) return null; 2917 PackageSetting ps = mSettings.mPackages.get(packageName); 2918 if (ps != null) { 2919 if (ps.pkg == null) { 2920 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2921 flags, userId); 2922 if (pInfo != null) { 2923 return pInfo.applicationInfo; 2924 } 2925 return null; 2926 } 2927 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2928 ps.readUserState(userId), userId); 2929 } 2930 return null; 2931 } 2932 2933 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2934 int userId) { 2935 if (!sUserManager.exists(userId)) return null; 2936 PackageSetting ps = mSettings.mPackages.get(packageName); 2937 if (ps != null) { 2938 PackageParser.Package pkg = ps.pkg; 2939 if (pkg == null) { 2940 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2941 return null; 2942 } 2943 // Only data remains, so we aren't worried about code paths 2944 pkg = new PackageParser.Package(packageName); 2945 pkg.applicationInfo.packageName = packageName; 2946 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2947 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2948 pkg.applicationInfo.dataDir = Environment 2949 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2950 .getAbsolutePath(); 2951 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2952 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2953 } 2954 return generatePackageInfo(pkg, flags, userId); 2955 } 2956 return null; 2957 } 2958 2959 @Override 2960 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2961 if (!sUserManager.exists(userId)) return null; 2962 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2963 // writer 2964 synchronized (mPackages) { 2965 PackageParser.Package p = mPackages.get(packageName); 2966 if (DEBUG_PACKAGE_INFO) Log.v( 2967 TAG, "getApplicationInfo " + packageName 2968 + ": " + p); 2969 if (p != null) { 2970 PackageSetting ps = mSettings.mPackages.get(packageName); 2971 if (ps == null) return null; 2972 // Note: isEnabledLP() does not apply here - always return info 2973 return PackageParser.generateApplicationInfo( 2974 p, flags, ps.readUserState(userId), userId); 2975 } 2976 if ("android".equals(packageName)||"system".equals(packageName)) { 2977 return mAndroidApplication; 2978 } 2979 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2980 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2981 } 2982 } 2983 return null; 2984 } 2985 2986 @Override 2987 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2988 final IPackageDataObserver observer) { 2989 mContext.enforceCallingOrSelfPermission( 2990 android.Manifest.permission.CLEAR_APP_CACHE, null); 2991 // Queue up an async operation since clearing cache may take a little while. 2992 mHandler.post(new Runnable() { 2993 public void run() { 2994 mHandler.removeCallbacks(this); 2995 int retCode = -1; 2996 synchronized (mInstallLock) { 2997 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2998 if (retCode < 0) { 2999 Slog.w(TAG, "Couldn't clear application caches"); 3000 } 3001 } 3002 if (observer != null) { 3003 try { 3004 observer.onRemoveCompleted(null, (retCode >= 0)); 3005 } catch (RemoteException e) { 3006 Slog.w(TAG, "RemoveException when invoking call back"); 3007 } 3008 } 3009 } 3010 }); 3011 } 3012 3013 @Override 3014 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3015 final IntentSender pi) { 3016 mContext.enforceCallingOrSelfPermission( 3017 android.Manifest.permission.CLEAR_APP_CACHE, null); 3018 // Queue up an async operation since clearing cache may take a little while. 3019 mHandler.post(new Runnable() { 3020 public void run() { 3021 mHandler.removeCallbacks(this); 3022 int retCode = -1; 3023 synchronized (mInstallLock) { 3024 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3025 if (retCode < 0) { 3026 Slog.w(TAG, "Couldn't clear application caches"); 3027 } 3028 } 3029 if(pi != null) { 3030 try { 3031 // Callback via pending intent 3032 int code = (retCode >= 0) ? 1 : 0; 3033 pi.sendIntent(null, code, null, 3034 null, null); 3035 } catch (SendIntentException e1) { 3036 Slog.i(TAG, "Failed to send pending intent"); 3037 } 3038 } 3039 } 3040 }); 3041 } 3042 3043 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3044 synchronized (mInstallLock) { 3045 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3046 throw new IOException("Failed to free enough space"); 3047 } 3048 } 3049 } 3050 3051 @Override 3052 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3053 if (!sUserManager.exists(userId)) return null; 3054 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3055 synchronized (mPackages) { 3056 PackageParser.Activity a = mActivities.mActivities.get(component); 3057 3058 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3059 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3060 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3061 if (ps == null) return null; 3062 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3063 userId); 3064 } 3065 if (mResolveComponentName.equals(component)) { 3066 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3067 new PackageUserState(), userId); 3068 } 3069 } 3070 return null; 3071 } 3072 3073 @Override 3074 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3075 String resolvedType) { 3076 synchronized (mPackages) { 3077 if (component.equals(mResolveComponentName)) { 3078 // The resolver supports EVERYTHING! 3079 return true; 3080 } 3081 PackageParser.Activity a = mActivities.mActivities.get(component); 3082 if (a == null) { 3083 return false; 3084 } 3085 for (int i=0; i<a.intents.size(); i++) { 3086 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3087 intent.getData(), intent.getCategories(), TAG) >= 0) { 3088 return true; 3089 } 3090 } 3091 return false; 3092 } 3093 } 3094 3095 @Override 3096 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3097 if (!sUserManager.exists(userId)) return null; 3098 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3099 synchronized (mPackages) { 3100 PackageParser.Activity a = mReceivers.mActivities.get(component); 3101 if (DEBUG_PACKAGE_INFO) Log.v( 3102 TAG, "getReceiverInfo " + component + ": " + a); 3103 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3104 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3105 if (ps == null) return null; 3106 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3107 userId); 3108 } 3109 } 3110 return null; 3111 } 3112 3113 @Override 3114 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3115 if (!sUserManager.exists(userId)) return null; 3116 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3117 synchronized (mPackages) { 3118 PackageParser.Service s = mServices.mServices.get(component); 3119 if (DEBUG_PACKAGE_INFO) Log.v( 3120 TAG, "getServiceInfo " + component + ": " + s); 3121 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3122 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3123 if (ps == null) return null; 3124 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3125 userId); 3126 } 3127 } 3128 return null; 3129 } 3130 3131 @Override 3132 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3133 if (!sUserManager.exists(userId)) return null; 3134 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3135 synchronized (mPackages) { 3136 PackageParser.Provider p = mProviders.mProviders.get(component); 3137 if (DEBUG_PACKAGE_INFO) Log.v( 3138 TAG, "getProviderInfo " + component + ": " + p); 3139 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3140 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3141 if (ps == null) return null; 3142 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3143 userId); 3144 } 3145 } 3146 return null; 3147 } 3148 3149 @Override 3150 public String[] getSystemSharedLibraryNames() { 3151 Set<String> libSet; 3152 synchronized (mPackages) { 3153 libSet = mSharedLibraries.keySet(); 3154 int size = libSet.size(); 3155 if (size > 0) { 3156 String[] libs = new String[size]; 3157 libSet.toArray(libs); 3158 return libs; 3159 } 3160 } 3161 return null; 3162 } 3163 3164 /** 3165 * @hide 3166 */ 3167 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3168 synchronized (mPackages) { 3169 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3170 if (lib != null && lib.apk != null) { 3171 return mPackages.get(lib.apk); 3172 } 3173 } 3174 return null; 3175 } 3176 3177 @Override 3178 public FeatureInfo[] getSystemAvailableFeatures() { 3179 Collection<FeatureInfo> featSet; 3180 synchronized (mPackages) { 3181 featSet = mAvailableFeatures.values(); 3182 int size = featSet.size(); 3183 if (size > 0) { 3184 FeatureInfo[] features = new FeatureInfo[size+1]; 3185 featSet.toArray(features); 3186 FeatureInfo fi = new FeatureInfo(); 3187 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3188 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3189 features[size] = fi; 3190 return features; 3191 } 3192 } 3193 return null; 3194 } 3195 3196 @Override 3197 public boolean hasSystemFeature(String name) { 3198 synchronized (mPackages) { 3199 return mAvailableFeatures.containsKey(name); 3200 } 3201 } 3202 3203 private void checkValidCaller(int uid, int userId) { 3204 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3205 return; 3206 3207 throw new SecurityException("Caller uid=" + uid 3208 + " is not privileged to communicate with user=" + userId); 3209 } 3210 3211 @Override 3212 public int checkPermission(String permName, String pkgName, int userId) { 3213 if (!sUserManager.exists(userId)) { 3214 return PackageManager.PERMISSION_DENIED; 3215 } 3216 3217 synchronized (mPackages) { 3218 final PackageParser.Package p = mPackages.get(pkgName); 3219 if (p != null && p.mExtras != null) { 3220 final PackageSetting ps = (PackageSetting) p.mExtras; 3221 final PermissionsState permissionsState = ps.getPermissionsState(); 3222 if (permissionsState.hasPermission(permName, userId)) { 3223 return PackageManager.PERMISSION_GRANTED; 3224 } 3225 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3226 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3227 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3228 return PackageManager.PERMISSION_GRANTED; 3229 } 3230 } 3231 } 3232 3233 return PackageManager.PERMISSION_DENIED; 3234 } 3235 3236 @Override 3237 public int checkUidPermission(String permName, int uid) { 3238 final int userId = UserHandle.getUserId(uid); 3239 3240 if (!sUserManager.exists(userId)) { 3241 return PackageManager.PERMISSION_DENIED; 3242 } 3243 3244 synchronized (mPackages) { 3245 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3246 if (obj != null) { 3247 final SettingBase ps = (SettingBase) obj; 3248 final PermissionsState permissionsState = ps.getPermissionsState(); 3249 if (permissionsState.hasPermission(permName, userId)) { 3250 return PackageManager.PERMISSION_GRANTED; 3251 } 3252 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3253 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3254 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3255 return PackageManager.PERMISSION_GRANTED; 3256 } 3257 } else { 3258 ArraySet<String> perms = mSystemPermissions.get(uid); 3259 if (perms != null) { 3260 if (perms.contains(permName)) { 3261 return PackageManager.PERMISSION_GRANTED; 3262 } 3263 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3264 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3265 return PackageManager.PERMISSION_GRANTED; 3266 } 3267 } 3268 } 3269 } 3270 3271 return PackageManager.PERMISSION_DENIED; 3272 } 3273 3274 @Override 3275 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3276 if (UserHandle.getCallingUserId() != userId) { 3277 mContext.enforceCallingPermission( 3278 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3279 "isPermissionRevokedByPolicy for user " + userId); 3280 } 3281 3282 if (checkPermission(permission, packageName, userId) 3283 == PackageManager.PERMISSION_GRANTED) { 3284 return false; 3285 } 3286 3287 final long identity = Binder.clearCallingIdentity(); 3288 try { 3289 final int flags = getPermissionFlags(permission, packageName, userId); 3290 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3291 } finally { 3292 Binder.restoreCallingIdentity(identity); 3293 } 3294 } 3295 3296 @Override 3297 public String getPermissionControllerPackageName() { 3298 synchronized (mPackages) { 3299 return mRequiredInstallerPackage; 3300 } 3301 } 3302 3303 /** 3304 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3305 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3306 * @param checkShell TODO(yamasani): 3307 * @param message the message to log on security exception 3308 */ 3309 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3310 boolean checkShell, String message) { 3311 if (userId < 0) { 3312 throw new IllegalArgumentException("Invalid userId " + userId); 3313 } 3314 if (checkShell) { 3315 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3316 } 3317 if (userId == UserHandle.getUserId(callingUid)) return; 3318 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3319 if (requireFullPermission) { 3320 mContext.enforceCallingOrSelfPermission( 3321 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3322 } else { 3323 try { 3324 mContext.enforceCallingOrSelfPermission( 3325 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3326 } catch (SecurityException se) { 3327 mContext.enforceCallingOrSelfPermission( 3328 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3329 } 3330 } 3331 } 3332 } 3333 3334 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3335 if (callingUid == Process.SHELL_UID) { 3336 if (userHandle >= 0 3337 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3338 throw new SecurityException("Shell does not have permission to access user " 3339 + userHandle); 3340 } else if (userHandle < 0) { 3341 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3342 + Debug.getCallers(3)); 3343 } 3344 } 3345 } 3346 3347 private BasePermission findPermissionTreeLP(String permName) { 3348 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3349 if (permName.startsWith(bp.name) && 3350 permName.length() > bp.name.length() && 3351 permName.charAt(bp.name.length()) == '.') { 3352 return bp; 3353 } 3354 } 3355 return null; 3356 } 3357 3358 private BasePermission checkPermissionTreeLP(String permName) { 3359 if (permName != null) { 3360 BasePermission bp = findPermissionTreeLP(permName); 3361 if (bp != null) { 3362 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3363 return bp; 3364 } 3365 throw new SecurityException("Calling uid " 3366 + Binder.getCallingUid() 3367 + " is not allowed to add to permission tree " 3368 + bp.name + " owned by uid " + bp.uid); 3369 } 3370 } 3371 throw new SecurityException("No permission tree found for " + permName); 3372 } 3373 3374 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3375 if (s1 == null) { 3376 return s2 == null; 3377 } 3378 if (s2 == null) { 3379 return false; 3380 } 3381 if (s1.getClass() != s2.getClass()) { 3382 return false; 3383 } 3384 return s1.equals(s2); 3385 } 3386 3387 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3388 if (pi1.icon != pi2.icon) return false; 3389 if (pi1.logo != pi2.logo) return false; 3390 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3391 if (!compareStrings(pi1.name, pi2.name)) return false; 3392 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3393 // We'll take care of setting this one. 3394 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3395 // These are not currently stored in settings. 3396 //if (!compareStrings(pi1.group, pi2.group)) return false; 3397 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3398 //if (pi1.labelRes != pi2.labelRes) return false; 3399 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3400 return true; 3401 } 3402 3403 int permissionInfoFootprint(PermissionInfo info) { 3404 int size = info.name.length(); 3405 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3406 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3407 return size; 3408 } 3409 3410 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3411 int size = 0; 3412 for (BasePermission perm : mSettings.mPermissions.values()) { 3413 if (perm.uid == tree.uid) { 3414 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3415 } 3416 } 3417 return size; 3418 } 3419 3420 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3421 // We calculate the max size of permissions defined by this uid and throw 3422 // if that plus the size of 'info' would exceed our stated maximum. 3423 if (tree.uid != Process.SYSTEM_UID) { 3424 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3425 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3426 throw new SecurityException("Permission tree size cap exceeded"); 3427 } 3428 } 3429 } 3430 3431 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3432 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3433 throw new SecurityException("Label must be specified in permission"); 3434 } 3435 BasePermission tree = checkPermissionTreeLP(info.name); 3436 BasePermission bp = mSettings.mPermissions.get(info.name); 3437 boolean added = bp == null; 3438 boolean changed = true; 3439 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3440 if (added) { 3441 enforcePermissionCapLocked(info, tree); 3442 bp = new BasePermission(info.name, tree.sourcePackage, 3443 BasePermission.TYPE_DYNAMIC); 3444 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3445 throw new SecurityException( 3446 "Not allowed to modify non-dynamic permission " 3447 + info.name); 3448 } else { 3449 if (bp.protectionLevel == fixedLevel 3450 && bp.perm.owner.equals(tree.perm.owner) 3451 && bp.uid == tree.uid 3452 && comparePermissionInfos(bp.perm.info, info)) { 3453 changed = false; 3454 } 3455 } 3456 bp.protectionLevel = fixedLevel; 3457 info = new PermissionInfo(info); 3458 info.protectionLevel = fixedLevel; 3459 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3460 bp.perm.info.packageName = tree.perm.info.packageName; 3461 bp.uid = tree.uid; 3462 if (added) { 3463 mSettings.mPermissions.put(info.name, bp); 3464 } 3465 if (changed) { 3466 if (!async) { 3467 mSettings.writeLPr(); 3468 } else { 3469 scheduleWriteSettingsLocked(); 3470 } 3471 } 3472 return added; 3473 } 3474 3475 @Override 3476 public boolean addPermission(PermissionInfo info) { 3477 synchronized (mPackages) { 3478 return addPermissionLocked(info, false); 3479 } 3480 } 3481 3482 @Override 3483 public boolean addPermissionAsync(PermissionInfo info) { 3484 synchronized (mPackages) { 3485 return addPermissionLocked(info, true); 3486 } 3487 } 3488 3489 @Override 3490 public void removePermission(String name) { 3491 synchronized (mPackages) { 3492 checkPermissionTreeLP(name); 3493 BasePermission bp = mSettings.mPermissions.get(name); 3494 if (bp != null) { 3495 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3496 throw new SecurityException( 3497 "Not allowed to modify non-dynamic permission " 3498 + name); 3499 } 3500 mSettings.mPermissions.remove(name); 3501 mSettings.writeLPr(); 3502 } 3503 } 3504 } 3505 3506 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3507 BasePermission bp) { 3508 int index = pkg.requestedPermissions.indexOf(bp.name); 3509 if (index == -1) { 3510 throw new SecurityException("Package " + pkg.packageName 3511 + " has not requested permission " + bp.name); 3512 } 3513 if (!bp.isRuntime() && !bp.isDevelopment()) { 3514 throw new SecurityException("Permission " + bp.name 3515 + " is not a changeable permission type"); 3516 } 3517 } 3518 3519 @Override 3520 public void grantRuntimePermission(String packageName, String name, final int userId) { 3521 if (!sUserManager.exists(userId)) { 3522 Log.e(TAG, "No such user:" + userId); 3523 return; 3524 } 3525 3526 mContext.enforceCallingOrSelfPermission( 3527 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3528 "grantRuntimePermission"); 3529 3530 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3531 "grantRuntimePermission"); 3532 3533 final int uid; 3534 final SettingBase sb; 3535 3536 synchronized (mPackages) { 3537 final PackageParser.Package pkg = mPackages.get(packageName); 3538 if (pkg == null) { 3539 throw new IllegalArgumentException("Unknown package: " + packageName); 3540 } 3541 3542 final BasePermission bp = mSettings.mPermissions.get(name); 3543 if (bp == null) { 3544 throw new IllegalArgumentException("Unknown permission: " + name); 3545 } 3546 3547 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3548 3549 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3550 sb = (SettingBase) pkg.mExtras; 3551 if (sb == null) { 3552 throw new IllegalArgumentException("Unknown package: " + packageName); 3553 } 3554 3555 final PermissionsState permissionsState = sb.getPermissionsState(); 3556 3557 final int flags = permissionsState.getPermissionFlags(name, userId); 3558 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3559 throw new SecurityException("Cannot grant system fixed permission: " 3560 + name + " for package: " + packageName); 3561 } 3562 3563 if (bp.isDevelopment()) { 3564 // Development permissions must be handled specially, since they are not 3565 // normal runtime permissions. For now they apply to all users. 3566 if (permissionsState.grantInstallPermission(bp) != 3567 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3568 scheduleWriteSettingsLocked(); 3569 } 3570 return; 3571 } 3572 3573 final int result = permissionsState.grantRuntimePermission(bp, userId); 3574 switch (result) { 3575 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3576 return; 3577 } 3578 3579 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3580 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3581 mHandler.post(new Runnable() { 3582 @Override 3583 public void run() { 3584 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3585 } 3586 }); 3587 } 3588 break; 3589 } 3590 3591 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3592 3593 // Not critical if that is lost - app has to request again. 3594 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3595 } 3596 3597 // Only need to do this if user is initialized. Otherwise it's a new user 3598 // and there are no processes running as the user yet and there's no need 3599 // to make an expensive call to remount processes for the changed permissions. 3600 if (READ_EXTERNAL_STORAGE.equals(name) 3601 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3602 final long token = Binder.clearCallingIdentity(); 3603 try { 3604 if (sUserManager.isInitialized(userId)) { 3605 MountServiceInternal mountServiceInternal = LocalServices.getService( 3606 MountServiceInternal.class); 3607 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3608 } 3609 } finally { 3610 Binder.restoreCallingIdentity(token); 3611 } 3612 } 3613 } 3614 3615 @Override 3616 public void revokeRuntimePermission(String packageName, String name, int userId) { 3617 if (!sUserManager.exists(userId)) { 3618 Log.e(TAG, "No such user:" + userId); 3619 return; 3620 } 3621 3622 mContext.enforceCallingOrSelfPermission( 3623 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3624 "revokeRuntimePermission"); 3625 3626 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3627 "revokeRuntimePermission"); 3628 3629 final int appId; 3630 3631 synchronized (mPackages) { 3632 final PackageParser.Package pkg = mPackages.get(packageName); 3633 if (pkg == null) { 3634 throw new IllegalArgumentException("Unknown package: " + packageName); 3635 } 3636 3637 final BasePermission bp = mSettings.mPermissions.get(name); 3638 if (bp == null) { 3639 throw new IllegalArgumentException("Unknown permission: " + name); 3640 } 3641 3642 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3643 3644 SettingBase sb = (SettingBase) pkg.mExtras; 3645 if (sb == null) { 3646 throw new IllegalArgumentException("Unknown package: " + packageName); 3647 } 3648 3649 final PermissionsState permissionsState = sb.getPermissionsState(); 3650 3651 final int flags = permissionsState.getPermissionFlags(name, userId); 3652 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3653 throw new SecurityException("Cannot revoke system fixed permission: " 3654 + name + " for package: " + packageName); 3655 } 3656 3657 if (bp.isDevelopment()) { 3658 // Development permissions must be handled specially, since they are not 3659 // normal runtime permissions. For now they apply to all users. 3660 if (permissionsState.revokeInstallPermission(bp) != 3661 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3662 scheduleWriteSettingsLocked(); 3663 } 3664 return; 3665 } 3666 3667 if (permissionsState.revokeRuntimePermission(bp, userId) == 3668 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3669 return; 3670 } 3671 3672 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3673 3674 // Critical, after this call app should never have the permission. 3675 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3676 3677 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3678 } 3679 3680 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3681 } 3682 3683 @Override 3684 public void resetRuntimePermissions() { 3685 mContext.enforceCallingOrSelfPermission( 3686 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3687 "revokeRuntimePermission"); 3688 3689 int callingUid = Binder.getCallingUid(); 3690 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3691 mContext.enforceCallingOrSelfPermission( 3692 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3693 "resetRuntimePermissions"); 3694 } 3695 3696 synchronized (mPackages) { 3697 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3698 for (int userId : UserManagerService.getInstance().getUserIds()) { 3699 final int packageCount = mPackages.size(); 3700 for (int i = 0; i < packageCount; i++) { 3701 PackageParser.Package pkg = mPackages.valueAt(i); 3702 if (!(pkg.mExtras instanceof PackageSetting)) { 3703 continue; 3704 } 3705 PackageSetting ps = (PackageSetting) pkg.mExtras; 3706 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3707 } 3708 } 3709 } 3710 } 3711 3712 @Override 3713 public int getPermissionFlags(String name, String packageName, int userId) { 3714 if (!sUserManager.exists(userId)) { 3715 return 0; 3716 } 3717 3718 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3719 3720 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3721 "getPermissionFlags"); 3722 3723 synchronized (mPackages) { 3724 final PackageParser.Package pkg = mPackages.get(packageName); 3725 if (pkg == null) { 3726 throw new IllegalArgumentException("Unknown package: " + packageName); 3727 } 3728 3729 final BasePermission bp = mSettings.mPermissions.get(name); 3730 if (bp == null) { 3731 throw new IllegalArgumentException("Unknown permission: " + name); 3732 } 3733 3734 SettingBase sb = (SettingBase) pkg.mExtras; 3735 if (sb == null) { 3736 throw new IllegalArgumentException("Unknown package: " + packageName); 3737 } 3738 3739 PermissionsState permissionsState = sb.getPermissionsState(); 3740 return permissionsState.getPermissionFlags(name, userId); 3741 } 3742 } 3743 3744 @Override 3745 public void updatePermissionFlags(String name, String packageName, int flagMask, 3746 int flagValues, int userId) { 3747 if (!sUserManager.exists(userId)) { 3748 return; 3749 } 3750 3751 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3752 3753 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3754 "updatePermissionFlags"); 3755 3756 // Only the system can change these flags and nothing else. 3757 if (getCallingUid() != Process.SYSTEM_UID) { 3758 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3759 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3760 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3761 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3762 } 3763 3764 synchronized (mPackages) { 3765 final PackageParser.Package pkg = mPackages.get(packageName); 3766 if (pkg == null) { 3767 throw new IllegalArgumentException("Unknown package: " + packageName); 3768 } 3769 3770 final BasePermission bp = mSettings.mPermissions.get(name); 3771 if (bp == null) { 3772 throw new IllegalArgumentException("Unknown permission: " + name); 3773 } 3774 3775 SettingBase sb = (SettingBase) pkg.mExtras; 3776 if (sb == null) { 3777 throw new IllegalArgumentException("Unknown package: " + packageName); 3778 } 3779 3780 PermissionsState permissionsState = sb.getPermissionsState(); 3781 3782 // Only the package manager can change flags for system component permissions. 3783 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3784 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3785 return; 3786 } 3787 3788 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3789 3790 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3791 // Install and runtime permissions are stored in different places, 3792 // so figure out what permission changed and persist the change. 3793 if (permissionsState.getInstallPermissionState(name) != null) { 3794 scheduleWriteSettingsLocked(); 3795 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3796 || hadState) { 3797 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3798 } 3799 } 3800 } 3801 } 3802 3803 /** 3804 * Update the permission flags for all packages and runtime permissions of a user in order 3805 * to allow device or profile owner to remove POLICY_FIXED. 3806 */ 3807 @Override 3808 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3809 if (!sUserManager.exists(userId)) { 3810 return; 3811 } 3812 3813 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3814 3815 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3816 "updatePermissionFlagsForAllApps"); 3817 3818 // Only the system can change system fixed flags. 3819 if (getCallingUid() != Process.SYSTEM_UID) { 3820 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3821 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3822 } 3823 3824 synchronized (mPackages) { 3825 boolean changed = false; 3826 final int packageCount = mPackages.size(); 3827 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3828 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3829 SettingBase sb = (SettingBase) pkg.mExtras; 3830 if (sb == null) { 3831 continue; 3832 } 3833 PermissionsState permissionsState = sb.getPermissionsState(); 3834 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3835 userId, flagMask, flagValues); 3836 } 3837 if (changed) { 3838 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3839 } 3840 } 3841 } 3842 3843 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3844 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3845 != PackageManager.PERMISSION_GRANTED 3846 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3847 != PackageManager.PERMISSION_GRANTED) { 3848 throw new SecurityException(message + " requires " 3849 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3850 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3851 } 3852 } 3853 3854 @Override 3855 public boolean shouldShowRequestPermissionRationale(String permissionName, 3856 String packageName, int userId) { 3857 if (UserHandle.getCallingUserId() != userId) { 3858 mContext.enforceCallingPermission( 3859 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3860 "canShowRequestPermissionRationale for user " + userId); 3861 } 3862 3863 final int uid = getPackageUid(packageName, userId); 3864 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3865 return false; 3866 } 3867 3868 if (checkPermission(permissionName, packageName, userId) 3869 == PackageManager.PERMISSION_GRANTED) { 3870 return false; 3871 } 3872 3873 final int flags; 3874 3875 final long identity = Binder.clearCallingIdentity(); 3876 try { 3877 flags = getPermissionFlags(permissionName, 3878 packageName, userId); 3879 } finally { 3880 Binder.restoreCallingIdentity(identity); 3881 } 3882 3883 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3884 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3885 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3886 3887 if ((flags & fixedFlags) != 0) { 3888 return false; 3889 } 3890 3891 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3892 } 3893 3894 @Override 3895 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3896 mContext.enforceCallingOrSelfPermission( 3897 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3898 "addOnPermissionsChangeListener"); 3899 3900 synchronized (mPackages) { 3901 mOnPermissionChangeListeners.addListenerLocked(listener); 3902 } 3903 } 3904 3905 @Override 3906 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3907 synchronized (mPackages) { 3908 mOnPermissionChangeListeners.removeListenerLocked(listener); 3909 } 3910 } 3911 3912 @Override 3913 public boolean isProtectedBroadcast(String actionName) { 3914 synchronized (mPackages) { 3915 return mProtectedBroadcasts.contains(actionName); 3916 } 3917 } 3918 3919 @Override 3920 public int checkSignatures(String pkg1, String pkg2) { 3921 synchronized (mPackages) { 3922 final PackageParser.Package p1 = mPackages.get(pkg1); 3923 final PackageParser.Package p2 = mPackages.get(pkg2); 3924 if (p1 == null || p1.mExtras == null 3925 || p2 == null || p2.mExtras == null) { 3926 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3927 } 3928 return compareSignatures(p1.mSignatures, p2.mSignatures); 3929 } 3930 } 3931 3932 @Override 3933 public int checkUidSignatures(int uid1, int uid2) { 3934 // Map to base uids. 3935 uid1 = UserHandle.getAppId(uid1); 3936 uid2 = UserHandle.getAppId(uid2); 3937 // reader 3938 synchronized (mPackages) { 3939 Signature[] s1; 3940 Signature[] s2; 3941 Object obj = mSettings.getUserIdLPr(uid1); 3942 if (obj != null) { 3943 if (obj instanceof SharedUserSetting) { 3944 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3945 } else if (obj instanceof PackageSetting) { 3946 s1 = ((PackageSetting)obj).signatures.mSignatures; 3947 } else { 3948 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3949 } 3950 } else { 3951 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3952 } 3953 obj = mSettings.getUserIdLPr(uid2); 3954 if (obj != null) { 3955 if (obj instanceof SharedUserSetting) { 3956 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3957 } else if (obj instanceof PackageSetting) { 3958 s2 = ((PackageSetting)obj).signatures.mSignatures; 3959 } else { 3960 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3961 } 3962 } else { 3963 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3964 } 3965 return compareSignatures(s1, s2); 3966 } 3967 } 3968 3969 private void killUid(int appId, int userId, String reason) { 3970 final long identity = Binder.clearCallingIdentity(); 3971 try { 3972 IActivityManager am = ActivityManagerNative.getDefault(); 3973 if (am != null) { 3974 try { 3975 am.killUid(appId, userId, reason); 3976 } catch (RemoteException e) { 3977 /* ignore - same process */ 3978 } 3979 } 3980 } finally { 3981 Binder.restoreCallingIdentity(identity); 3982 } 3983 } 3984 3985 /** 3986 * Compares two sets of signatures. Returns: 3987 * <br /> 3988 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3989 * <br /> 3990 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3991 * <br /> 3992 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3993 * <br /> 3994 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3995 * <br /> 3996 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3997 */ 3998 static int compareSignatures(Signature[] s1, Signature[] s2) { 3999 if (s1 == null) { 4000 return s2 == null 4001 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4002 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4003 } 4004 4005 if (s2 == null) { 4006 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4007 } 4008 4009 if (s1.length != s2.length) { 4010 return PackageManager.SIGNATURE_NO_MATCH; 4011 } 4012 4013 // Since both signature sets are of size 1, we can compare without HashSets. 4014 if (s1.length == 1) { 4015 return s1[0].equals(s2[0]) ? 4016 PackageManager.SIGNATURE_MATCH : 4017 PackageManager.SIGNATURE_NO_MATCH; 4018 } 4019 4020 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4021 for (Signature sig : s1) { 4022 set1.add(sig); 4023 } 4024 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4025 for (Signature sig : s2) { 4026 set2.add(sig); 4027 } 4028 // Make sure s2 contains all signatures in s1. 4029 if (set1.equals(set2)) { 4030 return PackageManager.SIGNATURE_MATCH; 4031 } 4032 return PackageManager.SIGNATURE_NO_MATCH; 4033 } 4034 4035 /** 4036 * If the database version for this type of package (internal storage or 4037 * external storage) is less than the version where package signatures 4038 * were updated, return true. 4039 */ 4040 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4041 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4042 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4043 } 4044 4045 /** 4046 * Used for backward compatibility to make sure any packages with 4047 * certificate chains get upgraded to the new style. {@code existingSigs} 4048 * will be in the old format (since they were stored on disk from before the 4049 * system upgrade) and {@code scannedSigs} will be in the newer format. 4050 */ 4051 private int compareSignaturesCompat(PackageSignatures existingSigs, 4052 PackageParser.Package scannedPkg) { 4053 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4054 return PackageManager.SIGNATURE_NO_MATCH; 4055 } 4056 4057 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4058 for (Signature sig : existingSigs.mSignatures) { 4059 existingSet.add(sig); 4060 } 4061 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4062 for (Signature sig : scannedPkg.mSignatures) { 4063 try { 4064 Signature[] chainSignatures = sig.getChainSignatures(); 4065 for (Signature chainSig : chainSignatures) { 4066 scannedCompatSet.add(chainSig); 4067 } 4068 } catch (CertificateEncodingException e) { 4069 scannedCompatSet.add(sig); 4070 } 4071 } 4072 /* 4073 * Make sure the expanded scanned set contains all signatures in the 4074 * existing one. 4075 */ 4076 if (scannedCompatSet.equals(existingSet)) { 4077 // Migrate the old signatures to the new scheme. 4078 existingSigs.assignSignatures(scannedPkg.mSignatures); 4079 // The new KeySets will be re-added later in the scanning process. 4080 synchronized (mPackages) { 4081 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4082 } 4083 return PackageManager.SIGNATURE_MATCH; 4084 } 4085 return PackageManager.SIGNATURE_NO_MATCH; 4086 } 4087 4088 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4089 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4090 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4091 } 4092 4093 private int compareSignaturesRecover(PackageSignatures existingSigs, 4094 PackageParser.Package scannedPkg) { 4095 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4096 return PackageManager.SIGNATURE_NO_MATCH; 4097 } 4098 4099 String msg = null; 4100 try { 4101 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4102 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4103 + scannedPkg.packageName); 4104 return PackageManager.SIGNATURE_MATCH; 4105 } 4106 } catch (CertificateException e) { 4107 msg = e.getMessage(); 4108 } 4109 4110 logCriticalInfo(Log.INFO, 4111 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4112 return PackageManager.SIGNATURE_NO_MATCH; 4113 } 4114 4115 @Override 4116 public String[] getPackagesForUid(int uid) { 4117 uid = UserHandle.getAppId(uid); 4118 // reader 4119 synchronized (mPackages) { 4120 Object obj = mSettings.getUserIdLPr(uid); 4121 if (obj instanceof SharedUserSetting) { 4122 final SharedUserSetting sus = (SharedUserSetting) obj; 4123 final int N = sus.packages.size(); 4124 final String[] res = new String[N]; 4125 final Iterator<PackageSetting> it = sus.packages.iterator(); 4126 int i = 0; 4127 while (it.hasNext()) { 4128 res[i++] = it.next().name; 4129 } 4130 return res; 4131 } else if (obj instanceof PackageSetting) { 4132 final PackageSetting ps = (PackageSetting) obj; 4133 return new String[] { ps.name }; 4134 } 4135 } 4136 return null; 4137 } 4138 4139 @Override 4140 public String getNameForUid(int uid) { 4141 // reader 4142 synchronized (mPackages) { 4143 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4144 if (obj instanceof SharedUserSetting) { 4145 final SharedUserSetting sus = (SharedUserSetting) obj; 4146 return sus.name + ":" + sus.userId; 4147 } else if (obj instanceof PackageSetting) { 4148 final PackageSetting ps = (PackageSetting) obj; 4149 return ps.name; 4150 } 4151 } 4152 return null; 4153 } 4154 4155 @Override 4156 public int getUidForSharedUser(String sharedUserName) { 4157 if(sharedUserName == null) { 4158 return -1; 4159 } 4160 // reader 4161 synchronized (mPackages) { 4162 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4163 if (suid == null) { 4164 return -1; 4165 } 4166 return suid.userId; 4167 } 4168 } 4169 4170 @Override 4171 public int getFlagsForUid(int uid) { 4172 synchronized (mPackages) { 4173 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4174 if (obj instanceof SharedUserSetting) { 4175 final SharedUserSetting sus = (SharedUserSetting) obj; 4176 return sus.pkgFlags; 4177 } else if (obj instanceof PackageSetting) { 4178 final PackageSetting ps = (PackageSetting) obj; 4179 return ps.pkgFlags; 4180 } 4181 } 4182 return 0; 4183 } 4184 4185 @Override 4186 public int getPrivateFlagsForUid(int uid) { 4187 synchronized (mPackages) { 4188 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4189 if (obj instanceof SharedUserSetting) { 4190 final SharedUserSetting sus = (SharedUserSetting) obj; 4191 return sus.pkgPrivateFlags; 4192 } else if (obj instanceof PackageSetting) { 4193 final PackageSetting ps = (PackageSetting) obj; 4194 return ps.pkgPrivateFlags; 4195 } 4196 } 4197 return 0; 4198 } 4199 4200 @Override 4201 public boolean isUidPrivileged(int uid) { 4202 uid = UserHandle.getAppId(uid); 4203 // reader 4204 synchronized (mPackages) { 4205 Object obj = mSettings.getUserIdLPr(uid); 4206 if (obj instanceof SharedUserSetting) { 4207 final SharedUserSetting sus = (SharedUserSetting) obj; 4208 final Iterator<PackageSetting> it = sus.packages.iterator(); 4209 while (it.hasNext()) { 4210 if (it.next().isPrivileged()) { 4211 return true; 4212 } 4213 } 4214 } else if (obj instanceof PackageSetting) { 4215 final PackageSetting ps = (PackageSetting) obj; 4216 return ps.isPrivileged(); 4217 } 4218 } 4219 return false; 4220 } 4221 4222 @Override 4223 public String[] getAppOpPermissionPackages(String permissionName) { 4224 synchronized (mPackages) { 4225 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4226 if (pkgs == null) { 4227 return null; 4228 } 4229 return pkgs.toArray(new String[pkgs.size()]); 4230 } 4231 } 4232 4233 @Override 4234 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4235 int flags, int userId) { 4236 if (!sUserManager.exists(userId)) return null; 4237 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4238 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4239 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4240 } 4241 4242 @Override 4243 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4244 IntentFilter filter, int match, ComponentName activity) { 4245 final int userId = UserHandle.getCallingUserId(); 4246 if (DEBUG_PREFERRED) { 4247 Log.v(TAG, "setLastChosenActivity intent=" + intent 4248 + " resolvedType=" + resolvedType 4249 + " flags=" + flags 4250 + " filter=" + filter 4251 + " match=" + match 4252 + " activity=" + activity); 4253 filter.dump(new PrintStreamPrinter(System.out), " "); 4254 } 4255 intent.setComponent(null); 4256 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4257 // Find any earlier preferred or last chosen entries and nuke them 4258 findPreferredActivity(intent, resolvedType, 4259 flags, query, 0, false, true, false, userId); 4260 // Add the new activity as the last chosen for this filter 4261 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4262 "Setting last chosen"); 4263 } 4264 4265 @Override 4266 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4267 final int userId = UserHandle.getCallingUserId(); 4268 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4269 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4270 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4271 false, false, false, userId); 4272 } 4273 4274 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4275 int flags, List<ResolveInfo> query, int userId) { 4276 if (query != null) { 4277 final int N = query.size(); 4278 if (N == 1) { 4279 return query.get(0); 4280 } else if (N > 1) { 4281 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4282 // If there is more than one activity with the same priority, 4283 // then let the user decide between them. 4284 ResolveInfo r0 = query.get(0); 4285 ResolveInfo r1 = query.get(1); 4286 if (DEBUG_INTENT_MATCHING || debug) { 4287 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4288 + r1.activityInfo.name + "=" + r1.priority); 4289 } 4290 // If the first activity has a higher priority, or a different 4291 // default, then it is always desireable to pick it. 4292 if (r0.priority != r1.priority 4293 || r0.preferredOrder != r1.preferredOrder 4294 || r0.isDefault != r1.isDefault) { 4295 return query.get(0); 4296 } 4297 // If we have saved a preference for a preferred activity for 4298 // this Intent, use that. 4299 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4300 flags, query, r0.priority, true, false, debug, userId); 4301 if (ri != null) { 4302 return ri; 4303 } 4304 ri = new ResolveInfo(mResolveInfo); 4305 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4306 ri.activityInfo.applicationInfo = new ApplicationInfo( 4307 ri.activityInfo.applicationInfo); 4308 if (userId != 0) { 4309 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4310 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4311 } 4312 // Make sure that the resolver is displayable in car mode 4313 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4314 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4315 return ri; 4316 } 4317 } 4318 return null; 4319 } 4320 4321 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4322 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4323 final int N = query.size(); 4324 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4325 .get(userId); 4326 // Get the list of persistent preferred activities that handle the intent 4327 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4328 List<PersistentPreferredActivity> pprefs = ppir != null 4329 ? ppir.queryIntent(intent, resolvedType, 4330 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4331 : null; 4332 if (pprefs != null && pprefs.size() > 0) { 4333 final int M = pprefs.size(); 4334 for (int i=0; i<M; i++) { 4335 final PersistentPreferredActivity ppa = pprefs.get(i); 4336 if (DEBUG_PREFERRED || debug) { 4337 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4338 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4339 + "\n component=" + ppa.mComponent); 4340 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4341 } 4342 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4343 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4344 if (DEBUG_PREFERRED || debug) { 4345 Slog.v(TAG, "Found persistent preferred activity:"); 4346 if (ai != null) { 4347 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4348 } else { 4349 Slog.v(TAG, " null"); 4350 } 4351 } 4352 if (ai == null) { 4353 // This previously registered persistent preferred activity 4354 // component is no longer known. Ignore it and do NOT remove it. 4355 continue; 4356 } 4357 for (int j=0; j<N; j++) { 4358 final ResolveInfo ri = query.get(j); 4359 if (!ri.activityInfo.applicationInfo.packageName 4360 .equals(ai.applicationInfo.packageName)) { 4361 continue; 4362 } 4363 if (!ri.activityInfo.name.equals(ai.name)) { 4364 continue; 4365 } 4366 // Found a persistent preference that can handle the intent. 4367 if (DEBUG_PREFERRED || debug) { 4368 Slog.v(TAG, "Returning persistent preferred activity: " + 4369 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4370 } 4371 return ri; 4372 } 4373 } 4374 } 4375 return null; 4376 } 4377 4378 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4379 List<ResolveInfo> query, int priority, boolean always, 4380 boolean removeMatches, boolean debug, int userId) { 4381 if (!sUserManager.exists(userId)) return null; 4382 // writer 4383 synchronized (mPackages) { 4384 if (intent.getSelector() != null) { 4385 intent = intent.getSelector(); 4386 } 4387 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4388 4389 // Try to find a matching persistent preferred activity. 4390 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4391 debug, userId); 4392 4393 // If a persistent preferred activity matched, use it. 4394 if (pri != null) { 4395 return pri; 4396 } 4397 4398 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4399 // Get the list of preferred activities that handle the intent 4400 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4401 List<PreferredActivity> prefs = pir != null 4402 ? pir.queryIntent(intent, resolvedType, 4403 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4404 : null; 4405 if (prefs != null && prefs.size() > 0) { 4406 boolean changed = false; 4407 try { 4408 // First figure out how good the original match set is. 4409 // We will only allow preferred activities that came 4410 // from the same match quality. 4411 int match = 0; 4412 4413 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4414 4415 final int N = query.size(); 4416 for (int j=0; j<N; j++) { 4417 final ResolveInfo ri = query.get(j); 4418 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4419 + ": 0x" + Integer.toHexString(match)); 4420 if (ri.match > match) { 4421 match = ri.match; 4422 } 4423 } 4424 4425 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4426 + Integer.toHexString(match)); 4427 4428 match &= IntentFilter.MATCH_CATEGORY_MASK; 4429 final int M = prefs.size(); 4430 for (int i=0; i<M; i++) { 4431 final PreferredActivity pa = prefs.get(i); 4432 if (DEBUG_PREFERRED || debug) { 4433 Slog.v(TAG, "Checking PreferredActivity ds=" 4434 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4435 + "\n component=" + pa.mPref.mComponent); 4436 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4437 } 4438 if (pa.mPref.mMatch != match) { 4439 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4440 + Integer.toHexString(pa.mPref.mMatch)); 4441 continue; 4442 } 4443 // If it's not an "always" type preferred activity and that's what we're 4444 // looking for, skip it. 4445 if (always && !pa.mPref.mAlways) { 4446 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4447 continue; 4448 } 4449 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4450 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4451 if (DEBUG_PREFERRED || debug) { 4452 Slog.v(TAG, "Found preferred activity:"); 4453 if (ai != null) { 4454 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4455 } else { 4456 Slog.v(TAG, " null"); 4457 } 4458 } 4459 if (ai == null) { 4460 // This previously registered preferred activity 4461 // component is no longer known. Most likely an update 4462 // to the app was installed and in the new version this 4463 // component no longer exists. Clean it up by removing 4464 // it from the preferred activities list, and skip it. 4465 Slog.w(TAG, "Removing dangling preferred activity: " 4466 + pa.mPref.mComponent); 4467 pir.removeFilter(pa); 4468 changed = true; 4469 continue; 4470 } 4471 for (int j=0; j<N; j++) { 4472 final ResolveInfo ri = query.get(j); 4473 if (!ri.activityInfo.applicationInfo.packageName 4474 .equals(ai.applicationInfo.packageName)) { 4475 continue; 4476 } 4477 if (!ri.activityInfo.name.equals(ai.name)) { 4478 continue; 4479 } 4480 4481 if (removeMatches) { 4482 pir.removeFilter(pa); 4483 changed = true; 4484 if (DEBUG_PREFERRED) { 4485 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4486 } 4487 break; 4488 } 4489 4490 // Okay we found a previously set preferred or last chosen app. 4491 // If the result set is different from when this 4492 // was created, we need to clear it and re-ask the 4493 // user their preference, if we're looking for an "always" type entry. 4494 if (always && !pa.mPref.sameSet(query)) { 4495 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4496 + intent + " type " + resolvedType); 4497 if (DEBUG_PREFERRED) { 4498 Slog.v(TAG, "Removing preferred activity since set changed " 4499 + pa.mPref.mComponent); 4500 } 4501 pir.removeFilter(pa); 4502 // Re-add the filter as a "last chosen" entry (!always) 4503 PreferredActivity lastChosen = new PreferredActivity( 4504 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4505 pir.addFilter(lastChosen); 4506 changed = true; 4507 return null; 4508 } 4509 4510 // Yay! Either the set matched or we're looking for the last chosen 4511 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4512 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4513 return ri; 4514 } 4515 } 4516 } finally { 4517 if (changed) { 4518 if (DEBUG_PREFERRED) { 4519 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4520 } 4521 scheduleWritePackageRestrictionsLocked(userId); 4522 } 4523 } 4524 } 4525 } 4526 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4527 return null; 4528 } 4529 4530 /* 4531 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4532 */ 4533 @Override 4534 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4535 int targetUserId) { 4536 mContext.enforceCallingOrSelfPermission( 4537 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4538 List<CrossProfileIntentFilter> matches = 4539 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4540 if (matches != null) { 4541 int size = matches.size(); 4542 for (int i = 0; i < size; i++) { 4543 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4544 } 4545 } 4546 if (hasWebURI(intent)) { 4547 // cross-profile app linking works only towards the parent. 4548 final UserInfo parent = getProfileParent(sourceUserId); 4549 synchronized(mPackages) { 4550 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4551 intent, resolvedType, 0, sourceUserId, parent.id); 4552 return xpDomainInfo != null; 4553 } 4554 } 4555 return false; 4556 } 4557 4558 private UserInfo getProfileParent(int userId) { 4559 final long identity = Binder.clearCallingIdentity(); 4560 try { 4561 return sUserManager.getProfileParent(userId); 4562 } finally { 4563 Binder.restoreCallingIdentity(identity); 4564 } 4565 } 4566 4567 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4568 String resolvedType, int userId) { 4569 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4570 if (resolver != null) { 4571 return resolver.queryIntent(intent, resolvedType, false, userId); 4572 } 4573 return null; 4574 } 4575 4576 @Override 4577 public List<ResolveInfo> queryIntentActivities(Intent intent, 4578 String resolvedType, int flags, int userId) { 4579 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4580 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4581 ComponentName comp = intent.getComponent(); 4582 if (comp == null) { 4583 if (intent.getSelector() != null) { 4584 intent = intent.getSelector(); 4585 comp = intent.getComponent(); 4586 } 4587 } 4588 4589 if (comp != null) { 4590 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4591 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4592 if (ai != null) { 4593 final ResolveInfo ri = new ResolveInfo(); 4594 ri.activityInfo = ai; 4595 list.add(ri); 4596 } 4597 return list; 4598 } 4599 4600 // reader 4601 synchronized (mPackages) { 4602 final String pkgName = intent.getPackage(); 4603 if (pkgName == null) { 4604 List<CrossProfileIntentFilter> matchingFilters = 4605 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4606 // Check for results that need to skip the current profile. 4607 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4608 resolvedType, flags, userId); 4609 if (xpResolveInfo != null) { 4610 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4611 result.add(xpResolveInfo); 4612 return filterIfNotSystemUser(result, userId); 4613 } 4614 4615 // Check for results in the current profile. 4616 List<ResolveInfo> result = mActivities.queryIntent( 4617 intent, resolvedType, flags, userId); 4618 4619 // Check for cross profile results. 4620 xpResolveInfo = queryCrossProfileIntents( 4621 matchingFilters, intent, resolvedType, flags, userId); 4622 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4623 result.add(xpResolveInfo); 4624 Collections.sort(result, mResolvePrioritySorter); 4625 } 4626 result = filterIfNotSystemUser(result, userId); 4627 if (hasWebURI(intent)) { 4628 CrossProfileDomainInfo xpDomainInfo = null; 4629 final UserInfo parent = getProfileParent(userId); 4630 if (parent != null) { 4631 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4632 flags, userId, parent.id); 4633 } 4634 if (xpDomainInfo != null) { 4635 if (xpResolveInfo != null) { 4636 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4637 // in the result. 4638 result.remove(xpResolveInfo); 4639 } 4640 if (result.size() == 0) { 4641 result.add(xpDomainInfo.resolveInfo); 4642 return result; 4643 } 4644 } else if (result.size() <= 1) { 4645 return result; 4646 } 4647 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4648 xpDomainInfo, userId); 4649 Collections.sort(result, mResolvePrioritySorter); 4650 } 4651 return result; 4652 } 4653 final PackageParser.Package pkg = mPackages.get(pkgName); 4654 if (pkg != null) { 4655 return filterIfNotSystemUser( 4656 mActivities.queryIntentForPackage( 4657 intent, resolvedType, flags, pkg.activities, userId), 4658 userId); 4659 } 4660 return new ArrayList<ResolveInfo>(); 4661 } 4662 } 4663 4664 private static class CrossProfileDomainInfo { 4665 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4666 ResolveInfo resolveInfo; 4667 /* Best domain verification status of the activities found in the other profile */ 4668 int bestDomainVerificationStatus; 4669 } 4670 4671 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4672 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4673 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4674 sourceUserId)) { 4675 return null; 4676 } 4677 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4678 resolvedType, flags, parentUserId); 4679 4680 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4681 return null; 4682 } 4683 CrossProfileDomainInfo result = null; 4684 int size = resultTargetUser.size(); 4685 for (int i = 0; i < size; i++) { 4686 ResolveInfo riTargetUser = resultTargetUser.get(i); 4687 // Intent filter verification is only for filters that specify a host. So don't return 4688 // those that handle all web uris. 4689 if (riTargetUser.handleAllWebDataURI) { 4690 continue; 4691 } 4692 String packageName = riTargetUser.activityInfo.packageName; 4693 PackageSetting ps = mSettings.mPackages.get(packageName); 4694 if (ps == null) { 4695 continue; 4696 } 4697 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4698 int status = (int)(verificationState >> 32); 4699 if (result == null) { 4700 result = new CrossProfileDomainInfo(); 4701 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4702 sourceUserId, parentUserId); 4703 result.bestDomainVerificationStatus = status; 4704 } else { 4705 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4706 result.bestDomainVerificationStatus); 4707 } 4708 } 4709 // Don't consider matches with status NEVER across profiles. 4710 if (result != null && result.bestDomainVerificationStatus 4711 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4712 return null; 4713 } 4714 return result; 4715 } 4716 4717 /** 4718 * Verification statuses are ordered from the worse to the best, except for 4719 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4720 */ 4721 private int bestDomainVerificationStatus(int status1, int status2) { 4722 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4723 return status2; 4724 } 4725 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4726 return status1; 4727 } 4728 return (int) MathUtils.max(status1, status2); 4729 } 4730 4731 private boolean isUserEnabled(int userId) { 4732 long callingId = Binder.clearCallingIdentity(); 4733 try { 4734 UserInfo userInfo = sUserManager.getUserInfo(userId); 4735 return userInfo != null && userInfo.isEnabled(); 4736 } finally { 4737 Binder.restoreCallingIdentity(callingId); 4738 } 4739 } 4740 4741 /** 4742 * Filter out activities with systemUserOnly flag set, when current user is not System. 4743 * 4744 * @return filtered list 4745 */ 4746 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4747 if (userId == UserHandle.USER_SYSTEM) { 4748 return resolveInfos; 4749 } 4750 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4751 ResolveInfo info = resolveInfos.get(i); 4752 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4753 resolveInfos.remove(i); 4754 } 4755 } 4756 return resolveInfos; 4757 } 4758 4759 private static boolean hasWebURI(Intent intent) { 4760 if (intent.getData() == null) { 4761 return false; 4762 } 4763 final String scheme = intent.getScheme(); 4764 if (TextUtils.isEmpty(scheme)) { 4765 return false; 4766 } 4767 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4768 } 4769 4770 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4771 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4772 int userId) { 4773 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4774 4775 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4776 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4777 candidates.size()); 4778 } 4779 4780 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4781 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4782 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4783 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4784 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4785 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4786 4787 synchronized (mPackages) { 4788 final int count = candidates.size(); 4789 // First, try to use linked apps. Partition the candidates into four lists: 4790 // one for the final results, one for the "do not use ever", one for "undefined status" 4791 // and finally one for "browser app type". 4792 for (int n=0; n<count; n++) { 4793 ResolveInfo info = candidates.get(n); 4794 String packageName = info.activityInfo.packageName; 4795 PackageSetting ps = mSettings.mPackages.get(packageName); 4796 if (ps != null) { 4797 // Add to the special match all list (Browser use case) 4798 if (info.handleAllWebDataURI) { 4799 matchAllList.add(info); 4800 continue; 4801 } 4802 // Try to get the status from User settings first 4803 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4804 int status = (int)(packedStatus >> 32); 4805 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4806 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4807 if (DEBUG_DOMAIN_VERIFICATION) { 4808 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4809 + " : linkgen=" + linkGeneration); 4810 } 4811 // Use link-enabled generation as preferredOrder, i.e. 4812 // prefer newly-enabled over earlier-enabled. 4813 info.preferredOrder = linkGeneration; 4814 alwaysList.add(info); 4815 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4816 if (DEBUG_DOMAIN_VERIFICATION) { 4817 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4818 } 4819 neverList.add(info); 4820 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4821 if (DEBUG_DOMAIN_VERIFICATION) { 4822 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4823 } 4824 alwaysAskList.add(info); 4825 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4826 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4827 if (DEBUG_DOMAIN_VERIFICATION) { 4828 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4829 } 4830 undefinedList.add(info); 4831 } 4832 } 4833 } 4834 4835 // We'll want to include browser possibilities in a few cases 4836 boolean includeBrowser = false; 4837 4838 // First try to add the "always" resolution(s) for the current user, if any 4839 if (alwaysList.size() > 0) { 4840 result.addAll(alwaysList); 4841 } else { 4842 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4843 result.addAll(undefinedList); 4844 // Maybe add one for the other profile. 4845 if (xpDomainInfo != null && ( 4846 xpDomainInfo.bestDomainVerificationStatus 4847 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4848 result.add(xpDomainInfo.resolveInfo); 4849 } 4850 includeBrowser = true; 4851 } 4852 4853 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4854 // If there were 'always' entries their preferred order has been set, so we also 4855 // back that off to make the alternatives equivalent 4856 if (alwaysAskList.size() > 0) { 4857 for (ResolveInfo i : result) { 4858 i.preferredOrder = 0; 4859 } 4860 result.addAll(alwaysAskList); 4861 includeBrowser = true; 4862 } 4863 4864 if (includeBrowser) { 4865 // Also add browsers (all of them or only the default one) 4866 if (DEBUG_DOMAIN_VERIFICATION) { 4867 Slog.v(TAG, " ...including browsers in candidate set"); 4868 } 4869 if ((matchFlags & MATCH_ALL) != 0) { 4870 result.addAll(matchAllList); 4871 } else { 4872 // Browser/generic handling case. If there's a default browser, go straight 4873 // to that (but only if there is no other higher-priority match). 4874 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4875 int maxMatchPrio = 0; 4876 ResolveInfo defaultBrowserMatch = null; 4877 final int numCandidates = matchAllList.size(); 4878 for (int n = 0; n < numCandidates; n++) { 4879 ResolveInfo info = matchAllList.get(n); 4880 // track the highest overall match priority... 4881 if (info.priority > maxMatchPrio) { 4882 maxMatchPrio = info.priority; 4883 } 4884 // ...and the highest-priority default browser match 4885 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4886 if (defaultBrowserMatch == null 4887 || (defaultBrowserMatch.priority < info.priority)) { 4888 if (debug) { 4889 Slog.v(TAG, "Considering default browser match " + info); 4890 } 4891 defaultBrowserMatch = info; 4892 } 4893 } 4894 } 4895 if (defaultBrowserMatch != null 4896 && defaultBrowserMatch.priority >= maxMatchPrio 4897 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4898 { 4899 if (debug) { 4900 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4901 } 4902 result.add(defaultBrowserMatch); 4903 } else { 4904 result.addAll(matchAllList); 4905 } 4906 } 4907 4908 // If there is nothing selected, add all candidates and remove the ones that the user 4909 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4910 if (result.size() == 0) { 4911 result.addAll(candidates); 4912 result.removeAll(neverList); 4913 } 4914 } 4915 } 4916 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4917 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4918 result.size()); 4919 for (ResolveInfo info : result) { 4920 Slog.v(TAG, " + " + info.activityInfo); 4921 } 4922 } 4923 return result; 4924 } 4925 4926 // Returns a packed value as a long: 4927 // 4928 // high 'int'-sized word: link status: undefined/ask/never/always. 4929 // low 'int'-sized word: relative priority among 'always' results. 4930 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4931 long result = ps.getDomainVerificationStatusForUser(userId); 4932 // if none available, get the master status 4933 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4934 if (ps.getIntentFilterVerificationInfo() != null) { 4935 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4936 } 4937 } 4938 return result; 4939 } 4940 4941 private ResolveInfo querySkipCurrentProfileIntents( 4942 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4943 int flags, int sourceUserId) { 4944 if (matchingFilters != null) { 4945 int size = matchingFilters.size(); 4946 for (int i = 0; i < size; i ++) { 4947 CrossProfileIntentFilter filter = matchingFilters.get(i); 4948 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4949 // Checking if there are activities in the target user that can handle the 4950 // intent. 4951 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4952 resolvedType, flags, sourceUserId); 4953 if (resolveInfo != null) { 4954 return resolveInfo; 4955 } 4956 } 4957 } 4958 } 4959 return null; 4960 } 4961 4962 // Return matching ResolveInfo if any for skip current profile intent filters. 4963 private ResolveInfo queryCrossProfileIntents( 4964 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4965 int flags, int sourceUserId) { 4966 if (matchingFilters != null) { 4967 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4968 // match the same intent. For performance reasons, it is better not to 4969 // run queryIntent twice for the same userId 4970 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4971 int size = matchingFilters.size(); 4972 for (int i = 0; i < size; i++) { 4973 CrossProfileIntentFilter filter = matchingFilters.get(i); 4974 int targetUserId = filter.getTargetUserId(); 4975 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4976 && !alreadyTriedUserIds.get(targetUserId)) { 4977 // Checking if there are activities in the target user that can handle the 4978 // intent. 4979 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4980 resolvedType, flags, sourceUserId); 4981 if (resolveInfo != null) return resolveInfo; 4982 alreadyTriedUserIds.put(targetUserId, true); 4983 } 4984 } 4985 } 4986 return null; 4987 } 4988 4989 /** 4990 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4991 * will forward the intent to the filter's target user. 4992 * Otherwise, returns null. 4993 */ 4994 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4995 String resolvedType, int flags, int sourceUserId) { 4996 int targetUserId = filter.getTargetUserId(); 4997 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4998 resolvedType, flags, targetUserId); 4999 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5000 && isUserEnabled(targetUserId)) { 5001 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5002 } 5003 return null; 5004 } 5005 5006 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5007 int sourceUserId, int targetUserId) { 5008 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5009 long ident = Binder.clearCallingIdentity(); 5010 boolean targetIsProfile; 5011 try { 5012 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5013 } finally { 5014 Binder.restoreCallingIdentity(ident); 5015 } 5016 String className; 5017 if (targetIsProfile) { 5018 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5019 } else { 5020 className = FORWARD_INTENT_TO_PARENT; 5021 } 5022 ComponentName forwardingActivityComponentName = new ComponentName( 5023 mAndroidApplication.packageName, className); 5024 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5025 sourceUserId); 5026 if (!targetIsProfile) { 5027 forwardingActivityInfo.showUserIcon = targetUserId; 5028 forwardingResolveInfo.noResourceId = true; 5029 } 5030 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5031 forwardingResolveInfo.priority = 0; 5032 forwardingResolveInfo.preferredOrder = 0; 5033 forwardingResolveInfo.match = 0; 5034 forwardingResolveInfo.isDefault = true; 5035 forwardingResolveInfo.filter = filter; 5036 forwardingResolveInfo.targetUserId = targetUserId; 5037 return forwardingResolveInfo; 5038 } 5039 5040 @Override 5041 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5042 Intent[] specifics, String[] specificTypes, Intent intent, 5043 String resolvedType, int flags, int userId) { 5044 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5045 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5046 false, "query intent activity options"); 5047 final String resultsAction = intent.getAction(); 5048 5049 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5050 | PackageManager.GET_RESOLVED_FILTER, userId); 5051 5052 if (DEBUG_INTENT_MATCHING) { 5053 Log.v(TAG, "Query " + intent + ": " + results); 5054 } 5055 5056 int specificsPos = 0; 5057 int N; 5058 5059 // todo: note that the algorithm used here is O(N^2). This 5060 // isn't a problem in our current environment, but if we start running 5061 // into situations where we have more than 5 or 10 matches then this 5062 // should probably be changed to something smarter... 5063 5064 // First we go through and resolve each of the specific items 5065 // that were supplied, taking care of removing any corresponding 5066 // duplicate items in the generic resolve list. 5067 if (specifics != null) { 5068 for (int i=0; i<specifics.length; i++) { 5069 final Intent sintent = specifics[i]; 5070 if (sintent == null) { 5071 continue; 5072 } 5073 5074 if (DEBUG_INTENT_MATCHING) { 5075 Log.v(TAG, "Specific #" + i + ": " + sintent); 5076 } 5077 5078 String action = sintent.getAction(); 5079 if (resultsAction != null && resultsAction.equals(action)) { 5080 // If this action was explicitly requested, then don't 5081 // remove things that have it. 5082 action = null; 5083 } 5084 5085 ResolveInfo ri = null; 5086 ActivityInfo ai = null; 5087 5088 ComponentName comp = sintent.getComponent(); 5089 if (comp == null) { 5090 ri = resolveIntent( 5091 sintent, 5092 specificTypes != null ? specificTypes[i] : null, 5093 flags, userId); 5094 if (ri == null) { 5095 continue; 5096 } 5097 if (ri == mResolveInfo) { 5098 // ACK! Must do something better with this. 5099 } 5100 ai = ri.activityInfo; 5101 comp = new ComponentName(ai.applicationInfo.packageName, 5102 ai.name); 5103 } else { 5104 ai = getActivityInfo(comp, flags, userId); 5105 if (ai == null) { 5106 continue; 5107 } 5108 } 5109 5110 // Look for any generic query activities that are duplicates 5111 // of this specific one, and remove them from the results. 5112 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5113 N = results.size(); 5114 int j; 5115 for (j=specificsPos; j<N; j++) { 5116 ResolveInfo sri = results.get(j); 5117 if ((sri.activityInfo.name.equals(comp.getClassName()) 5118 && sri.activityInfo.applicationInfo.packageName.equals( 5119 comp.getPackageName())) 5120 || (action != null && sri.filter.matchAction(action))) { 5121 results.remove(j); 5122 if (DEBUG_INTENT_MATCHING) Log.v( 5123 TAG, "Removing duplicate item from " + j 5124 + " due to specific " + specificsPos); 5125 if (ri == null) { 5126 ri = sri; 5127 } 5128 j--; 5129 N--; 5130 } 5131 } 5132 5133 // Add this specific item to its proper place. 5134 if (ri == null) { 5135 ri = new ResolveInfo(); 5136 ri.activityInfo = ai; 5137 } 5138 results.add(specificsPos, ri); 5139 ri.specificIndex = i; 5140 specificsPos++; 5141 } 5142 } 5143 5144 // Now we go through the remaining generic results and remove any 5145 // duplicate actions that are found here. 5146 N = results.size(); 5147 for (int i=specificsPos; i<N-1; i++) { 5148 final ResolveInfo rii = results.get(i); 5149 if (rii.filter == null) { 5150 continue; 5151 } 5152 5153 // Iterate over all of the actions of this result's intent 5154 // filter... typically this should be just one. 5155 final Iterator<String> it = rii.filter.actionsIterator(); 5156 if (it == null) { 5157 continue; 5158 } 5159 while (it.hasNext()) { 5160 final String action = it.next(); 5161 if (resultsAction != null && resultsAction.equals(action)) { 5162 // If this action was explicitly requested, then don't 5163 // remove things that have it. 5164 continue; 5165 } 5166 for (int j=i+1; j<N; j++) { 5167 final ResolveInfo rij = results.get(j); 5168 if (rij.filter != null && rij.filter.hasAction(action)) { 5169 results.remove(j); 5170 if (DEBUG_INTENT_MATCHING) Log.v( 5171 TAG, "Removing duplicate item from " + j 5172 + " due to action " + action + " at " + i); 5173 j--; 5174 N--; 5175 } 5176 } 5177 } 5178 5179 // If the caller didn't request filter information, drop it now 5180 // so we don't have to marshall/unmarshall it. 5181 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5182 rii.filter = null; 5183 } 5184 } 5185 5186 // Filter out the caller activity if so requested. 5187 if (caller != null) { 5188 N = results.size(); 5189 for (int i=0; i<N; i++) { 5190 ActivityInfo ainfo = results.get(i).activityInfo; 5191 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5192 && caller.getClassName().equals(ainfo.name)) { 5193 results.remove(i); 5194 break; 5195 } 5196 } 5197 } 5198 5199 // If the caller didn't request filter information, 5200 // drop them now so we don't have to 5201 // marshall/unmarshall it. 5202 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5203 N = results.size(); 5204 for (int i=0; i<N; i++) { 5205 results.get(i).filter = null; 5206 } 5207 } 5208 5209 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5210 return results; 5211 } 5212 5213 @Override 5214 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5215 int userId) { 5216 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5217 ComponentName comp = intent.getComponent(); 5218 if (comp == null) { 5219 if (intent.getSelector() != null) { 5220 intent = intent.getSelector(); 5221 comp = intent.getComponent(); 5222 } 5223 } 5224 if (comp != null) { 5225 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5226 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5227 if (ai != null) { 5228 ResolveInfo ri = new ResolveInfo(); 5229 ri.activityInfo = ai; 5230 list.add(ri); 5231 } 5232 return list; 5233 } 5234 5235 // reader 5236 synchronized (mPackages) { 5237 String pkgName = intent.getPackage(); 5238 if (pkgName == null) { 5239 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5240 } 5241 final PackageParser.Package pkg = mPackages.get(pkgName); 5242 if (pkg != null) { 5243 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5244 userId); 5245 } 5246 return null; 5247 } 5248 } 5249 5250 @Override 5251 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5252 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5253 if (!sUserManager.exists(userId)) return null; 5254 if (query != null) { 5255 if (query.size() >= 1) { 5256 // If there is more than one service with the same priority, 5257 // just arbitrarily pick the first one. 5258 return query.get(0); 5259 } 5260 } 5261 return null; 5262 } 5263 5264 @Override 5265 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5266 int userId) { 5267 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5268 ComponentName comp = intent.getComponent(); 5269 if (comp == null) { 5270 if (intent.getSelector() != null) { 5271 intent = intent.getSelector(); 5272 comp = intent.getComponent(); 5273 } 5274 } 5275 if (comp != null) { 5276 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5277 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5278 if (si != null) { 5279 final ResolveInfo ri = new ResolveInfo(); 5280 ri.serviceInfo = si; 5281 list.add(ri); 5282 } 5283 return list; 5284 } 5285 5286 // reader 5287 synchronized (mPackages) { 5288 String pkgName = intent.getPackage(); 5289 if (pkgName == null) { 5290 return mServices.queryIntent(intent, resolvedType, flags, userId); 5291 } 5292 final PackageParser.Package pkg = mPackages.get(pkgName); 5293 if (pkg != null) { 5294 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5295 userId); 5296 } 5297 return null; 5298 } 5299 } 5300 5301 @Override 5302 public List<ResolveInfo> queryIntentContentProviders( 5303 Intent intent, String resolvedType, int flags, int userId) { 5304 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5305 ComponentName comp = intent.getComponent(); 5306 if (comp == null) { 5307 if (intent.getSelector() != null) { 5308 intent = intent.getSelector(); 5309 comp = intent.getComponent(); 5310 } 5311 } 5312 if (comp != null) { 5313 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5314 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5315 if (pi != null) { 5316 final ResolveInfo ri = new ResolveInfo(); 5317 ri.providerInfo = pi; 5318 list.add(ri); 5319 } 5320 return list; 5321 } 5322 5323 // reader 5324 synchronized (mPackages) { 5325 String pkgName = intent.getPackage(); 5326 if (pkgName == null) { 5327 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5328 } 5329 final PackageParser.Package pkg = mPackages.get(pkgName); 5330 if (pkg != null) { 5331 return mProviders.queryIntentForPackage( 5332 intent, resolvedType, flags, pkg.providers, userId); 5333 } 5334 return null; 5335 } 5336 } 5337 5338 @Override 5339 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5340 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5341 5342 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5343 5344 // writer 5345 synchronized (mPackages) { 5346 ArrayList<PackageInfo> list; 5347 if (listUninstalled) { 5348 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5349 for (PackageSetting ps : mSettings.mPackages.values()) { 5350 PackageInfo pi; 5351 if (ps.pkg != null) { 5352 pi = generatePackageInfo(ps.pkg, flags, userId); 5353 } else { 5354 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5355 } 5356 if (pi != null) { 5357 list.add(pi); 5358 } 5359 } 5360 } else { 5361 list = new ArrayList<PackageInfo>(mPackages.size()); 5362 for (PackageParser.Package p : mPackages.values()) { 5363 PackageInfo pi = generatePackageInfo(p, flags, userId); 5364 if (pi != null) { 5365 list.add(pi); 5366 } 5367 } 5368 } 5369 5370 return new ParceledListSlice<PackageInfo>(list); 5371 } 5372 } 5373 5374 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5375 String[] permissions, boolean[] tmp, int flags, int userId) { 5376 int numMatch = 0; 5377 final PermissionsState permissionsState = ps.getPermissionsState(); 5378 for (int i=0; i<permissions.length; i++) { 5379 final String permission = permissions[i]; 5380 if (permissionsState.hasPermission(permission, userId)) { 5381 tmp[i] = true; 5382 numMatch++; 5383 } else { 5384 tmp[i] = false; 5385 } 5386 } 5387 if (numMatch == 0) { 5388 return; 5389 } 5390 PackageInfo pi; 5391 if (ps.pkg != null) { 5392 pi = generatePackageInfo(ps.pkg, flags, userId); 5393 } else { 5394 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5395 } 5396 // The above might return null in cases of uninstalled apps or install-state 5397 // skew across users/profiles. 5398 if (pi != null) { 5399 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5400 if (numMatch == permissions.length) { 5401 pi.requestedPermissions = permissions; 5402 } else { 5403 pi.requestedPermissions = new String[numMatch]; 5404 numMatch = 0; 5405 for (int i=0; i<permissions.length; i++) { 5406 if (tmp[i]) { 5407 pi.requestedPermissions[numMatch] = permissions[i]; 5408 numMatch++; 5409 } 5410 } 5411 } 5412 } 5413 list.add(pi); 5414 } 5415 } 5416 5417 @Override 5418 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5419 String[] permissions, int flags, int userId) { 5420 if (!sUserManager.exists(userId)) return null; 5421 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5422 5423 // writer 5424 synchronized (mPackages) { 5425 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5426 boolean[] tmpBools = new boolean[permissions.length]; 5427 if (listUninstalled) { 5428 for (PackageSetting ps : mSettings.mPackages.values()) { 5429 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5430 } 5431 } else { 5432 for (PackageParser.Package pkg : mPackages.values()) { 5433 PackageSetting ps = (PackageSetting)pkg.mExtras; 5434 if (ps != null) { 5435 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5436 userId); 5437 } 5438 } 5439 } 5440 5441 return new ParceledListSlice<PackageInfo>(list); 5442 } 5443 } 5444 5445 @Override 5446 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5447 if (!sUserManager.exists(userId)) return null; 5448 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5449 5450 // writer 5451 synchronized (mPackages) { 5452 ArrayList<ApplicationInfo> list; 5453 if (listUninstalled) { 5454 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5455 for (PackageSetting ps : mSettings.mPackages.values()) { 5456 ApplicationInfo ai; 5457 if (ps.pkg != null) { 5458 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5459 ps.readUserState(userId), userId); 5460 } else { 5461 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5462 } 5463 if (ai != null) { 5464 list.add(ai); 5465 } 5466 } 5467 } else { 5468 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5469 for (PackageParser.Package p : mPackages.values()) { 5470 if (p.mExtras != null) { 5471 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5472 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5473 if (ai != null) { 5474 list.add(ai); 5475 } 5476 } 5477 } 5478 } 5479 5480 return new ParceledListSlice<ApplicationInfo>(list); 5481 } 5482 } 5483 5484 public List<ApplicationInfo> getPersistentApplications(int flags) { 5485 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5486 5487 // reader 5488 synchronized (mPackages) { 5489 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5490 final int userId = UserHandle.getCallingUserId(); 5491 while (i.hasNext()) { 5492 final PackageParser.Package p = i.next(); 5493 if (p.applicationInfo != null 5494 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5495 && (!mSafeMode || isSystemApp(p))) { 5496 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5497 if (ps != null) { 5498 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5499 ps.readUserState(userId), userId); 5500 if (ai != null) { 5501 finalList.add(ai); 5502 } 5503 } 5504 } 5505 } 5506 } 5507 5508 return finalList; 5509 } 5510 5511 @Override 5512 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5513 if (!sUserManager.exists(userId)) return null; 5514 // reader 5515 synchronized (mPackages) { 5516 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5517 PackageSetting ps = provider != null 5518 ? mSettings.mPackages.get(provider.owner.packageName) 5519 : null; 5520 return ps != null 5521 && mSettings.isEnabledLPr(provider.info, flags, userId) 5522 && (!mSafeMode || (provider.info.applicationInfo.flags 5523 &ApplicationInfo.FLAG_SYSTEM) != 0) 5524 ? PackageParser.generateProviderInfo(provider, flags, 5525 ps.readUserState(userId), userId) 5526 : null; 5527 } 5528 } 5529 5530 /** 5531 * @deprecated 5532 */ 5533 @Deprecated 5534 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5535 // reader 5536 synchronized (mPackages) { 5537 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5538 .entrySet().iterator(); 5539 final int userId = UserHandle.getCallingUserId(); 5540 while (i.hasNext()) { 5541 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5542 PackageParser.Provider p = entry.getValue(); 5543 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5544 5545 if (ps != null && p.syncable 5546 && (!mSafeMode || (p.info.applicationInfo.flags 5547 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5548 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5549 ps.readUserState(userId), userId); 5550 if (info != null) { 5551 outNames.add(entry.getKey()); 5552 outInfo.add(info); 5553 } 5554 } 5555 } 5556 } 5557 } 5558 5559 @Override 5560 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5561 int uid, int flags) { 5562 ArrayList<ProviderInfo> finalList = null; 5563 // reader 5564 synchronized (mPackages) { 5565 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5566 final int userId = processName != null ? 5567 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5568 while (i.hasNext()) { 5569 final PackageParser.Provider p = i.next(); 5570 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5571 if (ps != null && p.info.authority != null 5572 && (processName == null 5573 || (p.info.processName.equals(processName) 5574 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5575 && mSettings.isEnabledLPr(p.info, flags, userId) 5576 && (!mSafeMode 5577 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5578 if (finalList == null) { 5579 finalList = new ArrayList<ProviderInfo>(3); 5580 } 5581 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5582 ps.readUserState(userId), userId); 5583 if (info != null) { 5584 finalList.add(info); 5585 } 5586 } 5587 } 5588 } 5589 5590 if (finalList != null) { 5591 Collections.sort(finalList, mProviderInitOrderSorter); 5592 return new ParceledListSlice<ProviderInfo>(finalList); 5593 } 5594 5595 return null; 5596 } 5597 5598 @Override 5599 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5600 int flags) { 5601 // reader 5602 synchronized (mPackages) { 5603 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5604 return PackageParser.generateInstrumentationInfo(i, flags); 5605 } 5606 } 5607 5608 @Override 5609 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5610 int flags) { 5611 ArrayList<InstrumentationInfo> finalList = 5612 new ArrayList<InstrumentationInfo>(); 5613 5614 // reader 5615 synchronized (mPackages) { 5616 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5617 while (i.hasNext()) { 5618 final PackageParser.Instrumentation p = i.next(); 5619 if (targetPackage == null 5620 || targetPackage.equals(p.info.targetPackage)) { 5621 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5622 flags); 5623 if (ii != null) { 5624 finalList.add(ii); 5625 } 5626 } 5627 } 5628 } 5629 5630 return finalList; 5631 } 5632 5633 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5634 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5635 if (overlays == null) { 5636 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5637 return; 5638 } 5639 for (PackageParser.Package opkg : overlays.values()) { 5640 // Not much to do if idmap fails: we already logged the error 5641 // and we certainly don't want to abort installation of pkg simply 5642 // because an overlay didn't fit properly. For these reasons, 5643 // ignore the return value of createIdmapForPackagePairLI. 5644 createIdmapForPackagePairLI(pkg, opkg); 5645 } 5646 } 5647 5648 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5649 PackageParser.Package opkg) { 5650 if (!opkg.mTrustedOverlay) { 5651 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5652 opkg.baseCodePath + ": overlay not trusted"); 5653 return false; 5654 } 5655 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5656 if (overlaySet == null) { 5657 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5658 opkg.baseCodePath + " but target package has no known overlays"); 5659 return false; 5660 } 5661 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5662 // TODO: generate idmap for split APKs 5663 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5664 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5665 + opkg.baseCodePath); 5666 return false; 5667 } 5668 PackageParser.Package[] overlayArray = 5669 overlaySet.values().toArray(new PackageParser.Package[0]); 5670 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5671 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5672 return p1.mOverlayPriority - p2.mOverlayPriority; 5673 } 5674 }; 5675 Arrays.sort(overlayArray, cmp); 5676 5677 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5678 int i = 0; 5679 for (PackageParser.Package p : overlayArray) { 5680 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5681 } 5682 return true; 5683 } 5684 5685 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5686 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5687 try { 5688 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5689 } finally { 5690 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5691 } 5692 } 5693 5694 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5695 final File[] files = dir.listFiles(); 5696 if (ArrayUtils.isEmpty(files)) { 5697 Log.d(TAG, "No files in app dir " + dir); 5698 return; 5699 } 5700 5701 if (DEBUG_PACKAGE_SCANNING) { 5702 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5703 + " flags=0x" + Integer.toHexString(parseFlags)); 5704 } 5705 5706 for (File file : files) { 5707 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5708 && !PackageInstallerService.isStageName(file.getName()); 5709 if (!isPackage) { 5710 // Ignore entries which are not packages 5711 continue; 5712 } 5713 try { 5714 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5715 scanFlags, currentTime, null); 5716 } catch (PackageManagerException e) { 5717 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5718 5719 // Delete invalid userdata apps 5720 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5721 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5722 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5723 if (file.isDirectory()) { 5724 mInstaller.rmPackageDir(file.getAbsolutePath()); 5725 } else { 5726 file.delete(); 5727 } 5728 } 5729 } 5730 } 5731 } 5732 5733 private static File getSettingsProblemFile() { 5734 File dataDir = Environment.getDataDirectory(); 5735 File systemDir = new File(dataDir, "system"); 5736 File fname = new File(systemDir, "uiderrors.txt"); 5737 return fname; 5738 } 5739 5740 static void reportSettingsProblem(int priority, String msg) { 5741 logCriticalInfo(priority, msg); 5742 } 5743 5744 static void logCriticalInfo(int priority, String msg) { 5745 Slog.println(priority, TAG, msg); 5746 EventLogTags.writePmCriticalInfo(msg); 5747 try { 5748 File fname = getSettingsProblemFile(); 5749 FileOutputStream out = new FileOutputStream(fname, true); 5750 PrintWriter pw = new FastPrintWriter(out); 5751 SimpleDateFormat formatter = new SimpleDateFormat(); 5752 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5753 pw.println(dateString + ": " + msg); 5754 pw.close(); 5755 FileUtils.setPermissions( 5756 fname.toString(), 5757 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5758 -1, -1); 5759 } catch (java.io.IOException e) { 5760 } 5761 } 5762 5763 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5764 PackageParser.Package pkg, File srcFile, int parseFlags) 5765 throws PackageManagerException { 5766 if (ps != null 5767 && ps.codePath.equals(srcFile) 5768 && ps.timeStamp == srcFile.lastModified() 5769 && !isCompatSignatureUpdateNeeded(pkg) 5770 && !isRecoverSignatureUpdateNeeded(pkg)) { 5771 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5772 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5773 ArraySet<PublicKey> signingKs; 5774 synchronized (mPackages) { 5775 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5776 } 5777 if (ps.signatures.mSignatures != null 5778 && ps.signatures.mSignatures.length != 0 5779 && signingKs != null) { 5780 // Optimization: reuse the existing cached certificates 5781 // if the package appears to be unchanged. 5782 pkg.mSignatures = ps.signatures.mSignatures; 5783 pkg.mSigningKeys = signingKs; 5784 return; 5785 } 5786 5787 Slog.w(TAG, "PackageSetting for " + ps.name 5788 + " is missing signatures. Collecting certs again to recover them."); 5789 } else { 5790 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5791 } 5792 5793 try { 5794 pp.collectCertificates(pkg, parseFlags); 5795 pp.collectManifestDigest(pkg); 5796 } catch (PackageParserException e) { 5797 throw PackageManagerException.from(e); 5798 } 5799 } 5800 5801 /** 5802 * Traces a package scan. 5803 * @see #scanPackageLI(File, int, int, long, UserHandle) 5804 */ 5805 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5806 long currentTime, UserHandle user) throws PackageManagerException { 5807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5808 try { 5809 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5810 } finally { 5811 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5812 } 5813 } 5814 5815 /** 5816 * Scans a package and returns the newly parsed package. 5817 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5818 */ 5819 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5820 long currentTime, UserHandle user) throws PackageManagerException { 5821 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5822 parseFlags |= mDefParseFlags; 5823 PackageParser pp = new PackageParser(); 5824 pp.setSeparateProcesses(mSeparateProcesses); 5825 pp.setOnlyCoreApps(mOnlyCore); 5826 pp.setDisplayMetrics(mMetrics); 5827 5828 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5829 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5830 } 5831 5832 final PackageParser.Package pkg; 5833 try { 5834 pkg = pp.parsePackage(scanFile, parseFlags); 5835 } catch (PackageParserException e) { 5836 throw PackageManagerException.from(e); 5837 } 5838 5839 PackageSetting ps = null; 5840 PackageSetting updatedPkg; 5841 // reader 5842 synchronized (mPackages) { 5843 // Look to see if we already know about this package. 5844 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5845 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5846 // This package has been renamed to its original name. Let's 5847 // use that. 5848 ps = mSettings.peekPackageLPr(oldName); 5849 } 5850 // If there was no original package, see one for the real package name. 5851 if (ps == null) { 5852 ps = mSettings.peekPackageLPr(pkg.packageName); 5853 } 5854 // Check to see if this package could be hiding/updating a system 5855 // package. Must look for it either under the original or real 5856 // package name depending on our state. 5857 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5858 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5859 } 5860 boolean updatedPkgBetter = false; 5861 // First check if this is a system package that may involve an update 5862 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5863 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5864 // it needs to drop FLAG_PRIVILEGED. 5865 if (locationIsPrivileged(scanFile)) { 5866 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5867 } else { 5868 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5869 } 5870 5871 if (ps != null && !ps.codePath.equals(scanFile)) { 5872 // The path has changed from what was last scanned... check the 5873 // version of the new path against what we have stored to determine 5874 // what to do. 5875 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5876 if (pkg.mVersionCode <= ps.versionCode) { 5877 // The system package has been updated and the code path does not match 5878 // Ignore entry. Skip it. 5879 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5880 + " ignored: updated version " + ps.versionCode 5881 + " better than this " + pkg.mVersionCode); 5882 if (!updatedPkg.codePath.equals(scanFile)) { 5883 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5884 + ps.name + " changing from " + updatedPkg.codePathString 5885 + " to " + scanFile); 5886 updatedPkg.codePath = scanFile; 5887 updatedPkg.codePathString = scanFile.toString(); 5888 updatedPkg.resourcePath = scanFile; 5889 updatedPkg.resourcePathString = scanFile.toString(); 5890 } 5891 updatedPkg.pkg = pkg; 5892 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5893 "Package " + ps.name + " at " + scanFile 5894 + " ignored: updated version " + ps.versionCode 5895 + " better than this " + pkg.mVersionCode); 5896 } else { 5897 // The current app on the system partition is better than 5898 // what we have updated to on the data partition; switch 5899 // back to the system partition version. 5900 // At this point, its safely assumed that package installation for 5901 // apps in system partition will go through. If not there won't be a working 5902 // version of the app 5903 // writer 5904 synchronized (mPackages) { 5905 // Just remove the loaded entries from package lists. 5906 mPackages.remove(ps.name); 5907 } 5908 5909 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5910 + " reverting from " + ps.codePathString 5911 + ": new version " + pkg.mVersionCode 5912 + " better than installed " + ps.versionCode); 5913 5914 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5915 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5916 synchronized (mInstallLock) { 5917 args.cleanUpResourcesLI(); 5918 } 5919 synchronized (mPackages) { 5920 mSettings.enableSystemPackageLPw(ps.name); 5921 } 5922 updatedPkgBetter = true; 5923 } 5924 } 5925 } 5926 5927 if (updatedPkg != null) { 5928 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5929 // initially 5930 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5931 5932 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5933 // flag set initially 5934 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5935 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5936 } 5937 } 5938 5939 // Verify certificates against what was last scanned 5940 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5941 5942 /* 5943 * A new system app appeared, but we already had a non-system one of the 5944 * same name installed earlier. 5945 */ 5946 boolean shouldHideSystemApp = false; 5947 if (updatedPkg == null && ps != null 5948 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5949 /* 5950 * Check to make sure the signatures match first. If they don't, 5951 * wipe the installed application and its data. 5952 */ 5953 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5954 != PackageManager.SIGNATURE_MATCH) { 5955 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5956 + " signatures don't match existing userdata copy; removing"); 5957 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5958 ps = null; 5959 } else { 5960 /* 5961 * If the newly-added system app is an older version than the 5962 * already installed version, hide it. It will be scanned later 5963 * and re-added like an update. 5964 */ 5965 if (pkg.mVersionCode <= ps.versionCode) { 5966 shouldHideSystemApp = true; 5967 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5968 + " but new version " + pkg.mVersionCode + " better than installed " 5969 + ps.versionCode + "; hiding system"); 5970 } else { 5971 /* 5972 * The newly found system app is a newer version that the 5973 * one previously installed. Simply remove the 5974 * already-installed application and replace it with our own 5975 * while keeping the application data. 5976 */ 5977 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5978 + " reverting from " + ps.codePathString + ": new version " 5979 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5980 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5981 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5982 synchronized (mInstallLock) { 5983 args.cleanUpResourcesLI(); 5984 } 5985 } 5986 } 5987 } 5988 5989 // The apk is forward locked (not public) if its code and resources 5990 // are kept in different files. (except for app in either system or 5991 // vendor path). 5992 // TODO grab this value from PackageSettings 5993 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5994 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5995 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5996 } 5997 } 5998 5999 // TODO: extend to support forward-locked splits 6000 String resourcePath = null; 6001 String baseResourcePath = null; 6002 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6003 if (ps != null && ps.resourcePathString != null) { 6004 resourcePath = ps.resourcePathString; 6005 baseResourcePath = ps.resourcePathString; 6006 } else { 6007 // Should not happen at all. Just log an error. 6008 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6009 } 6010 } else { 6011 resourcePath = pkg.codePath; 6012 baseResourcePath = pkg.baseCodePath; 6013 } 6014 6015 // Set application objects path explicitly. 6016 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6017 pkg.applicationInfo.setCodePath(pkg.codePath); 6018 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6019 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6020 pkg.applicationInfo.setResourcePath(resourcePath); 6021 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6022 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6023 6024 // Note that we invoke the following method only if we are about to unpack an application 6025 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6026 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6027 6028 /* 6029 * If the system app should be overridden by a previously installed 6030 * data, hide the system app now and let the /data/app scan pick it up 6031 * again. 6032 */ 6033 if (shouldHideSystemApp) { 6034 synchronized (mPackages) { 6035 mSettings.disableSystemPackageLPw(pkg.packageName); 6036 } 6037 } 6038 6039 return scannedPkg; 6040 } 6041 6042 private static String fixProcessName(String defProcessName, 6043 String processName, int uid) { 6044 if (processName == null) { 6045 return defProcessName; 6046 } 6047 return processName; 6048 } 6049 6050 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6051 throws PackageManagerException { 6052 if (pkgSetting.signatures.mSignatures != null) { 6053 // Already existing package. Make sure signatures match 6054 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6055 == PackageManager.SIGNATURE_MATCH; 6056 if (!match) { 6057 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6058 == PackageManager.SIGNATURE_MATCH; 6059 } 6060 if (!match) { 6061 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6062 == PackageManager.SIGNATURE_MATCH; 6063 } 6064 if (!match) { 6065 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6066 + pkg.packageName + " signatures do not match the " 6067 + "previously installed version; ignoring!"); 6068 } 6069 } 6070 6071 // Check for shared user signatures 6072 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6073 // Already existing package. Make sure signatures match 6074 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6075 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6076 if (!match) { 6077 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6078 == PackageManager.SIGNATURE_MATCH; 6079 } 6080 if (!match) { 6081 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6082 == PackageManager.SIGNATURE_MATCH; 6083 } 6084 if (!match) { 6085 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6086 "Package " + pkg.packageName 6087 + " has no signatures that match those in shared user " 6088 + pkgSetting.sharedUser.name + "; ignoring!"); 6089 } 6090 } 6091 } 6092 6093 /** 6094 * Enforces that only the system UID or root's UID can call a method exposed 6095 * via Binder. 6096 * 6097 * @param message used as message if SecurityException is thrown 6098 * @throws SecurityException if the caller is not system or root 6099 */ 6100 private static final void enforceSystemOrRoot(String message) { 6101 final int uid = Binder.getCallingUid(); 6102 if (uid != Process.SYSTEM_UID && uid != 0) { 6103 throw new SecurityException(message); 6104 } 6105 } 6106 6107 @Override 6108 public void performBootDexOpt() { 6109 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6110 6111 // Before everything else, see whether we need to fstrim. 6112 try { 6113 IMountService ms = PackageHelper.getMountService(); 6114 if (ms != null) { 6115 final boolean isUpgrade = isUpgrade(); 6116 boolean doTrim = isUpgrade; 6117 if (doTrim) { 6118 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6119 } else { 6120 final long interval = android.provider.Settings.Global.getLong( 6121 mContext.getContentResolver(), 6122 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6123 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6124 if (interval > 0) { 6125 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6126 if (timeSinceLast > interval) { 6127 doTrim = true; 6128 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6129 + "; running immediately"); 6130 } 6131 } 6132 } 6133 if (doTrim) { 6134 if (!isFirstBoot()) { 6135 try { 6136 ActivityManagerNative.getDefault().showBootMessage( 6137 mContext.getResources().getString( 6138 R.string.android_upgrading_fstrim), true); 6139 } catch (RemoteException e) { 6140 } 6141 } 6142 ms.runMaintenance(); 6143 } 6144 } else { 6145 Slog.e(TAG, "Mount service unavailable!"); 6146 } 6147 } catch (RemoteException e) { 6148 // Can't happen; MountService is local 6149 } 6150 6151 final ArraySet<PackageParser.Package> pkgs; 6152 synchronized (mPackages) { 6153 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6154 } 6155 6156 if (pkgs != null) { 6157 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6158 // in case the device runs out of space. 6159 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6160 // Give priority to core apps. 6161 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6162 PackageParser.Package pkg = it.next(); 6163 if (pkg.coreApp) { 6164 if (DEBUG_DEXOPT) { 6165 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6166 } 6167 sortedPkgs.add(pkg); 6168 it.remove(); 6169 } 6170 } 6171 // Give priority to system apps that listen for pre boot complete. 6172 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6173 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6174 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6175 PackageParser.Package pkg = it.next(); 6176 if (pkgNames.contains(pkg.packageName)) { 6177 if (DEBUG_DEXOPT) { 6178 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6179 } 6180 sortedPkgs.add(pkg); 6181 it.remove(); 6182 } 6183 } 6184 // Filter out packages that aren't recently used. 6185 filterRecentlyUsedApps(pkgs); 6186 // Add all remaining apps. 6187 for (PackageParser.Package pkg : pkgs) { 6188 if (DEBUG_DEXOPT) { 6189 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6190 } 6191 sortedPkgs.add(pkg); 6192 } 6193 6194 // If we want to be lazy, filter everything that wasn't recently used. 6195 if (mLazyDexOpt) { 6196 filterRecentlyUsedApps(sortedPkgs); 6197 } 6198 6199 int i = 0; 6200 int total = sortedPkgs.size(); 6201 File dataDir = Environment.getDataDirectory(); 6202 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6203 if (lowThreshold == 0) { 6204 throw new IllegalStateException("Invalid low memory threshold"); 6205 } 6206 for (PackageParser.Package pkg : sortedPkgs) { 6207 long usableSpace = dataDir.getUsableSpace(); 6208 if (usableSpace < lowThreshold) { 6209 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6210 break; 6211 } 6212 performBootDexOpt(pkg, ++i, total); 6213 } 6214 } 6215 } 6216 6217 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6218 // Filter out packages that aren't recently used. 6219 // 6220 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6221 // should do a full dexopt. 6222 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6223 int total = pkgs.size(); 6224 int skipped = 0; 6225 long now = System.currentTimeMillis(); 6226 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6227 PackageParser.Package pkg = i.next(); 6228 long then = pkg.mLastPackageUsageTimeInMills; 6229 if (then + mDexOptLRUThresholdInMills < now) { 6230 if (DEBUG_DEXOPT) { 6231 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6232 ((then == 0) ? "never" : new Date(then))); 6233 } 6234 i.remove(); 6235 skipped++; 6236 } 6237 } 6238 if (DEBUG_DEXOPT) { 6239 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6240 } 6241 } 6242 } 6243 6244 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6245 List<ResolveInfo> ris = null; 6246 try { 6247 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6248 intent, null, 0, userId); 6249 } catch (RemoteException e) { 6250 } 6251 ArraySet<String> pkgNames = new ArraySet<String>(); 6252 if (ris != null) { 6253 for (ResolveInfo ri : ris) { 6254 pkgNames.add(ri.activityInfo.packageName); 6255 } 6256 } 6257 return pkgNames; 6258 } 6259 6260 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6261 if (DEBUG_DEXOPT) { 6262 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6263 } 6264 if (!isFirstBoot()) { 6265 try { 6266 ActivityManagerNative.getDefault().showBootMessage( 6267 mContext.getResources().getString(R.string.android_upgrading_apk, 6268 curr, total), true); 6269 } catch (RemoteException e) { 6270 } 6271 } 6272 PackageParser.Package p = pkg; 6273 synchronized (mInstallLock) { 6274 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6275 false /* force dex */, false /* defer */, true /* include dependencies */, 6276 false /* boot complete */, false /*useJit*/); 6277 } 6278 } 6279 6280 @Override 6281 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6282 return performDexOptTraced(packageName, instructionSet, false); 6283 } 6284 6285 public boolean performDexOpt( 6286 String packageName, String instructionSet, boolean backgroundDexopt) { 6287 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6288 } 6289 6290 private boolean performDexOptTraced( 6291 String packageName, String instructionSet, boolean backgroundDexopt) { 6292 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6293 try { 6294 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6295 } finally { 6296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6297 } 6298 } 6299 6300 private boolean performDexOptInternal( 6301 String packageName, String instructionSet, boolean backgroundDexopt) { 6302 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6303 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6304 if (!dexopt && !updateUsage) { 6305 // We aren't going to dexopt or update usage, so bail early. 6306 return false; 6307 } 6308 PackageParser.Package p; 6309 final String targetInstructionSet; 6310 synchronized (mPackages) { 6311 p = mPackages.get(packageName); 6312 if (p == null) { 6313 return false; 6314 } 6315 if (updateUsage) { 6316 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6317 } 6318 mPackageUsage.write(false); 6319 if (!dexopt) { 6320 // We aren't going to dexopt, so bail early. 6321 return false; 6322 } 6323 6324 targetInstructionSet = instructionSet != null ? instructionSet : 6325 getPrimaryInstructionSet(p.applicationInfo); 6326 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6327 return false; 6328 } 6329 } 6330 long callingId = Binder.clearCallingIdentity(); 6331 try { 6332 synchronized (mInstallLock) { 6333 final String[] instructionSets = new String[] { targetInstructionSet }; 6334 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6335 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6336 true /* boot complete */, false /*useJit*/); 6337 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6338 } 6339 } finally { 6340 Binder.restoreCallingIdentity(callingId); 6341 } 6342 } 6343 6344 public ArraySet<String> getPackagesThatNeedDexOpt() { 6345 ArraySet<String> pkgs = null; 6346 synchronized (mPackages) { 6347 for (PackageParser.Package p : mPackages.values()) { 6348 if (DEBUG_DEXOPT) { 6349 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6350 } 6351 if (!p.mDexOptPerformed.isEmpty()) { 6352 continue; 6353 } 6354 if (pkgs == null) { 6355 pkgs = new ArraySet<String>(); 6356 } 6357 pkgs.add(p.packageName); 6358 } 6359 } 6360 return pkgs; 6361 } 6362 6363 public void shutdown() { 6364 mPackageUsage.write(true); 6365 } 6366 6367 @Override 6368 public void forceDexOpt(String packageName) { 6369 enforceSystemOrRoot("forceDexOpt"); 6370 6371 PackageParser.Package pkg; 6372 synchronized (mPackages) { 6373 pkg = mPackages.get(packageName); 6374 if (pkg == null) { 6375 throw new IllegalArgumentException("Missing package: " + packageName); 6376 } 6377 } 6378 6379 synchronized (mInstallLock) { 6380 final String[] instructionSets = new String[] { 6381 getPrimaryInstructionSet(pkg.applicationInfo) }; 6382 6383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6384 6385 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6386 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6387 true /* boot complete */, false /*useJit*/); 6388 6389 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6390 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6391 throw new IllegalStateException("Failed to dexopt: " + res); 6392 } 6393 } 6394 } 6395 6396 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6397 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6398 Slog.w(TAG, "Unable to update from " + oldPkg.name 6399 + " to " + newPkg.packageName 6400 + ": old package not in system partition"); 6401 return false; 6402 } else if (mPackages.get(oldPkg.name) != null) { 6403 Slog.w(TAG, "Unable to update from " + oldPkg.name 6404 + " to " + newPkg.packageName 6405 + ": old package still exists"); 6406 return false; 6407 } 6408 return true; 6409 } 6410 6411 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6412 int[] users = sUserManager.getUserIds(); 6413 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6414 if (res < 0) { 6415 return res; 6416 } 6417 for (int user : users) { 6418 if (user != 0) { 6419 res = mInstaller.createUserData(volumeUuid, packageName, 6420 UserHandle.getUid(user, uid), user, seinfo); 6421 if (res < 0) { 6422 return res; 6423 } 6424 } 6425 } 6426 return res; 6427 } 6428 6429 private int removeDataDirsLI(String volumeUuid, String packageName) { 6430 int[] users = sUserManager.getUserIds(); 6431 int res = 0; 6432 for (int user : users) { 6433 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6434 if (resInner < 0) { 6435 res = resInner; 6436 } 6437 } 6438 6439 return res; 6440 } 6441 6442 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6443 int[] users = sUserManager.getUserIds(); 6444 int res = 0; 6445 for (int user : users) { 6446 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6447 if (resInner < 0) { 6448 res = resInner; 6449 } 6450 } 6451 return res; 6452 } 6453 6454 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6455 PackageParser.Package changingLib) { 6456 if (file.path != null) { 6457 usesLibraryFiles.add(file.path); 6458 return; 6459 } 6460 PackageParser.Package p = mPackages.get(file.apk); 6461 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6462 // If we are doing this while in the middle of updating a library apk, 6463 // then we need to make sure to use that new apk for determining the 6464 // dependencies here. (We haven't yet finished committing the new apk 6465 // to the package manager state.) 6466 if (p == null || p.packageName.equals(changingLib.packageName)) { 6467 p = changingLib; 6468 } 6469 } 6470 if (p != null) { 6471 usesLibraryFiles.addAll(p.getAllCodePaths()); 6472 } 6473 } 6474 6475 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6476 PackageParser.Package changingLib) throws PackageManagerException { 6477 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6478 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6479 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6480 for (int i=0; i<N; i++) { 6481 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6482 if (file == null) { 6483 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6484 "Package " + pkg.packageName + " requires unavailable shared library " 6485 + pkg.usesLibraries.get(i) + "; failing!"); 6486 } 6487 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6488 } 6489 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6490 for (int i=0; i<N; i++) { 6491 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6492 if (file == null) { 6493 Slog.w(TAG, "Package " + pkg.packageName 6494 + " desires unavailable shared library " 6495 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6496 } else { 6497 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6498 } 6499 } 6500 N = usesLibraryFiles.size(); 6501 if (N > 0) { 6502 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6503 } else { 6504 pkg.usesLibraryFiles = null; 6505 } 6506 } 6507 } 6508 6509 private static boolean hasString(List<String> list, List<String> which) { 6510 if (list == null) { 6511 return false; 6512 } 6513 for (int i=list.size()-1; i>=0; i--) { 6514 for (int j=which.size()-1; j>=0; j--) { 6515 if (which.get(j).equals(list.get(i))) { 6516 return true; 6517 } 6518 } 6519 } 6520 return false; 6521 } 6522 6523 private void updateAllSharedLibrariesLPw() { 6524 for (PackageParser.Package pkg : mPackages.values()) { 6525 try { 6526 updateSharedLibrariesLPw(pkg, null); 6527 } catch (PackageManagerException e) { 6528 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6529 } 6530 } 6531 } 6532 6533 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6534 PackageParser.Package changingPkg) { 6535 ArrayList<PackageParser.Package> res = null; 6536 for (PackageParser.Package pkg : mPackages.values()) { 6537 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6538 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6539 if (res == null) { 6540 res = new ArrayList<PackageParser.Package>(); 6541 } 6542 res.add(pkg); 6543 try { 6544 updateSharedLibrariesLPw(pkg, changingPkg); 6545 } catch (PackageManagerException e) { 6546 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6547 } 6548 } 6549 } 6550 return res; 6551 } 6552 6553 /** 6554 * Derive the value of the {@code cpuAbiOverride} based on the provided 6555 * value and an optional stored value from the package settings. 6556 */ 6557 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6558 String cpuAbiOverride = null; 6559 6560 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6561 cpuAbiOverride = null; 6562 } else if (abiOverride != null) { 6563 cpuAbiOverride = abiOverride; 6564 } else if (settings != null) { 6565 cpuAbiOverride = settings.cpuAbiOverrideString; 6566 } 6567 6568 return cpuAbiOverride; 6569 } 6570 6571 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6572 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6573 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6574 try { 6575 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6576 } finally { 6577 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6578 } 6579 } 6580 6581 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6582 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6583 boolean success = false; 6584 try { 6585 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6586 currentTime, user); 6587 success = true; 6588 return res; 6589 } finally { 6590 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6591 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6592 } 6593 } 6594 } 6595 6596 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6597 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6598 final File scanFile = new File(pkg.codePath); 6599 if (pkg.applicationInfo.getCodePath() == null || 6600 pkg.applicationInfo.getResourcePath() == null) { 6601 // Bail out. The resource and code paths haven't been set. 6602 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6603 "Code and resource paths haven't been set correctly"); 6604 } 6605 6606 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6607 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6608 } else { 6609 // Only allow system apps to be flagged as core apps. 6610 pkg.coreApp = false; 6611 } 6612 6613 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6614 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6615 } 6616 6617 if (mCustomResolverComponentName != null && 6618 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6619 setUpCustomResolverActivity(pkg); 6620 } 6621 6622 if (pkg.packageName.equals("android")) { 6623 synchronized (mPackages) { 6624 if (mAndroidApplication != null) { 6625 Slog.w(TAG, "*************************************************"); 6626 Slog.w(TAG, "Core android package being redefined. Skipping."); 6627 Slog.w(TAG, " file=" + scanFile); 6628 Slog.w(TAG, "*************************************************"); 6629 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6630 "Core android package being redefined. Skipping."); 6631 } 6632 6633 // Set up information for our fall-back user intent resolution activity. 6634 mPlatformPackage = pkg; 6635 pkg.mVersionCode = mSdkVersion; 6636 mAndroidApplication = pkg.applicationInfo; 6637 6638 if (!mResolverReplaced) { 6639 mResolveActivity.applicationInfo = mAndroidApplication; 6640 mResolveActivity.name = ResolverActivity.class.getName(); 6641 mResolveActivity.packageName = mAndroidApplication.packageName; 6642 mResolveActivity.processName = "system:ui"; 6643 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6644 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6645 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6646 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6647 mResolveActivity.exported = true; 6648 mResolveActivity.enabled = true; 6649 mResolveInfo.activityInfo = mResolveActivity; 6650 mResolveInfo.priority = 0; 6651 mResolveInfo.preferredOrder = 0; 6652 mResolveInfo.match = 0; 6653 mResolveComponentName = new ComponentName( 6654 mAndroidApplication.packageName, mResolveActivity.name); 6655 } 6656 } 6657 } 6658 6659 if (DEBUG_PACKAGE_SCANNING) { 6660 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6661 Log.d(TAG, "Scanning package " + pkg.packageName); 6662 } 6663 6664 if (mPackages.containsKey(pkg.packageName) 6665 || mSharedLibraries.containsKey(pkg.packageName)) { 6666 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6667 "Application package " + pkg.packageName 6668 + " already installed. Skipping duplicate."); 6669 } 6670 6671 // If we're only installing presumed-existing packages, require that the 6672 // scanned APK is both already known and at the path previously established 6673 // for it. Previously unknown packages we pick up normally, but if we have an 6674 // a priori expectation about this package's install presence, enforce it. 6675 // With a singular exception for new system packages. When an OTA contains 6676 // a new system package, we allow the codepath to change from a system location 6677 // to the user-installed location. If we don't allow this change, any newer, 6678 // user-installed version of the application will be ignored. 6679 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6680 if (mExpectingBetter.containsKey(pkg.packageName)) { 6681 logCriticalInfo(Log.WARN, 6682 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6683 } else { 6684 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6685 if (known != null) { 6686 if (DEBUG_PACKAGE_SCANNING) { 6687 Log.d(TAG, "Examining " + pkg.codePath 6688 + " and requiring known paths " + known.codePathString 6689 + " & " + known.resourcePathString); 6690 } 6691 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6692 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6693 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6694 "Application package " + pkg.packageName 6695 + " found at " + pkg.applicationInfo.getCodePath() 6696 + " but expected at " + known.codePathString + "; ignoring."); 6697 } 6698 } 6699 } 6700 } 6701 6702 // Initialize package source and resource directories 6703 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6704 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6705 6706 SharedUserSetting suid = null; 6707 PackageSetting pkgSetting = null; 6708 6709 if (!isSystemApp(pkg)) { 6710 // Only system apps can use these features. 6711 pkg.mOriginalPackages = null; 6712 pkg.mRealPackage = null; 6713 pkg.mAdoptPermissions = null; 6714 } 6715 6716 // writer 6717 synchronized (mPackages) { 6718 if (pkg.mSharedUserId != null) { 6719 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6720 if (suid == null) { 6721 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6722 "Creating application package " + pkg.packageName 6723 + " for shared user failed"); 6724 } 6725 if (DEBUG_PACKAGE_SCANNING) { 6726 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6727 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6728 + "): packages=" + suid.packages); 6729 } 6730 } 6731 6732 // Check if we are renaming from an original package name. 6733 PackageSetting origPackage = null; 6734 String realName = null; 6735 if (pkg.mOriginalPackages != null) { 6736 // This package may need to be renamed to a previously 6737 // installed name. Let's check on that... 6738 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6739 if (pkg.mOriginalPackages.contains(renamed)) { 6740 // This package had originally been installed as the 6741 // original name, and we have already taken care of 6742 // transitioning to the new one. Just update the new 6743 // one to continue using the old name. 6744 realName = pkg.mRealPackage; 6745 if (!pkg.packageName.equals(renamed)) { 6746 // Callers into this function may have already taken 6747 // care of renaming the package; only do it here if 6748 // it is not already done. 6749 pkg.setPackageName(renamed); 6750 } 6751 6752 } else { 6753 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6754 if ((origPackage = mSettings.peekPackageLPr( 6755 pkg.mOriginalPackages.get(i))) != null) { 6756 // We do have the package already installed under its 6757 // original name... should we use it? 6758 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6759 // New package is not compatible with original. 6760 origPackage = null; 6761 continue; 6762 } else if (origPackage.sharedUser != null) { 6763 // Make sure uid is compatible between packages. 6764 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6765 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6766 + " to " + pkg.packageName + ": old uid " 6767 + origPackage.sharedUser.name 6768 + " differs from " + pkg.mSharedUserId); 6769 origPackage = null; 6770 continue; 6771 } 6772 } else { 6773 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6774 + pkg.packageName + " to old name " + origPackage.name); 6775 } 6776 break; 6777 } 6778 } 6779 } 6780 } 6781 6782 if (mTransferedPackages.contains(pkg.packageName)) { 6783 Slog.w(TAG, "Package " + pkg.packageName 6784 + " was transferred to another, but its .apk remains"); 6785 } 6786 6787 // Just create the setting, don't add it yet. For already existing packages 6788 // the PkgSetting exists already and doesn't have to be created. 6789 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6790 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6791 pkg.applicationInfo.primaryCpuAbi, 6792 pkg.applicationInfo.secondaryCpuAbi, 6793 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6794 user, false); 6795 if (pkgSetting == null) { 6796 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6797 "Creating application package " + pkg.packageName + " failed"); 6798 } 6799 6800 if (pkgSetting.origPackage != null) { 6801 // If we are first transitioning from an original package, 6802 // fix up the new package's name now. We need to do this after 6803 // looking up the package under its new name, so getPackageLP 6804 // can take care of fiddling things correctly. 6805 pkg.setPackageName(origPackage.name); 6806 6807 // File a report about this. 6808 String msg = "New package " + pkgSetting.realName 6809 + " renamed to replace old package " + pkgSetting.name; 6810 reportSettingsProblem(Log.WARN, msg); 6811 6812 // Make a note of it. 6813 mTransferedPackages.add(origPackage.name); 6814 6815 // No longer need to retain this. 6816 pkgSetting.origPackage = null; 6817 } 6818 6819 if (realName != null) { 6820 // Make a note of it. 6821 mTransferedPackages.add(pkg.packageName); 6822 } 6823 6824 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6825 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6826 } 6827 6828 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6829 // Check all shared libraries and map to their actual file path. 6830 // We only do this here for apps not on a system dir, because those 6831 // are the only ones that can fail an install due to this. We 6832 // will take care of the system apps by updating all of their 6833 // library paths after the scan is done. 6834 updateSharedLibrariesLPw(pkg, null); 6835 } 6836 6837 if (mFoundPolicyFile) { 6838 SELinuxMMAC.assignSeinfoValue(pkg); 6839 } 6840 6841 pkg.applicationInfo.uid = pkgSetting.appId; 6842 pkg.mExtras = pkgSetting; 6843 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6844 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6845 // We just determined the app is signed correctly, so bring 6846 // over the latest parsed certs. 6847 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6848 } else { 6849 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6850 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6851 "Package " + pkg.packageName + " upgrade keys do not match the " 6852 + "previously installed version"); 6853 } else { 6854 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6855 String msg = "System package " + pkg.packageName 6856 + " signature changed; retaining data."; 6857 reportSettingsProblem(Log.WARN, msg); 6858 } 6859 } 6860 } else { 6861 try { 6862 verifySignaturesLP(pkgSetting, pkg); 6863 // We just determined the app is signed correctly, so bring 6864 // over the latest parsed certs. 6865 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6866 } catch (PackageManagerException e) { 6867 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6868 throw e; 6869 } 6870 // The signature has changed, but this package is in the system 6871 // image... let's recover! 6872 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6873 // However... if this package is part of a shared user, but it 6874 // doesn't match the signature of the shared user, let's fail. 6875 // What this means is that you can't change the signatures 6876 // associated with an overall shared user, which doesn't seem all 6877 // that unreasonable. 6878 if (pkgSetting.sharedUser != null) { 6879 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6880 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6881 throw new PackageManagerException( 6882 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6883 "Signature mismatch for shared user : " 6884 + pkgSetting.sharedUser); 6885 } 6886 } 6887 // File a report about this. 6888 String msg = "System package " + pkg.packageName 6889 + " signature changed; retaining data."; 6890 reportSettingsProblem(Log.WARN, msg); 6891 } 6892 } 6893 // Verify that this new package doesn't have any content providers 6894 // that conflict with existing packages. Only do this if the 6895 // package isn't already installed, since we don't want to break 6896 // things that are installed. 6897 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6898 final int N = pkg.providers.size(); 6899 int i; 6900 for (i=0; i<N; i++) { 6901 PackageParser.Provider p = pkg.providers.get(i); 6902 if (p.info.authority != null) { 6903 String names[] = p.info.authority.split(";"); 6904 for (int j = 0; j < names.length; j++) { 6905 if (mProvidersByAuthority.containsKey(names[j])) { 6906 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6907 final String otherPackageName = 6908 ((other != null && other.getComponentName() != null) ? 6909 other.getComponentName().getPackageName() : "?"); 6910 throw new PackageManagerException( 6911 INSTALL_FAILED_CONFLICTING_PROVIDER, 6912 "Can't install because provider name " + names[j] 6913 + " (in package " + pkg.applicationInfo.packageName 6914 + ") is already used by " + otherPackageName); 6915 } 6916 } 6917 } 6918 } 6919 } 6920 6921 if (pkg.mAdoptPermissions != null) { 6922 // This package wants to adopt ownership of permissions from 6923 // another package. 6924 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6925 final String origName = pkg.mAdoptPermissions.get(i); 6926 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6927 if (orig != null) { 6928 if (verifyPackageUpdateLPr(orig, pkg)) { 6929 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6930 + pkg.packageName); 6931 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6932 } 6933 } 6934 } 6935 } 6936 } 6937 6938 final String pkgName = pkg.packageName; 6939 6940 final long scanFileTime = scanFile.lastModified(); 6941 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6942 pkg.applicationInfo.processName = fixProcessName( 6943 pkg.applicationInfo.packageName, 6944 pkg.applicationInfo.processName, 6945 pkg.applicationInfo.uid); 6946 6947 File dataPath; 6948 if (mPlatformPackage == pkg) { 6949 // The system package is special. 6950 dataPath = new File(Environment.getDataDirectory(), "system"); 6951 6952 pkg.applicationInfo.dataDir = dataPath.getPath(); 6953 6954 } else { 6955 // This is a normal package, need to make its data directory. 6956 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6957 UserHandle.USER_SYSTEM, pkg.packageName); 6958 6959 boolean uidError = false; 6960 if (dataPath.exists()) { 6961 int currentUid = 0; 6962 try { 6963 StructStat stat = Os.stat(dataPath.getPath()); 6964 currentUid = stat.st_uid; 6965 } catch (ErrnoException e) { 6966 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6967 } 6968 6969 // If we have mismatched owners for the data path, we have a problem. 6970 if (currentUid != pkg.applicationInfo.uid) { 6971 boolean recovered = false; 6972 if (currentUid == 0) { 6973 // The directory somehow became owned by root. Wow. 6974 // This is probably because the system was stopped while 6975 // installd was in the middle of messing with its libs 6976 // directory. Ask installd to fix that. 6977 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6978 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6979 if (ret >= 0) { 6980 recovered = true; 6981 String msg = "Package " + pkg.packageName 6982 + " unexpectedly changed to uid 0; recovered to " + 6983 + pkg.applicationInfo.uid; 6984 reportSettingsProblem(Log.WARN, msg); 6985 } 6986 } 6987 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6988 || (scanFlags&SCAN_BOOTING) != 0)) { 6989 // If this is a system app, we can at least delete its 6990 // current data so the application will still work. 6991 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6992 if (ret >= 0) { 6993 // TODO: Kill the processes first 6994 // Old data gone! 6995 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6996 ? "System package " : "Third party package "; 6997 String msg = prefix + pkg.packageName 6998 + " has changed from uid: " 6999 + currentUid + " to " 7000 + pkg.applicationInfo.uid + "; old data erased"; 7001 reportSettingsProblem(Log.WARN, msg); 7002 recovered = true; 7003 7004 // And now re-install the app. 7005 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7006 pkg.applicationInfo.seinfo); 7007 if (ret == -1) { 7008 // Ack should not happen! 7009 msg = prefix + pkg.packageName 7010 + " could not have data directory re-created after delete."; 7011 reportSettingsProblem(Log.WARN, msg); 7012 throw new PackageManagerException( 7013 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 7014 } 7015 } 7016 if (!recovered) { 7017 mHasSystemUidErrors = true; 7018 } 7019 } else if (!recovered) { 7020 // If we allow this install to proceed, we will be broken. 7021 // Abort, abort! 7022 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7023 "scanPackageLI"); 7024 } 7025 if (!recovered) { 7026 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7027 + pkg.applicationInfo.uid + "/fs_" 7028 + currentUid; 7029 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7030 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7031 String msg = "Package " + pkg.packageName 7032 + " has mismatched uid: " 7033 + currentUid + " on disk, " 7034 + pkg.applicationInfo.uid + " in settings"; 7035 // writer 7036 synchronized (mPackages) { 7037 mSettings.mReadMessages.append(msg); 7038 mSettings.mReadMessages.append('\n'); 7039 uidError = true; 7040 if (!pkgSetting.uidError) { 7041 reportSettingsProblem(Log.ERROR, msg); 7042 } 7043 } 7044 } 7045 } 7046 pkg.applicationInfo.dataDir = dataPath.getPath(); 7047 if (mShouldRestoreconData) { 7048 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7049 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7050 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7051 } 7052 } else { 7053 if (DEBUG_PACKAGE_SCANNING) { 7054 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7055 Log.v(TAG, "Want this data dir: " + dataPath); 7056 } 7057 //invoke installer to do the actual installation 7058 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7059 pkg.applicationInfo.seinfo); 7060 if (ret < 0) { 7061 // Error from installer 7062 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7063 "Unable to create data dirs [errorCode=" + ret + "]"); 7064 } 7065 7066 if (dataPath.exists()) { 7067 pkg.applicationInfo.dataDir = dataPath.getPath(); 7068 } else { 7069 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7070 pkg.applicationInfo.dataDir = null; 7071 } 7072 } 7073 7074 pkgSetting.uidError = uidError; 7075 } 7076 7077 final String path = scanFile.getPath(); 7078 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7079 7080 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7081 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7082 7083 // Some system apps still use directory structure for native libraries 7084 // in which case we might end up not detecting abi solely based on apk 7085 // structure. Try to detect abi based on directory structure. 7086 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7087 pkg.applicationInfo.primaryCpuAbi == null) { 7088 setBundledAppAbisAndRoots(pkg, pkgSetting); 7089 setNativeLibraryPaths(pkg); 7090 } 7091 7092 } else { 7093 if ((scanFlags & SCAN_MOVE) != 0) { 7094 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7095 // but we already have this packages package info in the PackageSetting. We just 7096 // use that and derive the native library path based on the new codepath. 7097 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7098 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7099 } 7100 7101 // Set native library paths again. For moves, the path will be updated based on the 7102 // ABIs we've determined above. For non-moves, the path will be updated based on the 7103 // ABIs we determined during compilation, but the path will depend on the final 7104 // package path (after the rename away from the stage path). 7105 setNativeLibraryPaths(pkg); 7106 } 7107 7108 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7109 final int[] userIds = sUserManager.getUserIds(); 7110 synchronized (mInstallLock) { 7111 // Make sure all user data directories are ready to roll; we're okay 7112 // if they already exist 7113 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7114 for (int userId : userIds) { 7115 if (userId != UserHandle.USER_SYSTEM) { 7116 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7117 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7118 pkg.applicationInfo.seinfo); 7119 } 7120 } 7121 } 7122 7123 // Create a native library symlink only if we have native libraries 7124 // and if the native libraries are 32 bit libraries. We do not provide 7125 // this symlink for 64 bit libraries. 7126 if (pkg.applicationInfo.primaryCpuAbi != null && 7127 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7128 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7129 try { 7130 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7131 for (int userId : userIds) { 7132 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7133 nativeLibPath, userId) < 0) { 7134 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7135 "Failed linking native library dir (user=" + userId + ")"); 7136 } 7137 } 7138 } finally { 7139 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7140 } 7141 } 7142 } 7143 7144 // This is a special case for the "system" package, where the ABI is 7145 // dictated by the zygote configuration (and init.rc). We should keep track 7146 // of this ABI so that we can deal with "normal" applications that run under 7147 // the same UID correctly. 7148 if (mPlatformPackage == pkg) { 7149 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7150 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7151 } 7152 7153 // If there's a mismatch between the abi-override in the package setting 7154 // and the abiOverride specified for the install. Warn about this because we 7155 // would've already compiled the app without taking the package setting into 7156 // account. 7157 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7158 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7159 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7160 " for package: " + pkg.packageName); 7161 } 7162 } 7163 7164 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7165 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7166 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7167 7168 // Copy the derived override back to the parsed package, so that we can 7169 // update the package settings accordingly. 7170 pkg.cpuAbiOverride = cpuAbiOverride; 7171 7172 if (DEBUG_ABI_SELECTION) { 7173 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7174 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7175 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7176 } 7177 7178 // Push the derived path down into PackageSettings so we know what to 7179 // clean up at uninstall time. 7180 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7181 7182 if (DEBUG_ABI_SELECTION) { 7183 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7184 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7185 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7186 } 7187 7188 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7189 // We don't do this here during boot because we can do it all 7190 // at once after scanning all existing packages. 7191 // 7192 // We also do this *before* we perform dexopt on this package, so that 7193 // we can avoid redundant dexopts, and also to make sure we've got the 7194 // code and package path correct. 7195 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7196 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7197 } 7198 7199 if ((scanFlags & SCAN_NO_DEX) == 0) { 7200 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7201 7202 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7203 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7204 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7205 7206 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7207 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7208 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7209 } 7210 } 7211 if (mFactoryTest && pkg.requestedPermissions.contains( 7212 android.Manifest.permission.FACTORY_TEST)) { 7213 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7214 } 7215 7216 ArrayList<PackageParser.Package> clientLibPkgs = null; 7217 7218 // writer 7219 synchronized (mPackages) { 7220 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7221 // Only system apps can add new shared libraries. 7222 if (pkg.libraryNames != null) { 7223 for (int i=0; i<pkg.libraryNames.size(); i++) { 7224 String name = pkg.libraryNames.get(i); 7225 boolean allowed = false; 7226 if (pkg.isUpdatedSystemApp()) { 7227 // New library entries can only be added through the 7228 // system image. This is important to get rid of a lot 7229 // of nasty edge cases: for example if we allowed a non- 7230 // system update of the app to add a library, then uninstalling 7231 // the update would make the library go away, and assumptions 7232 // we made such as through app install filtering would now 7233 // have allowed apps on the device which aren't compatible 7234 // with it. Better to just have the restriction here, be 7235 // conservative, and create many fewer cases that can negatively 7236 // impact the user experience. 7237 final PackageSetting sysPs = mSettings 7238 .getDisabledSystemPkgLPr(pkg.packageName); 7239 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7240 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7241 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7242 allowed = true; 7243 break; 7244 } 7245 } 7246 } 7247 } else { 7248 allowed = true; 7249 } 7250 if (allowed) { 7251 if (!mSharedLibraries.containsKey(name)) { 7252 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7253 } else if (!name.equals(pkg.packageName)) { 7254 Slog.w(TAG, "Package " + pkg.packageName + " library " 7255 + name + " already exists; skipping"); 7256 } 7257 } else { 7258 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7259 + name + " that is not declared on system image; skipping"); 7260 } 7261 } 7262 if ((scanFlags&SCAN_BOOTING) == 0) { 7263 // If we are not booting, we need to update any applications 7264 // that are clients of our shared library. If we are booting, 7265 // this will all be done once the scan is complete. 7266 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7267 } 7268 } 7269 } 7270 } 7271 7272 // We also need to dexopt any apps that are dependent on this library. Note that 7273 // if these fail, we should abort the install since installing the library will 7274 // result in some apps being broken. 7275 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7276 try { 7277 if (clientLibPkgs != null) { 7278 if ((scanFlags & SCAN_NO_DEX) == 0) { 7279 for (int i = 0; i < clientLibPkgs.size(); i++) { 7280 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7281 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7282 null /* instruction sets */, forceDex, 7283 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7284 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7285 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7286 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7287 "scanPackageLI failed to dexopt clientLibPkgs"); 7288 } 7289 } 7290 } 7291 } 7292 } finally { 7293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7294 } 7295 7296 // Request the ActivityManager to kill the process(only for existing packages) 7297 // so that we do not end up in a confused state while the user is still using the older 7298 // version of the application while the new one gets installed. 7299 if ((scanFlags & SCAN_REPLACING) != 0) { 7300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7301 7302 killApplication(pkg.applicationInfo.packageName, 7303 pkg.applicationInfo.uid, "replace pkg"); 7304 7305 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7306 } 7307 7308 // Also need to kill any apps that are dependent on the library. 7309 if (clientLibPkgs != null) { 7310 for (int i=0; i<clientLibPkgs.size(); i++) { 7311 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7312 killApplication(clientPkg.applicationInfo.packageName, 7313 clientPkg.applicationInfo.uid, "update lib"); 7314 } 7315 } 7316 7317 // Make sure we're not adding any bogus keyset info 7318 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7319 ksms.assertScannedPackageValid(pkg); 7320 7321 // writer 7322 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7323 7324 boolean createIdmapFailed = false; 7325 synchronized (mPackages) { 7326 // We don't expect installation to fail beyond this point 7327 7328 // Add the new setting to mSettings 7329 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7330 // Add the new setting to mPackages 7331 mPackages.put(pkg.applicationInfo.packageName, pkg); 7332 // Make sure we don't accidentally delete its data. 7333 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7334 while (iter.hasNext()) { 7335 PackageCleanItem item = iter.next(); 7336 if (pkgName.equals(item.packageName)) { 7337 iter.remove(); 7338 } 7339 } 7340 7341 // Take care of first install / last update times. 7342 if (currentTime != 0) { 7343 if (pkgSetting.firstInstallTime == 0) { 7344 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7345 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7346 pkgSetting.lastUpdateTime = currentTime; 7347 } 7348 } else if (pkgSetting.firstInstallTime == 0) { 7349 // We need *something*. Take time time stamp of the file. 7350 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7351 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7352 if (scanFileTime != pkgSetting.timeStamp) { 7353 // A package on the system image has changed; consider this 7354 // to be an update. 7355 pkgSetting.lastUpdateTime = scanFileTime; 7356 } 7357 } 7358 7359 // Add the package's KeySets to the global KeySetManagerService 7360 ksms.addScannedPackageLPw(pkg); 7361 7362 int N = pkg.providers.size(); 7363 StringBuilder r = null; 7364 int i; 7365 for (i=0; i<N; i++) { 7366 PackageParser.Provider p = pkg.providers.get(i); 7367 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7368 p.info.processName, pkg.applicationInfo.uid); 7369 mProviders.addProvider(p); 7370 p.syncable = p.info.isSyncable; 7371 if (p.info.authority != null) { 7372 String names[] = p.info.authority.split(";"); 7373 p.info.authority = null; 7374 for (int j = 0; j < names.length; j++) { 7375 if (j == 1 && p.syncable) { 7376 // We only want the first authority for a provider to possibly be 7377 // syncable, so if we already added this provider using a different 7378 // authority clear the syncable flag. We copy the provider before 7379 // changing it because the mProviders object contains a reference 7380 // to a provider that we don't want to change. 7381 // Only do this for the second authority since the resulting provider 7382 // object can be the same for all future authorities for this provider. 7383 p = new PackageParser.Provider(p); 7384 p.syncable = false; 7385 } 7386 if (!mProvidersByAuthority.containsKey(names[j])) { 7387 mProvidersByAuthority.put(names[j], p); 7388 if (p.info.authority == null) { 7389 p.info.authority = names[j]; 7390 } else { 7391 p.info.authority = p.info.authority + ";" + names[j]; 7392 } 7393 if (DEBUG_PACKAGE_SCANNING) { 7394 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7395 Log.d(TAG, "Registered content provider: " + names[j] 7396 + ", className = " + p.info.name + ", isSyncable = " 7397 + p.info.isSyncable); 7398 } 7399 } else { 7400 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7401 Slog.w(TAG, "Skipping provider name " + names[j] + 7402 " (in package " + pkg.applicationInfo.packageName + 7403 "): name already used by " 7404 + ((other != null && other.getComponentName() != null) 7405 ? other.getComponentName().getPackageName() : "?")); 7406 } 7407 } 7408 } 7409 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7410 if (r == null) { 7411 r = new StringBuilder(256); 7412 } else { 7413 r.append(' '); 7414 } 7415 r.append(p.info.name); 7416 } 7417 } 7418 if (r != null) { 7419 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7420 } 7421 7422 N = pkg.services.size(); 7423 r = null; 7424 for (i=0; i<N; i++) { 7425 PackageParser.Service s = pkg.services.get(i); 7426 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7427 s.info.processName, pkg.applicationInfo.uid); 7428 mServices.addService(s); 7429 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7430 if (r == null) { 7431 r = new StringBuilder(256); 7432 } else { 7433 r.append(' '); 7434 } 7435 r.append(s.info.name); 7436 } 7437 } 7438 if (r != null) { 7439 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7440 } 7441 7442 N = pkg.receivers.size(); 7443 r = null; 7444 for (i=0; i<N; i++) { 7445 PackageParser.Activity a = pkg.receivers.get(i); 7446 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7447 a.info.processName, pkg.applicationInfo.uid); 7448 mReceivers.addActivity(a, "receiver"); 7449 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7450 if (r == null) { 7451 r = new StringBuilder(256); 7452 } else { 7453 r.append(' '); 7454 } 7455 r.append(a.info.name); 7456 } 7457 } 7458 if (r != null) { 7459 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7460 } 7461 7462 N = pkg.activities.size(); 7463 r = null; 7464 for (i=0; i<N; i++) { 7465 PackageParser.Activity a = pkg.activities.get(i); 7466 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7467 a.info.processName, pkg.applicationInfo.uid); 7468 mActivities.addActivity(a, "activity"); 7469 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7470 if (r == null) { 7471 r = new StringBuilder(256); 7472 } else { 7473 r.append(' '); 7474 } 7475 r.append(a.info.name); 7476 } 7477 } 7478 if (r != null) { 7479 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7480 } 7481 7482 N = pkg.permissionGroups.size(); 7483 r = null; 7484 for (i=0; i<N; i++) { 7485 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7486 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7487 if (cur == null) { 7488 mPermissionGroups.put(pg.info.name, pg); 7489 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7490 if (r == null) { 7491 r = new StringBuilder(256); 7492 } else { 7493 r.append(' '); 7494 } 7495 r.append(pg.info.name); 7496 } 7497 } else { 7498 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7499 + pg.info.packageName + " ignored: original from " 7500 + cur.info.packageName); 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("DUP:"); 7508 r.append(pg.info.name); 7509 } 7510 } 7511 } 7512 if (r != null) { 7513 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7514 } 7515 7516 N = pkg.permissions.size(); 7517 r = null; 7518 for (i=0; i<N; i++) { 7519 PackageParser.Permission p = pkg.permissions.get(i); 7520 7521 // Assume by default that we did not install this permission into the system. 7522 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7523 7524 // Now that permission groups have a special meaning, we ignore permission 7525 // groups for legacy apps to prevent unexpected behavior. In particular, 7526 // permissions for one app being granted to someone just becuase they happen 7527 // to be in a group defined by another app (before this had no implications). 7528 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7529 p.group = mPermissionGroups.get(p.info.group); 7530 // Warn for a permission in an unknown group. 7531 if (p.info.group != null && p.group == null) { 7532 Slog.w(TAG, "Permission " + p.info.name + " from package " 7533 + p.info.packageName + " in an unknown group " + p.info.group); 7534 } 7535 } 7536 7537 ArrayMap<String, BasePermission> permissionMap = 7538 p.tree ? mSettings.mPermissionTrees 7539 : mSettings.mPermissions; 7540 BasePermission bp = permissionMap.get(p.info.name); 7541 7542 // Allow system apps to redefine non-system permissions 7543 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7544 final boolean currentOwnerIsSystem = (bp.perm != null 7545 && isSystemApp(bp.perm.owner)); 7546 if (isSystemApp(p.owner)) { 7547 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7548 // It's a built-in permission and no owner, take ownership now 7549 bp.packageSetting = pkgSetting; 7550 bp.perm = p; 7551 bp.uid = pkg.applicationInfo.uid; 7552 bp.sourcePackage = p.info.packageName; 7553 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7554 } else if (!currentOwnerIsSystem) { 7555 String msg = "New decl " + p.owner + " of permission " 7556 + p.info.name + " is system; overriding " + bp.sourcePackage; 7557 reportSettingsProblem(Log.WARN, msg); 7558 bp = null; 7559 } 7560 } 7561 } 7562 7563 if (bp == null) { 7564 bp = new BasePermission(p.info.name, p.info.packageName, 7565 BasePermission.TYPE_NORMAL); 7566 permissionMap.put(p.info.name, bp); 7567 } 7568 7569 if (bp.perm == null) { 7570 if (bp.sourcePackage == null 7571 || bp.sourcePackage.equals(p.info.packageName)) { 7572 BasePermission tree = findPermissionTreeLP(p.info.name); 7573 if (tree == null 7574 || tree.sourcePackage.equals(p.info.packageName)) { 7575 bp.packageSetting = pkgSetting; 7576 bp.perm = p; 7577 bp.uid = pkg.applicationInfo.uid; 7578 bp.sourcePackage = p.info.packageName; 7579 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7580 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7581 if (r == null) { 7582 r = new StringBuilder(256); 7583 } else { 7584 r.append(' '); 7585 } 7586 r.append(p.info.name); 7587 } 7588 } else { 7589 Slog.w(TAG, "Permission " + p.info.name + " from package " 7590 + p.info.packageName + " ignored: base tree " 7591 + tree.name + " is from package " 7592 + tree.sourcePackage); 7593 } 7594 } else { 7595 Slog.w(TAG, "Permission " + p.info.name + " from package " 7596 + p.info.packageName + " ignored: original from " 7597 + bp.sourcePackage); 7598 } 7599 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7600 if (r == null) { 7601 r = new StringBuilder(256); 7602 } else { 7603 r.append(' '); 7604 } 7605 r.append("DUP:"); 7606 r.append(p.info.name); 7607 } 7608 if (bp.perm == p) { 7609 bp.protectionLevel = p.info.protectionLevel; 7610 } 7611 } 7612 7613 if (r != null) { 7614 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7615 } 7616 7617 N = pkg.instrumentation.size(); 7618 r = null; 7619 for (i=0; i<N; i++) { 7620 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7621 a.info.packageName = pkg.applicationInfo.packageName; 7622 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7623 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7624 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7625 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7626 a.info.dataDir = pkg.applicationInfo.dataDir; 7627 7628 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7629 // need other information about the application, like the ABI and what not ? 7630 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7631 mInstrumentation.put(a.getComponentName(), a); 7632 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7633 if (r == null) { 7634 r = new StringBuilder(256); 7635 } else { 7636 r.append(' '); 7637 } 7638 r.append(a.info.name); 7639 } 7640 } 7641 if (r != null) { 7642 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7643 } 7644 7645 if (pkg.protectedBroadcasts != null) { 7646 N = pkg.protectedBroadcasts.size(); 7647 for (i=0; i<N; i++) { 7648 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7649 } 7650 } 7651 7652 pkgSetting.setTimeStamp(scanFileTime); 7653 7654 // Create idmap files for pairs of (packages, overlay packages). 7655 // Note: "android", ie framework-res.apk, is handled by native layers. 7656 if (pkg.mOverlayTarget != null) { 7657 // This is an overlay package. 7658 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7659 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7660 mOverlays.put(pkg.mOverlayTarget, 7661 new ArrayMap<String, PackageParser.Package>()); 7662 } 7663 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7664 map.put(pkg.packageName, pkg); 7665 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7666 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7667 createIdmapFailed = true; 7668 } 7669 } 7670 } else if (mOverlays.containsKey(pkg.packageName) && 7671 !pkg.packageName.equals("android")) { 7672 // This is a regular package, with one or more known overlay packages. 7673 createIdmapsForPackageLI(pkg); 7674 } 7675 } 7676 7677 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7678 7679 if (createIdmapFailed) { 7680 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7681 "scanPackageLI failed to createIdmap"); 7682 } 7683 return pkg; 7684 } 7685 7686 /** 7687 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7688 * is derived purely on the basis of the contents of {@code scanFile} and 7689 * {@code cpuAbiOverride}. 7690 * 7691 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7692 */ 7693 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7694 String cpuAbiOverride, boolean extractLibs) 7695 throws PackageManagerException { 7696 // TODO: We can probably be smarter about this stuff. For installed apps, 7697 // we can calculate this information at install time once and for all. For 7698 // system apps, we can probably assume that this information doesn't change 7699 // after the first boot scan. As things stand, we do lots of unnecessary work. 7700 7701 // Give ourselves some initial paths; we'll come back for another 7702 // pass once we've determined ABI below. 7703 setNativeLibraryPaths(pkg); 7704 7705 // We would never need to extract libs for forward-locked and external packages, 7706 // since the container service will do it for us. We shouldn't attempt to 7707 // extract libs from system app when it was not updated. 7708 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7709 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7710 extractLibs = false; 7711 } 7712 7713 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7714 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7715 7716 NativeLibraryHelper.Handle handle = null; 7717 try { 7718 handle = NativeLibraryHelper.Handle.create(pkg); 7719 // TODO(multiArch): This can be null for apps that didn't go through the 7720 // usual installation process. We can calculate it again, like we 7721 // do during install time. 7722 // 7723 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7724 // unnecessary. 7725 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7726 7727 // Null out the abis so that they can be recalculated. 7728 pkg.applicationInfo.primaryCpuAbi = null; 7729 pkg.applicationInfo.secondaryCpuAbi = null; 7730 if (isMultiArch(pkg.applicationInfo)) { 7731 // Warn if we've set an abiOverride for multi-lib packages.. 7732 // By definition, we need to copy both 32 and 64 bit libraries for 7733 // such packages. 7734 if (pkg.cpuAbiOverride != null 7735 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7736 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7737 } 7738 7739 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7740 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7741 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7742 if (extractLibs) { 7743 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7744 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7745 useIsaSpecificSubdirs); 7746 } else { 7747 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7748 } 7749 } 7750 7751 maybeThrowExceptionForMultiArchCopy( 7752 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7753 7754 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7755 if (extractLibs) { 7756 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7757 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7758 useIsaSpecificSubdirs); 7759 } else { 7760 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7761 } 7762 } 7763 7764 maybeThrowExceptionForMultiArchCopy( 7765 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7766 7767 if (abi64 >= 0) { 7768 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7769 } 7770 7771 if (abi32 >= 0) { 7772 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7773 if (abi64 >= 0) { 7774 pkg.applicationInfo.secondaryCpuAbi = abi; 7775 } else { 7776 pkg.applicationInfo.primaryCpuAbi = abi; 7777 } 7778 } 7779 } else { 7780 String[] abiList = (cpuAbiOverride != null) ? 7781 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7782 7783 // Enable gross and lame hacks for apps that are built with old 7784 // SDK tools. We must scan their APKs for renderscript bitcode and 7785 // not launch them if it's present. Don't bother checking on devices 7786 // that don't have 64 bit support. 7787 boolean needsRenderScriptOverride = false; 7788 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7789 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7790 abiList = Build.SUPPORTED_32_BIT_ABIS; 7791 needsRenderScriptOverride = true; 7792 } 7793 7794 final int copyRet; 7795 if (extractLibs) { 7796 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7797 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7798 } else { 7799 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7800 } 7801 7802 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7803 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7804 "Error unpackaging native libs for app, errorCode=" + copyRet); 7805 } 7806 7807 if (copyRet >= 0) { 7808 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7809 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7810 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7811 } else if (needsRenderScriptOverride) { 7812 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7813 } 7814 } 7815 } catch (IOException ioe) { 7816 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7817 } finally { 7818 IoUtils.closeQuietly(handle); 7819 } 7820 7821 // Now that we've calculated the ABIs and determined if it's an internal app, 7822 // we will go ahead and populate the nativeLibraryPath. 7823 setNativeLibraryPaths(pkg); 7824 } 7825 7826 /** 7827 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7828 * i.e, so that all packages can be run inside a single process if required. 7829 * 7830 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7831 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7832 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7833 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7834 * updating a package that belongs to a shared user. 7835 * 7836 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7837 * adds unnecessary complexity. 7838 */ 7839 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7840 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7841 boolean bootComplete) { 7842 String requiredInstructionSet = null; 7843 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7844 requiredInstructionSet = VMRuntime.getInstructionSet( 7845 scannedPackage.applicationInfo.primaryCpuAbi); 7846 } 7847 7848 PackageSetting requirer = null; 7849 for (PackageSetting ps : packagesForUser) { 7850 // If packagesForUser contains scannedPackage, we skip it. This will happen 7851 // when scannedPackage is an update of an existing package. Without this check, 7852 // we will never be able to change the ABI of any package belonging to a shared 7853 // user, even if it's compatible with other packages. 7854 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7855 if (ps.primaryCpuAbiString == null) { 7856 continue; 7857 } 7858 7859 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7860 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7861 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7862 // this but there's not much we can do. 7863 String errorMessage = "Instruction set mismatch, " 7864 + ((requirer == null) ? "[caller]" : requirer) 7865 + " requires " + requiredInstructionSet + " whereas " + ps 7866 + " requires " + instructionSet; 7867 Slog.w(TAG, errorMessage); 7868 } 7869 7870 if (requiredInstructionSet == null) { 7871 requiredInstructionSet = instructionSet; 7872 requirer = ps; 7873 } 7874 } 7875 } 7876 7877 if (requiredInstructionSet != null) { 7878 String adjustedAbi; 7879 if (requirer != null) { 7880 // requirer != null implies that either scannedPackage was null or that scannedPackage 7881 // did not require an ABI, in which case we have to adjust scannedPackage to match 7882 // the ABI of the set (which is the same as requirer's ABI) 7883 adjustedAbi = requirer.primaryCpuAbiString; 7884 if (scannedPackage != null) { 7885 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7886 } 7887 } else { 7888 // requirer == null implies that we're updating all ABIs in the set to 7889 // match scannedPackage. 7890 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7891 } 7892 7893 for (PackageSetting ps : packagesForUser) { 7894 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7895 if (ps.primaryCpuAbiString != null) { 7896 continue; 7897 } 7898 7899 ps.primaryCpuAbiString = adjustedAbi; 7900 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7901 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7902 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7903 7904 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7905 7906 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7907 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7908 bootComplete, false /*useJit*/); 7909 7910 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7911 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7912 ps.primaryCpuAbiString = null; 7913 ps.pkg.applicationInfo.primaryCpuAbi = null; 7914 return; 7915 } else { 7916 mInstaller.rmdex(ps.codePathString, 7917 getDexCodeInstructionSet(getPreferredInstructionSet())); 7918 } 7919 } 7920 } 7921 } 7922 } 7923 } 7924 7925 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7926 synchronized (mPackages) { 7927 mResolverReplaced = true; 7928 // Set up information for custom user intent resolution activity. 7929 mResolveActivity.applicationInfo = pkg.applicationInfo; 7930 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7931 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7932 mResolveActivity.processName = pkg.applicationInfo.packageName; 7933 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7934 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7935 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7936 mResolveActivity.theme = 0; 7937 mResolveActivity.exported = true; 7938 mResolveActivity.enabled = true; 7939 mResolveInfo.activityInfo = mResolveActivity; 7940 mResolveInfo.priority = 0; 7941 mResolveInfo.preferredOrder = 0; 7942 mResolveInfo.match = 0; 7943 mResolveComponentName = mCustomResolverComponentName; 7944 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7945 mResolveComponentName); 7946 } 7947 } 7948 7949 private static String calculateBundledApkRoot(final String codePathString) { 7950 final File codePath = new File(codePathString); 7951 final File codeRoot; 7952 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7953 codeRoot = Environment.getRootDirectory(); 7954 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7955 codeRoot = Environment.getOemDirectory(); 7956 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7957 codeRoot = Environment.getVendorDirectory(); 7958 } else { 7959 // Unrecognized code path; take its top real segment as the apk root: 7960 // e.g. /something/app/blah.apk => /something 7961 try { 7962 File f = codePath.getCanonicalFile(); 7963 File parent = f.getParentFile(); // non-null because codePath is a file 7964 File tmp; 7965 while ((tmp = parent.getParentFile()) != null) { 7966 f = parent; 7967 parent = tmp; 7968 } 7969 codeRoot = f; 7970 Slog.w(TAG, "Unrecognized code path " 7971 + codePath + " - using " + codeRoot); 7972 } catch (IOException e) { 7973 // Can't canonicalize the code path -- shenanigans? 7974 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7975 return Environment.getRootDirectory().getPath(); 7976 } 7977 } 7978 return codeRoot.getPath(); 7979 } 7980 7981 /** 7982 * Derive and set the location of native libraries for the given package, 7983 * which varies depending on where and how the package was installed. 7984 */ 7985 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7986 final ApplicationInfo info = pkg.applicationInfo; 7987 final String codePath = pkg.codePath; 7988 final File codeFile = new File(codePath); 7989 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7990 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7991 7992 info.nativeLibraryRootDir = null; 7993 info.nativeLibraryRootRequiresIsa = false; 7994 info.nativeLibraryDir = null; 7995 info.secondaryNativeLibraryDir = null; 7996 7997 if (isApkFile(codeFile)) { 7998 // Monolithic install 7999 if (bundledApp) { 8000 // If "/system/lib64/apkname" exists, assume that is the per-package 8001 // native library directory to use; otherwise use "/system/lib/apkname". 8002 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8003 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8004 getPrimaryInstructionSet(info)); 8005 8006 // This is a bundled system app so choose the path based on the ABI. 8007 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8008 // is just the default path. 8009 final String apkName = deriveCodePathName(codePath); 8010 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8011 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8012 apkName).getAbsolutePath(); 8013 8014 if (info.secondaryCpuAbi != null) { 8015 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8016 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8017 secondaryLibDir, apkName).getAbsolutePath(); 8018 } 8019 } else if (asecApp) { 8020 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8021 .getAbsolutePath(); 8022 } else { 8023 final String apkName = deriveCodePathName(codePath); 8024 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8025 .getAbsolutePath(); 8026 } 8027 8028 info.nativeLibraryRootRequiresIsa = false; 8029 info.nativeLibraryDir = info.nativeLibraryRootDir; 8030 } else { 8031 // Cluster install 8032 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8033 info.nativeLibraryRootRequiresIsa = true; 8034 8035 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8036 getPrimaryInstructionSet(info)).getAbsolutePath(); 8037 8038 if (info.secondaryCpuAbi != null) { 8039 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8040 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8041 } 8042 } 8043 } 8044 8045 /** 8046 * Calculate the abis and roots for a bundled app. These can uniquely 8047 * be determined from the contents of the system partition, i.e whether 8048 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8049 * of this information, and instead assume that the system was built 8050 * sensibly. 8051 */ 8052 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8053 PackageSetting pkgSetting) { 8054 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8055 8056 // If "/system/lib64/apkname" exists, assume that is the per-package 8057 // native library directory to use; otherwise use "/system/lib/apkname". 8058 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8059 setBundledAppAbi(pkg, apkRoot, apkName); 8060 // pkgSetting might be null during rescan following uninstall of updates 8061 // to a bundled app, so accommodate that possibility. The settings in 8062 // that case will be established later from the parsed package. 8063 // 8064 // If the settings aren't null, sync them up with what we've just derived. 8065 // note that apkRoot isn't stored in the package settings. 8066 if (pkgSetting != null) { 8067 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8068 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8069 } 8070 } 8071 8072 /** 8073 * Deduces the ABI of a bundled app and sets the relevant fields on the 8074 * parsed pkg object. 8075 * 8076 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8077 * under which system libraries are installed. 8078 * @param apkName the name of the installed package. 8079 */ 8080 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8081 final File codeFile = new File(pkg.codePath); 8082 8083 final boolean has64BitLibs; 8084 final boolean has32BitLibs; 8085 if (isApkFile(codeFile)) { 8086 // Monolithic install 8087 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8088 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8089 } else { 8090 // Cluster install 8091 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8092 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8093 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8094 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8095 has64BitLibs = (new File(rootDir, isa)).exists(); 8096 } else { 8097 has64BitLibs = false; 8098 } 8099 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8100 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8101 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8102 has32BitLibs = (new File(rootDir, isa)).exists(); 8103 } else { 8104 has32BitLibs = false; 8105 } 8106 } 8107 8108 if (has64BitLibs && !has32BitLibs) { 8109 // The package has 64 bit libs, but not 32 bit libs. Its primary 8110 // ABI should be 64 bit. We can safely assume here that the bundled 8111 // native libraries correspond to the most preferred ABI in the list. 8112 8113 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8114 pkg.applicationInfo.secondaryCpuAbi = null; 8115 } else if (has32BitLibs && !has64BitLibs) { 8116 // The package has 32 bit libs but not 64 bit libs. Its primary 8117 // ABI should be 32 bit. 8118 8119 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8120 pkg.applicationInfo.secondaryCpuAbi = null; 8121 } else if (has32BitLibs && has64BitLibs) { 8122 // The application has both 64 and 32 bit bundled libraries. We check 8123 // here that the app declares multiArch support, and warn if it doesn't. 8124 // 8125 // We will be lenient here and record both ABIs. The primary will be the 8126 // ABI that's higher on the list, i.e, a device that's configured to prefer 8127 // 64 bit apps will see a 64 bit primary ABI, 8128 8129 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8130 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8131 } 8132 8133 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8134 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8135 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8136 } else { 8137 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8138 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8139 } 8140 } else { 8141 pkg.applicationInfo.primaryCpuAbi = null; 8142 pkg.applicationInfo.secondaryCpuAbi = null; 8143 } 8144 } 8145 8146 private void killApplication(String pkgName, int appId, String reason) { 8147 // Request the ActivityManager to kill the process(only for existing packages) 8148 // so that we do not end up in a confused state while the user is still using the older 8149 // version of the application while the new one gets installed. 8150 IActivityManager am = ActivityManagerNative.getDefault(); 8151 if (am != null) { 8152 try { 8153 am.killApplicationWithAppId(pkgName, appId, reason); 8154 } catch (RemoteException e) { 8155 } 8156 } 8157 } 8158 8159 void removePackageLI(PackageSetting ps, boolean chatty) { 8160 if (DEBUG_INSTALL) { 8161 if (chatty) 8162 Log.d(TAG, "Removing package " + ps.name); 8163 } 8164 8165 // writer 8166 synchronized (mPackages) { 8167 mPackages.remove(ps.name); 8168 final PackageParser.Package pkg = ps.pkg; 8169 if (pkg != null) { 8170 cleanPackageDataStructuresLILPw(pkg, chatty); 8171 } 8172 } 8173 } 8174 8175 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8176 if (DEBUG_INSTALL) { 8177 if (chatty) 8178 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8179 } 8180 8181 // writer 8182 synchronized (mPackages) { 8183 mPackages.remove(pkg.applicationInfo.packageName); 8184 cleanPackageDataStructuresLILPw(pkg, chatty); 8185 } 8186 } 8187 8188 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8189 int N = pkg.providers.size(); 8190 StringBuilder r = null; 8191 int i; 8192 for (i=0; i<N; i++) { 8193 PackageParser.Provider p = pkg.providers.get(i); 8194 mProviders.removeProvider(p); 8195 if (p.info.authority == null) { 8196 8197 /* There was another ContentProvider with this authority when 8198 * this app was installed so this authority is null, 8199 * Ignore it as we don't have to unregister the provider. 8200 */ 8201 continue; 8202 } 8203 String names[] = p.info.authority.split(";"); 8204 for (int j = 0; j < names.length; j++) { 8205 if (mProvidersByAuthority.get(names[j]) == p) { 8206 mProvidersByAuthority.remove(names[j]); 8207 if (DEBUG_REMOVE) { 8208 if (chatty) 8209 Log.d(TAG, "Unregistered content provider: " + names[j] 8210 + ", className = " + p.info.name + ", isSyncable = " 8211 + p.info.isSyncable); 8212 } 8213 } 8214 } 8215 if (DEBUG_REMOVE && chatty) { 8216 if (r == null) { 8217 r = new StringBuilder(256); 8218 } else { 8219 r.append(' '); 8220 } 8221 r.append(p.info.name); 8222 } 8223 } 8224 if (r != null) { 8225 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8226 } 8227 8228 N = pkg.services.size(); 8229 r = null; 8230 for (i=0; i<N; i++) { 8231 PackageParser.Service s = pkg.services.get(i); 8232 mServices.removeService(s); 8233 if (chatty) { 8234 if (r == null) { 8235 r = new StringBuilder(256); 8236 } else { 8237 r.append(' '); 8238 } 8239 r.append(s.info.name); 8240 } 8241 } 8242 if (r != null) { 8243 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8244 } 8245 8246 N = pkg.receivers.size(); 8247 r = null; 8248 for (i=0; i<N; i++) { 8249 PackageParser.Activity a = pkg.receivers.get(i); 8250 mReceivers.removeActivity(a, "receiver"); 8251 if (DEBUG_REMOVE && chatty) { 8252 if (r == null) { 8253 r = new StringBuilder(256); 8254 } else { 8255 r.append(' '); 8256 } 8257 r.append(a.info.name); 8258 } 8259 } 8260 if (r != null) { 8261 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8262 } 8263 8264 N = pkg.activities.size(); 8265 r = null; 8266 for (i=0; i<N; i++) { 8267 PackageParser.Activity a = pkg.activities.get(i); 8268 mActivities.removeActivity(a, "activity"); 8269 if (DEBUG_REMOVE && chatty) { 8270 if (r == null) { 8271 r = new StringBuilder(256); 8272 } else { 8273 r.append(' '); 8274 } 8275 r.append(a.info.name); 8276 } 8277 } 8278 if (r != null) { 8279 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8280 } 8281 8282 N = pkg.permissions.size(); 8283 r = null; 8284 for (i=0; i<N; i++) { 8285 PackageParser.Permission p = pkg.permissions.get(i); 8286 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8287 if (bp == null) { 8288 bp = mSettings.mPermissionTrees.get(p.info.name); 8289 } 8290 if (bp != null && bp.perm == p) { 8291 bp.perm = null; 8292 if (DEBUG_REMOVE && chatty) { 8293 if (r == null) { 8294 r = new StringBuilder(256); 8295 } else { 8296 r.append(' '); 8297 } 8298 r.append(p.info.name); 8299 } 8300 } 8301 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8302 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8303 if (appOpPerms != null) { 8304 appOpPerms.remove(pkg.packageName); 8305 } 8306 } 8307 } 8308 if (r != null) { 8309 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8310 } 8311 8312 N = pkg.requestedPermissions.size(); 8313 r = null; 8314 for (i=0; i<N; i++) { 8315 String perm = pkg.requestedPermissions.get(i); 8316 BasePermission bp = mSettings.mPermissions.get(perm); 8317 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8318 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8319 if (appOpPerms != null) { 8320 appOpPerms.remove(pkg.packageName); 8321 if (appOpPerms.isEmpty()) { 8322 mAppOpPermissionPackages.remove(perm); 8323 } 8324 } 8325 } 8326 } 8327 if (r != null) { 8328 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8329 } 8330 8331 N = pkg.instrumentation.size(); 8332 r = null; 8333 for (i=0; i<N; i++) { 8334 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8335 mInstrumentation.remove(a.getComponentName()); 8336 if (DEBUG_REMOVE && chatty) { 8337 if (r == null) { 8338 r = new StringBuilder(256); 8339 } else { 8340 r.append(' '); 8341 } 8342 r.append(a.info.name); 8343 } 8344 } 8345 if (r != null) { 8346 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8347 } 8348 8349 r = null; 8350 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8351 // Only system apps can hold shared libraries. 8352 if (pkg.libraryNames != null) { 8353 for (i=0; i<pkg.libraryNames.size(); i++) { 8354 String name = pkg.libraryNames.get(i); 8355 SharedLibraryEntry cur = mSharedLibraries.get(name); 8356 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8357 mSharedLibraries.remove(name); 8358 if (DEBUG_REMOVE && chatty) { 8359 if (r == null) { 8360 r = new StringBuilder(256); 8361 } else { 8362 r.append(' '); 8363 } 8364 r.append(name); 8365 } 8366 } 8367 } 8368 } 8369 } 8370 if (r != null) { 8371 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8372 } 8373 } 8374 8375 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8376 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8377 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8378 return true; 8379 } 8380 } 8381 return false; 8382 } 8383 8384 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8385 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8386 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8387 8388 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8389 int flags) { 8390 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8391 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8392 } 8393 8394 private void updatePermissionsLPw(String changingPkg, 8395 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8396 // Make sure there are no dangling permission trees. 8397 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8398 while (it.hasNext()) { 8399 final BasePermission bp = it.next(); 8400 if (bp.packageSetting == null) { 8401 // We may not yet have parsed the package, so just see if 8402 // we still know about its settings. 8403 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8404 } 8405 if (bp.packageSetting == null) { 8406 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8407 + " from package " + bp.sourcePackage); 8408 it.remove(); 8409 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8410 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8411 Slog.i(TAG, "Removing old permission tree: " + bp.name 8412 + " from package " + bp.sourcePackage); 8413 flags |= UPDATE_PERMISSIONS_ALL; 8414 it.remove(); 8415 } 8416 } 8417 } 8418 8419 // Make sure all dynamic permissions have been assigned to a package, 8420 // and make sure there are no dangling permissions. 8421 it = mSettings.mPermissions.values().iterator(); 8422 while (it.hasNext()) { 8423 final BasePermission bp = it.next(); 8424 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8425 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8426 + bp.name + " pkg=" + bp.sourcePackage 8427 + " info=" + bp.pendingInfo); 8428 if (bp.packageSetting == null && bp.pendingInfo != null) { 8429 final BasePermission tree = findPermissionTreeLP(bp.name); 8430 if (tree != null && tree.perm != null) { 8431 bp.packageSetting = tree.packageSetting; 8432 bp.perm = new PackageParser.Permission(tree.perm.owner, 8433 new PermissionInfo(bp.pendingInfo)); 8434 bp.perm.info.packageName = tree.perm.info.packageName; 8435 bp.perm.info.name = bp.name; 8436 bp.uid = tree.uid; 8437 } 8438 } 8439 } 8440 if (bp.packageSetting == null) { 8441 // We may not yet have parsed the package, so just see if 8442 // we still know about its settings. 8443 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8444 } 8445 if (bp.packageSetting == null) { 8446 Slog.w(TAG, "Removing dangling permission: " + bp.name 8447 + " from package " + bp.sourcePackage); 8448 it.remove(); 8449 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8450 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8451 Slog.i(TAG, "Removing old permission: " + bp.name 8452 + " from package " + bp.sourcePackage); 8453 flags |= UPDATE_PERMISSIONS_ALL; 8454 it.remove(); 8455 } 8456 } 8457 } 8458 8459 // Now update the permissions for all packages, in particular 8460 // replace the granted permissions of the system packages. 8461 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8462 for (PackageParser.Package pkg : mPackages.values()) { 8463 if (pkg != pkgInfo) { 8464 // Only replace for packages on requested volume 8465 final String volumeUuid = getVolumeUuidForPackage(pkg); 8466 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8467 && Objects.equals(replaceVolumeUuid, volumeUuid); 8468 grantPermissionsLPw(pkg, replace, changingPkg); 8469 } 8470 } 8471 } 8472 8473 if (pkgInfo != null) { 8474 // Only replace for packages on requested volume 8475 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8476 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8477 && Objects.equals(replaceVolumeUuid, volumeUuid); 8478 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8479 } 8480 } 8481 8482 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8483 String packageOfInterest) { 8484 // IMPORTANT: There are two types of permissions: install and runtime. 8485 // Install time permissions are granted when the app is installed to 8486 // all device users and users added in the future. Runtime permissions 8487 // are granted at runtime explicitly to specific users. Normal and signature 8488 // protected permissions are install time permissions. Dangerous permissions 8489 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8490 // otherwise they are runtime permissions. This function does not manage 8491 // runtime permissions except for the case an app targeting Lollipop MR1 8492 // being upgraded to target a newer SDK, in which case dangerous permissions 8493 // are transformed from install time to runtime ones. 8494 8495 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8496 if (ps == null) { 8497 return; 8498 } 8499 8500 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8501 8502 PermissionsState permissionsState = ps.getPermissionsState(); 8503 PermissionsState origPermissions = permissionsState; 8504 8505 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8506 8507 boolean runtimePermissionsRevoked = false; 8508 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8509 8510 boolean changedInstallPermission = false; 8511 8512 if (replace) { 8513 ps.installPermissionsFixed = false; 8514 if (!ps.isSharedUser()) { 8515 origPermissions = new PermissionsState(permissionsState); 8516 permissionsState.reset(); 8517 } else { 8518 // We need to know only about runtime permission changes since the 8519 // calling code always writes the install permissions state but 8520 // the runtime ones are written only if changed. The only cases of 8521 // changed runtime permissions here are promotion of an install to 8522 // runtime and revocation of a runtime from a shared user. 8523 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8524 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8525 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8526 runtimePermissionsRevoked = true; 8527 } 8528 } 8529 } 8530 8531 permissionsState.setGlobalGids(mGlobalGids); 8532 8533 final int N = pkg.requestedPermissions.size(); 8534 for (int i=0; i<N; i++) { 8535 final String name = pkg.requestedPermissions.get(i); 8536 final BasePermission bp = mSettings.mPermissions.get(name); 8537 8538 if (DEBUG_INSTALL) { 8539 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8540 } 8541 8542 if (bp == null || bp.packageSetting == null) { 8543 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8544 Slog.w(TAG, "Unknown permission " + name 8545 + " in package " + pkg.packageName); 8546 } 8547 continue; 8548 } 8549 8550 final String perm = bp.name; 8551 boolean allowedSig = false; 8552 int grant = GRANT_DENIED; 8553 8554 // Keep track of app op permissions. 8555 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8556 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8557 if (pkgs == null) { 8558 pkgs = new ArraySet<>(); 8559 mAppOpPermissionPackages.put(bp.name, pkgs); 8560 } 8561 pkgs.add(pkg.packageName); 8562 } 8563 8564 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8565 switch (level) { 8566 case PermissionInfo.PROTECTION_NORMAL: { 8567 // For all apps normal permissions are install time ones. 8568 grant = GRANT_INSTALL; 8569 } break; 8570 8571 case PermissionInfo.PROTECTION_DANGEROUS: { 8572 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8573 // For legacy apps dangerous permissions are install time ones. 8574 grant = GRANT_INSTALL_LEGACY; 8575 } else if (origPermissions.hasInstallPermission(bp.name)) { 8576 // For legacy apps that became modern, install becomes runtime. 8577 grant = GRANT_UPGRADE; 8578 } else if (mPromoteSystemApps 8579 && isSystemApp(ps) 8580 && mExistingSystemPackages.contains(ps.name)) { 8581 // For legacy system apps, install becomes runtime. 8582 // We cannot check hasInstallPermission() for system apps since those 8583 // permissions were granted implicitly and not persisted pre-M. 8584 grant = GRANT_UPGRADE; 8585 } else { 8586 // For modern apps keep runtime permissions unchanged. 8587 grant = GRANT_RUNTIME; 8588 } 8589 } break; 8590 8591 case PermissionInfo.PROTECTION_SIGNATURE: { 8592 // For all apps signature permissions are install time ones. 8593 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8594 if (allowedSig) { 8595 grant = GRANT_INSTALL; 8596 } 8597 } break; 8598 } 8599 8600 if (DEBUG_INSTALL) { 8601 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8602 } 8603 8604 if (grant != GRANT_DENIED) { 8605 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8606 // If this is an existing, non-system package, then 8607 // we can't add any new permissions to it. 8608 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8609 // Except... if this is a permission that was added 8610 // to the platform (note: need to only do this when 8611 // updating the platform). 8612 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8613 grant = GRANT_DENIED; 8614 } 8615 } 8616 } 8617 8618 switch (grant) { 8619 case GRANT_INSTALL: { 8620 // Revoke this as runtime permission to handle the case of 8621 // a runtime permission being downgraded to an install one. 8622 for (int userId : UserManagerService.getInstance().getUserIds()) { 8623 if (origPermissions.getRuntimePermissionState( 8624 bp.name, userId) != null) { 8625 // Revoke the runtime permission and clear the flags. 8626 origPermissions.revokeRuntimePermission(bp, userId); 8627 origPermissions.updatePermissionFlags(bp, userId, 8628 PackageManager.MASK_PERMISSION_FLAGS, 0); 8629 // If we revoked a permission permission, we have to write. 8630 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8631 changedRuntimePermissionUserIds, userId); 8632 } 8633 } 8634 // Grant an install permission. 8635 if (permissionsState.grantInstallPermission(bp) != 8636 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8637 changedInstallPermission = true; 8638 } 8639 } break; 8640 8641 case GRANT_INSTALL_LEGACY: { 8642 // Grant an install permission. 8643 if (permissionsState.grantInstallPermission(bp) != 8644 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8645 changedInstallPermission = true; 8646 } 8647 } break; 8648 8649 case GRANT_RUNTIME: { 8650 // Grant previously granted runtime permissions. 8651 for (int userId : UserManagerService.getInstance().getUserIds()) { 8652 PermissionState permissionState = origPermissions 8653 .getRuntimePermissionState(bp.name, userId); 8654 final int flags = permissionState != null 8655 ? permissionState.getFlags() : 0; 8656 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8657 if (permissionsState.grantRuntimePermission(bp, userId) == 8658 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8659 // If we cannot put the permission as it was, we have to write. 8660 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8661 changedRuntimePermissionUserIds, userId); 8662 } 8663 } 8664 // Propagate the permission flags. 8665 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8666 } 8667 } break; 8668 8669 case GRANT_UPGRADE: { 8670 // Grant runtime permissions for a previously held install permission. 8671 PermissionState permissionState = origPermissions 8672 .getInstallPermissionState(bp.name); 8673 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8674 8675 if (origPermissions.revokeInstallPermission(bp) 8676 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8677 // We will be transferring the permission flags, so clear them. 8678 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8679 PackageManager.MASK_PERMISSION_FLAGS, 0); 8680 changedInstallPermission = true; 8681 } 8682 8683 // If the permission is not to be promoted to runtime we ignore it and 8684 // also its other flags as they are not applicable to install permissions. 8685 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8686 for (int userId : currentUserIds) { 8687 if (permissionsState.grantRuntimePermission(bp, userId) != 8688 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8689 // Transfer the permission flags. 8690 permissionsState.updatePermissionFlags(bp, userId, 8691 flags, flags); 8692 // If we granted the permission, we have to write. 8693 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8694 changedRuntimePermissionUserIds, userId); 8695 } 8696 } 8697 } 8698 } break; 8699 8700 default: { 8701 if (packageOfInterest == null 8702 || packageOfInterest.equals(pkg.packageName)) { 8703 Slog.w(TAG, "Not granting permission " + perm 8704 + " to package " + pkg.packageName 8705 + " because it was previously installed without"); 8706 } 8707 } break; 8708 } 8709 } else { 8710 if (permissionsState.revokeInstallPermission(bp) != 8711 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8712 // Also drop the permission flags. 8713 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8714 PackageManager.MASK_PERMISSION_FLAGS, 0); 8715 changedInstallPermission = true; 8716 Slog.i(TAG, "Un-granting permission " + perm 8717 + " from package " + pkg.packageName 8718 + " (protectionLevel=" + bp.protectionLevel 8719 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8720 + ")"); 8721 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8722 // Don't print warning for app op permissions, since it is fine for them 8723 // not to be granted, there is a UI for the user to decide. 8724 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8725 Slog.w(TAG, "Not granting permission " + perm 8726 + " to package " + pkg.packageName 8727 + " (protectionLevel=" + bp.protectionLevel 8728 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8729 + ")"); 8730 } 8731 } 8732 } 8733 } 8734 8735 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8736 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8737 // This is the first that we have heard about this package, so the 8738 // permissions we have now selected are fixed until explicitly 8739 // changed. 8740 ps.installPermissionsFixed = true; 8741 } 8742 8743 // Persist the runtime permissions state for users with changes. If permissions 8744 // were revoked because no app in the shared user declares them we have to 8745 // write synchronously to avoid losing runtime permissions state. 8746 for (int userId : changedRuntimePermissionUserIds) { 8747 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8748 } 8749 8750 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8751 } 8752 8753 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8754 boolean allowed = false; 8755 final int NP = PackageParser.NEW_PERMISSIONS.length; 8756 for (int ip=0; ip<NP; ip++) { 8757 final PackageParser.NewPermissionInfo npi 8758 = PackageParser.NEW_PERMISSIONS[ip]; 8759 if (npi.name.equals(perm) 8760 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8761 allowed = true; 8762 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8763 + pkg.packageName); 8764 break; 8765 } 8766 } 8767 return allowed; 8768 } 8769 8770 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8771 BasePermission bp, PermissionsState origPermissions) { 8772 boolean allowed; 8773 allowed = (compareSignatures( 8774 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8775 == PackageManager.SIGNATURE_MATCH) 8776 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8777 == PackageManager.SIGNATURE_MATCH); 8778 if (!allowed && (bp.protectionLevel 8779 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8780 if (isSystemApp(pkg)) { 8781 // For updated system applications, a system permission 8782 // is granted only if it had been defined by the original application. 8783 if (pkg.isUpdatedSystemApp()) { 8784 final PackageSetting sysPs = mSettings 8785 .getDisabledSystemPkgLPr(pkg.packageName); 8786 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8787 // If the original was granted this permission, we take 8788 // that grant decision as read and propagate it to the 8789 // update. 8790 if (sysPs.isPrivileged()) { 8791 allowed = true; 8792 } 8793 } else { 8794 // The system apk may have been updated with an older 8795 // version of the one on the data partition, but which 8796 // granted a new system permission that it didn't have 8797 // before. In this case we do want to allow the app to 8798 // now get the new permission if the ancestral apk is 8799 // privileged to get it. 8800 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8801 for (int j=0; 8802 j<sysPs.pkg.requestedPermissions.size(); j++) { 8803 if (perm.equals( 8804 sysPs.pkg.requestedPermissions.get(j))) { 8805 allowed = true; 8806 break; 8807 } 8808 } 8809 } 8810 } 8811 } else { 8812 allowed = isPrivilegedApp(pkg); 8813 } 8814 } 8815 } 8816 if (!allowed) { 8817 if (!allowed && (bp.protectionLevel 8818 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8819 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8820 // If this was a previously normal/dangerous permission that got moved 8821 // to a system permission as part of the runtime permission redesign, then 8822 // we still want to blindly grant it to old apps. 8823 allowed = true; 8824 } 8825 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8826 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8827 // If this permission is to be granted to the system installer and 8828 // this app is an installer, then it gets the permission. 8829 allowed = true; 8830 } 8831 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8832 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8833 // If this permission is to be granted to the system verifier and 8834 // this app is a verifier, then it gets the permission. 8835 allowed = true; 8836 } 8837 if (!allowed && (bp.protectionLevel 8838 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8839 && isSystemApp(pkg)) { 8840 // Any pre-installed system app is allowed to get this permission. 8841 allowed = true; 8842 } 8843 if (!allowed && (bp.protectionLevel 8844 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8845 // For development permissions, a development permission 8846 // is granted only if it was already granted. 8847 allowed = origPermissions.hasInstallPermission(perm); 8848 } 8849 } 8850 return allowed; 8851 } 8852 8853 final class ActivityIntentResolver 8854 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8855 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8856 boolean defaultOnly, int userId) { 8857 if (!sUserManager.exists(userId)) return null; 8858 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8859 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8860 } 8861 8862 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8863 int userId) { 8864 if (!sUserManager.exists(userId)) return null; 8865 mFlags = flags; 8866 return super.queryIntent(intent, resolvedType, 8867 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8868 } 8869 8870 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8871 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8872 if (!sUserManager.exists(userId)) return null; 8873 if (packageActivities == null) { 8874 return null; 8875 } 8876 mFlags = flags; 8877 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8878 final int N = packageActivities.size(); 8879 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8880 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8881 8882 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8883 for (int i = 0; i < N; ++i) { 8884 intentFilters = packageActivities.get(i).intents; 8885 if (intentFilters != null && intentFilters.size() > 0) { 8886 PackageParser.ActivityIntentInfo[] array = 8887 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8888 intentFilters.toArray(array); 8889 listCut.add(array); 8890 } 8891 } 8892 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8893 } 8894 8895 public final void addActivity(PackageParser.Activity a, String type) { 8896 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8897 mActivities.put(a.getComponentName(), a); 8898 if (DEBUG_SHOW_INFO) 8899 Log.v( 8900 TAG, " " + type + " " + 8901 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8902 if (DEBUG_SHOW_INFO) 8903 Log.v(TAG, " Class=" + a.info.name); 8904 final int NI = a.intents.size(); 8905 for (int j=0; j<NI; j++) { 8906 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8907 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8908 intent.setPriority(0); 8909 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8910 + a.className + " with priority > 0, forcing to 0"); 8911 } 8912 if (DEBUG_SHOW_INFO) { 8913 Log.v(TAG, " IntentFilter:"); 8914 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8915 } 8916 if (!intent.debugCheck()) { 8917 Log.w(TAG, "==> For Activity " + a.info.name); 8918 } 8919 addFilter(intent); 8920 } 8921 } 8922 8923 public final void removeActivity(PackageParser.Activity a, String type) { 8924 mActivities.remove(a.getComponentName()); 8925 if (DEBUG_SHOW_INFO) { 8926 Log.v(TAG, " " + type + " " 8927 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8928 : a.info.name) + ":"); 8929 Log.v(TAG, " Class=" + a.info.name); 8930 } 8931 final int NI = a.intents.size(); 8932 for (int j=0; j<NI; j++) { 8933 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8934 if (DEBUG_SHOW_INFO) { 8935 Log.v(TAG, " IntentFilter:"); 8936 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8937 } 8938 removeFilter(intent); 8939 } 8940 } 8941 8942 @Override 8943 protected boolean allowFilterResult( 8944 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8945 ActivityInfo filterAi = filter.activity.info; 8946 for (int i=dest.size()-1; i>=0; i--) { 8947 ActivityInfo destAi = dest.get(i).activityInfo; 8948 if (destAi.name == filterAi.name 8949 && destAi.packageName == filterAi.packageName) { 8950 return false; 8951 } 8952 } 8953 return true; 8954 } 8955 8956 @Override 8957 protected ActivityIntentInfo[] newArray(int size) { 8958 return new ActivityIntentInfo[size]; 8959 } 8960 8961 @Override 8962 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8963 if (!sUserManager.exists(userId)) return true; 8964 PackageParser.Package p = filter.activity.owner; 8965 if (p != null) { 8966 PackageSetting ps = (PackageSetting)p.mExtras; 8967 if (ps != null) { 8968 // System apps are never considered stopped for purposes of 8969 // filtering, because there may be no way for the user to 8970 // actually re-launch them. 8971 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8972 && ps.getStopped(userId); 8973 } 8974 } 8975 return false; 8976 } 8977 8978 @Override 8979 protected boolean isPackageForFilter(String packageName, 8980 PackageParser.ActivityIntentInfo info) { 8981 return packageName.equals(info.activity.owner.packageName); 8982 } 8983 8984 @Override 8985 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8986 int match, int userId) { 8987 if (!sUserManager.exists(userId)) return null; 8988 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8989 return null; 8990 } 8991 final PackageParser.Activity activity = info.activity; 8992 if (mSafeMode && (activity.info.applicationInfo.flags 8993 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8994 return null; 8995 } 8996 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8997 if (ps == null) { 8998 return null; 8999 } 9000 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9001 ps.readUserState(userId), userId); 9002 if (ai == null) { 9003 return null; 9004 } 9005 final ResolveInfo res = new ResolveInfo(); 9006 res.activityInfo = ai; 9007 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9008 res.filter = info; 9009 } 9010 if (info != null) { 9011 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9012 } 9013 res.priority = info.getPriority(); 9014 res.preferredOrder = activity.owner.mPreferredOrder; 9015 //System.out.println("Result: " + res.activityInfo.className + 9016 // " = " + res.priority); 9017 res.match = match; 9018 res.isDefault = info.hasDefault; 9019 res.labelRes = info.labelRes; 9020 res.nonLocalizedLabel = info.nonLocalizedLabel; 9021 if (userNeedsBadging(userId)) { 9022 res.noResourceId = true; 9023 } else { 9024 res.icon = info.icon; 9025 } 9026 res.iconResourceId = info.icon; 9027 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9028 return res; 9029 } 9030 9031 @Override 9032 protected void sortResults(List<ResolveInfo> results) { 9033 Collections.sort(results, mResolvePrioritySorter); 9034 } 9035 9036 @Override 9037 protected void dumpFilter(PrintWriter out, String prefix, 9038 PackageParser.ActivityIntentInfo filter) { 9039 out.print(prefix); out.print( 9040 Integer.toHexString(System.identityHashCode(filter.activity))); 9041 out.print(' '); 9042 filter.activity.printComponentShortName(out); 9043 out.print(" filter "); 9044 out.println(Integer.toHexString(System.identityHashCode(filter))); 9045 } 9046 9047 @Override 9048 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9049 return filter.activity; 9050 } 9051 9052 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9053 PackageParser.Activity activity = (PackageParser.Activity)label; 9054 out.print(prefix); out.print( 9055 Integer.toHexString(System.identityHashCode(activity))); 9056 out.print(' '); 9057 activity.printComponentShortName(out); 9058 if (count > 1) { 9059 out.print(" ("); out.print(count); out.print(" filters)"); 9060 } 9061 out.println(); 9062 } 9063 9064// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9065// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9066// final List<ResolveInfo> retList = Lists.newArrayList(); 9067// while (i.hasNext()) { 9068// final ResolveInfo resolveInfo = i.next(); 9069// if (isEnabledLP(resolveInfo.activityInfo)) { 9070// retList.add(resolveInfo); 9071// } 9072// } 9073// return retList; 9074// } 9075 9076 // Keys are String (activity class name), values are Activity. 9077 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9078 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9079 private int mFlags; 9080 } 9081 9082 private final class ServiceIntentResolver 9083 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9084 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9085 boolean defaultOnly, int userId) { 9086 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9087 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9088 } 9089 9090 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9091 int userId) { 9092 if (!sUserManager.exists(userId)) return null; 9093 mFlags = flags; 9094 return super.queryIntent(intent, resolvedType, 9095 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9096 } 9097 9098 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9099 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9100 if (!sUserManager.exists(userId)) return null; 9101 if (packageServices == null) { 9102 return null; 9103 } 9104 mFlags = flags; 9105 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9106 final int N = packageServices.size(); 9107 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9108 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9109 9110 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9111 for (int i = 0; i < N; ++i) { 9112 intentFilters = packageServices.get(i).intents; 9113 if (intentFilters != null && intentFilters.size() > 0) { 9114 PackageParser.ServiceIntentInfo[] array = 9115 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9116 intentFilters.toArray(array); 9117 listCut.add(array); 9118 } 9119 } 9120 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9121 } 9122 9123 public final void addService(PackageParser.Service s) { 9124 mServices.put(s.getComponentName(), s); 9125 if (DEBUG_SHOW_INFO) { 9126 Log.v(TAG, " " 9127 + (s.info.nonLocalizedLabel != null 9128 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9129 Log.v(TAG, " Class=" + s.info.name); 9130 } 9131 final int NI = s.intents.size(); 9132 int j; 9133 for (j=0; j<NI; j++) { 9134 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9135 if (DEBUG_SHOW_INFO) { 9136 Log.v(TAG, " IntentFilter:"); 9137 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9138 } 9139 if (!intent.debugCheck()) { 9140 Log.w(TAG, "==> For Service " + s.info.name); 9141 } 9142 addFilter(intent); 9143 } 9144 } 9145 9146 public final void removeService(PackageParser.Service s) { 9147 mServices.remove(s.getComponentName()); 9148 if (DEBUG_SHOW_INFO) { 9149 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9150 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9151 Log.v(TAG, " Class=" + s.info.name); 9152 } 9153 final int NI = s.intents.size(); 9154 int j; 9155 for (j=0; j<NI; j++) { 9156 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9157 if (DEBUG_SHOW_INFO) { 9158 Log.v(TAG, " IntentFilter:"); 9159 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9160 } 9161 removeFilter(intent); 9162 } 9163 } 9164 9165 @Override 9166 protected boolean allowFilterResult( 9167 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9168 ServiceInfo filterSi = filter.service.info; 9169 for (int i=dest.size()-1; i>=0; i--) { 9170 ServiceInfo destAi = dest.get(i).serviceInfo; 9171 if (destAi.name == filterSi.name 9172 && destAi.packageName == filterSi.packageName) { 9173 return false; 9174 } 9175 } 9176 return true; 9177 } 9178 9179 @Override 9180 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9181 return new PackageParser.ServiceIntentInfo[size]; 9182 } 9183 9184 @Override 9185 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9186 if (!sUserManager.exists(userId)) return true; 9187 PackageParser.Package p = filter.service.owner; 9188 if (p != null) { 9189 PackageSetting ps = (PackageSetting)p.mExtras; 9190 if (ps != null) { 9191 // System apps are never considered stopped for purposes of 9192 // filtering, because there may be no way for the user to 9193 // actually re-launch them. 9194 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9195 && ps.getStopped(userId); 9196 } 9197 } 9198 return false; 9199 } 9200 9201 @Override 9202 protected boolean isPackageForFilter(String packageName, 9203 PackageParser.ServiceIntentInfo info) { 9204 return packageName.equals(info.service.owner.packageName); 9205 } 9206 9207 @Override 9208 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9209 int match, int userId) { 9210 if (!sUserManager.exists(userId)) return null; 9211 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9212 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9213 return null; 9214 } 9215 final PackageParser.Service service = info.service; 9216 if (mSafeMode && (service.info.applicationInfo.flags 9217 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9218 return null; 9219 } 9220 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9221 if (ps == null) { 9222 return null; 9223 } 9224 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9225 ps.readUserState(userId), userId); 9226 if (si == null) { 9227 return null; 9228 } 9229 final ResolveInfo res = new ResolveInfo(); 9230 res.serviceInfo = si; 9231 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9232 res.filter = filter; 9233 } 9234 res.priority = info.getPriority(); 9235 res.preferredOrder = service.owner.mPreferredOrder; 9236 res.match = match; 9237 res.isDefault = info.hasDefault; 9238 res.labelRes = info.labelRes; 9239 res.nonLocalizedLabel = info.nonLocalizedLabel; 9240 res.icon = info.icon; 9241 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9242 return res; 9243 } 9244 9245 @Override 9246 protected void sortResults(List<ResolveInfo> results) { 9247 Collections.sort(results, mResolvePrioritySorter); 9248 } 9249 9250 @Override 9251 protected void dumpFilter(PrintWriter out, String prefix, 9252 PackageParser.ServiceIntentInfo filter) { 9253 out.print(prefix); out.print( 9254 Integer.toHexString(System.identityHashCode(filter.service))); 9255 out.print(' '); 9256 filter.service.printComponentShortName(out); 9257 out.print(" filter "); 9258 out.println(Integer.toHexString(System.identityHashCode(filter))); 9259 } 9260 9261 @Override 9262 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9263 return filter.service; 9264 } 9265 9266 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9267 PackageParser.Service service = (PackageParser.Service)label; 9268 out.print(prefix); out.print( 9269 Integer.toHexString(System.identityHashCode(service))); 9270 out.print(' '); 9271 service.printComponentShortName(out); 9272 if (count > 1) { 9273 out.print(" ("); out.print(count); out.print(" filters)"); 9274 } 9275 out.println(); 9276 } 9277 9278// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9279// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9280// final List<ResolveInfo> retList = Lists.newArrayList(); 9281// while (i.hasNext()) { 9282// final ResolveInfo resolveInfo = (ResolveInfo) i; 9283// if (isEnabledLP(resolveInfo.serviceInfo)) { 9284// retList.add(resolveInfo); 9285// } 9286// } 9287// return retList; 9288// } 9289 9290 // Keys are String (activity class name), values are Activity. 9291 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9292 = new ArrayMap<ComponentName, PackageParser.Service>(); 9293 private int mFlags; 9294 }; 9295 9296 private final class ProviderIntentResolver 9297 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9298 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9299 boolean defaultOnly, int userId) { 9300 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9301 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9302 } 9303 9304 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9305 int userId) { 9306 if (!sUserManager.exists(userId)) 9307 return null; 9308 mFlags = flags; 9309 return super.queryIntent(intent, resolvedType, 9310 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9311 } 9312 9313 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9314 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9315 if (!sUserManager.exists(userId)) 9316 return null; 9317 if (packageProviders == null) { 9318 return null; 9319 } 9320 mFlags = flags; 9321 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9322 final int N = packageProviders.size(); 9323 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9324 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9325 9326 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9327 for (int i = 0; i < N; ++i) { 9328 intentFilters = packageProviders.get(i).intents; 9329 if (intentFilters != null && intentFilters.size() > 0) { 9330 PackageParser.ProviderIntentInfo[] array = 9331 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9332 intentFilters.toArray(array); 9333 listCut.add(array); 9334 } 9335 } 9336 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9337 } 9338 9339 public final void addProvider(PackageParser.Provider p) { 9340 if (mProviders.containsKey(p.getComponentName())) { 9341 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9342 return; 9343 } 9344 9345 mProviders.put(p.getComponentName(), p); 9346 if (DEBUG_SHOW_INFO) { 9347 Log.v(TAG, " " 9348 + (p.info.nonLocalizedLabel != null 9349 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9350 Log.v(TAG, " Class=" + p.info.name); 9351 } 9352 final int NI = p.intents.size(); 9353 int j; 9354 for (j = 0; j < NI; j++) { 9355 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9356 if (DEBUG_SHOW_INFO) { 9357 Log.v(TAG, " IntentFilter:"); 9358 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9359 } 9360 if (!intent.debugCheck()) { 9361 Log.w(TAG, "==> For Provider " + p.info.name); 9362 } 9363 addFilter(intent); 9364 } 9365 } 9366 9367 public final void removeProvider(PackageParser.Provider p) { 9368 mProviders.remove(p.getComponentName()); 9369 if (DEBUG_SHOW_INFO) { 9370 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9371 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9372 Log.v(TAG, " Class=" + p.info.name); 9373 } 9374 final int NI = p.intents.size(); 9375 int j; 9376 for (j = 0; j < NI; j++) { 9377 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9378 if (DEBUG_SHOW_INFO) { 9379 Log.v(TAG, " IntentFilter:"); 9380 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9381 } 9382 removeFilter(intent); 9383 } 9384 } 9385 9386 @Override 9387 protected boolean allowFilterResult( 9388 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9389 ProviderInfo filterPi = filter.provider.info; 9390 for (int i = dest.size() - 1; i >= 0; i--) { 9391 ProviderInfo destPi = dest.get(i).providerInfo; 9392 if (destPi.name == filterPi.name 9393 && destPi.packageName == filterPi.packageName) { 9394 return false; 9395 } 9396 } 9397 return true; 9398 } 9399 9400 @Override 9401 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9402 return new PackageParser.ProviderIntentInfo[size]; 9403 } 9404 9405 @Override 9406 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9407 if (!sUserManager.exists(userId)) 9408 return true; 9409 PackageParser.Package p = filter.provider.owner; 9410 if (p != null) { 9411 PackageSetting ps = (PackageSetting) p.mExtras; 9412 if (ps != null) { 9413 // System apps are never considered stopped for purposes of 9414 // filtering, because there may be no way for the user to 9415 // actually re-launch them. 9416 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9417 && ps.getStopped(userId); 9418 } 9419 } 9420 return false; 9421 } 9422 9423 @Override 9424 protected boolean isPackageForFilter(String packageName, 9425 PackageParser.ProviderIntentInfo info) { 9426 return packageName.equals(info.provider.owner.packageName); 9427 } 9428 9429 @Override 9430 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9431 int match, int userId) { 9432 if (!sUserManager.exists(userId)) 9433 return null; 9434 final PackageParser.ProviderIntentInfo info = filter; 9435 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9436 return null; 9437 } 9438 final PackageParser.Provider provider = info.provider; 9439 if (mSafeMode && (provider.info.applicationInfo.flags 9440 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9441 return null; 9442 } 9443 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9444 if (ps == null) { 9445 return null; 9446 } 9447 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9448 ps.readUserState(userId), userId); 9449 if (pi == null) { 9450 return null; 9451 } 9452 final ResolveInfo res = new ResolveInfo(); 9453 res.providerInfo = pi; 9454 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9455 res.filter = filter; 9456 } 9457 res.priority = info.getPriority(); 9458 res.preferredOrder = provider.owner.mPreferredOrder; 9459 res.match = match; 9460 res.isDefault = info.hasDefault; 9461 res.labelRes = info.labelRes; 9462 res.nonLocalizedLabel = info.nonLocalizedLabel; 9463 res.icon = info.icon; 9464 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9465 return res; 9466 } 9467 9468 @Override 9469 protected void sortResults(List<ResolveInfo> results) { 9470 Collections.sort(results, mResolvePrioritySorter); 9471 } 9472 9473 @Override 9474 protected void dumpFilter(PrintWriter out, String prefix, 9475 PackageParser.ProviderIntentInfo filter) { 9476 out.print(prefix); 9477 out.print( 9478 Integer.toHexString(System.identityHashCode(filter.provider))); 9479 out.print(' '); 9480 filter.provider.printComponentShortName(out); 9481 out.print(" filter "); 9482 out.println(Integer.toHexString(System.identityHashCode(filter))); 9483 } 9484 9485 @Override 9486 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9487 return filter.provider; 9488 } 9489 9490 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9491 PackageParser.Provider provider = (PackageParser.Provider)label; 9492 out.print(prefix); out.print( 9493 Integer.toHexString(System.identityHashCode(provider))); 9494 out.print(' '); 9495 provider.printComponentShortName(out); 9496 if (count > 1) { 9497 out.print(" ("); out.print(count); out.print(" filters)"); 9498 } 9499 out.println(); 9500 } 9501 9502 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9503 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9504 private int mFlags; 9505 }; 9506 9507 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9508 new Comparator<ResolveInfo>() { 9509 public int compare(ResolveInfo r1, ResolveInfo r2) { 9510 int v1 = r1.priority; 9511 int v2 = r2.priority; 9512 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9513 if (v1 != v2) { 9514 return (v1 > v2) ? -1 : 1; 9515 } 9516 v1 = r1.preferredOrder; 9517 v2 = r2.preferredOrder; 9518 if (v1 != v2) { 9519 return (v1 > v2) ? -1 : 1; 9520 } 9521 if (r1.isDefault != r2.isDefault) { 9522 return r1.isDefault ? -1 : 1; 9523 } 9524 v1 = r1.match; 9525 v2 = r2.match; 9526 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9527 if (v1 != v2) { 9528 return (v1 > v2) ? -1 : 1; 9529 } 9530 if (r1.system != r2.system) { 9531 return r1.system ? -1 : 1; 9532 } 9533 return 0; 9534 } 9535 }; 9536 9537 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9538 new Comparator<ProviderInfo>() { 9539 public int compare(ProviderInfo p1, ProviderInfo p2) { 9540 final int v1 = p1.initOrder; 9541 final int v2 = p2.initOrder; 9542 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9543 } 9544 }; 9545 9546 final void sendPackageBroadcast(final String action, final String pkg, 9547 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9548 final int[] userIds) { 9549 mHandler.post(new Runnable() { 9550 @Override 9551 public void run() { 9552 try { 9553 final IActivityManager am = ActivityManagerNative.getDefault(); 9554 if (am == null) return; 9555 final int[] resolvedUserIds; 9556 if (userIds == null) { 9557 resolvedUserIds = am.getRunningUserIds(); 9558 } else { 9559 resolvedUserIds = userIds; 9560 } 9561 for (int id : resolvedUserIds) { 9562 final Intent intent = new Intent(action, 9563 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9564 if (extras != null) { 9565 intent.putExtras(extras); 9566 } 9567 if (targetPkg != null) { 9568 intent.setPackage(targetPkg); 9569 } 9570 // Modify the UID when posting to other users 9571 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9572 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9573 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9574 intent.putExtra(Intent.EXTRA_UID, uid); 9575 } 9576 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9577 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9578 if (DEBUG_BROADCASTS) { 9579 RuntimeException here = new RuntimeException("here"); 9580 here.fillInStackTrace(); 9581 Slog.d(TAG, "Sending to user " + id + ": " 9582 + intent.toShortString(false, true, false, false) 9583 + " " + intent.getExtras(), here); 9584 } 9585 am.broadcastIntent(null, intent, null, finishedReceiver, 9586 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9587 null, finishedReceiver != null, false, id); 9588 } 9589 } catch (RemoteException ex) { 9590 } 9591 } 9592 }); 9593 } 9594 9595 /** 9596 * Check if the external storage media is available. This is true if there 9597 * is a mounted external storage medium or if the external storage is 9598 * emulated. 9599 */ 9600 private boolean isExternalMediaAvailable() { 9601 return mMediaMounted || Environment.isExternalStorageEmulated(); 9602 } 9603 9604 @Override 9605 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9606 // writer 9607 synchronized (mPackages) { 9608 if (!isExternalMediaAvailable()) { 9609 // If the external storage is no longer mounted at this point, 9610 // the caller may not have been able to delete all of this 9611 // packages files and can not delete any more. Bail. 9612 return null; 9613 } 9614 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9615 if (lastPackage != null) { 9616 pkgs.remove(lastPackage); 9617 } 9618 if (pkgs.size() > 0) { 9619 return pkgs.get(0); 9620 } 9621 } 9622 return null; 9623 } 9624 9625 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9626 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9627 userId, andCode ? 1 : 0, packageName); 9628 if (mSystemReady) { 9629 msg.sendToTarget(); 9630 } else { 9631 if (mPostSystemReadyMessages == null) { 9632 mPostSystemReadyMessages = new ArrayList<>(); 9633 } 9634 mPostSystemReadyMessages.add(msg); 9635 } 9636 } 9637 9638 void startCleaningPackages() { 9639 // reader 9640 synchronized (mPackages) { 9641 if (!isExternalMediaAvailable()) { 9642 return; 9643 } 9644 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9645 return; 9646 } 9647 } 9648 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9649 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9650 IActivityManager am = ActivityManagerNative.getDefault(); 9651 if (am != null) { 9652 try { 9653 am.startService(null, intent, null, mContext.getOpPackageName(), 9654 UserHandle.USER_SYSTEM); 9655 } catch (RemoteException e) { 9656 } 9657 } 9658 } 9659 9660 @Override 9661 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9662 int installFlags, String installerPackageName, VerificationParams verificationParams, 9663 String packageAbiOverride) { 9664 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9665 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9666 } 9667 9668 @Override 9669 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9670 int installFlags, String installerPackageName, VerificationParams verificationParams, 9671 String packageAbiOverride, int userId) { 9672 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9673 9674 final int callingUid = Binder.getCallingUid(); 9675 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9676 9677 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9678 try { 9679 if (observer != null) { 9680 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9681 } 9682 } catch (RemoteException re) { 9683 } 9684 return; 9685 } 9686 9687 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9688 installFlags |= PackageManager.INSTALL_FROM_ADB; 9689 9690 } else { 9691 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9692 // about installerPackageName. 9693 9694 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9695 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9696 } 9697 9698 UserHandle user; 9699 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9700 user = UserHandle.ALL; 9701 } else { 9702 user = new UserHandle(userId); 9703 } 9704 9705 // Only system components can circumvent runtime permissions when installing. 9706 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9707 && mContext.checkCallingOrSelfPermission(Manifest.permission 9708 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9709 throw new SecurityException("You need the " 9710 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9711 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9712 } 9713 9714 verificationParams.setInstallerUid(callingUid); 9715 9716 final File originFile = new File(originPath); 9717 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9718 9719 final Message msg = mHandler.obtainMessage(INIT_COPY); 9720 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9721 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9722 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9723 msg.obj = params; 9724 9725 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9726 System.identityHashCode(msg.obj)); 9727 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9728 System.identityHashCode(msg.obj)); 9729 9730 mHandler.sendMessage(msg); 9731 } 9732 9733 void installStage(String packageName, File stagedDir, String stagedCid, 9734 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9735 String installerPackageName, int installerUid, UserHandle user) { 9736 final VerificationParams verifParams = new VerificationParams( 9737 null, sessionParams.originatingUri, sessionParams.referrerUri, 9738 sessionParams.originatingUid, null); 9739 verifParams.setInstallerUid(installerUid); 9740 9741 final OriginInfo origin; 9742 if (stagedDir != null) { 9743 origin = OriginInfo.fromStagedFile(stagedDir); 9744 } else { 9745 origin = OriginInfo.fromStagedContainer(stagedCid); 9746 } 9747 9748 final Message msg = mHandler.obtainMessage(INIT_COPY); 9749 final InstallParams params = new InstallParams(origin, null, observer, 9750 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9751 verifParams, user, sessionParams.abiOverride, 9752 sessionParams.grantedRuntimePermissions); 9753 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9754 msg.obj = params; 9755 9756 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9757 System.identityHashCode(msg.obj)); 9758 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9759 System.identityHashCode(msg.obj)); 9760 9761 mHandler.sendMessage(msg); 9762 } 9763 9764 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9765 Bundle extras = new Bundle(1); 9766 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9767 9768 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9769 packageName, extras, null, null, new int[] {userId}); 9770 try { 9771 IActivityManager am = ActivityManagerNative.getDefault(); 9772 final boolean isSystem = 9773 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9774 if (isSystem && am.isUserRunning(userId, false)) { 9775 // The just-installed/enabled app is bundled on the system, so presumed 9776 // to be able to run automatically without needing an explicit launch. 9777 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9778 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9779 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9780 .setPackage(packageName); 9781 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9782 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9783 } 9784 } catch (RemoteException e) { 9785 // shouldn't happen 9786 Slog.w(TAG, "Unable to bootstrap installed package", e); 9787 } 9788 } 9789 9790 @Override 9791 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9792 int userId) { 9793 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9794 PackageSetting pkgSetting; 9795 final int uid = Binder.getCallingUid(); 9796 enforceCrossUserPermission(uid, userId, true, true, 9797 "setApplicationHiddenSetting for user " + userId); 9798 9799 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9800 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9801 return false; 9802 } 9803 9804 long callingId = Binder.clearCallingIdentity(); 9805 try { 9806 boolean sendAdded = false; 9807 boolean sendRemoved = false; 9808 // writer 9809 synchronized (mPackages) { 9810 pkgSetting = mSettings.mPackages.get(packageName); 9811 if (pkgSetting == null) { 9812 return false; 9813 } 9814 if (pkgSetting.getHidden(userId) != hidden) { 9815 pkgSetting.setHidden(hidden, userId); 9816 mSettings.writePackageRestrictionsLPr(userId); 9817 if (hidden) { 9818 sendRemoved = true; 9819 } else { 9820 sendAdded = true; 9821 } 9822 } 9823 } 9824 if (sendAdded) { 9825 sendPackageAddedForUser(packageName, pkgSetting, userId); 9826 return true; 9827 } 9828 if (sendRemoved) { 9829 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9830 "hiding pkg"); 9831 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9832 return true; 9833 } 9834 } finally { 9835 Binder.restoreCallingIdentity(callingId); 9836 } 9837 return false; 9838 } 9839 9840 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9841 int userId) { 9842 final PackageRemovedInfo info = new PackageRemovedInfo(); 9843 info.removedPackage = packageName; 9844 info.removedUsers = new int[] {userId}; 9845 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9846 info.sendBroadcast(false, false, false); 9847 } 9848 9849 /** 9850 * Returns true if application is not found or there was an error. Otherwise it returns 9851 * the hidden state of the package for the given user. 9852 */ 9853 @Override 9854 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9855 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9856 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9857 false, "getApplicationHidden for user " + userId); 9858 PackageSetting pkgSetting; 9859 long callingId = Binder.clearCallingIdentity(); 9860 try { 9861 // writer 9862 synchronized (mPackages) { 9863 pkgSetting = mSettings.mPackages.get(packageName); 9864 if (pkgSetting == null) { 9865 return true; 9866 } 9867 return pkgSetting.getHidden(userId); 9868 } 9869 } finally { 9870 Binder.restoreCallingIdentity(callingId); 9871 } 9872 } 9873 9874 /** 9875 * @hide 9876 */ 9877 @Override 9878 public int installExistingPackageAsUser(String packageName, int userId) { 9879 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9880 null); 9881 PackageSetting pkgSetting; 9882 final int uid = Binder.getCallingUid(); 9883 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9884 + userId); 9885 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9886 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9887 } 9888 9889 long callingId = Binder.clearCallingIdentity(); 9890 try { 9891 boolean sendAdded = false; 9892 9893 // writer 9894 synchronized (mPackages) { 9895 pkgSetting = mSettings.mPackages.get(packageName); 9896 if (pkgSetting == null) { 9897 return PackageManager.INSTALL_FAILED_INVALID_URI; 9898 } 9899 if (!pkgSetting.getInstalled(userId)) { 9900 pkgSetting.setInstalled(true, userId); 9901 pkgSetting.setHidden(false, userId); 9902 mSettings.writePackageRestrictionsLPr(userId); 9903 sendAdded = true; 9904 } 9905 } 9906 9907 if (sendAdded) { 9908 sendPackageAddedForUser(packageName, pkgSetting, userId); 9909 } 9910 } finally { 9911 Binder.restoreCallingIdentity(callingId); 9912 } 9913 9914 return PackageManager.INSTALL_SUCCEEDED; 9915 } 9916 9917 boolean isUserRestricted(int userId, String restrictionKey) { 9918 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9919 if (restrictions.getBoolean(restrictionKey, false)) { 9920 Log.w(TAG, "User is restricted: " + restrictionKey); 9921 return true; 9922 } 9923 return false; 9924 } 9925 9926 @Override 9927 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9928 mContext.enforceCallingOrSelfPermission( 9929 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9930 "Only package verification agents can verify applications"); 9931 9932 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9933 final PackageVerificationResponse response = new PackageVerificationResponse( 9934 verificationCode, Binder.getCallingUid()); 9935 msg.arg1 = id; 9936 msg.obj = response; 9937 mHandler.sendMessage(msg); 9938 } 9939 9940 @Override 9941 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9942 long millisecondsToDelay) { 9943 mContext.enforceCallingOrSelfPermission( 9944 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9945 "Only package verification agents can extend verification timeouts"); 9946 9947 final PackageVerificationState state = mPendingVerification.get(id); 9948 final PackageVerificationResponse response = new PackageVerificationResponse( 9949 verificationCodeAtTimeout, Binder.getCallingUid()); 9950 9951 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9952 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9953 } 9954 if (millisecondsToDelay < 0) { 9955 millisecondsToDelay = 0; 9956 } 9957 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9958 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9959 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9960 } 9961 9962 if ((state != null) && !state.timeoutExtended()) { 9963 state.extendTimeout(); 9964 9965 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9966 msg.arg1 = id; 9967 msg.obj = response; 9968 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9969 } 9970 } 9971 9972 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9973 int verificationCode, UserHandle user) { 9974 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9975 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9976 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9977 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9978 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9979 9980 mContext.sendBroadcastAsUser(intent, user, 9981 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9982 } 9983 9984 private ComponentName matchComponentForVerifier(String packageName, 9985 List<ResolveInfo> receivers) { 9986 ActivityInfo targetReceiver = null; 9987 9988 final int NR = receivers.size(); 9989 for (int i = 0; i < NR; i++) { 9990 final ResolveInfo info = receivers.get(i); 9991 if (info.activityInfo == null) { 9992 continue; 9993 } 9994 9995 if (packageName.equals(info.activityInfo.packageName)) { 9996 targetReceiver = info.activityInfo; 9997 break; 9998 } 9999 } 10000 10001 if (targetReceiver == null) { 10002 return null; 10003 } 10004 10005 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10006 } 10007 10008 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10009 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10010 if (pkgInfo.verifiers.length == 0) { 10011 return null; 10012 } 10013 10014 final int N = pkgInfo.verifiers.length; 10015 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10016 for (int i = 0; i < N; i++) { 10017 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10018 10019 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10020 receivers); 10021 if (comp == null) { 10022 continue; 10023 } 10024 10025 final int verifierUid = getUidForVerifier(verifierInfo); 10026 if (verifierUid == -1) { 10027 continue; 10028 } 10029 10030 if (DEBUG_VERIFY) { 10031 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10032 + " with the correct signature"); 10033 } 10034 sufficientVerifiers.add(comp); 10035 verificationState.addSufficientVerifier(verifierUid); 10036 } 10037 10038 return sufficientVerifiers; 10039 } 10040 10041 private int getUidForVerifier(VerifierInfo verifierInfo) { 10042 synchronized (mPackages) { 10043 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10044 if (pkg == null) { 10045 return -1; 10046 } else if (pkg.mSignatures.length != 1) { 10047 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10048 + " has more than one signature; ignoring"); 10049 return -1; 10050 } 10051 10052 /* 10053 * If the public key of the package's signature does not match 10054 * our expected public key, then this is a different package and 10055 * we should skip. 10056 */ 10057 10058 final byte[] expectedPublicKey; 10059 try { 10060 final Signature verifierSig = pkg.mSignatures[0]; 10061 final PublicKey publicKey = verifierSig.getPublicKey(); 10062 expectedPublicKey = publicKey.getEncoded(); 10063 } catch (CertificateException e) { 10064 return -1; 10065 } 10066 10067 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10068 10069 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10070 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10071 + " does not have the expected public key; ignoring"); 10072 return -1; 10073 } 10074 10075 return pkg.applicationInfo.uid; 10076 } 10077 } 10078 10079 @Override 10080 public void finishPackageInstall(int token) { 10081 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10082 10083 if (DEBUG_INSTALL) { 10084 Slog.v(TAG, "BM finishing package install for " + token); 10085 } 10086 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10087 10088 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10089 mHandler.sendMessage(msg); 10090 } 10091 10092 /** 10093 * Get the verification agent timeout. 10094 * 10095 * @return verification timeout in milliseconds 10096 */ 10097 private long getVerificationTimeout() { 10098 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10099 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10100 DEFAULT_VERIFICATION_TIMEOUT); 10101 } 10102 10103 /** 10104 * Get the default verification agent response code. 10105 * 10106 * @return default verification response code 10107 */ 10108 private int getDefaultVerificationResponse() { 10109 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10110 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10111 DEFAULT_VERIFICATION_RESPONSE); 10112 } 10113 10114 /** 10115 * Check whether or not package verification has been enabled. 10116 * 10117 * @return true if verification should be performed 10118 */ 10119 private boolean isVerificationEnabled(int userId, int installFlags) { 10120 if (!DEFAULT_VERIFY_ENABLE) { 10121 return false; 10122 } 10123 // TODO: fix b/25118622; don't bypass verification 10124 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10125 return false; 10126 } 10127 10128 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10129 10130 // Check if installing from ADB 10131 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10132 // Do not run verification in a test harness environment 10133 if (ActivityManager.isRunningInTestHarness()) { 10134 return false; 10135 } 10136 if (ensureVerifyAppsEnabled) { 10137 return true; 10138 } 10139 // Check if the developer does not want package verification for ADB installs 10140 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10141 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10142 return false; 10143 } 10144 } 10145 10146 if (ensureVerifyAppsEnabled) { 10147 return true; 10148 } 10149 10150 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10151 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10152 } 10153 10154 @Override 10155 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10156 throws RemoteException { 10157 mContext.enforceCallingOrSelfPermission( 10158 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10159 "Only intentfilter verification agents can verify applications"); 10160 10161 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10162 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10163 Binder.getCallingUid(), verificationCode, failedDomains); 10164 msg.arg1 = id; 10165 msg.obj = response; 10166 mHandler.sendMessage(msg); 10167 } 10168 10169 @Override 10170 public int getIntentVerificationStatus(String packageName, int userId) { 10171 synchronized (mPackages) { 10172 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10173 } 10174 } 10175 10176 @Override 10177 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10178 mContext.enforceCallingOrSelfPermission( 10179 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10180 10181 boolean result = false; 10182 synchronized (mPackages) { 10183 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10184 } 10185 if (result) { 10186 scheduleWritePackageRestrictionsLocked(userId); 10187 } 10188 return result; 10189 } 10190 10191 @Override 10192 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10193 synchronized (mPackages) { 10194 return mSettings.getIntentFilterVerificationsLPr(packageName); 10195 } 10196 } 10197 10198 @Override 10199 public List<IntentFilter> getAllIntentFilters(String packageName) { 10200 if (TextUtils.isEmpty(packageName)) { 10201 return Collections.<IntentFilter>emptyList(); 10202 } 10203 synchronized (mPackages) { 10204 PackageParser.Package pkg = mPackages.get(packageName); 10205 if (pkg == null || pkg.activities == null) { 10206 return Collections.<IntentFilter>emptyList(); 10207 } 10208 final int count = pkg.activities.size(); 10209 ArrayList<IntentFilter> result = new ArrayList<>(); 10210 for (int n=0; n<count; n++) { 10211 PackageParser.Activity activity = pkg.activities.get(n); 10212 if (activity.intents != null || activity.intents.size() > 0) { 10213 result.addAll(activity.intents); 10214 } 10215 } 10216 return result; 10217 } 10218 } 10219 10220 @Override 10221 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10222 mContext.enforceCallingOrSelfPermission( 10223 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10224 10225 synchronized (mPackages) { 10226 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10227 if (packageName != null) { 10228 result |= updateIntentVerificationStatus(packageName, 10229 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10230 userId); 10231 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10232 packageName, userId); 10233 } 10234 return result; 10235 } 10236 } 10237 10238 @Override 10239 public String getDefaultBrowserPackageName(int userId) { 10240 synchronized (mPackages) { 10241 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10242 } 10243 } 10244 10245 /** 10246 * Get the "allow unknown sources" setting. 10247 * 10248 * @return the current "allow unknown sources" setting 10249 */ 10250 private int getUnknownSourcesSettings() { 10251 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10252 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10253 -1); 10254 } 10255 10256 @Override 10257 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10258 final int uid = Binder.getCallingUid(); 10259 // writer 10260 synchronized (mPackages) { 10261 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10262 if (targetPackageSetting == null) { 10263 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10264 } 10265 10266 PackageSetting installerPackageSetting; 10267 if (installerPackageName != null) { 10268 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10269 if (installerPackageSetting == null) { 10270 throw new IllegalArgumentException("Unknown installer package: " 10271 + installerPackageName); 10272 } 10273 } else { 10274 installerPackageSetting = null; 10275 } 10276 10277 Signature[] callerSignature; 10278 Object obj = mSettings.getUserIdLPr(uid); 10279 if (obj != null) { 10280 if (obj instanceof SharedUserSetting) { 10281 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10282 } else if (obj instanceof PackageSetting) { 10283 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10284 } else { 10285 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10286 } 10287 } else { 10288 throw new SecurityException("Unknown calling uid " + uid); 10289 } 10290 10291 // Verify: can't set installerPackageName to a package that is 10292 // not signed with the same cert as the caller. 10293 if (installerPackageSetting != null) { 10294 if (compareSignatures(callerSignature, 10295 installerPackageSetting.signatures.mSignatures) 10296 != PackageManager.SIGNATURE_MATCH) { 10297 throw new SecurityException( 10298 "Caller does not have same cert as new installer package " 10299 + installerPackageName); 10300 } 10301 } 10302 10303 // Verify: if target already has an installer package, it must 10304 // be signed with the same cert as the caller. 10305 if (targetPackageSetting.installerPackageName != null) { 10306 PackageSetting setting = mSettings.mPackages.get( 10307 targetPackageSetting.installerPackageName); 10308 // If the currently set package isn't valid, then it's always 10309 // okay to change it. 10310 if (setting != null) { 10311 if (compareSignatures(callerSignature, 10312 setting.signatures.mSignatures) 10313 != PackageManager.SIGNATURE_MATCH) { 10314 throw new SecurityException( 10315 "Caller does not have same cert as old installer package " 10316 + targetPackageSetting.installerPackageName); 10317 } 10318 } 10319 } 10320 10321 // Okay! 10322 targetPackageSetting.installerPackageName = installerPackageName; 10323 scheduleWriteSettingsLocked(); 10324 } 10325 } 10326 10327 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10328 // Queue up an async operation since the package installation may take a little while. 10329 mHandler.post(new Runnable() { 10330 public void run() { 10331 mHandler.removeCallbacks(this); 10332 // Result object to be returned 10333 PackageInstalledInfo res = new PackageInstalledInfo(); 10334 res.returnCode = currentStatus; 10335 res.uid = -1; 10336 res.pkg = null; 10337 res.removedInfo = new PackageRemovedInfo(); 10338 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10339 args.doPreInstall(res.returnCode); 10340 synchronized (mInstallLock) { 10341 installPackageTracedLI(args, res); 10342 } 10343 args.doPostInstall(res.returnCode, res.uid); 10344 } 10345 10346 // A restore should be performed at this point if (a) the install 10347 // succeeded, (b) the operation is not an update, and (c) the new 10348 // package has not opted out of backup participation. 10349 final boolean update = res.removedInfo.removedPackage != null; 10350 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10351 boolean doRestore = !update 10352 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10353 10354 // Set up the post-install work request bookkeeping. This will be used 10355 // and cleaned up by the post-install event handling regardless of whether 10356 // there's a restore pass performed. Token values are >= 1. 10357 int token; 10358 if (mNextInstallToken < 0) mNextInstallToken = 1; 10359 token = mNextInstallToken++; 10360 10361 PostInstallData data = new PostInstallData(args, res); 10362 mRunningInstalls.put(token, data); 10363 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10364 10365 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10366 // Pass responsibility to the Backup Manager. It will perform a 10367 // restore if appropriate, then pass responsibility back to the 10368 // Package Manager to run the post-install observer callbacks 10369 // and broadcasts. 10370 IBackupManager bm = IBackupManager.Stub.asInterface( 10371 ServiceManager.getService(Context.BACKUP_SERVICE)); 10372 if (bm != null) { 10373 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10374 + " to BM for possible restore"); 10375 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10376 try { 10377 // TODO: http://b/22388012 10378 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10379 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10380 } else { 10381 doRestore = false; 10382 } 10383 } catch (RemoteException e) { 10384 // can't happen; the backup manager is local 10385 } catch (Exception e) { 10386 Slog.e(TAG, "Exception trying to enqueue restore", e); 10387 doRestore = false; 10388 } 10389 } else { 10390 Slog.e(TAG, "Backup Manager not found!"); 10391 doRestore = false; 10392 } 10393 } 10394 10395 if (!doRestore) { 10396 // No restore possible, or the Backup Manager was mysteriously not 10397 // available -- just fire the post-install work request directly. 10398 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10399 10400 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10401 10402 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10403 mHandler.sendMessage(msg); 10404 } 10405 } 10406 }); 10407 } 10408 10409 private abstract class HandlerParams { 10410 private static final int MAX_RETRIES = 4; 10411 10412 /** 10413 * Number of times startCopy() has been attempted and had a non-fatal 10414 * error. 10415 */ 10416 private int mRetries = 0; 10417 10418 /** User handle for the user requesting the information or installation. */ 10419 private final UserHandle mUser; 10420 String traceMethod; 10421 int traceCookie; 10422 10423 HandlerParams(UserHandle user) { 10424 mUser = user; 10425 } 10426 10427 UserHandle getUser() { 10428 return mUser; 10429 } 10430 10431 HandlerParams setTraceMethod(String traceMethod) { 10432 this.traceMethod = traceMethod; 10433 return this; 10434 } 10435 10436 HandlerParams setTraceCookie(int traceCookie) { 10437 this.traceCookie = traceCookie; 10438 return this; 10439 } 10440 10441 final boolean startCopy() { 10442 boolean res; 10443 try { 10444 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10445 10446 if (++mRetries > MAX_RETRIES) { 10447 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10448 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10449 handleServiceError(); 10450 return false; 10451 } else { 10452 handleStartCopy(); 10453 res = true; 10454 } 10455 } catch (RemoteException e) { 10456 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10457 mHandler.sendEmptyMessage(MCS_RECONNECT); 10458 res = false; 10459 } 10460 handleReturnCode(); 10461 return res; 10462 } 10463 10464 final void serviceError() { 10465 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10466 handleServiceError(); 10467 handleReturnCode(); 10468 } 10469 10470 abstract void handleStartCopy() throws RemoteException; 10471 abstract void handleServiceError(); 10472 abstract void handleReturnCode(); 10473 } 10474 10475 class MeasureParams extends HandlerParams { 10476 private final PackageStats mStats; 10477 private boolean mSuccess; 10478 10479 private final IPackageStatsObserver mObserver; 10480 10481 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10482 super(new UserHandle(stats.userHandle)); 10483 mObserver = observer; 10484 mStats = stats; 10485 } 10486 10487 @Override 10488 public String toString() { 10489 return "MeasureParams{" 10490 + Integer.toHexString(System.identityHashCode(this)) 10491 + " " + mStats.packageName + "}"; 10492 } 10493 10494 @Override 10495 void handleStartCopy() throws RemoteException { 10496 synchronized (mInstallLock) { 10497 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10498 } 10499 10500 if (mSuccess) { 10501 final boolean mounted; 10502 if (Environment.isExternalStorageEmulated()) { 10503 mounted = true; 10504 } else { 10505 final String status = Environment.getExternalStorageState(); 10506 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10507 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10508 } 10509 10510 if (mounted) { 10511 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10512 10513 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10514 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10515 10516 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10517 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10518 10519 // Always subtract cache size, since it's a subdirectory 10520 mStats.externalDataSize -= mStats.externalCacheSize; 10521 10522 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10523 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10524 10525 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10526 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10527 } 10528 } 10529 } 10530 10531 @Override 10532 void handleReturnCode() { 10533 if (mObserver != null) { 10534 try { 10535 mObserver.onGetStatsCompleted(mStats, mSuccess); 10536 } catch (RemoteException e) { 10537 Slog.i(TAG, "Observer no longer exists."); 10538 } 10539 } 10540 } 10541 10542 @Override 10543 void handleServiceError() { 10544 Slog.e(TAG, "Could not measure application " + mStats.packageName 10545 + " external storage"); 10546 } 10547 } 10548 10549 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10550 throws RemoteException { 10551 long result = 0; 10552 for (File path : paths) { 10553 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10554 } 10555 return result; 10556 } 10557 10558 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10559 for (File path : paths) { 10560 try { 10561 mcs.clearDirectory(path.getAbsolutePath()); 10562 } catch (RemoteException e) { 10563 } 10564 } 10565 } 10566 10567 static class OriginInfo { 10568 /** 10569 * Location where install is coming from, before it has been 10570 * copied/renamed into place. This could be a single monolithic APK 10571 * file, or a cluster directory. This location may be untrusted. 10572 */ 10573 final File file; 10574 final String cid; 10575 10576 /** 10577 * Flag indicating that {@link #file} or {@link #cid} has already been 10578 * staged, meaning downstream users don't need to defensively copy the 10579 * contents. 10580 */ 10581 final boolean staged; 10582 10583 /** 10584 * Flag indicating that {@link #file} or {@link #cid} is an already 10585 * installed app that is being moved. 10586 */ 10587 final boolean existing; 10588 10589 final String resolvedPath; 10590 final File resolvedFile; 10591 10592 static OriginInfo fromNothing() { 10593 return new OriginInfo(null, null, false, false); 10594 } 10595 10596 static OriginInfo fromUntrustedFile(File file) { 10597 return new OriginInfo(file, null, false, false); 10598 } 10599 10600 static OriginInfo fromExistingFile(File file) { 10601 return new OriginInfo(file, null, false, true); 10602 } 10603 10604 static OriginInfo fromStagedFile(File file) { 10605 return new OriginInfo(file, null, true, false); 10606 } 10607 10608 static OriginInfo fromStagedContainer(String cid) { 10609 return new OriginInfo(null, cid, true, false); 10610 } 10611 10612 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10613 this.file = file; 10614 this.cid = cid; 10615 this.staged = staged; 10616 this.existing = existing; 10617 10618 if (cid != null) { 10619 resolvedPath = PackageHelper.getSdDir(cid); 10620 resolvedFile = new File(resolvedPath); 10621 } else if (file != null) { 10622 resolvedPath = file.getAbsolutePath(); 10623 resolvedFile = file; 10624 } else { 10625 resolvedPath = null; 10626 resolvedFile = null; 10627 } 10628 } 10629 } 10630 10631 class MoveInfo { 10632 final int moveId; 10633 final String fromUuid; 10634 final String toUuid; 10635 final String packageName; 10636 final String dataAppName; 10637 final int appId; 10638 final String seinfo; 10639 10640 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10641 String dataAppName, int appId, String seinfo) { 10642 this.moveId = moveId; 10643 this.fromUuid = fromUuid; 10644 this.toUuid = toUuid; 10645 this.packageName = packageName; 10646 this.dataAppName = dataAppName; 10647 this.appId = appId; 10648 this.seinfo = seinfo; 10649 } 10650 } 10651 10652 class InstallParams extends HandlerParams { 10653 final OriginInfo origin; 10654 final MoveInfo move; 10655 final IPackageInstallObserver2 observer; 10656 int installFlags; 10657 final String installerPackageName; 10658 final String volumeUuid; 10659 final VerificationParams verificationParams; 10660 private InstallArgs mArgs; 10661 private int mRet; 10662 final String packageAbiOverride; 10663 final String[] grantedRuntimePermissions; 10664 10665 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10666 int installFlags, String installerPackageName, String volumeUuid, 10667 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10668 String[] grantedPermissions) { 10669 super(user); 10670 this.origin = origin; 10671 this.move = move; 10672 this.observer = observer; 10673 this.installFlags = installFlags; 10674 this.installerPackageName = installerPackageName; 10675 this.volumeUuid = volumeUuid; 10676 this.verificationParams = verificationParams; 10677 this.packageAbiOverride = packageAbiOverride; 10678 this.grantedRuntimePermissions = grantedPermissions; 10679 } 10680 10681 @Override 10682 public String toString() { 10683 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10684 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10685 } 10686 10687 public ManifestDigest getManifestDigest() { 10688 if (verificationParams == null) { 10689 return null; 10690 } 10691 return verificationParams.getManifestDigest(); 10692 } 10693 10694 private int installLocationPolicy(PackageInfoLite pkgLite) { 10695 String packageName = pkgLite.packageName; 10696 int installLocation = pkgLite.installLocation; 10697 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10698 // reader 10699 synchronized (mPackages) { 10700 PackageParser.Package pkg = mPackages.get(packageName); 10701 if (pkg != null) { 10702 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10703 // Check for downgrading. 10704 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10705 try { 10706 checkDowngrade(pkg, pkgLite); 10707 } catch (PackageManagerException e) { 10708 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10709 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10710 } 10711 } 10712 // Check for updated system application. 10713 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10714 if (onSd) { 10715 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10716 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10717 } 10718 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10719 } else { 10720 if (onSd) { 10721 // Install flag overrides everything. 10722 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10723 } 10724 // If current upgrade specifies particular preference 10725 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10726 // Application explicitly specified internal. 10727 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10728 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10729 // App explictly prefers external. Let policy decide 10730 } else { 10731 // Prefer previous location 10732 if (isExternal(pkg)) { 10733 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10734 } 10735 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10736 } 10737 } 10738 } else { 10739 // Invalid install. Return error code 10740 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10741 } 10742 } 10743 } 10744 // All the special cases have been taken care of. 10745 // Return result based on recommended install location. 10746 if (onSd) { 10747 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10748 } 10749 return pkgLite.recommendedInstallLocation; 10750 } 10751 10752 /* 10753 * Invoke remote method to get package information and install 10754 * location values. Override install location based on default 10755 * policy if needed and then create install arguments based 10756 * on the install location. 10757 */ 10758 public void handleStartCopy() throws RemoteException { 10759 int ret = PackageManager.INSTALL_SUCCEEDED; 10760 10761 // If we're already staged, we've firmly committed to an install location 10762 if (origin.staged) { 10763 if (origin.file != null) { 10764 installFlags |= PackageManager.INSTALL_INTERNAL; 10765 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10766 } else if (origin.cid != null) { 10767 installFlags |= PackageManager.INSTALL_EXTERNAL; 10768 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10769 } else { 10770 throw new IllegalStateException("Invalid stage location"); 10771 } 10772 } 10773 10774 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10775 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10776 PackageInfoLite pkgLite = null; 10777 10778 if (onInt && onSd) { 10779 // Check if both bits are set. 10780 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10781 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10782 } else { 10783 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10784 packageAbiOverride); 10785 10786 /* 10787 * If we have too little free space, try to free cache 10788 * before giving up. 10789 */ 10790 if (!origin.staged && pkgLite.recommendedInstallLocation 10791 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10792 // TODO: focus freeing disk space on the target device 10793 final StorageManager storage = StorageManager.from(mContext); 10794 final long lowThreshold = storage.getStorageLowBytes( 10795 Environment.getDataDirectory()); 10796 10797 final long sizeBytes = mContainerService.calculateInstalledSize( 10798 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10799 10800 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10801 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10802 installFlags, packageAbiOverride); 10803 } 10804 10805 /* 10806 * The cache free must have deleted the file we 10807 * downloaded to install. 10808 * 10809 * TODO: fix the "freeCache" call to not delete 10810 * the file we care about. 10811 */ 10812 if (pkgLite.recommendedInstallLocation 10813 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10814 pkgLite.recommendedInstallLocation 10815 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10816 } 10817 } 10818 } 10819 10820 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10821 int loc = pkgLite.recommendedInstallLocation; 10822 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10823 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10824 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10825 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10826 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10827 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10828 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10829 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10830 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10831 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10832 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10833 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10834 } else { 10835 // Override with defaults if needed. 10836 loc = installLocationPolicy(pkgLite); 10837 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10838 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10839 } else if (!onSd && !onInt) { 10840 // Override install location with flags 10841 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10842 // Set the flag to install on external media. 10843 installFlags |= PackageManager.INSTALL_EXTERNAL; 10844 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10845 } else { 10846 // Make sure the flag for installing on external 10847 // media is unset 10848 installFlags |= PackageManager.INSTALL_INTERNAL; 10849 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10850 } 10851 } 10852 } 10853 } 10854 10855 final InstallArgs args = createInstallArgs(this); 10856 mArgs = args; 10857 10858 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10859 // TODO: http://b/22976637 10860 // Apps installed for "all" users use the device owner to verify the app 10861 UserHandle verifierUser = getUser(); 10862 if (verifierUser == UserHandle.ALL) { 10863 verifierUser = UserHandle.SYSTEM; 10864 } 10865 10866 /* 10867 * Determine if we have any installed package verifiers. If we 10868 * do, then we'll defer to them to verify the packages. 10869 */ 10870 final int requiredUid = mRequiredVerifierPackage == null ? -1 10871 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10872 if (!origin.existing && requiredUid != -1 10873 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10874 final Intent verification = new Intent( 10875 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10876 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10877 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10878 PACKAGE_MIME_TYPE); 10879 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10880 10881 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10882 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10883 verifierUser.getIdentifier()); 10884 10885 if (DEBUG_VERIFY) { 10886 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10887 + verification.toString() + " with " + pkgLite.verifiers.length 10888 + " optional verifiers"); 10889 } 10890 10891 final int verificationId = mPendingVerificationToken++; 10892 10893 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10894 10895 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10896 installerPackageName); 10897 10898 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10899 installFlags); 10900 10901 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10902 pkgLite.packageName); 10903 10904 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10905 pkgLite.versionCode); 10906 10907 if (verificationParams != null) { 10908 if (verificationParams.getVerificationURI() != null) { 10909 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10910 verificationParams.getVerificationURI()); 10911 } 10912 if (verificationParams.getOriginatingURI() != null) { 10913 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10914 verificationParams.getOriginatingURI()); 10915 } 10916 if (verificationParams.getReferrer() != null) { 10917 verification.putExtra(Intent.EXTRA_REFERRER, 10918 verificationParams.getReferrer()); 10919 } 10920 if (verificationParams.getOriginatingUid() >= 0) { 10921 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10922 verificationParams.getOriginatingUid()); 10923 } 10924 if (verificationParams.getInstallerUid() >= 0) { 10925 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10926 verificationParams.getInstallerUid()); 10927 } 10928 } 10929 10930 final PackageVerificationState verificationState = new PackageVerificationState( 10931 requiredUid, args); 10932 10933 mPendingVerification.append(verificationId, verificationState); 10934 10935 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10936 receivers, verificationState); 10937 10938 /* 10939 * If any sufficient verifiers were listed in the package 10940 * manifest, attempt to ask them. 10941 */ 10942 if (sufficientVerifiers != null) { 10943 final int N = sufficientVerifiers.size(); 10944 if (N == 0) { 10945 Slog.i(TAG, "Additional verifiers required, but none installed."); 10946 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10947 } else { 10948 for (int i = 0; i < N; i++) { 10949 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10950 10951 final Intent sufficientIntent = new Intent(verification); 10952 sufficientIntent.setComponent(verifierComponent); 10953 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10954 } 10955 } 10956 } 10957 10958 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10959 mRequiredVerifierPackage, receivers); 10960 if (ret == PackageManager.INSTALL_SUCCEEDED 10961 && mRequiredVerifierPackage != null) { 10962 Trace.asyncTraceBegin( 10963 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10964 /* 10965 * Send the intent to the required verification agent, 10966 * but only start the verification timeout after the 10967 * target BroadcastReceivers have run. 10968 */ 10969 verification.setComponent(requiredVerifierComponent); 10970 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10971 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10972 new BroadcastReceiver() { 10973 @Override 10974 public void onReceive(Context context, Intent intent) { 10975 final Message msg = mHandler 10976 .obtainMessage(CHECK_PENDING_VERIFICATION); 10977 msg.arg1 = verificationId; 10978 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10979 } 10980 }, null, 0, null, null); 10981 10982 /* 10983 * We don't want the copy to proceed until verification 10984 * succeeds, so null out this field. 10985 */ 10986 mArgs = null; 10987 } 10988 } else { 10989 /* 10990 * No package verification is enabled, so immediately start 10991 * the remote call to initiate copy using temporary file. 10992 */ 10993 ret = args.copyApk(mContainerService, true); 10994 } 10995 } 10996 10997 mRet = ret; 10998 } 10999 11000 @Override 11001 void handleReturnCode() { 11002 // If mArgs is null, then MCS couldn't be reached. When it 11003 // reconnects, it will try again to install. At that point, this 11004 // will succeed. 11005 if (mArgs != null) { 11006 processPendingInstall(mArgs, mRet); 11007 } 11008 } 11009 11010 @Override 11011 void handleServiceError() { 11012 mArgs = createInstallArgs(this); 11013 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11014 } 11015 11016 public boolean isForwardLocked() { 11017 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11018 } 11019 } 11020 11021 /** 11022 * Used during creation of InstallArgs 11023 * 11024 * @param installFlags package installation flags 11025 * @return true if should be installed on external storage 11026 */ 11027 private static boolean installOnExternalAsec(int installFlags) { 11028 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11029 return false; 11030 } 11031 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11032 return true; 11033 } 11034 return false; 11035 } 11036 11037 /** 11038 * Used during creation of InstallArgs 11039 * 11040 * @param installFlags package installation flags 11041 * @return true if should be installed as forward locked 11042 */ 11043 private static boolean installForwardLocked(int installFlags) { 11044 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11045 } 11046 11047 private InstallArgs createInstallArgs(InstallParams params) { 11048 if (params.move != null) { 11049 return new MoveInstallArgs(params); 11050 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11051 return new AsecInstallArgs(params); 11052 } else { 11053 return new FileInstallArgs(params); 11054 } 11055 } 11056 11057 /** 11058 * Create args that describe an existing installed package. Typically used 11059 * when cleaning up old installs, or used as a move source. 11060 */ 11061 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11062 String resourcePath, String[] instructionSets) { 11063 final boolean isInAsec; 11064 if (installOnExternalAsec(installFlags)) { 11065 /* Apps on SD card are always in ASEC containers. */ 11066 isInAsec = true; 11067 } else if (installForwardLocked(installFlags) 11068 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11069 /* 11070 * Forward-locked apps are only in ASEC containers if they're the 11071 * new style 11072 */ 11073 isInAsec = true; 11074 } else { 11075 isInAsec = false; 11076 } 11077 11078 if (isInAsec) { 11079 return new AsecInstallArgs(codePath, instructionSets, 11080 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11081 } else { 11082 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11083 } 11084 } 11085 11086 static abstract class InstallArgs { 11087 /** @see InstallParams#origin */ 11088 final OriginInfo origin; 11089 /** @see InstallParams#move */ 11090 final MoveInfo move; 11091 11092 final IPackageInstallObserver2 observer; 11093 // Always refers to PackageManager flags only 11094 final int installFlags; 11095 final String installerPackageName; 11096 final String volumeUuid; 11097 final ManifestDigest manifestDigest; 11098 final UserHandle user; 11099 final String abiOverride; 11100 final String[] installGrantPermissions; 11101 /** If non-null, drop an async trace when the install completes */ 11102 final String traceMethod; 11103 final int traceCookie; 11104 11105 // The list of instruction sets supported by this app. This is currently 11106 // only used during the rmdex() phase to clean up resources. We can get rid of this 11107 // if we move dex files under the common app path. 11108 /* nullable */ String[] instructionSets; 11109 11110 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11111 int installFlags, String installerPackageName, String volumeUuid, 11112 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11113 String abiOverride, String[] installGrantPermissions, 11114 String traceMethod, int traceCookie) { 11115 this.origin = origin; 11116 this.move = move; 11117 this.installFlags = installFlags; 11118 this.observer = observer; 11119 this.installerPackageName = installerPackageName; 11120 this.volumeUuid = volumeUuid; 11121 this.manifestDigest = manifestDigest; 11122 this.user = user; 11123 this.instructionSets = instructionSets; 11124 this.abiOverride = abiOverride; 11125 this.installGrantPermissions = installGrantPermissions; 11126 this.traceMethod = traceMethod; 11127 this.traceCookie = traceCookie; 11128 } 11129 11130 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11131 abstract int doPreInstall(int status); 11132 11133 /** 11134 * Rename package into final resting place. All paths on the given 11135 * scanned package should be updated to reflect the rename. 11136 */ 11137 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11138 abstract int doPostInstall(int status, int uid); 11139 11140 /** @see PackageSettingBase#codePathString */ 11141 abstract String getCodePath(); 11142 /** @see PackageSettingBase#resourcePathString */ 11143 abstract String getResourcePath(); 11144 11145 // Need installer lock especially for dex file removal. 11146 abstract void cleanUpResourcesLI(); 11147 abstract boolean doPostDeleteLI(boolean delete); 11148 11149 /** 11150 * Called before the source arguments are copied. This is used mostly 11151 * for MoveParams when it needs to read the source file to put it in the 11152 * destination. 11153 */ 11154 int doPreCopy() { 11155 return PackageManager.INSTALL_SUCCEEDED; 11156 } 11157 11158 /** 11159 * Called after the source arguments are copied. This is used mostly for 11160 * MoveParams when it needs to read the source file to put it in the 11161 * destination. 11162 * 11163 * @return 11164 */ 11165 int doPostCopy(int uid) { 11166 return PackageManager.INSTALL_SUCCEEDED; 11167 } 11168 11169 protected boolean isFwdLocked() { 11170 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11171 } 11172 11173 protected boolean isExternalAsec() { 11174 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11175 } 11176 11177 UserHandle getUser() { 11178 return user; 11179 } 11180 } 11181 11182 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11183 if (!allCodePaths.isEmpty()) { 11184 if (instructionSets == null) { 11185 throw new IllegalStateException("instructionSet == null"); 11186 } 11187 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11188 for (String codePath : allCodePaths) { 11189 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11190 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11191 if (retCode < 0) { 11192 Slog.w(TAG, "Couldn't remove dex file for package: " 11193 + " at location " + codePath + ", retcode=" + retCode); 11194 // we don't consider this to be a failure of the core package deletion 11195 } 11196 } 11197 } 11198 } 11199 } 11200 11201 /** 11202 * Logic to handle installation of non-ASEC applications, including copying 11203 * and renaming logic. 11204 */ 11205 class FileInstallArgs extends InstallArgs { 11206 private File codeFile; 11207 private File resourceFile; 11208 11209 // Example topology: 11210 // /data/app/com.example/base.apk 11211 // /data/app/com.example/split_foo.apk 11212 // /data/app/com.example/lib/arm/libfoo.so 11213 // /data/app/com.example/lib/arm64/libfoo.so 11214 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11215 11216 /** New install */ 11217 FileInstallArgs(InstallParams params) { 11218 super(params.origin, params.move, params.observer, params.installFlags, 11219 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11220 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11221 params.grantedRuntimePermissions, 11222 params.traceMethod, params.traceCookie); 11223 if (isFwdLocked()) { 11224 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11225 } 11226 } 11227 11228 /** Existing install */ 11229 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11230 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11231 null, null, null, 0); 11232 this.codeFile = (codePath != null) ? new File(codePath) : null; 11233 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11234 } 11235 11236 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11237 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11238 try { 11239 return doCopyApk(imcs, temp); 11240 } finally { 11241 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11242 } 11243 } 11244 11245 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11246 if (origin.staged) { 11247 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11248 codeFile = origin.file; 11249 resourceFile = origin.file; 11250 return PackageManager.INSTALL_SUCCEEDED; 11251 } 11252 11253 try { 11254 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11255 codeFile = tempDir; 11256 resourceFile = tempDir; 11257 } catch (IOException e) { 11258 Slog.w(TAG, "Failed to create copy file: " + e); 11259 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11260 } 11261 11262 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11263 @Override 11264 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11265 if (!FileUtils.isValidExtFilename(name)) { 11266 throw new IllegalArgumentException("Invalid filename: " + name); 11267 } 11268 try { 11269 final File file = new File(codeFile, name); 11270 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11271 O_RDWR | O_CREAT, 0644); 11272 Os.chmod(file.getAbsolutePath(), 0644); 11273 return new ParcelFileDescriptor(fd); 11274 } catch (ErrnoException e) { 11275 throw new RemoteException("Failed to open: " + e.getMessage()); 11276 } 11277 } 11278 }; 11279 11280 int ret = PackageManager.INSTALL_SUCCEEDED; 11281 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11282 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11283 Slog.e(TAG, "Failed to copy package"); 11284 return ret; 11285 } 11286 11287 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11288 NativeLibraryHelper.Handle handle = null; 11289 try { 11290 handle = NativeLibraryHelper.Handle.create(codeFile); 11291 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11292 abiOverride); 11293 } catch (IOException e) { 11294 Slog.e(TAG, "Copying native libraries failed", e); 11295 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11296 } finally { 11297 IoUtils.closeQuietly(handle); 11298 } 11299 11300 return ret; 11301 } 11302 11303 int doPreInstall(int status) { 11304 if (status != PackageManager.INSTALL_SUCCEEDED) { 11305 cleanUp(); 11306 } 11307 return status; 11308 } 11309 11310 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11311 if (status != PackageManager.INSTALL_SUCCEEDED) { 11312 cleanUp(); 11313 return false; 11314 } 11315 11316 final File targetDir = codeFile.getParentFile(); 11317 final File beforeCodeFile = codeFile; 11318 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11319 11320 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11321 try { 11322 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11323 } catch (ErrnoException e) { 11324 Slog.w(TAG, "Failed to rename", e); 11325 return false; 11326 } 11327 11328 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11329 Slog.w(TAG, "Failed to restorecon"); 11330 return false; 11331 } 11332 11333 // Reflect the rename internally 11334 codeFile = afterCodeFile; 11335 resourceFile = afterCodeFile; 11336 11337 // Reflect the rename in scanned details 11338 pkg.codePath = afterCodeFile.getAbsolutePath(); 11339 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11340 pkg.baseCodePath); 11341 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11342 pkg.splitCodePaths); 11343 11344 // Reflect the rename in app info 11345 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11346 pkg.applicationInfo.setCodePath(pkg.codePath); 11347 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11348 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11349 pkg.applicationInfo.setResourcePath(pkg.codePath); 11350 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11351 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11352 11353 return true; 11354 } 11355 11356 int doPostInstall(int status, int uid) { 11357 if (status != PackageManager.INSTALL_SUCCEEDED) { 11358 cleanUp(); 11359 } 11360 return status; 11361 } 11362 11363 @Override 11364 String getCodePath() { 11365 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11366 } 11367 11368 @Override 11369 String getResourcePath() { 11370 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11371 } 11372 11373 private boolean cleanUp() { 11374 if (codeFile == null || !codeFile.exists()) { 11375 return false; 11376 } 11377 11378 if (codeFile.isDirectory()) { 11379 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11380 } else { 11381 codeFile.delete(); 11382 } 11383 11384 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11385 resourceFile.delete(); 11386 } 11387 11388 return true; 11389 } 11390 11391 void cleanUpResourcesLI() { 11392 // Try enumerating all code paths before deleting 11393 List<String> allCodePaths = Collections.EMPTY_LIST; 11394 if (codeFile != null && codeFile.exists()) { 11395 try { 11396 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11397 allCodePaths = pkg.getAllCodePaths(); 11398 } catch (PackageParserException e) { 11399 // Ignored; we tried our best 11400 } 11401 } 11402 11403 cleanUp(); 11404 removeDexFiles(allCodePaths, instructionSets); 11405 } 11406 11407 boolean doPostDeleteLI(boolean delete) { 11408 // XXX err, shouldn't we respect the delete flag? 11409 cleanUpResourcesLI(); 11410 return true; 11411 } 11412 } 11413 11414 private boolean isAsecExternal(String cid) { 11415 final String asecPath = PackageHelper.getSdFilesystem(cid); 11416 return !asecPath.startsWith(mAsecInternalPath); 11417 } 11418 11419 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11420 PackageManagerException { 11421 if (copyRet < 0) { 11422 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11423 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11424 throw new PackageManagerException(copyRet, message); 11425 } 11426 } 11427 } 11428 11429 /** 11430 * Extract the MountService "container ID" from the full code path of an 11431 * .apk. 11432 */ 11433 static String cidFromCodePath(String fullCodePath) { 11434 int eidx = fullCodePath.lastIndexOf("/"); 11435 String subStr1 = fullCodePath.substring(0, eidx); 11436 int sidx = subStr1.lastIndexOf("/"); 11437 return subStr1.substring(sidx+1, eidx); 11438 } 11439 11440 /** 11441 * Logic to handle installation of ASEC applications, including copying and 11442 * renaming logic. 11443 */ 11444 class AsecInstallArgs extends InstallArgs { 11445 static final String RES_FILE_NAME = "pkg.apk"; 11446 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11447 11448 String cid; 11449 String packagePath; 11450 String resourcePath; 11451 11452 /** New install */ 11453 AsecInstallArgs(InstallParams params) { 11454 super(params.origin, params.move, params.observer, params.installFlags, 11455 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11456 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11457 params.grantedRuntimePermissions, 11458 params.traceMethod, params.traceCookie); 11459 } 11460 11461 /** Existing install */ 11462 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11463 boolean isExternal, boolean isForwardLocked) { 11464 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11465 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11466 instructionSets, null, null, null, 0); 11467 // Hackily pretend we're still looking at a full code path 11468 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11469 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11470 } 11471 11472 // Extract cid from fullCodePath 11473 int eidx = fullCodePath.lastIndexOf("/"); 11474 String subStr1 = fullCodePath.substring(0, eidx); 11475 int sidx = subStr1.lastIndexOf("/"); 11476 cid = subStr1.substring(sidx+1, eidx); 11477 setMountPath(subStr1); 11478 } 11479 11480 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11481 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11482 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11483 instructionSets, null, null, null, 0); 11484 this.cid = cid; 11485 setMountPath(PackageHelper.getSdDir(cid)); 11486 } 11487 11488 void createCopyFile() { 11489 cid = mInstallerService.allocateExternalStageCidLegacy(); 11490 } 11491 11492 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11493 if (origin.staged) { 11494 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11495 cid = origin.cid; 11496 setMountPath(PackageHelper.getSdDir(cid)); 11497 return PackageManager.INSTALL_SUCCEEDED; 11498 } 11499 11500 if (temp) { 11501 createCopyFile(); 11502 } else { 11503 /* 11504 * Pre-emptively destroy the container since it's destroyed if 11505 * copying fails due to it existing anyway. 11506 */ 11507 PackageHelper.destroySdDir(cid); 11508 } 11509 11510 final String newMountPath = imcs.copyPackageToContainer( 11511 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11512 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11513 11514 if (newMountPath != null) { 11515 setMountPath(newMountPath); 11516 return PackageManager.INSTALL_SUCCEEDED; 11517 } else { 11518 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11519 } 11520 } 11521 11522 @Override 11523 String getCodePath() { 11524 return packagePath; 11525 } 11526 11527 @Override 11528 String getResourcePath() { 11529 return resourcePath; 11530 } 11531 11532 int doPreInstall(int status) { 11533 if (status != PackageManager.INSTALL_SUCCEEDED) { 11534 // Destroy container 11535 PackageHelper.destroySdDir(cid); 11536 } else { 11537 boolean mounted = PackageHelper.isContainerMounted(cid); 11538 if (!mounted) { 11539 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11540 Process.SYSTEM_UID); 11541 if (newMountPath != null) { 11542 setMountPath(newMountPath); 11543 } else { 11544 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11545 } 11546 } 11547 } 11548 return status; 11549 } 11550 11551 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11552 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11553 String newMountPath = null; 11554 if (PackageHelper.isContainerMounted(cid)) { 11555 // Unmount the container 11556 if (!PackageHelper.unMountSdDir(cid)) { 11557 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11558 return false; 11559 } 11560 } 11561 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11562 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11563 " which might be stale. Will try to clean up."); 11564 // Clean up the stale container and proceed to recreate. 11565 if (!PackageHelper.destroySdDir(newCacheId)) { 11566 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11567 return false; 11568 } 11569 // Successfully cleaned up stale container. Try to rename again. 11570 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11571 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11572 + " inspite of cleaning it up."); 11573 return false; 11574 } 11575 } 11576 if (!PackageHelper.isContainerMounted(newCacheId)) { 11577 Slog.w(TAG, "Mounting container " + newCacheId); 11578 newMountPath = PackageHelper.mountSdDir(newCacheId, 11579 getEncryptKey(), Process.SYSTEM_UID); 11580 } else { 11581 newMountPath = PackageHelper.getSdDir(newCacheId); 11582 } 11583 if (newMountPath == null) { 11584 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11585 return false; 11586 } 11587 Log.i(TAG, "Succesfully renamed " + cid + 11588 " to " + newCacheId + 11589 " at new path: " + newMountPath); 11590 cid = newCacheId; 11591 11592 final File beforeCodeFile = new File(packagePath); 11593 setMountPath(newMountPath); 11594 final File afterCodeFile = new File(packagePath); 11595 11596 // Reflect the rename in scanned details 11597 pkg.codePath = afterCodeFile.getAbsolutePath(); 11598 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11599 pkg.baseCodePath); 11600 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11601 pkg.splitCodePaths); 11602 11603 // Reflect the rename in app info 11604 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11605 pkg.applicationInfo.setCodePath(pkg.codePath); 11606 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11607 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11608 pkg.applicationInfo.setResourcePath(pkg.codePath); 11609 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11610 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11611 11612 return true; 11613 } 11614 11615 private void setMountPath(String mountPath) { 11616 final File mountFile = new File(mountPath); 11617 11618 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11619 if (monolithicFile.exists()) { 11620 packagePath = monolithicFile.getAbsolutePath(); 11621 if (isFwdLocked()) { 11622 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11623 } else { 11624 resourcePath = packagePath; 11625 } 11626 } else { 11627 packagePath = mountFile.getAbsolutePath(); 11628 resourcePath = packagePath; 11629 } 11630 } 11631 11632 int doPostInstall(int status, int uid) { 11633 if (status != PackageManager.INSTALL_SUCCEEDED) { 11634 cleanUp(); 11635 } else { 11636 final int groupOwner; 11637 final String protectedFile; 11638 if (isFwdLocked()) { 11639 groupOwner = UserHandle.getSharedAppGid(uid); 11640 protectedFile = RES_FILE_NAME; 11641 } else { 11642 groupOwner = -1; 11643 protectedFile = null; 11644 } 11645 11646 if (uid < Process.FIRST_APPLICATION_UID 11647 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11648 Slog.e(TAG, "Failed to finalize " + cid); 11649 PackageHelper.destroySdDir(cid); 11650 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11651 } 11652 11653 boolean mounted = PackageHelper.isContainerMounted(cid); 11654 if (!mounted) { 11655 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11656 } 11657 } 11658 return status; 11659 } 11660 11661 private void cleanUp() { 11662 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11663 11664 // Destroy secure container 11665 PackageHelper.destroySdDir(cid); 11666 } 11667 11668 private List<String> getAllCodePaths() { 11669 final File codeFile = new File(getCodePath()); 11670 if (codeFile != null && codeFile.exists()) { 11671 try { 11672 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11673 return pkg.getAllCodePaths(); 11674 } catch (PackageParserException e) { 11675 // Ignored; we tried our best 11676 } 11677 } 11678 return Collections.EMPTY_LIST; 11679 } 11680 11681 void cleanUpResourcesLI() { 11682 // Enumerate all code paths before deleting 11683 cleanUpResourcesLI(getAllCodePaths()); 11684 } 11685 11686 private void cleanUpResourcesLI(List<String> allCodePaths) { 11687 cleanUp(); 11688 removeDexFiles(allCodePaths, instructionSets); 11689 } 11690 11691 String getPackageName() { 11692 return getAsecPackageName(cid); 11693 } 11694 11695 boolean doPostDeleteLI(boolean delete) { 11696 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11697 final List<String> allCodePaths = getAllCodePaths(); 11698 boolean mounted = PackageHelper.isContainerMounted(cid); 11699 if (mounted) { 11700 // Unmount first 11701 if (PackageHelper.unMountSdDir(cid)) { 11702 mounted = false; 11703 } 11704 } 11705 if (!mounted && delete) { 11706 cleanUpResourcesLI(allCodePaths); 11707 } 11708 return !mounted; 11709 } 11710 11711 @Override 11712 int doPreCopy() { 11713 if (isFwdLocked()) { 11714 if (!PackageHelper.fixSdPermissions(cid, 11715 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11716 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11717 } 11718 } 11719 11720 return PackageManager.INSTALL_SUCCEEDED; 11721 } 11722 11723 @Override 11724 int doPostCopy(int uid) { 11725 if (isFwdLocked()) { 11726 if (uid < Process.FIRST_APPLICATION_UID 11727 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11728 RES_FILE_NAME)) { 11729 Slog.e(TAG, "Failed to finalize " + cid); 11730 PackageHelper.destroySdDir(cid); 11731 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11732 } 11733 } 11734 11735 return PackageManager.INSTALL_SUCCEEDED; 11736 } 11737 } 11738 11739 /** 11740 * Logic to handle movement of existing installed applications. 11741 */ 11742 class MoveInstallArgs extends InstallArgs { 11743 private File codeFile; 11744 private File resourceFile; 11745 11746 /** New install */ 11747 MoveInstallArgs(InstallParams params) { 11748 super(params.origin, params.move, params.observer, params.installFlags, 11749 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11750 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11751 params.grantedRuntimePermissions, 11752 params.traceMethod, params.traceCookie); 11753 } 11754 11755 int copyApk(IMediaContainerService imcs, boolean temp) { 11756 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11757 + move.fromUuid + " to " + move.toUuid); 11758 synchronized (mInstaller) { 11759 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11760 move.dataAppName, move.appId, move.seinfo) != 0) { 11761 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11762 } 11763 } 11764 11765 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11766 resourceFile = codeFile; 11767 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11768 11769 return PackageManager.INSTALL_SUCCEEDED; 11770 } 11771 11772 int doPreInstall(int status) { 11773 if (status != PackageManager.INSTALL_SUCCEEDED) { 11774 cleanUp(move.toUuid); 11775 } 11776 return status; 11777 } 11778 11779 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11780 if (status != PackageManager.INSTALL_SUCCEEDED) { 11781 cleanUp(move.toUuid); 11782 return false; 11783 } 11784 11785 // Reflect the move in app info 11786 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11787 pkg.applicationInfo.setCodePath(pkg.codePath); 11788 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11789 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11790 pkg.applicationInfo.setResourcePath(pkg.codePath); 11791 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11792 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11793 11794 return true; 11795 } 11796 11797 int doPostInstall(int status, int uid) { 11798 if (status == PackageManager.INSTALL_SUCCEEDED) { 11799 cleanUp(move.fromUuid); 11800 } else { 11801 cleanUp(move.toUuid); 11802 } 11803 return status; 11804 } 11805 11806 @Override 11807 String getCodePath() { 11808 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11809 } 11810 11811 @Override 11812 String getResourcePath() { 11813 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11814 } 11815 11816 private boolean cleanUp(String volumeUuid) { 11817 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11818 move.dataAppName); 11819 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11820 synchronized (mInstallLock) { 11821 // Clean up both app data and code 11822 removeDataDirsLI(volumeUuid, move.packageName); 11823 if (codeFile.isDirectory()) { 11824 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11825 } else { 11826 codeFile.delete(); 11827 } 11828 } 11829 return true; 11830 } 11831 11832 void cleanUpResourcesLI() { 11833 throw new UnsupportedOperationException(); 11834 } 11835 11836 boolean doPostDeleteLI(boolean delete) { 11837 throw new UnsupportedOperationException(); 11838 } 11839 } 11840 11841 static String getAsecPackageName(String packageCid) { 11842 int idx = packageCid.lastIndexOf("-"); 11843 if (idx == -1) { 11844 return packageCid; 11845 } 11846 return packageCid.substring(0, idx); 11847 } 11848 11849 // Utility method used to create code paths based on package name and available index. 11850 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11851 String idxStr = ""; 11852 int idx = 1; 11853 // Fall back to default value of idx=1 if prefix is not 11854 // part of oldCodePath 11855 if (oldCodePath != null) { 11856 String subStr = oldCodePath; 11857 // Drop the suffix right away 11858 if (suffix != null && subStr.endsWith(suffix)) { 11859 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11860 } 11861 // If oldCodePath already contains prefix find out the 11862 // ending index to either increment or decrement. 11863 int sidx = subStr.lastIndexOf(prefix); 11864 if (sidx != -1) { 11865 subStr = subStr.substring(sidx + prefix.length()); 11866 if (subStr != null) { 11867 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11868 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11869 } 11870 try { 11871 idx = Integer.parseInt(subStr); 11872 if (idx <= 1) { 11873 idx++; 11874 } else { 11875 idx--; 11876 } 11877 } catch(NumberFormatException e) { 11878 } 11879 } 11880 } 11881 } 11882 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11883 return prefix + idxStr; 11884 } 11885 11886 private File getNextCodePath(File targetDir, String packageName) { 11887 int suffix = 1; 11888 File result; 11889 do { 11890 result = new File(targetDir, packageName + "-" + suffix); 11891 suffix++; 11892 } while (result.exists()); 11893 return result; 11894 } 11895 11896 // Utility method that returns the relative package path with respect 11897 // to the installation directory. Like say for /data/data/com.test-1.apk 11898 // string com.test-1 is returned. 11899 static String deriveCodePathName(String codePath) { 11900 if (codePath == null) { 11901 return null; 11902 } 11903 final File codeFile = new File(codePath); 11904 final String name = codeFile.getName(); 11905 if (codeFile.isDirectory()) { 11906 return name; 11907 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11908 final int lastDot = name.lastIndexOf('.'); 11909 return name.substring(0, lastDot); 11910 } else { 11911 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11912 return null; 11913 } 11914 } 11915 11916 class PackageInstalledInfo { 11917 String name; 11918 int uid; 11919 // The set of users that originally had this package installed. 11920 int[] origUsers; 11921 // The set of users that now have this package installed. 11922 int[] newUsers; 11923 PackageParser.Package pkg; 11924 int returnCode; 11925 String returnMsg; 11926 PackageRemovedInfo removedInfo; 11927 11928 public void setError(int code, String msg) { 11929 returnCode = code; 11930 returnMsg = msg; 11931 Slog.w(TAG, msg); 11932 } 11933 11934 public void setError(String msg, PackageParserException e) { 11935 returnCode = e.error; 11936 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11937 Slog.w(TAG, msg, e); 11938 } 11939 11940 public void setError(String msg, PackageManagerException e) { 11941 returnCode = e.error; 11942 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11943 Slog.w(TAG, msg, e); 11944 } 11945 11946 // In some error cases we want to convey more info back to the observer 11947 String origPackage; 11948 String origPermission; 11949 } 11950 11951 /* 11952 * Install a non-existing package. 11953 */ 11954 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11955 UserHandle user, String installerPackageName, String volumeUuid, 11956 PackageInstalledInfo res) { 11957 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11958 11959 // Remember this for later, in case we need to rollback this install 11960 String pkgName = pkg.packageName; 11961 11962 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11963 // TODO: b/23350563 11964 final boolean dataDirExists = Environment 11965 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11966 11967 synchronized(mPackages) { 11968 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11969 // A package with the same name is already installed, though 11970 // it has been renamed to an older name. The package we 11971 // are trying to install should be installed as an update to 11972 // the existing one, but that has not been requested, so bail. 11973 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11974 + " without first uninstalling package running as " 11975 + mSettings.mRenamedPackages.get(pkgName)); 11976 return; 11977 } 11978 if (mPackages.containsKey(pkgName)) { 11979 // Don't allow installation over an existing package with the same name. 11980 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11981 + " without first uninstalling."); 11982 return; 11983 } 11984 } 11985 11986 try { 11987 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11988 System.currentTimeMillis(), user); 11989 11990 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11991 // delete the partially installed application. the data directory will have to be 11992 // restored if it was already existing 11993 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11994 // remove package from internal structures. Note that we want deletePackageX to 11995 // delete the package data and cache directories that it created in 11996 // scanPackageLocked, unless those directories existed before we even tried to 11997 // install. 11998 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11999 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12000 res.removedInfo, true); 12001 } 12002 12003 } catch (PackageManagerException e) { 12004 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12005 } 12006 12007 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12008 } 12009 12010 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12011 // Can't rotate keys during boot or if sharedUser. 12012 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12013 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12014 return false; 12015 } 12016 // app is using upgradeKeySets; make sure all are valid 12017 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12018 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12019 for (int i = 0; i < upgradeKeySets.length; i++) { 12020 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12021 Slog.wtf(TAG, "Package " 12022 + (oldPs.name != null ? oldPs.name : "<null>") 12023 + " contains upgrade-key-set reference to unknown key-set: " 12024 + upgradeKeySets[i] 12025 + " reverting to signatures check."); 12026 return false; 12027 } 12028 } 12029 return true; 12030 } 12031 12032 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12033 // Upgrade keysets are being used. Determine if new package has a superset of the 12034 // required keys. 12035 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12036 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12037 for (int i = 0; i < upgradeKeySets.length; i++) { 12038 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12039 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12040 return true; 12041 } 12042 } 12043 return false; 12044 } 12045 12046 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12047 UserHandle user, String installerPackageName, String volumeUuid, 12048 PackageInstalledInfo res) { 12049 final PackageParser.Package oldPackage; 12050 final String pkgName = pkg.packageName; 12051 final int[] allUsers; 12052 final boolean[] perUserInstalled; 12053 12054 // First find the old package info and check signatures 12055 synchronized(mPackages) { 12056 oldPackage = mPackages.get(pkgName); 12057 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12058 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12059 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12060 if(!checkUpgradeKeySetLP(ps, pkg)) { 12061 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12062 "New package not signed by keys specified by upgrade-keysets: " 12063 + pkgName); 12064 return; 12065 } 12066 } else { 12067 // default to original signature matching 12068 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12069 != PackageManager.SIGNATURE_MATCH) { 12070 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12071 "New package has a different signature: " + pkgName); 12072 return; 12073 } 12074 } 12075 12076 // In case of rollback, remember per-user/profile install state 12077 allUsers = sUserManager.getUserIds(); 12078 perUserInstalled = new boolean[allUsers.length]; 12079 for (int i = 0; i < allUsers.length; i++) { 12080 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12081 } 12082 } 12083 12084 boolean sysPkg = (isSystemApp(oldPackage)); 12085 if (sysPkg) { 12086 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12087 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12088 } else { 12089 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12090 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12091 } 12092 } 12093 12094 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12095 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12096 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12097 String volumeUuid, PackageInstalledInfo res) { 12098 String pkgName = deletedPackage.packageName; 12099 boolean deletedPkg = true; 12100 boolean updatedSettings = false; 12101 12102 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12103 + deletedPackage); 12104 long origUpdateTime; 12105 if (pkg.mExtras != null) { 12106 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12107 } else { 12108 origUpdateTime = 0; 12109 } 12110 12111 // First delete the existing package while retaining the data directory 12112 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12113 res.removedInfo, true)) { 12114 // If the existing package wasn't successfully deleted 12115 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12116 deletedPkg = false; 12117 } else { 12118 // Successfully deleted the old package; proceed with replace. 12119 12120 // If deleted package lived in a container, give users a chance to 12121 // relinquish resources before killing. 12122 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12123 if (DEBUG_INSTALL) { 12124 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12125 } 12126 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12127 final ArrayList<String> pkgList = new ArrayList<String>(1); 12128 pkgList.add(deletedPackage.applicationInfo.packageName); 12129 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12130 } 12131 12132 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12133 try { 12134 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12135 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12136 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12137 perUserInstalled, res, user); 12138 updatedSettings = true; 12139 } catch (PackageManagerException e) { 12140 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12141 } 12142 } 12143 12144 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12145 // remove package from internal structures. Note that we want deletePackageX to 12146 // delete the package data and cache directories that it created in 12147 // scanPackageLocked, unless those directories existed before we even tried to 12148 // install. 12149 if(updatedSettings) { 12150 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12151 deletePackageLI( 12152 pkgName, null, true, allUsers, perUserInstalled, 12153 PackageManager.DELETE_KEEP_DATA, 12154 res.removedInfo, true); 12155 } 12156 // Since we failed to install the new package we need to restore the old 12157 // package that we deleted. 12158 if (deletedPkg) { 12159 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12160 File restoreFile = new File(deletedPackage.codePath); 12161 // Parse old package 12162 boolean oldExternal = isExternal(deletedPackage); 12163 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12164 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12165 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12166 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12167 try { 12168 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12169 null); 12170 } catch (PackageManagerException e) { 12171 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12172 + e.getMessage()); 12173 return; 12174 } 12175 // Restore of old package succeeded. Update permissions. 12176 // writer 12177 synchronized (mPackages) { 12178 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12179 UPDATE_PERMISSIONS_ALL); 12180 // can downgrade to reader 12181 mSettings.writeLPr(); 12182 } 12183 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12184 } 12185 } 12186 } 12187 12188 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12189 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12190 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12191 String volumeUuid, PackageInstalledInfo res) { 12192 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12193 + ", old=" + deletedPackage); 12194 boolean disabledSystem = false; 12195 boolean updatedSettings = false; 12196 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12197 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12198 != 0) { 12199 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12200 } 12201 String packageName = deletedPackage.packageName; 12202 if (packageName == null) { 12203 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12204 "Attempt to delete null packageName."); 12205 return; 12206 } 12207 PackageParser.Package oldPkg; 12208 PackageSetting oldPkgSetting; 12209 // reader 12210 synchronized (mPackages) { 12211 oldPkg = mPackages.get(packageName); 12212 oldPkgSetting = mSettings.mPackages.get(packageName); 12213 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12214 (oldPkgSetting == null)) { 12215 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12216 "Couldn't find package:" + packageName + " information"); 12217 return; 12218 } 12219 } 12220 12221 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12222 12223 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12224 res.removedInfo.removedPackage = packageName; 12225 // Remove existing system package 12226 removePackageLI(oldPkgSetting, true); 12227 // writer 12228 synchronized (mPackages) { 12229 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12230 if (!disabledSystem && deletedPackage != null) { 12231 // We didn't need to disable the .apk as a current system package, 12232 // which means we are replacing another update that is already 12233 // installed. We need to make sure to delete the older one's .apk. 12234 res.removedInfo.args = createInstallArgsForExisting(0, 12235 deletedPackage.applicationInfo.getCodePath(), 12236 deletedPackage.applicationInfo.getResourcePath(), 12237 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12238 } else { 12239 res.removedInfo.args = null; 12240 } 12241 } 12242 12243 // Successfully disabled the old package. Now proceed with re-installation 12244 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12245 12246 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12247 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12248 12249 PackageParser.Package newPackage = null; 12250 try { 12251 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12252 if (newPackage.mExtras != null) { 12253 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12254 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12255 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12256 12257 // is the update attempting to change shared user? that isn't going to work... 12258 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12259 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12260 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12261 + " to " + newPkgSetting.sharedUser); 12262 updatedSettings = true; 12263 } 12264 } 12265 12266 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12267 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12268 perUserInstalled, res, user); 12269 updatedSettings = true; 12270 } 12271 12272 } catch (PackageManagerException e) { 12273 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12274 } 12275 12276 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12277 // Re installation failed. Restore old information 12278 // Remove new pkg information 12279 if (newPackage != null) { 12280 removeInstalledPackageLI(newPackage, true); 12281 } 12282 // Add back the old system package 12283 try { 12284 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12285 } catch (PackageManagerException e) { 12286 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12287 } 12288 // Restore the old system information in Settings 12289 synchronized (mPackages) { 12290 if (disabledSystem) { 12291 mSettings.enableSystemPackageLPw(packageName); 12292 } 12293 if (updatedSettings) { 12294 mSettings.setInstallerPackageName(packageName, 12295 oldPkgSetting.installerPackageName); 12296 } 12297 mSettings.writeLPr(); 12298 } 12299 } 12300 } 12301 12302 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12303 // Collect all used permissions in the UID 12304 ArraySet<String> usedPermissions = new ArraySet<>(); 12305 final int packageCount = su.packages.size(); 12306 for (int i = 0; i < packageCount; i++) { 12307 PackageSetting ps = su.packages.valueAt(i); 12308 if (ps.pkg == null) { 12309 continue; 12310 } 12311 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12312 for (int j = 0; j < requestedPermCount; j++) { 12313 String permission = ps.pkg.requestedPermissions.get(j); 12314 BasePermission bp = mSettings.mPermissions.get(permission); 12315 if (bp != null) { 12316 usedPermissions.add(permission); 12317 } 12318 } 12319 } 12320 12321 PermissionsState permissionsState = su.getPermissionsState(); 12322 // Prune install permissions 12323 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12324 final int installPermCount = installPermStates.size(); 12325 for (int i = installPermCount - 1; i >= 0; i--) { 12326 PermissionState permissionState = installPermStates.get(i); 12327 if (!usedPermissions.contains(permissionState.getName())) { 12328 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12329 if (bp != null) { 12330 permissionsState.revokeInstallPermission(bp); 12331 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12332 PackageManager.MASK_PERMISSION_FLAGS, 0); 12333 } 12334 } 12335 } 12336 12337 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12338 12339 // Prune runtime permissions 12340 for (int userId : allUserIds) { 12341 List<PermissionState> runtimePermStates = permissionsState 12342 .getRuntimePermissionStates(userId); 12343 final int runtimePermCount = runtimePermStates.size(); 12344 for (int i = runtimePermCount - 1; i >= 0; i--) { 12345 PermissionState permissionState = runtimePermStates.get(i); 12346 if (!usedPermissions.contains(permissionState.getName())) { 12347 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12348 if (bp != null) { 12349 permissionsState.revokeRuntimePermission(bp, userId); 12350 permissionsState.updatePermissionFlags(bp, userId, 12351 PackageManager.MASK_PERMISSION_FLAGS, 0); 12352 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12353 runtimePermissionChangedUserIds, userId); 12354 } 12355 } 12356 } 12357 } 12358 12359 return runtimePermissionChangedUserIds; 12360 } 12361 12362 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12363 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12364 UserHandle user) { 12365 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12366 12367 String pkgName = newPackage.packageName; 12368 synchronized (mPackages) { 12369 //write settings. the installStatus will be incomplete at this stage. 12370 //note that the new package setting would have already been 12371 //added to mPackages. It hasn't been persisted yet. 12372 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12373 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12374 mSettings.writeLPr(); 12375 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12376 } 12377 12378 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12379 synchronized (mPackages) { 12380 updatePermissionsLPw(newPackage.packageName, newPackage, 12381 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12382 ? UPDATE_PERMISSIONS_ALL : 0)); 12383 // For system-bundled packages, we assume that installing an upgraded version 12384 // of the package implies that the user actually wants to run that new code, 12385 // so we enable the package. 12386 PackageSetting ps = mSettings.mPackages.get(pkgName); 12387 if (ps != null) { 12388 if (isSystemApp(newPackage)) { 12389 // NB: implicit assumption that system package upgrades apply to all users 12390 if (DEBUG_INSTALL) { 12391 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12392 } 12393 if (res.origUsers != null) { 12394 for (int userHandle : res.origUsers) { 12395 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12396 userHandle, installerPackageName); 12397 } 12398 } 12399 // Also convey the prior install/uninstall state 12400 if (allUsers != null && perUserInstalled != null) { 12401 for (int i = 0; i < allUsers.length; i++) { 12402 if (DEBUG_INSTALL) { 12403 Slog.d(TAG, " user " + allUsers[i] 12404 + " => " + perUserInstalled[i]); 12405 } 12406 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12407 } 12408 // these install state changes will be persisted in the 12409 // upcoming call to mSettings.writeLPr(). 12410 } 12411 } 12412 // It's implied that when a user requests installation, they want the app to be 12413 // installed and enabled. 12414 int userId = user.getIdentifier(); 12415 if (userId != UserHandle.USER_ALL) { 12416 ps.setInstalled(true, userId); 12417 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12418 } 12419 } 12420 res.name = pkgName; 12421 res.uid = newPackage.applicationInfo.uid; 12422 res.pkg = newPackage; 12423 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12424 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12425 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12426 //to update install status 12427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12428 mSettings.writeLPr(); 12429 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12430 } 12431 12432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12433 } 12434 12435 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12436 try { 12437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12438 installPackageLI(args, res); 12439 } finally { 12440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12441 } 12442 } 12443 12444 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12445 final int installFlags = args.installFlags; 12446 final String installerPackageName = args.installerPackageName; 12447 final String volumeUuid = args.volumeUuid; 12448 final File tmpPackageFile = new File(args.getCodePath()); 12449 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12450 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12451 || (args.volumeUuid != null)); 12452 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12453 boolean replace = false; 12454 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12455 if (args.move != null) { 12456 // moving a complete application; perfom an initial scan on the new install location 12457 scanFlags |= SCAN_INITIAL; 12458 } 12459 // Result object to be returned 12460 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12461 12462 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12463 12464 // Retrieve PackageSettings and parse package 12465 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12466 | PackageParser.PARSE_ENFORCE_CODE 12467 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12468 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12469 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12470 PackageParser pp = new PackageParser(); 12471 pp.setSeparateProcesses(mSeparateProcesses); 12472 pp.setDisplayMetrics(mMetrics); 12473 12474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12475 final PackageParser.Package pkg; 12476 try { 12477 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12478 } catch (PackageParserException e) { 12479 res.setError("Failed parse during installPackageLI", e); 12480 return; 12481 } finally { 12482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12483 } 12484 12485 // Mark that we have an install time CPU ABI override. 12486 pkg.cpuAbiOverride = args.abiOverride; 12487 12488 String pkgName = res.name = pkg.packageName; 12489 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12490 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12491 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12492 return; 12493 } 12494 } 12495 12496 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12497 try { 12498 pp.collectCertificates(pkg, parseFlags); 12499 } catch (PackageParserException e) { 12500 res.setError("Failed collect during installPackageLI", e); 12501 return; 12502 } finally { 12503 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12504 } 12505 12506 /* If the installer passed in a manifest digest, compare it now. */ 12507 if (args.manifestDigest != null) { 12508 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12509 try { 12510 pp.collectManifestDigest(pkg); 12511 } catch (PackageParserException e) { 12512 res.setError("Failed collect during installPackageLI", e); 12513 return; 12514 } finally { 12515 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12516 } 12517 12518 if (DEBUG_INSTALL) { 12519 final String parsedManifest = pkg.manifestDigest == null ? "null" 12520 : pkg.manifestDigest.toString(); 12521 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12522 + parsedManifest); 12523 } 12524 12525 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12526 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12527 return; 12528 } 12529 } else if (DEBUG_INSTALL) { 12530 final String parsedManifest = pkg.manifestDigest == null 12531 ? "null" : pkg.manifestDigest.toString(); 12532 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12533 } 12534 12535 // Get rid of all references to package scan path via parser. 12536 pp = null; 12537 String oldCodePath = null; 12538 boolean systemApp = false; 12539 synchronized (mPackages) { 12540 // Check if installing already existing package 12541 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12542 String oldName = mSettings.mRenamedPackages.get(pkgName); 12543 if (pkg.mOriginalPackages != null 12544 && pkg.mOriginalPackages.contains(oldName) 12545 && mPackages.containsKey(oldName)) { 12546 // This package is derived from an original package, 12547 // and this device has been updating from that original 12548 // name. We must continue using the original name, so 12549 // rename the new package here. 12550 pkg.setPackageName(oldName); 12551 pkgName = pkg.packageName; 12552 replace = true; 12553 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12554 + oldName + " pkgName=" + pkgName); 12555 } else if (mPackages.containsKey(pkgName)) { 12556 // This package, under its official name, already exists 12557 // on the device; we should replace it. 12558 replace = true; 12559 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12560 } 12561 12562 // Prevent apps opting out from runtime permissions 12563 if (replace) { 12564 PackageParser.Package oldPackage = mPackages.get(pkgName); 12565 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12566 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12567 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12568 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12569 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12570 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12571 + " doesn't support runtime permissions but the old" 12572 + " target SDK " + oldTargetSdk + " does."); 12573 return; 12574 } 12575 } 12576 } 12577 12578 PackageSetting ps = mSettings.mPackages.get(pkgName); 12579 if (ps != null) { 12580 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12581 12582 // Quick sanity check that we're signed correctly if updating; 12583 // we'll check this again later when scanning, but we want to 12584 // bail early here before tripping over redefined permissions. 12585 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12586 if (!checkUpgradeKeySetLP(ps, pkg)) { 12587 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12588 + pkg.packageName + " upgrade keys do not match the " 12589 + "previously installed version"); 12590 return; 12591 } 12592 } else { 12593 try { 12594 verifySignaturesLP(ps, pkg); 12595 } catch (PackageManagerException e) { 12596 res.setError(e.error, e.getMessage()); 12597 return; 12598 } 12599 } 12600 12601 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12602 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12603 systemApp = (ps.pkg.applicationInfo.flags & 12604 ApplicationInfo.FLAG_SYSTEM) != 0; 12605 } 12606 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12607 } 12608 12609 // Check whether the newly-scanned package wants to define an already-defined perm 12610 int N = pkg.permissions.size(); 12611 for (int i = N-1; i >= 0; i--) { 12612 PackageParser.Permission perm = pkg.permissions.get(i); 12613 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12614 if (bp != null) { 12615 // If the defining package is signed with our cert, it's okay. This 12616 // also includes the "updating the same package" case, of course. 12617 // "updating same package" could also involve key-rotation. 12618 final boolean sigsOk; 12619 if (bp.sourcePackage.equals(pkg.packageName) 12620 && (bp.packageSetting instanceof PackageSetting) 12621 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12622 scanFlags))) { 12623 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12624 } else { 12625 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12626 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12627 } 12628 if (!sigsOk) { 12629 // If the owning package is the system itself, we log but allow 12630 // install to proceed; we fail the install on all other permission 12631 // redefinitions. 12632 if (!bp.sourcePackage.equals("android")) { 12633 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12634 + pkg.packageName + " attempting to redeclare permission " 12635 + perm.info.name + " already owned by " + bp.sourcePackage); 12636 res.origPermission = perm.info.name; 12637 res.origPackage = bp.sourcePackage; 12638 return; 12639 } else { 12640 Slog.w(TAG, "Package " + pkg.packageName 12641 + " attempting to redeclare system permission " 12642 + perm.info.name + "; ignoring new declaration"); 12643 pkg.permissions.remove(i); 12644 } 12645 } 12646 } 12647 } 12648 12649 } 12650 12651 if (systemApp && onExternal) { 12652 // Disable updates to system apps on sdcard 12653 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12654 "Cannot install updates to system apps on sdcard"); 12655 return; 12656 } 12657 12658 if (args.move != null) { 12659 // We did an in-place move, so dex is ready to roll 12660 scanFlags |= SCAN_NO_DEX; 12661 scanFlags |= SCAN_MOVE; 12662 12663 synchronized (mPackages) { 12664 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12665 if (ps == null) { 12666 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12667 "Missing settings for moved package " + pkgName); 12668 } 12669 12670 // We moved the entire application as-is, so bring over the 12671 // previously derived ABI information. 12672 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12673 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12674 } 12675 12676 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12677 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12678 scanFlags |= SCAN_NO_DEX; 12679 12680 try { 12681 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12682 true /* extract libs */); 12683 } catch (PackageManagerException pme) { 12684 Slog.e(TAG, "Error deriving application ABI", pme); 12685 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12686 return; 12687 } 12688 12689 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12690 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12691 12692 int result = mPackageDexOptimizer 12693 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12694 false /* defer */, false /* inclDependencies */, 12695 true /*bootComplete*/, quickInstall /*useJit*/); 12696 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12697 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12698 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12699 return; 12700 } 12701 } 12702 12703 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12704 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12705 return; 12706 } 12707 12708 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12709 12710 if (replace) { 12711 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12712 installerPackageName, volumeUuid, res); 12713 } else { 12714 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12715 args.user, installerPackageName, volumeUuid, res); 12716 } 12717 synchronized (mPackages) { 12718 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12719 if (ps != null) { 12720 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12721 } 12722 } 12723 } 12724 12725 private void startIntentFilterVerifications(int userId, boolean replacing, 12726 PackageParser.Package pkg) { 12727 if (mIntentFilterVerifierComponent == null) { 12728 Slog.w(TAG, "No IntentFilter verification will not be done as " 12729 + "there is no IntentFilterVerifier available!"); 12730 return; 12731 } 12732 12733 final int verifierUid = getPackageUid( 12734 mIntentFilterVerifierComponent.getPackageName(), 12735 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12736 12737 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12738 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12739 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12740 mHandler.sendMessage(msg); 12741 } 12742 12743 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12744 PackageParser.Package pkg) { 12745 int size = pkg.activities.size(); 12746 if (size == 0) { 12747 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12748 "No activity, so no need to verify any IntentFilter!"); 12749 return; 12750 } 12751 12752 final boolean hasDomainURLs = hasDomainURLs(pkg); 12753 if (!hasDomainURLs) { 12754 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12755 "No domain URLs, so no need to verify any IntentFilter!"); 12756 return; 12757 } 12758 12759 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12760 + " if any IntentFilter from the " + size 12761 + " Activities needs verification ..."); 12762 12763 int count = 0; 12764 final String packageName = pkg.packageName; 12765 12766 synchronized (mPackages) { 12767 // If this is a new install and we see that we've already run verification for this 12768 // package, we have nothing to do: it means the state was restored from backup. 12769 if (!replacing) { 12770 IntentFilterVerificationInfo ivi = 12771 mSettings.getIntentFilterVerificationLPr(packageName); 12772 if (ivi != null) { 12773 if (DEBUG_DOMAIN_VERIFICATION) { 12774 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12775 + ivi.getStatusString()); 12776 } 12777 return; 12778 } 12779 } 12780 12781 // If any filters need to be verified, then all need to be. 12782 boolean needToVerify = false; 12783 for (PackageParser.Activity a : pkg.activities) { 12784 for (ActivityIntentInfo filter : a.intents) { 12785 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12786 if (DEBUG_DOMAIN_VERIFICATION) { 12787 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12788 } 12789 needToVerify = true; 12790 break; 12791 } 12792 } 12793 } 12794 12795 if (needToVerify) { 12796 final int verificationId = mIntentFilterVerificationToken++; 12797 for (PackageParser.Activity a : pkg.activities) { 12798 for (ActivityIntentInfo filter : a.intents) { 12799 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12800 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12801 "Verification needed for IntentFilter:" + filter.toString()); 12802 mIntentFilterVerifier.addOneIntentFilterVerification( 12803 verifierUid, userId, verificationId, filter, packageName); 12804 count++; 12805 } 12806 } 12807 } 12808 } 12809 } 12810 12811 if (count > 0) { 12812 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12813 + " IntentFilter verification" + (count > 1 ? "s" : "") 12814 + " for userId:" + userId); 12815 mIntentFilterVerifier.startVerifications(userId); 12816 } else { 12817 if (DEBUG_DOMAIN_VERIFICATION) { 12818 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12819 } 12820 } 12821 } 12822 12823 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12824 final ComponentName cn = filter.activity.getComponentName(); 12825 final String packageName = cn.getPackageName(); 12826 12827 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12828 packageName); 12829 if (ivi == null) { 12830 return true; 12831 } 12832 int status = ivi.getStatus(); 12833 switch (status) { 12834 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12835 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12836 return true; 12837 12838 default: 12839 // Nothing to do 12840 return false; 12841 } 12842 } 12843 12844 private static boolean isMultiArch(PackageSetting ps) { 12845 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12846 } 12847 12848 private static boolean isMultiArch(ApplicationInfo info) { 12849 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12850 } 12851 12852 private static boolean isExternal(PackageParser.Package pkg) { 12853 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12854 } 12855 12856 private static boolean isExternal(PackageSetting ps) { 12857 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12858 } 12859 12860 private static boolean isExternal(ApplicationInfo info) { 12861 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12862 } 12863 12864 private static boolean isSystemApp(PackageParser.Package pkg) { 12865 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12866 } 12867 12868 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12869 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12870 } 12871 12872 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12873 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12874 } 12875 12876 private static boolean isSystemApp(PackageSetting ps) { 12877 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12878 } 12879 12880 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12881 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12882 } 12883 12884 private int packageFlagsToInstallFlags(PackageSetting ps) { 12885 int installFlags = 0; 12886 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12887 // This existing package was an external ASEC install when we have 12888 // the external flag without a UUID 12889 installFlags |= PackageManager.INSTALL_EXTERNAL; 12890 } 12891 if (ps.isForwardLocked()) { 12892 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12893 } 12894 return installFlags; 12895 } 12896 12897 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12898 if (isExternal(pkg)) { 12899 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12900 return StorageManager.UUID_PRIMARY_PHYSICAL; 12901 } else { 12902 return pkg.volumeUuid; 12903 } 12904 } else { 12905 return StorageManager.UUID_PRIVATE_INTERNAL; 12906 } 12907 } 12908 12909 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12910 if (isExternal(pkg)) { 12911 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12912 return mSettings.getExternalVersion(); 12913 } else { 12914 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12915 } 12916 } else { 12917 return mSettings.getInternalVersion(); 12918 } 12919 } 12920 12921 private void deleteTempPackageFiles() { 12922 final FilenameFilter filter = new FilenameFilter() { 12923 public boolean accept(File dir, String name) { 12924 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12925 } 12926 }; 12927 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12928 file.delete(); 12929 } 12930 } 12931 12932 @Override 12933 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12934 int flags) { 12935 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12936 flags); 12937 } 12938 12939 @Override 12940 public void deletePackage(final String packageName, 12941 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12942 mContext.enforceCallingOrSelfPermission( 12943 android.Manifest.permission.DELETE_PACKAGES, null); 12944 Preconditions.checkNotNull(packageName); 12945 Preconditions.checkNotNull(observer); 12946 final int uid = Binder.getCallingUid(); 12947 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12948 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12949 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12950 mContext.enforceCallingPermission( 12951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12952 "deletePackage for user " + userId); 12953 } 12954 12955 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12956 try { 12957 observer.onPackageDeleted(packageName, 12958 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12959 } catch (RemoteException re) { 12960 } 12961 return; 12962 } 12963 12964 for (int currentUserId : users) { 12965 if (getBlockUninstallForUser(packageName, currentUserId)) { 12966 try { 12967 observer.onPackageDeleted(packageName, 12968 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12969 } catch (RemoteException re) { 12970 } 12971 return; 12972 } 12973 } 12974 12975 if (DEBUG_REMOVE) { 12976 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12977 } 12978 // Queue up an async operation since the package deletion may take a little while. 12979 mHandler.post(new Runnable() { 12980 public void run() { 12981 mHandler.removeCallbacks(this); 12982 final int returnCode = deletePackageX(packageName, userId, flags); 12983 try { 12984 observer.onPackageDeleted(packageName, returnCode, null); 12985 } catch (RemoteException e) { 12986 Log.i(TAG, "Observer no longer exists."); 12987 } //end catch 12988 } //end run 12989 }); 12990 } 12991 12992 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12993 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12994 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12995 try { 12996 if (dpm != null) { 12997 // Does the package contains the device owner? 12998 if (dpm.isDeviceOwnerPackage(packageName)) { 12999 return true; 13000 } 13001 // Does it contain a device admin for any user? 13002 int[] users; 13003 if (userId == UserHandle.USER_ALL) { 13004 users = sUserManager.getUserIds(); 13005 } else { 13006 users = new int[]{userId}; 13007 } 13008 for (int i = 0; i < users.length; ++i) { 13009 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13010 return true; 13011 } 13012 } 13013 } 13014 } catch (RemoteException e) { 13015 } 13016 return false; 13017 } 13018 13019 /** 13020 * This method is an internal method that could be get invoked either 13021 * to delete an installed package or to clean up a failed installation. 13022 * After deleting an installed package, a broadcast is sent to notify any 13023 * listeners that the package has been installed. For cleaning up a failed 13024 * installation, the broadcast is not necessary since the package's 13025 * installation wouldn't have sent the initial broadcast either 13026 * The key steps in deleting a package are 13027 * deleting the package information in internal structures like mPackages, 13028 * deleting the packages base directories through installd 13029 * updating mSettings to reflect current status 13030 * persisting settings for later use 13031 * sending a broadcast if necessary 13032 */ 13033 private int deletePackageX(String packageName, int userId, int flags) { 13034 final PackageRemovedInfo info = new PackageRemovedInfo(); 13035 final boolean res; 13036 13037 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13038 ? UserHandle.ALL : new UserHandle(userId); 13039 13040 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13041 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13042 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13043 } 13044 13045 boolean removedForAllUsers = false; 13046 boolean systemUpdate = false; 13047 13048 // for the uninstall-updates case and restricted profiles, remember the per- 13049 // userhandle installed state 13050 int[] allUsers; 13051 boolean[] perUserInstalled; 13052 synchronized (mPackages) { 13053 PackageSetting ps = mSettings.mPackages.get(packageName); 13054 allUsers = sUserManager.getUserIds(); 13055 perUserInstalled = new boolean[allUsers.length]; 13056 for (int i = 0; i < allUsers.length; i++) { 13057 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13058 } 13059 } 13060 13061 synchronized (mInstallLock) { 13062 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13063 res = deletePackageLI(packageName, removeForUser, 13064 true, allUsers, perUserInstalled, 13065 flags | REMOVE_CHATTY, info, true); 13066 systemUpdate = info.isRemovedPackageSystemUpdate; 13067 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13068 removedForAllUsers = true; 13069 } 13070 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13071 + " removedForAllUsers=" + removedForAllUsers); 13072 } 13073 13074 if (res) { 13075 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13076 13077 // If the removed package was a system update, the old system package 13078 // was re-enabled; we need to broadcast this information 13079 if (systemUpdate) { 13080 Bundle extras = new Bundle(1); 13081 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13082 ? info.removedAppId : info.uid); 13083 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13084 13085 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13086 extras, null, null, null); 13087 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13088 extras, null, null, null); 13089 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13090 null, packageName, null, null); 13091 } 13092 } 13093 // Force a gc here. 13094 Runtime.getRuntime().gc(); 13095 // Delete the resources here after sending the broadcast to let 13096 // other processes clean up before deleting resources. 13097 if (info.args != null) { 13098 synchronized (mInstallLock) { 13099 info.args.doPostDeleteLI(true); 13100 } 13101 } 13102 13103 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13104 } 13105 13106 class PackageRemovedInfo { 13107 String removedPackage; 13108 int uid = -1; 13109 int removedAppId = -1; 13110 int[] removedUsers = null; 13111 boolean isRemovedPackageSystemUpdate = false; 13112 // Clean up resources deleted packages. 13113 InstallArgs args = null; 13114 13115 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13116 Bundle extras = new Bundle(1); 13117 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13118 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13119 if (replacing) { 13120 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13121 } 13122 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13123 if (removedPackage != null) { 13124 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13125 extras, null, null, removedUsers); 13126 if (fullRemove && !replacing) { 13127 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13128 extras, null, null, removedUsers); 13129 } 13130 } 13131 if (removedAppId >= 0) { 13132 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13133 removedUsers); 13134 } 13135 } 13136 } 13137 13138 /* 13139 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13140 * flag is not set, the data directory is removed as well. 13141 * make sure this flag is set for partially installed apps. If not its meaningless to 13142 * delete a partially installed application. 13143 */ 13144 private void removePackageDataLI(PackageSetting ps, 13145 int[] allUserHandles, boolean[] perUserInstalled, 13146 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13147 String packageName = ps.name; 13148 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13149 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13150 // Retrieve object to delete permissions for shared user later on 13151 final PackageSetting deletedPs; 13152 // reader 13153 synchronized (mPackages) { 13154 deletedPs = mSettings.mPackages.get(packageName); 13155 if (outInfo != null) { 13156 outInfo.removedPackage = packageName; 13157 outInfo.removedUsers = deletedPs != null 13158 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13159 : null; 13160 } 13161 } 13162 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13163 removeDataDirsLI(ps.volumeUuid, packageName); 13164 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13165 } 13166 // writer 13167 synchronized (mPackages) { 13168 if (deletedPs != null) { 13169 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13170 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13171 clearDefaultBrowserIfNeeded(packageName); 13172 if (outInfo != null) { 13173 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13174 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13175 } 13176 updatePermissionsLPw(deletedPs.name, null, 0); 13177 if (deletedPs.sharedUser != null) { 13178 // Remove permissions associated with package. Since runtime 13179 // permissions are per user we have to kill the removed package 13180 // or packages running under the shared user of the removed 13181 // package if revoking the permissions requested only by the removed 13182 // package is successful and this causes a change in gids. 13183 for (int userId : UserManagerService.getInstance().getUserIds()) { 13184 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13185 userId); 13186 if (userIdToKill == UserHandle.USER_ALL 13187 || userIdToKill >= UserHandle.USER_SYSTEM) { 13188 // If gids changed for this user, kill all affected packages. 13189 mHandler.post(new Runnable() { 13190 @Override 13191 public void run() { 13192 // This has to happen with no lock held. 13193 killApplication(deletedPs.name, deletedPs.appId, 13194 KILL_APP_REASON_GIDS_CHANGED); 13195 } 13196 }); 13197 break; 13198 } 13199 } 13200 } 13201 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13202 } 13203 // make sure to preserve per-user disabled state if this removal was just 13204 // a downgrade of a system app to the factory package 13205 if (allUserHandles != null && perUserInstalled != null) { 13206 if (DEBUG_REMOVE) { 13207 Slog.d(TAG, "Propagating install state across downgrade"); 13208 } 13209 for (int i = 0; i < allUserHandles.length; i++) { 13210 if (DEBUG_REMOVE) { 13211 Slog.d(TAG, " user " + allUserHandles[i] 13212 + " => " + perUserInstalled[i]); 13213 } 13214 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13215 } 13216 } 13217 } 13218 // can downgrade to reader 13219 if (writeSettings) { 13220 // Save settings now 13221 mSettings.writeLPr(); 13222 } 13223 } 13224 if (outInfo != null) { 13225 // A user ID was deleted here. Go through all users and remove it 13226 // from KeyStore. 13227 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13228 } 13229 } 13230 13231 static boolean locationIsPrivileged(File path) { 13232 try { 13233 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13234 .getCanonicalPath(); 13235 return path.getCanonicalPath().startsWith(privilegedAppDir); 13236 } catch (IOException e) { 13237 Slog.e(TAG, "Unable to access code path " + path); 13238 } 13239 return false; 13240 } 13241 13242 /* 13243 * Tries to delete system package. 13244 */ 13245 private boolean deleteSystemPackageLI(PackageSetting newPs, 13246 int[] allUserHandles, boolean[] perUserInstalled, 13247 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13248 final boolean applyUserRestrictions 13249 = (allUserHandles != null) && (perUserInstalled != null); 13250 PackageSetting disabledPs = null; 13251 // Confirm if the system package has been updated 13252 // An updated system app can be deleted. This will also have to restore 13253 // the system pkg from system partition 13254 // reader 13255 synchronized (mPackages) { 13256 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13257 } 13258 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13259 + " disabledPs=" + disabledPs); 13260 if (disabledPs == null) { 13261 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13262 return false; 13263 } else if (DEBUG_REMOVE) { 13264 Slog.d(TAG, "Deleting system pkg from data partition"); 13265 } 13266 if (DEBUG_REMOVE) { 13267 if (applyUserRestrictions) { 13268 Slog.d(TAG, "Remembering install states:"); 13269 for (int i = 0; i < allUserHandles.length; i++) { 13270 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13271 } 13272 } 13273 } 13274 // Delete the updated package 13275 outInfo.isRemovedPackageSystemUpdate = true; 13276 if (disabledPs.versionCode < newPs.versionCode) { 13277 // Delete data for downgrades 13278 flags &= ~PackageManager.DELETE_KEEP_DATA; 13279 } else { 13280 // Preserve data by setting flag 13281 flags |= PackageManager.DELETE_KEEP_DATA; 13282 } 13283 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13284 allUserHandles, perUserInstalled, outInfo, writeSettings); 13285 if (!ret) { 13286 return false; 13287 } 13288 // writer 13289 synchronized (mPackages) { 13290 // Reinstate the old system package 13291 mSettings.enableSystemPackageLPw(newPs.name); 13292 // Remove any native libraries from the upgraded package. 13293 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13294 } 13295 // Install the system package 13296 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13297 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13298 if (locationIsPrivileged(disabledPs.codePath)) { 13299 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13300 } 13301 13302 final PackageParser.Package newPkg; 13303 try { 13304 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13305 } catch (PackageManagerException e) { 13306 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13307 return false; 13308 } 13309 13310 // writer 13311 synchronized (mPackages) { 13312 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13313 13314 // Propagate the permissions state as we do not want to drop on the floor 13315 // runtime permissions. The update permissions method below will take 13316 // care of removing obsolete permissions and grant install permissions. 13317 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13318 updatePermissionsLPw(newPkg.packageName, newPkg, 13319 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13320 13321 if (applyUserRestrictions) { 13322 if (DEBUG_REMOVE) { 13323 Slog.d(TAG, "Propagating install state across reinstall"); 13324 } 13325 for (int i = 0; i < allUserHandles.length; i++) { 13326 if (DEBUG_REMOVE) { 13327 Slog.d(TAG, " user " + allUserHandles[i] 13328 + " => " + perUserInstalled[i]); 13329 } 13330 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13331 13332 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13333 } 13334 // Regardless of writeSettings we need to ensure that this restriction 13335 // state propagation is persisted 13336 mSettings.writeAllUsersPackageRestrictionsLPr(); 13337 } 13338 // can downgrade to reader here 13339 if (writeSettings) { 13340 mSettings.writeLPr(); 13341 } 13342 } 13343 return true; 13344 } 13345 13346 private boolean deleteInstalledPackageLI(PackageSetting ps, 13347 boolean deleteCodeAndResources, int flags, 13348 int[] allUserHandles, boolean[] perUserInstalled, 13349 PackageRemovedInfo outInfo, boolean writeSettings) { 13350 if (outInfo != null) { 13351 outInfo.uid = ps.appId; 13352 } 13353 13354 // Delete package data from internal structures and also remove data if flag is set 13355 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13356 13357 // Delete application code and resources 13358 if (deleteCodeAndResources && (outInfo != null)) { 13359 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13360 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13361 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13362 } 13363 return true; 13364 } 13365 13366 @Override 13367 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13368 int userId) { 13369 mContext.enforceCallingOrSelfPermission( 13370 android.Manifest.permission.DELETE_PACKAGES, null); 13371 synchronized (mPackages) { 13372 PackageSetting ps = mSettings.mPackages.get(packageName); 13373 if (ps == null) { 13374 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13375 return false; 13376 } 13377 if (!ps.getInstalled(userId)) { 13378 // Can't block uninstall for an app that is not installed or enabled. 13379 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13380 return false; 13381 } 13382 ps.setBlockUninstall(blockUninstall, userId); 13383 mSettings.writePackageRestrictionsLPr(userId); 13384 } 13385 return true; 13386 } 13387 13388 @Override 13389 public boolean getBlockUninstallForUser(String packageName, int userId) { 13390 synchronized (mPackages) { 13391 PackageSetting ps = mSettings.mPackages.get(packageName); 13392 if (ps == null) { 13393 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13394 return false; 13395 } 13396 return ps.getBlockUninstall(userId); 13397 } 13398 } 13399 13400 /* 13401 * This method handles package deletion in general 13402 */ 13403 private boolean deletePackageLI(String packageName, UserHandle user, 13404 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13405 int flags, PackageRemovedInfo outInfo, 13406 boolean writeSettings) { 13407 if (packageName == null) { 13408 Slog.w(TAG, "Attempt to delete null packageName."); 13409 return false; 13410 } 13411 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13412 PackageSetting ps; 13413 boolean dataOnly = false; 13414 int removeUser = -1; 13415 int appId = -1; 13416 synchronized (mPackages) { 13417 ps = mSettings.mPackages.get(packageName); 13418 if (ps == null) { 13419 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13420 return false; 13421 } 13422 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13423 && user.getIdentifier() != UserHandle.USER_ALL) { 13424 // The caller is asking that the package only be deleted for a single 13425 // user. To do this, we just mark its uninstalled state and delete 13426 // its data. If this is a system app, we only allow this to happen if 13427 // they have set the special DELETE_SYSTEM_APP which requests different 13428 // semantics than normal for uninstalling system apps. 13429 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13430 final int userId = user.getIdentifier(); 13431 ps.setUserState(userId, 13432 COMPONENT_ENABLED_STATE_DEFAULT, 13433 false, //installed 13434 true, //stopped 13435 true, //notLaunched 13436 false, //hidden 13437 null, null, null, 13438 false, // blockUninstall 13439 ps.readUserState(userId).domainVerificationStatus, 0); 13440 if (!isSystemApp(ps)) { 13441 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13442 // Other user still have this package installed, so all 13443 // we need to do is clear this user's data and save that 13444 // it is uninstalled. 13445 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13446 removeUser = user.getIdentifier(); 13447 appId = ps.appId; 13448 scheduleWritePackageRestrictionsLocked(removeUser); 13449 } else { 13450 // We need to set it back to 'installed' so the uninstall 13451 // broadcasts will be sent correctly. 13452 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13453 ps.setInstalled(true, user.getIdentifier()); 13454 } 13455 } else { 13456 // This is a system app, so we assume that the 13457 // other users still have this package installed, so all 13458 // we need to do is clear this user's data and save that 13459 // it is uninstalled. 13460 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13461 removeUser = user.getIdentifier(); 13462 appId = ps.appId; 13463 scheduleWritePackageRestrictionsLocked(removeUser); 13464 } 13465 } 13466 } 13467 13468 if (removeUser >= 0) { 13469 // From above, we determined that we are deleting this only 13470 // for a single user. Continue the work here. 13471 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13472 if (outInfo != null) { 13473 outInfo.removedPackage = packageName; 13474 outInfo.removedAppId = appId; 13475 outInfo.removedUsers = new int[] {removeUser}; 13476 } 13477 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13478 removeKeystoreDataIfNeeded(removeUser, appId); 13479 schedulePackageCleaning(packageName, removeUser, false); 13480 synchronized (mPackages) { 13481 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13482 scheduleWritePackageRestrictionsLocked(removeUser); 13483 } 13484 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13485 } 13486 return true; 13487 } 13488 13489 if (dataOnly) { 13490 // Delete application data first 13491 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13492 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13493 return true; 13494 } 13495 13496 boolean ret = false; 13497 if (isSystemApp(ps)) { 13498 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13499 // When an updated system application is deleted we delete the existing resources as well and 13500 // fall back to existing code in system partition 13501 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13502 flags, outInfo, writeSettings); 13503 } else { 13504 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13505 // Kill application pre-emptively especially for apps on sd. 13506 killApplication(packageName, ps.appId, "uninstall pkg"); 13507 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13508 allUserHandles, perUserInstalled, 13509 outInfo, writeSettings); 13510 } 13511 13512 return ret; 13513 } 13514 13515 private final class ClearStorageConnection implements ServiceConnection { 13516 IMediaContainerService mContainerService; 13517 13518 @Override 13519 public void onServiceConnected(ComponentName name, IBinder service) { 13520 synchronized (this) { 13521 mContainerService = IMediaContainerService.Stub.asInterface(service); 13522 notifyAll(); 13523 } 13524 } 13525 13526 @Override 13527 public void onServiceDisconnected(ComponentName name) { 13528 } 13529 } 13530 13531 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13532 final boolean mounted; 13533 if (Environment.isExternalStorageEmulated()) { 13534 mounted = true; 13535 } else { 13536 final String status = Environment.getExternalStorageState(); 13537 13538 mounted = status.equals(Environment.MEDIA_MOUNTED) 13539 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13540 } 13541 13542 if (!mounted) { 13543 return; 13544 } 13545 13546 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13547 int[] users; 13548 if (userId == UserHandle.USER_ALL) { 13549 users = sUserManager.getUserIds(); 13550 } else { 13551 users = new int[] { userId }; 13552 } 13553 final ClearStorageConnection conn = new ClearStorageConnection(); 13554 if (mContext.bindServiceAsUser( 13555 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13556 try { 13557 for (int curUser : users) { 13558 long timeout = SystemClock.uptimeMillis() + 5000; 13559 synchronized (conn) { 13560 long now = SystemClock.uptimeMillis(); 13561 while (conn.mContainerService == null && now < timeout) { 13562 try { 13563 conn.wait(timeout - now); 13564 } catch (InterruptedException e) { 13565 } 13566 } 13567 } 13568 if (conn.mContainerService == null) { 13569 return; 13570 } 13571 13572 final UserEnvironment userEnv = new UserEnvironment(curUser); 13573 clearDirectory(conn.mContainerService, 13574 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13575 if (allData) { 13576 clearDirectory(conn.mContainerService, 13577 userEnv.buildExternalStorageAppDataDirs(packageName)); 13578 clearDirectory(conn.mContainerService, 13579 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13580 } 13581 } 13582 } finally { 13583 mContext.unbindService(conn); 13584 } 13585 } 13586 } 13587 13588 @Override 13589 public void clearApplicationUserData(final String packageName, 13590 final IPackageDataObserver observer, final int userId) { 13591 mContext.enforceCallingOrSelfPermission( 13592 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13593 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13594 // Queue up an async operation since the package deletion may take a little while. 13595 mHandler.post(new Runnable() { 13596 public void run() { 13597 mHandler.removeCallbacks(this); 13598 final boolean succeeded; 13599 synchronized (mInstallLock) { 13600 succeeded = clearApplicationUserDataLI(packageName, userId); 13601 } 13602 clearExternalStorageDataSync(packageName, userId, true); 13603 if (succeeded) { 13604 // invoke DeviceStorageMonitor's update method to clear any notifications 13605 DeviceStorageMonitorInternal 13606 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13607 if (dsm != null) { 13608 dsm.checkMemory(); 13609 } 13610 } 13611 if(observer != null) { 13612 try { 13613 observer.onRemoveCompleted(packageName, succeeded); 13614 } catch (RemoteException e) { 13615 Log.i(TAG, "Observer no longer exists."); 13616 } 13617 } //end if observer 13618 } //end run 13619 }); 13620 } 13621 13622 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13623 if (packageName == null) { 13624 Slog.w(TAG, "Attempt to delete null packageName."); 13625 return false; 13626 } 13627 13628 // Try finding details about the requested package 13629 PackageParser.Package pkg; 13630 synchronized (mPackages) { 13631 pkg = mPackages.get(packageName); 13632 if (pkg == null) { 13633 final PackageSetting ps = mSettings.mPackages.get(packageName); 13634 if (ps != null) { 13635 pkg = ps.pkg; 13636 } 13637 } 13638 13639 if (pkg == null) { 13640 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13641 return false; 13642 } 13643 13644 PackageSetting ps = (PackageSetting) pkg.mExtras; 13645 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13646 } 13647 13648 // Always delete data directories for package, even if we found no other 13649 // record of app. This helps users recover from UID mismatches without 13650 // resorting to a full data wipe. 13651 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13652 if (retCode < 0) { 13653 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13654 return false; 13655 } 13656 13657 final int appId = pkg.applicationInfo.uid; 13658 removeKeystoreDataIfNeeded(userId, appId); 13659 13660 // Create a native library symlink only if we have native libraries 13661 // and if the native libraries are 32 bit libraries. We do not provide 13662 // this symlink for 64 bit libraries. 13663 if (pkg.applicationInfo.primaryCpuAbi != null && 13664 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13665 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13666 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13667 nativeLibPath, userId) < 0) { 13668 Slog.w(TAG, "Failed linking native library dir"); 13669 return false; 13670 } 13671 } 13672 13673 return true; 13674 } 13675 13676 /** 13677 * Reverts user permission state changes (permissions and flags) in 13678 * all packages for a given user. 13679 * 13680 * @param userId The device user for which to do a reset. 13681 */ 13682 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13683 final int packageCount = mPackages.size(); 13684 for (int i = 0; i < packageCount; i++) { 13685 PackageParser.Package pkg = mPackages.valueAt(i); 13686 PackageSetting ps = (PackageSetting) pkg.mExtras; 13687 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13688 } 13689 } 13690 13691 /** 13692 * Reverts user permission state changes (permissions and flags). 13693 * 13694 * @param ps The package for which to reset. 13695 * @param userId The device user for which to do a reset. 13696 */ 13697 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13698 final PackageSetting ps, final int userId) { 13699 if (ps.pkg == null) { 13700 return; 13701 } 13702 13703 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13704 | FLAG_PERMISSION_USER_FIXED 13705 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13706 13707 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13708 | FLAG_PERMISSION_POLICY_FIXED; 13709 13710 boolean writeInstallPermissions = false; 13711 boolean writeRuntimePermissions = false; 13712 13713 final int permissionCount = ps.pkg.requestedPermissions.size(); 13714 for (int i = 0; i < permissionCount; i++) { 13715 String permission = ps.pkg.requestedPermissions.get(i); 13716 13717 BasePermission bp = mSettings.mPermissions.get(permission); 13718 if (bp == null) { 13719 continue; 13720 } 13721 13722 // If shared user we just reset the state to which only this app contributed. 13723 if (ps.sharedUser != null) { 13724 boolean used = false; 13725 final int packageCount = ps.sharedUser.packages.size(); 13726 for (int j = 0; j < packageCount; j++) { 13727 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13728 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13729 && pkg.pkg.requestedPermissions.contains(permission)) { 13730 used = true; 13731 break; 13732 } 13733 } 13734 if (used) { 13735 continue; 13736 } 13737 } 13738 13739 PermissionsState permissionsState = ps.getPermissionsState(); 13740 13741 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13742 13743 // Always clear the user settable flags. 13744 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13745 bp.name) != null; 13746 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13747 if (hasInstallState) { 13748 writeInstallPermissions = true; 13749 } else { 13750 writeRuntimePermissions = true; 13751 } 13752 } 13753 13754 // Below is only runtime permission handling. 13755 if (!bp.isRuntime()) { 13756 continue; 13757 } 13758 13759 // Never clobber system or policy. 13760 if ((oldFlags & policyOrSystemFlags) != 0) { 13761 continue; 13762 } 13763 13764 // If this permission was granted by default, make sure it is. 13765 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13766 if (permissionsState.grantRuntimePermission(bp, userId) 13767 != PERMISSION_OPERATION_FAILURE) { 13768 writeRuntimePermissions = true; 13769 } 13770 } else { 13771 // Otherwise, reset the permission. 13772 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13773 switch (revokeResult) { 13774 case PERMISSION_OPERATION_SUCCESS: { 13775 writeRuntimePermissions = true; 13776 } break; 13777 13778 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13779 writeRuntimePermissions = true; 13780 final int appId = ps.appId; 13781 mHandler.post(new Runnable() { 13782 @Override 13783 public void run() { 13784 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13785 } 13786 }); 13787 } break; 13788 } 13789 } 13790 } 13791 13792 // Synchronously write as we are taking permissions away. 13793 if (writeRuntimePermissions) { 13794 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13795 } 13796 13797 // Synchronously write as we are taking permissions away. 13798 if (writeInstallPermissions) { 13799 mSettings.writeLPr(); 13800 } 13801 } 13802 13803 /** 13804 * Remove entries from the keystore daemon. Will only remove it if the 13805 * {@code appId} is valid. 13806 */ 13807 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13808 if (appId < 0) { 13809 return; 13810 } 13811 13812 final KeyStore keyStore = KeyStore.getInstance(); 13813 if (keyStore != null) { 13814 if (userId == UserHandle.USER_ALL) { 13815 for (final int individual : sUserManager.getUserIds()) { 13816 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13817 } 13818 } else { 13819 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13820 } 13821 } else { 13822 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13823 } 13824 } 13825 13826 @Override 13827 public void deleteApplicationCacheFiles(final String packageName, 13828 final IPackageDataObserver observer) { 13829 mContext.enforceCallingOrSelfPermission( 13830 android.Manifest.permission.DELETE_CACHE_FILES, null); 13831 // Queue up an async operation since the package deletion may take a little while. 13832 final int userId = UserHandle.getCallingUserId(); 13833 mHandler.post(new Runnable() { 13834 public void run() { 13835 mHandler.removeCallbacks(this); 13836 final boolean succeded; 13837 synchronized (mInstallLock) { 13838 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13839 } 13840 clearExternalStorageDataSync(packageName, userId, false); 13841 if (observer != null) { 13842 try { 13843 observer.onRemoveCompleted(packageName, succeded); 13844 } catch (RemoteException e) { 13845 Log.i(TAG, "Observer no longer exists."); 13846 } 13847 } //end if observer 13848 } //end run 13849 }); 13850 } 13851 13852 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13853 if (packageName == null) { 13854 Slog.w(TAG, "Attempt to delete null packageName."); 13855 return false; 13856 } 13857 PackageParser.Package p; 13858 synchronized (mPackages) { 13859 p = mPackages.get(packageName); 13860 } 13861 if (p == null) { 13862 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13863 return false; 13864 } 13865 final ApplicationInfo applicationInfo = p.applicationInfo; 13866 if (applicationInfo == null) { 13867 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13868 return false; 13869 } 13870 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13871 if (retCode < 0) { 13872 Slog.w(TAG, "Couldn't remove cache files for package: " 13873 + packageName + " u" + userId); 13874 return false; 13875 } 13876 return true; 13877 } 13878 13879 @Override 13880 public void getPackageSizeInfo(final String packageName, int userHandle, 13881 final IPackageStatsObserver observer) { 13882 mContext.enforceCallingOrSelfPermission( 13883 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13884 if (packageName == null) { 13885 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13886 } 13887 13888 PackageStats stats = new PackageStats(packageName, userHandle); 13889 13890 /* 13891 * Queue up an async operation since the package measurement may take a 13892 * little while. 13893 */ 13894 Message msg = mHandler.obtainMessage(INIT_COPY); 13895 msg.obj = new MeasureParams(stats, observer); 13896 mHandler.sendMessage(msg); 13897 } 13898 13899 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13900 PackageStats pStats) { 13901 if (packageName == null) { 13902 Slog.w(TAG, "Attempt to get size of null packageName."); 13903 return false; 13904 } 13905 PackageParser.Package p; 13906 boolean dataOnly = false; 13907 String libDirRoot = null; 13908 String asecPath = null; 13909 PackageSetting ps = null; 13910 synchronized (mPackages) { 13911 p = mPackages.get(packageName); 13912 ps = mSettings.mPackages.get(packageName); 13913 if(p == null) { 13914 dataOnly = true; 13915 if((ps == null) || (ps.pkg == null)) { 13916 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13917 return false; 13918 } 13919 p = ps.pkg; 13920 } 13921 if (ps != null) { 13922 libDirRoot = ps.legacyNativeLibraryPathString; 13923 } 13924 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13925 final long token = Binder.clearCallingIdentity(); 13926 try { 13927 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13928 if (secureContainerId != null) { 13929 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13930 } 13931 } finally { 13932 Binder.restoreCallingIdentity(token); 13933 } 13934 } 13935 } 13936 String publicSrcDir = null; 13937 if(!dataOnly) { 13938 final ApplicationInfo applicationInfo = p.applicationInfo; 13939 if (applicationInfo == null) { 13940 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13941 return false; 13942 } 13943 if (p.isForwardLocked()) { 13944 publicSrcDir = applicationInfo.getBaseResourcePath(); 13945 } 13946 } 13947 // TODO: extend to measure size of split APKs 13948 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13949 // not just the first level. 13950 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13951 // just the primary. 13952 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13953 13954 String apkPath; 13955 File packageDir = new File(p.codePath); 13956 13957 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13958 apkPath = packageDir.getAbsolutePath(); 13959 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13960 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13961 libDirRoot = null; 13962 } 13963 } else { 13964 apkPath = p.baseCodePath; 13965 } 13966 13967 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13968 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13969 if (res < 0) { 13970 return false; 13971 } 13972 13973 // Fix-up for forward-locked applications in ASEC containers. 13974 if (!isExternal(p)) { 13975 pStats.codeSize += pStats.externalCodeSize; 13976 pStats.externalCodeSize = 0L; 13977 } 13978 13979 return true; 13980 } 13981 13982 13983 @Override 13984 public void addPackageToPreferred(String packageName) { 13985 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13986 } 13987 13988 @Override 13989 public void removePackageFromPreferred(String packageName) { 13990 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13991 } 13992 13993 @Override 13994 public List<PackageInfo> getPreferredPackages(int flags) { 13995 return new ArrayList<PackageInfo>(); 13996 } 13997 13998 private int getUidTargetSdkVersionLockedLPr(int uid) { 13999 Object obj = mSettings.getUserIdLPr(uid); 14000 if (obj instanceof SharedUserSetting) { 14001 final SharedUserSetting sus = (SharedUserSetting) obj; 14002 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14003 final Iterator<PackageSetting> it = sus.packages.iterator(); 14004 while (it.hasNext()) { 14005 final PackageSetting ps = it.next(); 14006 if (ps.pkg != null) { 14007 int v = ps.pkg.applicationInfo.targetSdkVersion; 14008 if (v < vers) vers = v; 14009 } 14010 } 14011 return vers; 14012 } else if (obj instanceof PackageSetting) { 14013 final PackageSetting ps = (PackageSetting) obj; 14014 if (ps.pkg != null) { 14015 return ps.pkg.applicationInfo.targetSdkVersion; 14016 } 14017 } 14018 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14019 } 14020 14021 @Override 14022 public void addPreferredActivity(IntentFilter filter, int match, 14023 ComponentName[] set, ComponentName activity, int userId) { 14024 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14025 "Adding preferred"); 14026 } 14027 14028 private void addPreferredActivityInternal(IntentFilter filter, int match, 14029 ComponentName[] set, ComponentName activity, boolean always, int userId, 14030 String opname) { 14031 // writer 14032 int callingUid = Binder.getCallingUid(); 14033 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14034 if (filter.countActions() == 0) { 14035 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14036 return; 14037 } 14038 synchronized (mPackages) { 14039 if (mContext.checkCallingOrSelfPermission( 14040 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14041 != PackageManager.PERMISSION_GRANTED) { 14042 if (getUidTargetSdkVersionLockedLPr(callingUid) 14043 < Build.VERSION_CODES.FROYO) { 14044 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14045 + callingUid); 14046 return; 14047 } 14048 mContext.enforceCallingOrSelfPermission( 14049 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14050 } 14051 14052 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14053 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14054 + userId + ":"); 14055 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14056 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14057 scheduleWritePackageRestrictionsLocked(userId); 14058 } 14059 } 14060 14061 @Override 14062 public void replacePreferredActivity(IntentFilter filter, int match, 14063 ComponentName[] set, ComponentName activity, int userId) { 14064 if (filter.countActions() != 1) { 14065 throw new IllegalArgumentException( 14066 "replacePreferredActivity expects filter to have only 1 action."); 14067 } 14068 if (filter.countDataAuthorities() != 0 14069 || filter.countDataPaths() != 0 14070 || filter.countDataSchemes() > 1 14071 || filter.countDataTypes() != 0) { 14072 throw new IllegalArgumentException( 14073 "replacePreferredActivity expects filter to have no data authorities, " + 14074 "paths, or types; and at most one scheme."); 14075 } 14076 14077 final int callingUid = Binder.getCallingUid(); 14078 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14079 synchronized (mPackages) { 14080 if (mContext.checkCallingOrSelfPermission( 14081 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14082 != PackageManager.PERMISSION_GRANTED) { 14083 if (getUidTargetSdkVersionLockedLPr(callingUid) 14084 < Build.VERSION_CODES.FROYO) { 14085 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14086 + Binder.getCallingUid()); 14087 return; 14088 } 14089 mContext.enforceCallingOrSelfPermission( 14090 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14091 } 14092 14093 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14094 if (pir != null) { 14095 // Get all of the existing entries that exactly match this filter. 14096 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14097 if (existing != null && existing.size() == 1) { 14098 PreferredActivity cur = existing.get(0); 14099 if (DEBUG_PREFERRED) { 14100 Slog.i(TAG, "Checking replace of preferred:"); 14101 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14102 if (!cur.mPref.mAlways) { 14103 Slog.i(TAG, " -- CUR; not mAlways!"); 14104 } else { 14105 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14106 Slog.i(TAG, " -- CUR: mSet=" 14107 + Arrays.toString(cur.mPref.mSetComponents)); 14108 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14109 Slog.i(TAG, " -- NEW: mMatch=" 14110 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14111 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14112 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14113 } 14114 } 14115 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14116 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14117 && cur.mPref.sameSet(set)) { 14118 // Setting the preferred activity to what it happens to be already 14119 if (DEBUG_PREFERRED) { 14120 Slog.i(TAG, "Replacing with same preferred activity " 14121 + cur.mPref.mShortComponent + " for user " 14122 + userId + ":"); 14123 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14124 } 14125 return; 14126 } 14127 } 14128 14129 if (existing != null) { 14130 if (DEBUG_PREFERRED) { 14131 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14132 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14133 } 14134 for (int i = 0; i < existing.size(); i++) { 14135 PreferredActivity pa = existing.get(i); 14136 if (DEBUG_PREFERRED) { 14137 Slog.i(TAG, "Removing existing preferred activity " 14138 + pa.mPref.mComponent + ":"); 14139 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14140 } 14141 pir.removeFilter(pa); 14142 } 14143 } 14144 } 14145 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14146 "Replacing preferred"); 14147 } 14148 } 14149 14150 @Override 14151 public void clearPackagePreferredActivities(String packageName) { 14152 final int uid = Binder.getCallingUid(); 14153 // writer 14154 synchronized (mPackages) { 14155 PackageParser.Package pkg = mPackages.get(packageName); 14156 if (pkg == null || pkg.applicationInfo.uid != uid) { 14157 if (mContext.checkCallingOrSelfPermission( 14158 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14159 != PackageManager.PERMISSION_GRANTED) { 14160 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14161 < Build.VERSION_CODES.FROYO) { 14162 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14163 + Binder.getCallingUid()); 14164 return; 14165 } 14166 mContext.enforceCallingOrSelfPermission( 14167 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14168 } 14169 } 14170 14171 int user = UserHandle.getCallingUserId(); 14172 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14173 scheduleWritePackageRestrictionsLocked(user); 14174 } 14175 } 14176 } 14177 14178 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14179 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14180 ArrayList<PreferredActivity> removed = null; 14181 boolean changed = false; 14182 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14183 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14184 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14185 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14186 continue; 14187 } 14188 Iterator<PreferredActivity> it = pir.filterIterator(); 14189 while (it.hasNext()) { 14190 PreferredActivity pa = it.next(); 14191 // Mark entry for removal only if it matches the package name 14192 // and the entry is of type "always". 14193 if (packageName == null || 14194 (pa.mPref.mComponent.getPackageName().equals(packageName) 14195 && pa.mPref.mAlways)) { 14196 if (removed == null) { 14197 removed = new ArrayList<PreferredActivity>(); 14198 } 14199 removed.add(pa); 14200 } 14201 } 14202 if (removed != null) { 14203 for (int j=0; j<removed.size(); j++) { 14204 PreferredActivity pa = removed.get(j); 14205 pir.removeFilter(pa); 14206 } 14207 changed = true; 14208 } 14209 } 14210 return changed; 14211 } 14212 14213 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14214 private void clearIntentFilterVerificationsLPw(int userId) { 14215 final int packageCount = mPackages.size(); 14216 for (int i = 0; i < packageCount; i++) { 14217 PackageParser.Package pkg = mPackages.valueAt(i); 14218 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14219 } 14220 } 14221 14222 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14223 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14224 if (userId == UserHandle.USER_ALL) { 14225 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14226 sUserManager.getUserIds())) { 14227 for (int oneUserId : sUserManager.getUserIds()) { 14228 scheduleWritePackageRestrictionsLocked(oneUserId); 14229 } 14230 } 14231 } else { 14232 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14233 scheduleWritePackageRestrictionsLocked(userId); 14234 } 14235 } 14236 } 14237 14238 void clearDefaultBrowserIfNeeded(String packageName) { 14239 for (int oneUserId : sUserManager.getUserIds()) { 14240 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14241 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14242 if (packageName.equals(defaultBrowserPackageName)) { 14243 setDefaultBrowserPackageName(null, oneUserId); 14244 } 14245 } 14246 } 14247 14248 @Override 14249 public void resetApplicationPreferences(int userId) { 14250 mContext.enforceCallingOrSelfPermission( 14251 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14252 // writer 14253 synchronized (mPackages) { 14254 final long identity = Binder.clearCallingIdentity(); 14255 try { 14256 clearPackagePreferredActivitiesLPw(null, userId); 14257 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14258 // TODO: We have to reset the default SMS and Phone. This requires 14259 // significant refactoring to keep all default apps in the package 14260 // manager (cleaner but more work) or have the services provide 14261 // callbacks to the package manager to request a default app reset. 14262 applyFactoryDefaultBrowserLPw(userId); 14263 clearIntentFilterVerificationsLPw(userId); 14264 primeDomainVerificationsLPw(userId); 14265 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14266 scheduleWritePackageRestrictionsLocked(userId); 14267 } finally { 14268 Binder.restoreCallingIdentity(identity); 14269 } 14270 } 14271 } 14272 14273 @Override 14274 public int getPreferredActivities(List<IntentFilter> outFilters, 14275 List<ComponentName> outActivities, String packageName) { 14276 14277 int num = 0; 14278 final int userId = UserHandle.getCallingUserId(); 14279 // reader 14280 synchronized (mPackages) { 14281 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14282 if (pir != null) { 14283 final Iterator<PreferredActivity> it = pir.filterIterator(); 14284 while (it.hasNext()) { 14285 final PreferredActivity pa = it.next(); 14286 if (packageName == null 14287 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14288 && pa.mPref.mAlways)) { 14289 if (outFilters != null) { 14290 outFilters.add(new IntentFilter(pa)); 14291 } 14292 if (outActivities != null) { 14293 outActivities.add(pa.mPref.mComponent); 14294 } 14295 } 14296 } 14297 } 14298 } 14299 14300 return num; 14301 } 14302 14303 @Override 14304 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14305 int userId) { 14306 int callingUid = Binder.getCallingUid(); 14307 if (callingUid != Process.SYSTEM_UID) { 14308 throw new SecurityException( 14309 "addPersistentPreferredActivity can only be run by the system"); 14310 } 14311 if (filter.countActions() == 0) { 14312 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14313 return; 14314 } 14315 synchronized (mPackages) { 14316 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14317 " :"); 14318 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14319 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14320 new PersistentPreferredActivity(filter, activity)); 14321 scheduleWritePackageRestrictionsLocked(userId); 14322 } 14323 } 14324 14325 @Override 14326 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14327 int callingUid = Binder.getCallingUid(); 14328 if (callingUid != Process.SYSTEM_UID) { 14329 throw new SecurityException( 14330 "clearPackagePersistentPreferredActivities can only be run by the system"); 14331 } 14332 ArrayList<PersistentPreferredActivity> removed = null; 14333 boolean changed = false; 14334 synchronized (mPackages) { 14335 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14336 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14337 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14338 .valueAt(i); 14339 if (userId != thisUserId) { 14340 continue; 14341 } 14342 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14343 while (it.hasNext()) { 14344 PersistentPreferredActivity ppa = it.next(); 14345 // Mark entry for removal only if it matches the package name. 14346 if (ppa.mComponent.getPackageName().equals(packageName)) { 14347 if (removed == null) { 14348 removed = new ArrayList<PersistentPreferredActivity>(); 14349 } 14350 removed.add(ppa); 14351 } 14352 } 14353 if (removed != null) { 14354 for (int j=0; j<removed.size(); j++) { 14355 PersistentPreferredActivity ppa = removed.get(j); 14356 ppir.removeFilter(ppa); 14357 } 14358 changed = true; 14359 } 14360 } 14361 14362 if (changed) { 14363 scheduleWritePackageRestrictionsLocked(userId); 14364 } 14365 } 14366 } 14367 14368 /** 14369 * Common machinery for picking apart a restored XML blob and passing 14370 * it to a caller-supplied functor to be applied to the running system. 14371 */ 14372 private void restoreFromXml(XmlPullParser parser, int userId, 14373 String expectedStartTag, BlobXmlRestorer functor) 14374 throws IOException, XmlPullParserException { 14375 int type; 14376 while ((type = parser.next()) != XmlPullParser.START_TAG 14377 && type != XmlPullParser.END_DOCUMENT) { 14378 } 14379 if (type != XmlPullParser.START_TAG) { 14380 // oops didn't find a start tag?! 14381 if (DEBUG_BACKUP) { 14382 Slog.e(TAG, "Didn't find start tag during restore"); 14383 } 14384 return; 14385 } 14386 14387 // this is supposed to be TAG_PREFERRED_BACKUP 14388 if (!expectedStartTag.equals(parser.getName())) { 14389 if (DEBUG_BACKUP) { 14390 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14391 } 14392 return; 14393 } 14394 14395 // skip interfering stuff, then we're aligned with the backing implementation 14396 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14397 functor.apply(parser, userId); 14398 } 14399 14400 private interface BlobXmlRestorer { 14401 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14402 } 14403 14404 /** 14405 * Non-Binder method, support for the backup/restore mechanism: write the 14406 * full set of preferred activities in its canonical XML format. Returns the 14407 * XML output as a byte array, or null if there is none. 14408 */ 14409 @Override 14410 public byte[] getPreferredActivityBackup(int userId) { 14411 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14412 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14413 } 14414 14415 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14416 try { 14417 final XmlSerializer serializer = new FastXmlSerializer(); 14418 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14419 serializer.startDocument(null, true); 14420 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14421 14422 synchronized (mPackages) { 14423 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14424 } 14425 14426 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14427 serializer.endDocument(); 14428 serializer.flush(); 14429 } catch (Exception e) { 14430 if (DEBUG_BACKUP) { 14431 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14432 } 14433 return null; 14434 } 14435 14436 return dataStream.toByteArray(); 14437 } 14438 14439 @Override 14440 public void restorePreferredActivities(byte[] backup, int userId) { 14441 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14442 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14443 } 14444 14445 try { 14446 final XmlPullParser parser = Xml.newPullParser(); 14447 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14448 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14449 new BlobXmlRestorer() { 14450 @Override 14451 public void apply(XmlPullParser parser, int userId) 14452 throws XmlPullParserException, IOException { 14453 synchronized (mPackages) { 14454 mSettings.readPreferredActivitiesLPw(parser, userId); 14455 } 14456 } 14457 } ); 14458 } catch (Exception e) { 14459 if (DEBUG_BACKUP) { 14460 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14461 } 14462 } 14463 } 14464 14465 /** 14466 * Non-Binder method, support for the backup/restore mechanism: write the 14467 * default browser (etc) settings in its canonical XML format. Returns the default 14468 * browser XML representation as a byte array, or null if there is none. 14469 */ 14470 @Override 14471 public byte[] getDefaultAppsBackup(int userId) { 14472 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14473 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14474 } 14475 14476 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14477 try { 14478 final XmlSerializer serializer = new FastXmlSerializer(); 14479 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14480 serializer.startDocument(null, true); 14481 serializer.startTag(null, TAG_DEFAULT_APPS); 14482 14483 synchronized (mPackages) { 14484 mSettings.writeDefaultAppsLPr(serializer, userId); 14485 } 14486 14487 serializer.endTag(null, TAG_DEFAULT_APPS); 14488 serializer.endDocument(); 14489 serializer.flush(); 14490 } catch (Exception e) { 14491 if (DEBUG_BACKUP) { 14492 Slog.e(TAG, "Unable to write default apps for backup", e); 14493 } 14494 return null; 14495 } 14496 14497 return dataStream.toByteArray(); 14498 } 14499 14500 @Override 14501 public void restoreDefaultApps(byte[] backup, int userId) { 14502 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14503 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14504 } 14505 14506 try { 14507 final XmlPullParser parser = Xml.newPullParser(); 14508 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14509 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14510 new BlobXmlRestorer() { 14511 @Override 14512 public void apply(XmlPullParser parser, int userId) 14513 throws XmlPullParserException, IOException { 14514 synchronized (mPackages) { 14515 mSettings.readDefaultAppsLPw(parser, userId); 14516 } 14517 } 14518 } ); 14519 } catch (Exception e) { 14520 if (DEBUG_BACKUP) { 14521 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14522 } 14523 } 14524 } 14525 14526 @Override 14527 public byte[] getIntentFilterVerificationBackup(int userId) { 14528 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14529 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14530 } 14531 14532 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14533 try { 14534 final XmlSerializer serializer = new FastXmlSerializer(); 14535 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14536 serializer.startDocument(null, true); 14537 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14538 14539 synchronized (mPackages) { 14540 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14541 } 14542 14543 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14544 serializer.endDocument(); 14545 serializer.flush(); 14546 } catch (Exception e) { 14547 if (DEBUG_BACKUP) { 14548 Slog.e(TAG, "Unable to write default apps for backup", e); 14549 } 14550 return null; 14551 } 14552 14553 return dataStream.toByteArray(); 14554 } 14555 14556 @Override 14557 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14558 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14559 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14560 } 14561 14562 try { 14563 final XmlPullParser parser = Xml.newPullParser(); 14564 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14565 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14566 new BlobXmlRestorer() { 14567 @Override 14568 public void apply(XmlPullParser parser, int userId) 14569 throws XmlPullParserException, IOException { 14570 synchronized (mPackages) { 14571 mSettings.readAllDomainVerificationsLPr(parser, userId); 14572 mSettings.writeLPr(); 14573 } 14574 } 14575 } ); 14576 } catch (Exception e) { 14577 if (DEBUG_BACKUP) { 14578 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14579 } 14580 } 14581 } 14582 14583 @Override 14584 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14585 int sourceUserId, int targetUserId, int flags) { 14586 mContext.enforceCallingOrSelfPermission( 14587 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14588 int callingUid = Binder.getCallingUid(); 14589 enforceOwnerRights(ownerPackage, callingUid); 14590 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14591 if (intentFilter.countActions() == 0) { 14592 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14593 return; 14594 } 14595 synchronized (mPackages) { 14596 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14597 ownerPackage, targetUserId, flags); 14598 CrossProfileIntentResolver resolver = 14599 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14600 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14601 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14602 if (existing != null) { 14603 int size = existing.size(); 14604 for (int i = 0; i < size; i++) { 14605 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14606 return; 14607 } 14608 } 14609 } 14610 resolver.addFilter(newFilter); 14611 scheduleWritePackageRestrictionsLocked(sourceUserId); 14612 } 14613 } 14614 14615 @Override 14616 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14617 mContext.enforceCallingOrSelfPermission( 14618 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14619 int callingUid = Binder.getCallingUid(); 14620 enforceOwnerRights(ownerPackage, callingUid); 14621 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14622 synchronized (mPackages) { 14623 CrossProfileIntentResolver resolver = 14624 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14625 ArraySet<CrossProfileIntentFilter> set = 14626 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14627 for (CrossProfileIntentFilter filter : set) { 14628 if (filter.getOwnerPackage().equals(ownerPackage)) { 14629 resolver.removeFilter(filter); 14630 } 14631 } 14632 scheduleWritePackageRestrictionsLocked(sourceUserId); 14633 } 14634 } 14635 14636 // Enforcing that callingUid is owning pkg on userId 14637 private void enforceOwnerRights(String pkg, int callingUid) { 14638 // The system owns everything. 14639 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14640 return; 14641 } 14642 int callingUserId = UserHandle.getUserId(callingUid); 14643 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14644 if (pi == null) { 14645 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14646 + callingUserId); 14647 } 14648 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14649 throw new SecurityException("Calling uid " + callingUid 14650 + " does not own package " + pkg); 14651 } 14652 } 14653 14654 @Override 14655 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14656 Intent intent = new Intent(Intent.ACTION_MAIN); 14657 intent.addCategory(Intent.CATEGORY_HOME); 14658 14659 final int callingUserId = UserHandle.getCallingUserId(); 14660 List<ResolveInfo> list = queryIntentActivities(intent, null, 14661 PackageManager.GET_META_DATA, callingUserId); 14662 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14663 true, false, false, callingUserId); 14664 14665 allHomeCandidates.clear(); 14666 if (list != null) { 14667 for (ResolveInfo ri : list) { 14668 allHomeCandidates.add(ri); 14669 } 14670 } 14671 return (preferred == null || preferred.activityInfo == null) 14672 ? null 14673 : new ComponentName(preferred.activityInfo.packageName, 14674 preferred.activityInfo.name); 14675 } 14676 14677 @Override 14678 public void setApplicationEnabledSetting(String appPackageName, 14679 int newState, int flags, int userId, String callingPackage) { 14680 if (!sUserManager.exists(userId)) return; 14681 if (callingPackage == null) { 14682 callingPackage = Integer.toString(Binder.getCallingUid()); 14683 } 14684 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14685 } 14686 14687 @Override 14688 public void setComponentEnabledSetting(ComponentName componentName, 14689 int newState, int flags, int userId) { 14690 if (!sUserManager.exists(userId)) return; 14691 setEnabledSetting(componentName.getPackageName(), 14692 componentName.getClassName(), newState, flags, userId, null); 14693 } 14694 14695 private void setEnabledSetting(final String packageName, String className, int newState, 14696 final int flags, int userId, String callingPackage) { 14697 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14698 || newState == COMPONENT_ENABLED_STATE_ENABLED 14699 || newState == COMPONENT_ENABLED_STATE_DISABLED 14700 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14701 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14702 throw new IllegalArgumentException("Invalid new component state: " 14703 + newState); 14704 } 14705 PackageSetting pkgSetting; 14706 final int uid = Binder.getCallingUid(); 14707 final int permission = mContext.checkCallingOrSelfPermission( 14708 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14709 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14710 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14711 boolean sendNow = false; 14712 boolean isApp = (className == null); 14713 String componentName = isApp ? packageName : className; 14714 int packageUid = -1; 14715 ArrayList<String> components; 14716 14717 // writer 14718 synchronized (mPackages) { 14719 pkgSetting = mSettings.mPackages.get(packageName); 14720 if (pkgSetting == null) { 14721 if (className == null) { 14722 throw new IllegalArgumentException( 14723 "Unknown package: " + packageName); 14724 } 14725 throw new IllegalArgumentException( 14726 "Unknown component: " + packageName 14727 + "/" + className); 14728 } 14729 // Allow root and verify that userId is not being specified by a different user 14730 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14731 throw new SecurityException( 14732 "Permission Denial: attempt to change component state from pid=" 14733 + Binder.getCallingPid() 14734 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14735 } 14736 if (className == null) { 14737 // We're dealing with an application/package level state change 14738 if (pkgSetting.getEnabled(userId) == newState) { 14739 // Nothing to do 14740 return; 14741 } 14742 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14743 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14744 // Don't care about who enables an app. 14745 callingPackage = null; 14746 } 14747 pkgSetting.setEnabled(newState, userId, callingPackage); 14748 // pkgSetting.pkg.mSetEnabled = newState; 14749 } else { 14750 // We're dealing with a component level state change 14751 // First, verify that this is a valid class name. 14752 PackageParser.Package pkg = pkgSetting.pkg; 14753 if (pkg == null || !pkg.hasComponentClassName(className)) { 14754 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14755 throw new IllegalArgumentException("Component class " + className 14756 + " does not exist in " + packageName); 14757 } else { 14758 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14759 + className + " does not exist in " + packageName); 14760 } 14761 } 14762 switch (newState) { 14763 case COMPONENT_ENABLED_STATE_ENABLED: 14764 if (!pkgSetting.enableComponentLPw(className, userId)) { 14765 return; 14766 } 14767 break; 14768 case COMPONENT_ENABLED_STATE_DISABLED: 14769 if (!pkgSetting.disableComponentLPw(className, userId)) { 14770 return; 14771 } 14772 break; 14773 case COMPONENT_ENABLED_STATE_DEFAULT: 14774 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14775 return; 14776 } 14777 break; 14778 default: 14779 Slog.e(TAG, "Invalid new component state: " + newState); 14780 return; 14781 } 14782 } 14783 scheduleWritePackageRestrictionsLocked(userId); 14784 components = mPendingBroadcasts.get(userId, packageName); 14785 final boolean newPackage = components == null; 14786 if (newPackage) { 14787 components = new ArrayList<String>(); 14788 } 14789 if (!components.contains(componentName)) { 14790 components.add(componentName); 14791 } 14792 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14793 sendNow = true; 14794 // Purge entry from pending broadcast list if another one exists already 14795 // since we are sending one right away. 14796 mPendingBroadcasts.remove(userId, packageName); 14797 } else { 14798 if (newPackage) { 14799 mPendingBroadcasts.put(userId, packageName, components); 14800 } 14801 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14802 // Schedule a message 14803 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14804 } 14805 } 14806 } 14807 14808 long callingId = Binder.clearCallingIdentity(); 14809 try { 14810 if (sendNow) { 14811 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14812 sendPackageChangedBroadcast(packageName, 14813 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14814 } 14815 } finally { 14816 Binder.restoreCallingIdentity(callingId); 14817 } 14818 } 14819 14820 private void sendPackageChangedBroadcast(String packageName, 14821 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14822 if (DEBUG_INSTALL) 14823 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14824 + componentNames); 14825 Bundle extras = new Bundle(4); 14826 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14827 String nameList[] = new String[componentNames.size()]; 14828 componentNames.toArray(nameList); 14829 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14830 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14831 extras.putInt(Intent.EXTRA_UID, packageUid); 14832 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14833 new int[] {UserHandle.getUserId(packageUid)}); 14834 } 14835 14836 @Override 14837 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14838 if (!sUserManager.exists(userId)) return; 14839 final int uid = Binder.getCallingUid(); 14840 final int permission = mContext.checkCallingOrSelfPermission( 14841 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14842 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14843 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14844 // writer 14845 synchronized (mPackages) { 14846 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14847 allowedByPermission, uid, userId)) { 14848 scheduleWritePackageRestrictionsLocked(userId); 14849 } 14850 } 14851 } 14852 14853 @Override 14854 public String getInstallerPackageName(String packageName) { 14855 // reader 14856 synchronized (mPackages) { 14857 return mSettings.getInstallerPackageNameLPr(packageName); 14858 } 14859 } 14860 14861 @Override 14862 public int getApplicationEnabledSetting(String packageName, int userId) { 14863 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14864 int uid = Binder.getCallingUid(); 14865 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14866 // reader 14867 synchronized (mPackages) { 14868 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14869 } 14870 } 14871 14872 @Override 14873 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14874 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14875 int uid = Binder.getCallingUid(); 14876 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14877 // reader 14878 synchronized (mPackages) { 14879 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14880 } 14881 } 14882 14883 @Override 14884 public void enterSafeMode() { 14885 enforceSystemOrRoot("Only the system can request entering safe mode"); 14886 14887 if (!mSystemReady) { 14888 mSafeMode = true; 14889 } 14890 } 14891 14892 @Override 14893 public void systemReady() { 14894 mSystemReady = true; 14895 14896 // Read the compatibilty setting when the system is ready. 14897 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14898 mContext.getContentResolver(), 14899 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14900 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14901 if (DEBUG_SETTINGS) { 14902 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14903 } 14904 14905 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14906 14907 synchronized (mPackages) { 14908 // Verify that all of the preferred activity components actually 14909 // exist. It is possible for applications to be updated and at 14910 // that point remove a previously declared activity component that 14911 // had been set as a preferred activity. We try to clean this up 14912 // the next time we encounter that preferred activity, but it is 14913 // possible for the user flow to never be able to return to that 14914 // situation so here we do a sanity check to make sure we haven't 14915 // left any junk around. 14916 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14917 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14918 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14919 removed.clear(); 14920 for (PreferredActivity pa : pir.filterSet()) { 14921 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14922 removed.add(pa); 14923 } 14924 } 14925 if (removed.size() > 0) { 14926 for (int r=0; r<removed.size(); r++) { 14927 PreferredActivity pa = removed.get(r); 14928 Slog.w(TAG, "Removing dangling preferred activity: " 14929 + pa.mPref.mComponent); 14930 pir.removeFilter(pa); 14931 } 14932 mSettings.writePackageRestrictionsLPr( 14933 mSettings.mPreferredActivities.keyAt(i)); 14934 } 14935 } 14936 14937 for (int userId : UserManagerService.getInstance().getUserIds()) { 14938 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14939 grantPermissionsUserIds = ArrayUtils.appendInt( 14940 grantPermissionsUserIds, userId); 14941 } 14942 } 14943 } 14944 sUserManager.systemReady(); 14945 14946 // If we upgraded grant all default permissions before kicking off. 14947 for (int userId : grantPermissionsUserIds) { 14948 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14949 } 14950 14951 // Kick off any messages waiting for system ready 14952 if (mPostSystemReadyMessages != null) { 14953 for (Message msg : mPostSystemReadyMessages) { 14954 msg.sendToTarget(); 14955 } 14956 mPostSystemReadyMessages = null; 14957 } 14958 14959 // Watch for external volumes that come and go over time 14960 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14961 storage.registerListener(mStorageListener); 14962 14963 mInstallerService.systemReady(); 14964 mPackageDexOptimizer.systemReady(); 14965 14966 MountServiceInternal mountServiceInternal = LocalServices.getService( 14967 MountServiceInternal.class); 14968 mountServiceInternal.addExternalStoragePolicy( 14969 new MountServiceInternal.ExternalStorageMountPolicy() { 14970 @Override 14971 public int getMountMode(int uid, String packageName) { 14972 if (Process.isIsolated(uid)) { 14973 return Zygote.MOUNT_EXTERNAL_NONE; 14974 } 14975 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14976 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14977 } 14978 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14979 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14980 } 14981 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14982 return Zygote.MOUNT_EXTERNAL_READ; 14983 } 14984 return Zygote.MOUNT_EXTERNAL_WRITE; 14985 } 14986 14987 @Override 14988 public boolean hasExternalStorage(int uid, String packageName) { 14989 return true; 14990 } 14991 }); 14992 } 14993 14994 @Override 14995 public boolean isSafeMode() { 14996 return mSafeMode; 14997 } 14998 14999 @Override 15000 public boolean hasSystemUidErrors() { 15001 return mHasSystemUidErrors; 15002 } 15003 15004 static String arrayToString(int[] array) { 15005 StringBuffer buf = new StringBuffer(128); 15006 buf.append('['); 15007 if (array != null) { 15008 for (int i=0; i<array.length; i++) { 15009 if (i > 0) buf.append(", "); 15010 buf.append(array[i]); 15011 } 15012 } 15013 buf.append(']'); 15014 return buf.toString(); 15015 } 15016 15017 static class DumpState { 15018 public static final int DUMP_LIBS = 1 << 0; 15019 public static final int DUMP_FEATURES = 1 << 1; 15020 public static final int DUMP_RESOLVERS = 1 << 2; 15021 public static final int DUMP_PERMISSIONS = 1 << 3; 15022 public static final int DUMP_PACKAGES = 1 << 4; 15023 public static final int DUMP_SHARED_USERS = 1 << 5; 15024 public static final int DUMP_MESSAGES = 1 << 6; 15025 public static final int DUMP_PROVIDERS = 1 << 7; 15026 public static final int DUMP_VERIFIERS = 1 << 8; 15027 public static final int DUMP_PREFERRED = 1 << 9; 15028 public static final int DUMP_PREFERRED_XML = 1 << 10; 15029 public static final int DUMP_KEYSETS = 1 << 11; 15030 public static final int DUMP_VERSION = 1 << 12; 15031 public static final int DUMP_INSTALLS = 1 << 13; 15032 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 15033 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 15034 15035 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15036 15037 private int mTypes; 15038 15039 private int mOptions; 15040 15041 private boolean mTitlePrinted; 15042 15043 private SharedUserSetting mSharedUser; 15044 15045 public boolean isDumping(int type) { 15046 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15047 return true; 15048 } 15049 15050 return (mTypes & type) != 0; 15051 } 15052 15053 public void setDump(int type) { 15054 mTypes |= type; 15055 } 15056 15057 public boolean isOptionEnabled(int option) { 15058 return (mOptions & option) != 0; 15059 } 15060 15061 public void setOptionEnabled(int option) { 15062 mOptions |= option; 15063 } 15064 15065 public boolean onTitlePrinted() { 15066 final boolean printed = mTitlePrinted; 15067 mTitlePrinted = true; 15068 return printed; 15069 } 15070 15071 public boolean getTitlePrinted() { 15072 return mTitlePrinted; 15073 } 15074 15075 public void setTitlePrinted(boolean enabled) { 15076 mTitlePrinted = enabled; 15077 } 15078 15079 public SharedUserSetting getSharedUser() { 15080 return mSharedUser; 15081 } 15082 15083 public void setSharedUser(SharedUserSetting user) { 15084 mSharedUser = user; 15085 } 15086 } 15087 15088 @Override 15089 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15090 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15091 != PackageManager.PERMISSION_GRANTED) { 15092 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15093 + Binder.getCallingPid() 15094 + ", uid=" + Binder.getCallingUid() 15095 + " without permission " 15096 + android.Manifest.permission.DUMP); 15097 return; 15098 } 15099 15100 DumpState dumpState = new DumpState(); 15101 boolean fullPreferred = false; 15102 boolean checkin = false; 15103 15104 String packageName = null; 15105 ArraySet<String> permissionNames = null; 15106 15107 int opti = 0; 15108 while (opti < args.length) { 15109 String opt = args[opti]; 15110 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15111 break; 15112 } 15113 opti++; 15114 15115 if ("-a".equals(opt)) { 15116 // Right now we only know how to print all. 15117 } else if ("-h".equals(opt)) { 15118 pw.println("Package manager dump options:"); 15119 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15120 pw.println(" --checkin: dump for a checkin"); 15121 pw.println(" -f: print details of intent filters"); 15122 pw.println(" -h: print this help"); 15123 pw.println(" cmd may be one of:"); 15124 pw.println(" l[ibraries]: list known shared libraries"); 15125 pw.println(" f[ibraries]: list device features"); 15126 pw.println(" k[eysets]: print known keysets"); 15127 pw.println(" r[esolvers]: dump intent resolvers"); 15128 pw.println(" perm[issions]: dump permissions"); 15129 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15130 pw.println(" pref[erred]: print preferred package settings"); 15131 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15132 pw.println(" prov[iders]: dump content providers"); 15133 pw.println(" p[ackages]: dump installed packages"); 15134 pw.println(" s[hared-users]: dump shared user IDs"); 15135 pw.println(" m[essages]: print collected runtime messages"); 15136 pw.println(" v[erifiers]: print package verifier info"); 15137 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15138 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15139 pw.println(" version: print database version info"); 15140 pw.println(" write: write current settings now"); 15141 pw.println(" installs: details about install sessions"); 15142 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15143 pw.println(" <package.name>: info about given package"); 15144 return; 15145 } else if ("--checkin".equals(opt)) { 15146 checkin = true; 15147 } else if ("-f".equals(opt)) { 15148 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15149 } else { 15150 pw.println("Unknown argument: " + opt + "; use -h for help"); 15151 } 15152 } 15153 15154 // Is the caller requesting to dump a particular piece of data? 15155 if (opti < args.length) { 15156 String cmd = args[opti]; 15157 opti++; 15158 // Is this a package name? 15159 if ("android".equals(cmd) || cmd.contains(".")) { 15160 packageName = cmd; 15161 // When dumping a single package, we always dump all of its 15162 // filter information since the amount of data will be reasonable. 15163 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15164 } else if ("check-permission".equals(cmd)) { 15165 if (opti >= args.length) { 15166 pw.println("Error: check-permission missing permission argument"); 15167 return; 15168 } 15169 String perm = args[opti]; 15170 opti++; 15171 if (opti >= args.length) { 15172 pw.println("Error: check-permission missing package argument"); 15173 return; 15174 } 15175 String pkg = args[opti]; 15176 opti++; 15177 int user = UserHandle.getUserId(Binder.getCallingUid()); 15178 if (opti < args.length) { 15179 try { 15180 user = Integer.parseInt(args[opti]); 15181 } catch (NumberFormatException e) { 15182 pw.println("Error: check-permission user argument is not a number: " 15183 + args[opti]); 15184 return; 15185 } 15186 } 15187 pw.println(checkPermission(perm, pkg, user)); 15188 return; 15189 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15190 dumpState.setDump(DumpState.DUMP_LIBS); 15191 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15192 dumpState.setDump(DumpState.DUMP_FEATURES); 15193 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15194 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15195 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15196 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15197 } else if ("permission".equals(cmd)) { 15198 if (opti >= args.length) { 15199 pw.println("Error: permission requires permission name"); 15200 return; 15201 } 15202 permissionNames = new ArraySet<>(); 15203 while (opti < args.length) { 15204 permissionNames.add(args[opti]); 15205 opti++; 15206 } 15207 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15208 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15209 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15210 dumpState.setDump(DumpState.DUMP_PREFERRED); 15211 } else if ("preferred-xml".equals(cmd)) { 15212 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15213 if (opti < args.length && "--full".equals(args[opti])) { 15214 fullPreferred = true; 15215 opti++; 15216 } 15217 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15218 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15219 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15220 dumpState.setDump(DumpState.DUMP_PACKAGES); 15221 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15222 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15223 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15224 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15225 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15226 dumpState.setDump(DumpState.DUMP_MESSAGES); 15227 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15228 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15229 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15230 || "intent-filter-verifiers".equals(cmd)) { 15231 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15232 } else if ("version".equals(cmd)) { 15233 dumpState.setDump(DumpState.DUMP_VERSION); 15234 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15235 dumpState.setDump(DumpState.DUMP_KEYSETS); 15236 } else if ("installs".equals(cmd)) { 15237 dumpState.setDump(DumpState.DUMP_INSTALLS); 15238 } else if ("write".equals(cmd)) { 15239 synchronized (mPackages) { 15240 mSettings.writeLPr(); 15241 pw.println("Settings written."); 15242 return; 15243 } 15244 } 15245 } 15246 15247 if (checkin) { 15248 pw.println("vers,1"); 15249 } 15250 15251 // reader 15252 synchronized (mPackages) { 15253 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15254 if (!checkin) { 15255 if (dumpState.onTitlePrinted()) 15256 pw.println(); 15257 pw.println("Database versions:"); 15258 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15259 } 15260 } 15261 15262 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15263 if (!checkin) { 15264 if (dumpState.onTitlePrinted()) 15265 pw.println(); 15266 pw.println("Verifiers:"); 15267 pw.print(" Required: "); 15268 pw.print(mRequiredVerifierPackage); 15269 pw.print(" (uid="); 15270 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15271 pw.println(")"); 15272 } else if (mRequiredVerifierPackage != null) { 15273 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15274 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15275 } 15276 } 15277 15278 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15279 packageName == null) { 15280 if (mIntentFilterVerifierComponent != null) { 15281 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15282 if (!checkin) { 15283 if (dumpState.onTitlePrinted()) 15284 pw.println(); 15285 pw.println("Intent Filter Verifier:"); 15286 pw.print(" Using: "); 15287 pw.print(verifierPackageName); 15288 pw.print(" (uid="); 15289 pw.print(getPackageUid(verifierPackageName, 0)); 15290 pw.println(")"); 15291 } else if (verifierPackageName != null) { 15292 pw.print("ifv,"); pw.print(verifierPackageName); 15293 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15294 } 15295 } else { 15296 pw.println(); 15297 pw.println("No Intent Filter Verifier available!"); 15298 } 15299 } 15300 15301 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15302 boolean printedHeader = false; 15303 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15304 while (it.hasNext()) { 15305 String name = it.next(); 15306 SharedLibraryEntry ent = mSharedLibraries.get(name); 15307 if (!checkin) { 15308 if (!printedHeader) { 15309 if (dumpState.onTitlePrinted()) 15310 pw.println(); 15311 pw.println("Libraries:"); 15312 printedHeader = true; 15313 } 15314 pw.print(" "); 15315 } else { 15316 pw.print("lib,"); 15317 } 15318 pw.print(name); 15319 if (!checkin) { 15320 pw.print(" -> "); 15321 } 15322 if (ent.path != null) { 15323 if (!checkin) { 15324 pw.print("(jar) "); 15325 pw.print(ent.path); 15326 } else { 15327 pw.print(",jar,"); 15328 pw.print(ent.path); 15329 } 15330 } else { 15331 if (!checkin) { 15332 pw.print("(apk) "); 15333 pw.print(ent.apk); 15334 } else { 15335 pw.print(",apk,"); 15336 pw.print(ent.apk); 15337 } 15338 } 15339 pw.println(); 15340 } 15341 } 15342 15343 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15344 if (dumpState.onTitlePrinted()) 15345 pw.println(); 15346 if (!checkin) { 15347 pw.println("Features:"); 15348 } 15349 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15350 while (it.hasNext()) { 15351 String name = it.next(); 15352 if (!checkin) { 15353 pw.print(" "); 15354 } else { 15355 pw.print("feat,"); 15356 } 15357 pw.println(name); 15358 } 15359 } 15360 15361 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15362 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15363 : "Activity Resolver Table:", " ", packageName, 15364 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15365 dumpState.setTitlePrinted(true); 15366 } 15367 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15368 : "Receiver Resolver Table:", " ", packageName, 15369 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15370 dumpState.setTitlePrinted(true); 15371 } 15372 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15373 : "Service Resolver Table:", " ", packageName, 15374 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15375 dumpState.setTitlePrinted(true); 15376 } 15377 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15378 : "Provider Resolver Table:", " ", packageName, 15379 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15380 dumpState.setTitlePrinted(true); 15381 } 15382 } 15383 15384 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15385 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15386 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15387 int user = mSettings.mPreferredActivities.keyAt(i); 15388 if (pir.dump(pw, 15389 dumpState.getTitlePrinted() 15390 ? "\nPreferred Activities User " + user + ":" 15391 : "Preferred Activities User " + user + ":", " ", 15392 packageName, true, false)) { 15393 dumpState.setTitlePrinted(true); 15394 } 15395 } 15396 } 15397 15398 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15399 pw.flush(); 15400 FileOutputStream fout = new FileOutputStream(fd); 15401 BufferedOutputStream str = new BufferedOutputStream(fout); 15402 XmlSerializer serializer = new FastXmlSerializer(); 15403 try { 15404 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15405 serializer.startDocument(null, true); 15406 serializer.setFeature( 15407 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15408 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15409 serializer.endDocument(); 15410 serializer.flush(); 15411 } catch (IllegalArgumentException e) { 15412 pw.println("Failed writing: " + e); 15413 } catch (IllegalStateException e) { 15414 pw.println("Failed writing: " + e); 15415 } catch (IOException e) { 15416 pw.println("Failed writing: " + e); 15417 } 15418 } 15419 15420 if (!checkin 15421 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15422 && packageName == null) { 15423 pw.println(); 15424 int count = mSettings.mPackages.size(); 15425 if (count == 0) { 15426 pw.println("No applications!"); 15427 pw.println(); 15428 } else { 15429 final String prefix = " "; 15430 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15431 if (allPackageSettings.size() == 0) { 15432 pw.println("No domain preferred apps!"); 15433 pw.println(); 15434 } else { 15435 pw.println("App verification status:"); 15436 pw.println(); 15437 count = 0; 15438 for (PackageSetting ps : allPackageSettings) { 15439 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15440 if (ivi == null || ivi.getPackageName() == null) continue; 15441 pw.println(prefix + "Package: " + ivi.getPackageName()); 15442 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15443 pw.println(prefix + "Status: " + ivi.getStatusString()); 15444 pw.println(); 15445 count++; 15446 } 15447 if (count == 0) { 15448 pw.println(prefix + "No app verification established."); 15449 pw.println(); 15450 } 15451 for (int userId : sUserManager.getUserIds()) { 15452 pw.println("App linkages for user " + userId + ":"); 15453 pw.println(); 15454 count = 0; 15455 for (PackageSetting ps : allPackageSettings) { 15456 final long status = ps.getDomainVerificationStatusForUser(userId); 15457 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15458 continue; 15459 } 15460 pw.println(prefix + "Package: " + ps.name); 15461 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15462 String statusStr = IntentFilterVerificationInfo. 15463 getStatusStringFromValue(status); 15464 pw.println(prefix + "Status: " + statusStr); 15465 pw.println(); 15466 count++; 15467 } 15468 if (count == 0) { 15469 pw.println(prefix + "No configured app linkages."); 15470 pw.println(); 15471 } 15472 } 15473 } 15474 } 15475 } 15476 15477 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15478 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15479 if (packageName == null && permissionNames == null) { 15480 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15481 if (iperm == 0) { 15482 if (dumpState.onTitlePrinted()) 15483 pw.println(); 15484 pw.println("AppOp Permissions:"); 15485 } 15486 pw.print(" AppOp Permission "); 15487 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15488 pw.println(":"); 15489 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15490 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15491 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15492 } 15493 } 15494 } 15495 } 15496 15497 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15498 boolean printedSomething = false; 15499 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15500 if (packageName != null && !packageName.equals(p.info.packageName)) { 15501 continue; 15502 } 15503 if (!printedSomething) { 15504 if (dumpState.onTitlePrinted()) 15505 pw.println(); 15506 pw.println("Registered ContentProviders:"); 15507 printedSomething = true; 15508 } 15509 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15510 pw.print(" "); pw.println(p.toString()); 15511 } 15512 printedSomething = false; 15513 for (Map.Entry<String, PackageParser.Provider> entry : 15514 mProvidersByAuthority.entrySet()) { 15515 PackageParser.Provider p = entry.getValue(); 15516 if (packageName != null && !packageName.equals(p.info.packageName)) { 15517 continue; 15518 } 15519 if (!printedSomething) { 15520 if (dumpState.onTitlePrinted()) 15521 pw.println(); 15522 pw.println("ContentProvider Authorities:"); 15523 printedSomething = true; 15524 } 15525 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15526 pw.print(" "); pw.println(p.toString()); 15527 if (p.info != null && p.info.applicationInfo != null) { 15528 final String appInfo = p.info.applicationInfo.toString(); 15529 pw.print(" applicationInfo="); pw.println(appInfo); 15530 } 15531 } 15532 } 15533 15534 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15535 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15536 } 15537 15538 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15539 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15540 } 15541 15542 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15543 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15544 } 15545 15546 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15547 // XXX should handle packageName != null by dumping only install data that 15548 // the given package is involved with. 15549 if (dumpState.onTitlePrinted()) pw.println(); 15550 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15551 } 15552 15553 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15554 if (dumpState.onTitlePrinted()) pw.println(); 15555 mSettings.dumpReadMessagesLPr(pw, dumpState); 15556 15557 pw.println(); 15558 pw.println("Package warning messages:"); 15559 BufferedReader in = null; 15560 String line = null; 15561 try { 15562 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15563 while ((line = in.readLine()) != null) { 15564 if (line.contains("ignored: updated version")) continue; 15565 pw.println(line); 15566 } 15567 } catch (IOException ignored) { 15568 } finally { 15569 IoUtils.closeQuietly(in); 15570 } 15571 } 15572 15573 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15574 BufferedReader in = null; 15575 String line = null; 15576 try { 15577 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15578 while ((line = in.readLine()) != null) { 15579 if (line.contains("ignored: updated version")) continue; 15580 pw.print("msg,"); 15581 pw.println(line); 15582 } 15583 } catch (IOException ignored) { 15584 } finally { 15585 IoUtils.closeQuietly(in); 15586 } 15587 } 15588 } 15589 } 15590 15591 private String dumpDomainString(String packageName) { 15592 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15593 List<IntentFilter> filters = getAllIntentFilters(packageName); 15594 15595 ArraySet<String> result = new ArraySet<>(); 15596 if (iviList.size() > 0) { 15597 for (IntentFilterVerificationInfo ivi : iviList) { 15598 for (String host : ivi.getDomains()) { 15599 result.add(host); 15600 } 15601 } 15602 } 15603 if (filters != null && filters.size() > 0) { 15604 for (IntentFilter filter : filters) { 15605 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15606 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15607 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15608 result.addAll(filter.getHostsList()); 15609 } 15610 } 15611 } 15612 15613 StringBuilder sb = new StringBuilder(result.size() * 16); 15614 for (String domain : result) { 15615 if (sb.length() > 0) sb.append(" "); 15616 sb.append(domain); 15617 } 15618 return sb.toString(); 15619 } 15620 15621 // ------- apps on sdcard specific code ------- 15622 static final boolean DEBUG_SD_INSTALL = false; 15623 15624 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15625 15626 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15627 15628 private boolean mMediaMounted = false; 15629 15630 static String getEncryptKey() { 15631 try { 15632 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15633 SD_ENCRYPTION_KEYSTORE_NAME); 15634 if (sdEncKey == null) { 15635 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15636 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15637 if (sdEncKey == null) { 15638 Slog.e(TAG, "Failed to create encryption keys"); 15639 return null; 15640 } 15641 } 15642 return sdEncKey; 15643 } catch (NoSuchAlgorithmException nsae) { 15644 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15645 return null; 15646 } catch (IOException ioe) { 15647 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15648 return null; 15649 } 15650 } 15651 15652 /* 15653 * Update media status on PackageManager. 15654 */ 15655 @Override 15656 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15657 int callingUid = Binder.getCallingUid(); 15658 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15659 throw new SecurityException("Media status can only be updated by the system"); 15660 } 15661 // reader; this apparently protects mMediaMounted, but should probably 15662 // be a different lock in that case. 15663 synchronized (mPackages) { 15664 Log.i(TAG, "Updating external media status from " 15665 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15666 + (mediaStatus ? "mounted" : "unmounted")); 15667 if (DEBUG_SD_INSTALL) 15668 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15669 + ", mMediaMounted=" + mMediaMounted); 15670 if (mediaStatus == mMediaMounted) { 15671 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15672 : 0, -1); 15673 mHandler.sendMessage(msg); 15674 return; 15675 } 15676 mMediaMounted = mediaStatus; 15677 } 15678 // Queue up an async operation since the package installation may take a 15679 // little while. 15680 mHandler.post(new Runnable() { 15681 public void run() { 15682 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15683 } 15684 }); 15685 } 15686 15687 /** 15688 * Called by MountService when the initial ASECs to scan are available. 15689 * Should block until all the ASEC containers are finished being scanned. 15690 */ 15691 public void scanAvailableAsecs() { 15692 updateExternalMediaStatusInner(true, false, false); 15693 if (mShouldRestoreconData) { 15694 SELinuxMMAC.setRestoreconDone(); 15695 mShouldRestoreconData = false; 15696 } 15697 } 15698 15699 /* 15700 * Collect information of applications on external media, map them against 15701 * existing containers and update information based on current mount status. 15702 * Please note that we always have to report status if reportStatus has been 15703 * set to true especially when unloading packages. 15704 */ 15705 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15706 boolean externalStorage) { 15707 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15708 int[] uidArr = EmptyArray.INT; 15709 15710 final String[] list = PackageHelper.getSecureContainerList(); 15711 if (ArrayUtils.isEmpty(list)) { 15712 Log.i(TAG, "No secure containers found"); 15713 } else { 15714 // Process list of secure containers and categorize them 15715 // as active or stale based on their package internal state. 15716 15717 // reader 15718 synchronized (mPackages) { 15719 for (String cid : list) { 15720 // Leave stages untouched for now; installer service owns them 15721 if (PackageInstallerService.isStageName(cid)) continue; 15722 15723 if (DEBUG_SD_INSTALL) 15724 Log.i(TAG, "Processing container " + cid); 15725 String pkgName = getAsecPackageName(cid); 15726 if (pkgName == null) { 15727 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15728 continue; 15729 } 15730 if (DEBUG_SD_INSTALL) 15731 Log.i(TAG, "Looking for pkg : " + pkgName); 15732 15733 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15734 if (ps == null) { 15735 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15736 continue; 15737 } 15738 15739 /* 15740 * Skip packages that are not external if we're unmounting 15741 * external storage. 15742 */ 15743 if (externalStorage && !isMounted && !isExternal(ps)) { 15744 continue; 15745 } 15746 15747 final AsecInstallArgs args = new AsecInstallArgs(cid, 15748 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15749 // The package status is changed only if the code path 15750 // matches between settings and the container id. 15751 if (ps.codePathString != null 15752 && ps.codePathString.startsWith(args.getCodePath())) { 15753 if (DEBUG_SD_INSTALL) { 15754 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15755 + " at code path: " + ps.codePathString); 15756 } 15757 15758 // We do have a valid package installed on sdcard 15759 processCids.put(args, ps.codePathString); 15760 final int uid = ps.appId; 15761 if (uid != -1) { 15762 uidArr = ArrayUtils.appendInt(uidArr, uid); 15763 } 15764 } else { 15765 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15766 + ps.codePathString); 15767 } 15768 } 15769 } 15770 15771 Arrays.sort(uidArr); 15772 } 15773 15774 // Process packages with valid entries. 15775 if (isMounted) { 15776 if (DEBUG_SD_INSTALL) 15777 Log.i(TAG, "Loading packages"); 15778 loadMediaPackages(processCids, uidArr, externalStorage); 15779 startCleaningPackages(); 15780 mInstallerService.onSecureContainersAvailable(); 15781 } else { 15782 if (DEBUG_SD_INSTALL) 15783 Log.i(TAG, "Unloading packages"); 15784 unloadMediaPackages(processCids, uidArr, reportStatus); 15785 } 15786 } 15787 15788 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15789 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15790 final int size = infos.size(); 15791 final String[] packageNames = new String[size]; 15792 final int[] packageUids = new int[size]; 15793 for (int i = 0; i < size; i++) { 15794 final ApplicationInfo info = infos.get(i); 15795 packageNames[i] = info.packageName; 15796 packageUids[i] = info.uid; 15797 } 15798 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15799 finishedReceiver); 15800 } 15801 15802 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15803 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15804 sendResourcesChangedBroadcast(mediaStatus, replacing, 15805 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15806 } 15807 15808 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15809 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15810 int size = pkgList.length; 15811 if (size > 0) { 15812 // Send broadcasts here 15813 Bundle extras = new Bundle(); 15814 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15815 if (uidArr != null) { 15816 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15817 } 15818 if (replacing) { 15819 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15820 } 15821 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15822 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15823 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15824 } 15825 } 15826 15827 /* 15828 * Look at potentially valid container ids from processCids If package 15829 * information doesn't match the one on record or package scanning fails, 15830 * the cid is added to list of removeCids. We currently don't delete stale 15831 * containers. 15832 */ 15833 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15834 boolean externalStorage) { 15835 ArrayList<String> pkgList = new ArrayList<String>(); 15836 Set<AsecInstallArgs> keys = processCids.keySet(); 15837 15838 for (AsecInstallArgs args : keys) { 15839 String codePath = processCids.get(args); 15840 if (DEBUG_SD_INSTALL) 15841 Log.i(TAG, "Loading container : " + args.cid); 15842 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15843 try { 15844 // Make sure there are no container errors first. 15845 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15846 Slog.e(TAG, "Failed to mount cid : " + args.cid 15847 + " when installing from sdcard"); 15848 continue; 15849 } 15850 // Check code path here. 15851 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15852 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15853 + " does not match one in settings " + codePath); 15854 continue; 15855 } 15856 // Parse package 15857 int parseFlags = mDefParseFlags; 15858 if (args.isExternalAsec()) { 15859 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15860 } 15861 if (args.isFwdLocked()) { 15862 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15863 } 15864 15865 synchronized (mInstallLock) { 15866 PackageParser.Package pkg = null; 15867 try { 15868 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15869 } catch (PackageManagerException e) { 15870 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15871 } 15872 // Scan the package 15873 if (pkg != null) { 15874 /* 15875 * TODO why is the lock being held? doPostInstall is 15876 * called in other places without the lock. This needs 15877 * to be straightened out. 15878 */ 15879 // writer 15880 synchronized (mPackages) { 15881 retCode = PackageManager.INSTALL_SUCCEEDED; 15882 pkgList.add(pkg.packageName); 15883 // Post process args 15884 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15885 pkg.applicationInfo.uid); 15886 } 15887 } else { 15888 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15889 } 15890 } 15891 15892 } finally { 15893 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15894 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15895 } 15896 } 15897 } 15898 // writer 15899 synchronized (mPackages) { 15900 // If the platform SDK has changed since the last time we booted, 15901 // we need to re-grant app permission to catch any new ones that 15902 // appear. This is really a hack, and means that apps can in some 15903 // cases get permissions that the user didn't initially explicitly 15904 // allow... it would be nice to have some better way to handle 15905 // this situation. 15906 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15907 : mSettings.getInternalVersion(); 15908 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15909 : StorageManager.UUID_PRIVATE_INTERNAL; 15910 15911 int updateFlags = UPDATE_PERMISSIONS_ALL; 15912 if (ver.sdkVersion != mSdkVersion) { 15913 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15914 + mSdkVersion + "; regranting permissions for external"); 15915 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15916 } 15917 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15918 15919 // Yay, everything is now upgraded 15920 ver.forceCurrent(); 15921 15922 // can downgrade to reader 15923 // Persist settings 15924 mSettings.writeLPr(); 15925 } 15926 // Send a broadcast to let everyone know we are done processing 15927 if (pkgList.size() > 0) { 15928 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15929 } 15930 } 15931 15932 /* 15933 * Utility method to unload a list of specified containers 15934 */ 15935 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15936 // Just unmount all valid containers. 15937 for (AsecInstallArgs arg : cidArgs) { 15938 synchronized (mInstallLock) { 15939 arg.doPostDeleteLI(false); 15940 } 15941 } 15942 } 15943 15944 /* 15945 * Unload packages mounted on external media. This involves deleting package 15946 * data from internal structures, sending broadcasts about diabled packages, 15947 * gc'ing to free up references, unmounting all secure containers 15948 * corresponding to packages on external media, and posting a 15949 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15950 * that we always have to post this message if status has been requested no 15951 * matter what. 15952 */ 15953 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15954 final boolean reportStatus) { 15955 if (DEBUG_SD_INSTALL) 15956 Log.i(TAG, "unloading media packages"); 15957 ArrayList<String> pkgList = new ArrayList<String>(); 15958 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15959 final Set<AsecInstallArgs> keys = processCids.keySet(); 15960 for (AsecInstallArgs args : keys) { 15961 String pkgName = args.getPackageName(); 15962 if (DEBUG_SD_INSTALL) 15963 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15964 // Delete package internally 15965 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15966 synchronized (mInstallLock) { 15967 boolean res = deletePackageLI(pkgName, null, false, null, null, 15968 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15969 if (res) { 15970 pkgList.add(pkgName); 15971 } else { 15972 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15973 failedList.add(args); 15974 } 15975 } 15976 } 15977 15978 // reader 15979 synchronized (mPackages) { 15980 // We didn't update the settings after removing each package; 15981 // write them now for all packages. 15982 mSettings.writeLPr(); 15983 } 15984 15985 // We have to absolutely send UPDATED_MEDIA_STATUS only 15986 // after confirming that all the receivers processed the ordered 15987 // broadcast when packages get disabled, force a gc to clean things up. 15988 // and unload all the containers. 15989 if (pkgList.size() > 0) { 15990 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15991 new IIntentReceiver.Stub() { 15992 public void performReceive(Intent intent, int resultCode, String data, 15993 Bundle extras, boolean ordered, boolean sticky, 15994 int sendingUser) throws RemoteException { 15995 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15996 reportStatus ? 1 : 0, 1, keys); 15997 mHandler.sendMessage(msg); 15998 } 15999 }); 16000 } else { 16001 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16002 keys); 16003 mHandler.sendMessage(msg); 16004 } 16005 } 16006 16007 private void loadPrivatePackages(final VolumeInfo vol) { 16008 mHandler.post(new Runnable() { 16009 @Override 16010 public void run() { 16011 loadPrivatePackagesInner(vol); 16012 } 16013 }); 16014 } 16015 16016 private void loadPrivatePackagesInner(VolumeInfo vol) { 16017 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16018 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16019 16020 final VersionInfo ver; 16021 final List<PackageSetting> packages; 16022 synchronized (mPackages) { 16023 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16024 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16025 } 16026 16027 for (PackageSetting ps : packages) { 16028 synchronized (mInstallLock) { 16029 final PackageParser.Package pkg; 16030 try { 16031 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16032 loaded.add(pkg.applicationInfo); 16033 } catch (PackageManagerException e) { 16034 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16035 } 16036 16037 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16038 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16039 } 16040 } 16041 } 16042 16043 synchronized (mPackages) { 16044 int updateFlags = UPDATE_PERMISSIONS_ALL; 16045 if (ver.sdkVersion != mSdkVersion) { 16046 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16047 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16048 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16049 } 16050 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16051 16052 // Yay, everything is now upgraded 16053 ver.forceCurrent(); 16054 16055 mSettings.writeLPr(); 16056 } 16057 16058 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16059 sendResourcesChangedBroadcast(true, false, loaded, null); 16060 } 16061 16062 private void unloadPrivatePackages(final VolumeInfo vol) { 16063 mHandler.post(new Runnable() { 16064 @Override 16065 public void run() { 16066 unloadPrivatePackagesInner(vol); 16067 } 16068 }); 16069 } 16070 16071 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16072 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16073 synchronized (mInstallLock) { 16074 synchronized (mPackages) { 16075 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16076 for (PackageSetting ps : packages) { 16077 if (ps.pkg == null) continue; 16078 16079 final ApplicationInfo info = ps.pkg.applicationInfo; 16080 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16081 if (deletePackageLI(ps.name, null, false, null, null, 16082 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16083 unloaded.add(info); 16084 } else { 16085 Slog.w(TAG, "Failed to unload " + ps.codePath); 16086 } 16087 } 16088 16089 mSettings.writeLPr(); 16090 } 16091 } 16092 16093 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16094 sendResourcesChangedBroadcast(false, false, unloaded, null); 16095 } 16096 16097 /** 16098 * Examine all users present on given mounted volume, and destroy data 16099 * belonging to users that are no longer valid, or whose user ID has been 16100 * recycled. 16101 */ 16102 private void reconcileUsers(String volumeUuid) { 16103 final File[] files = FileUtils 16104 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16105 for (File file : files) { 16106 if (!file.isDirectory()) continue; 16107 16108 final int userId; 16109 final UserInfo info; 16110 try { 16111 userId = Integer.parseInt(file.getName()); 16112 info = sUserManager.getUserInfo(userId); 16113 } catch (NumberFormatException e) { 16114 Slog.w(TAG, "Invalid user directory " + file); 16115 continue; 16116 } 16117 16118 boolean destroyUser = false; 16119 if (info == null) { 16120 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16121 + " because no matching user was found"); 16122 destroyUser = true; 16123 } else { 16124 try { 16125 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16126 } catch (IOException e) { 16127 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16128 + " because we failed to enforce serial number: " + e); 16129 destroyUser = true; 16130 } 16131 } 16132 16133 if (destroyUser) { 16134 synchronized (mInstallLock) { 16135 mInstaller.removeUserDataDirs(volumeUuid, userId); 16136 } 16137 } 16138 } 16139 16140 final UserManager um = mContext.getSystemService(UserManager.class); 16141 for (UserInfo user : um.getUsers()) { 16142 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16143 if (userDir.exists()) continue; 16144 16145 try { 16146 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16147 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16148 } catch (IOException e) { 16149 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16150 } 16151 } 16152 } 16153 16154 /** 16155 * Examine all apps present on given mounted volume, and destroy apps that 16156 * aren't expected, either due to uninstallation or reinstallation on 16157 * another volume. 16158 */ 16159 private void reconcileApps(String volumeUuid) { 16160 final File[] files = FileUtils 16161 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16162 for (File file : files) { 16163 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16164 && !PackageInstallerService.isStageName(file.getName()); 16165 if (!isPackage) { 16166 // Ignore entries which are not packages 16167 continue; 16168 } 16169 16170 boolean destroyApp = false; 16171 String packageName = null; 16172 try { 16173 final PackageLite pkg = PackageParser.parsePackageLite(file, 16174 PackageParser.PARSE_MUST_BE_APK); 16175 packageName = pkg.packageName; 16176 16177 synchronized (mPackages) { 16178 final PackageSetting ps = mSettings.mPackages.get(packageName); 16179 if (ps == null) { 16180 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16181 + volumeUuid + " because we found no install record"); 16182 destroyApp = true; 16183 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16184 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16185 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16186 destroyApp = true; 16187 } 16188 } 16189 16190 } catch (PackageParserException e) { 16191 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16192 destroyApp = true; 16193 } 16194 16195 if (destroyApp) { 16196 synchronized (mInstallLock) { 16197 if (packageName != null) { 16198 removeDataDirsLI(volumeUuid, packageName); 16199 } 16200 if (file.isDirectory()) { 16201 mInstaller.rmPackageDir(file.getAbsolutePath()); 16202 } else { 16203 file.delete(); 16204 } 16205 } 16206 } 16207 } 16208 } 16209 16210 private void unfreezePackage(String packageName) { 16211 synchronized (mPackages) { 16212 final PackageSetting ps = mSettings.mPackages.get(packageName); 16213 if (ps != null) { 16214 ps.frozen = false; 16215 } 16216 } 16217 } 16218 16219 @Override 16220 public int movePackage(final String packageName, final String volumeUuid) { 16221 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16222 16223 final int moveId = mNextMoveId.getAndIncrement(); 16224 try { 16225 movePackageInternal(packageName, volumeUuid, moveId); 16226 } catch (PackageManagerException e) { 16227 Slog.w(TAG, "Failed to move " + packageName, e); 16228 mMoveCallbacks.notifyStatusChanged(moveId, 16229 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16230 } 16231 return moveId; 16232 } 16233 16234 private void movePackageInternal(final String packageName, final String volumeUuid, 16235 final int moveId) throws PackageManagerException { 16236 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16237 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16238 final PackageManager pm = mContext.getPackageManager(); 16239 16240 final boolean currentAsec; 16241 final String currentVolumeUuid; 16242 final File codeFile; 16243 final String installerPackageName; 16244 final String packageAbiOverride; 16245 final int appId; 16246 final String seinfo; 16247 final String label; 16248 16249 // reader 16250 synchronized (mPackages) { 16251 final PackageParser.Package pkg = mPackages.get(packageName); 16252 final PackageSetting ps = mSettings.mPackages.get(packageName); 16253 if (pkg == null || ps == null) { 16254 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16255 } 16256 16257 if (pkg.applicationInfo.isSystemApp()) { 16258 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16259 "Cannot move system application"); 16260 } 16261 16262 if (pkg.applicationInfo.isExternalAsec()) { 16263 currentAsec = true; 16264 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16265 } else if (pkg.applicationInfo.isForwardLocked()) { 16266 currentAsec = true; 16267 currentVolumeUuid = "forward_locked"; 16268 } else { 16269 currentAsec = false; 16270 currentVolumeUuid = ps.volumeUuid; 16271 16272 final File probe = new File(pkg.codePath); 16273 final File probeOat = new File(probe, "oat"); 16274 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16275 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16276 "Move only supported for modern cluster style installs"); 16277 } 16278 } 16279 16280 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16281 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16282 "Package already moved to " + volumeUuid); 16283 } 16284 16285 if (ps.frozen) { 16286 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16287 "Failed to move already frozen package"); 16288 } 16289 ps.frozen = true; 16290 16291 codeFile = new File(pkg.codePath); 16292 installerPackageName = ps.installerPackageName; 16293 packageAbiOverride = ps.cpuAbiOverrideString; 16294 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16295 seinfo = pkg.applicationInfo.seinfo; 16296 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16297 } 16298 16299 // Now that we're guarded by frozen state, kill app during move 16300 final long token = Binder.clearCallingIdentity(); 16301 try { 16302 killApplication(packageName, appId, "move pkg"); 16303 } finally { 16304 Binder.restoreCallingIdentity(token); 16305 } 16306 16307 final Bundle extras = new Bundle(); 16308 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16309 extras.putString(Intent.EXTRA_TITLE, label); 16310 mMoveCallbacks.notifyCreated(moveId, extras); 16311 16312 int installFlags; 16313 final boolean moveCompleteApp; 16314 final File measurePath; 16315 16316 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16317 installFlags = INSTALL_INTERNAL; 16318 moveCompleteApp = !currentAsec; 16319 measurePath = Environment.getDataAppDirectory(volumeUuid); 16320 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16321 installFlags = INSTALL_EXTERNAL; 16322 moveCompleteApp = false; 16323 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16324 } else { 16325 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16326 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16327 || !volume.isMountedWritable()) { 16328 unfreezePackage(packageName); 16329 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16330 "Move location not mounted private volume"); 16331 } 16332 16333 Preconditions.checkState(!currentAsec); 16334 16335 installFlags = INSTALL_INTERNAL; 16336 moveCompleteApp = true; 16337 measurePath = Environment.getDataAppDirectory(volumeUuid); 16338 } 16339 16340 final PackageStats stats = new PackageStats(null, -1); 16341 synchronized (mInstaller) { 16342 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16343 unfreezePackage(packageName); 16344 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16345 "Failed to measure package size"); 16346 } 16347 } 16348 16349 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16350 + stats.dataSize); 16351 16352 final long startFreeBytes = measurePath.getFreeSpace(); 16353 final long sizeBytes; 16354 if (moveCompleteApp) { 16355 sizeBytes = stats.codeSize + stats.dataSize; 16356 } else { 16357 sizeBytes = stats.codeSize; 16358 } 16359 16360 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16361 unfreezePackage(packageName); 16362 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16363 "Not enough free space to move"); 16364 } 16365 16366 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16367 16368 final CountDownLatch installedLatch = new CountDownLatch(1); 16369 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16370 @Override 16371 public void onUserActionRequired(Intent intent) throws RemoteException { 16372 throw new IllegalStateException(); 16373 } 16374 16375 @Override 16376 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16377 Bundle extras) throws RemoteException { 16378 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16379 + PackageManager.installStatusToString(returnCode, msg)); 16380 16381 installedLatch.countDown(); 16382 16383 // Regardless of success or failure of the move operation, 16384 // always unfreeze the package 16385 unfreezePackage(packageName); 16386 16387 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16388 switch (status) { 16389 case PackageInstaller.STATUS_SUCCESS: 16390 mMoveCallbacks.notifyStatusChanged(moveId, 16391 PackageManager.MOVE_SUCCEEDED); 16392 break; 16393 case PackageInstaller.STATUS_FAILURE_STORAGE: 16394 mMoveCallbacks.notifyStatusChanged(moveId, 16395 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16396 break; 16397 default: 16398 mMoveCallbacks.notifyStatusChanged(moveId, 16399 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16400 break; 16401 } 16402 } 16403 }; 16404 16405 final MoveInfo move; 16406 if (moveCompleteApp) { 16407 // Kick off a thread to report progress estimates 16408 new Thread() { 16409 @Override 16410 public void run() { 16411 while (true) { 16412 try { 16413 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16414 break; 16415 } 16416 } catch (InterruptedException ignored) { 16417 } 16418 16419 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16420 final int progress = 10 + (int) MathUtils.constrain( 16421 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16422 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16423 } 16424 } 16425 }.start(); 16426 16427 final String dataAppName = codeFile.getName(); 16428 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16429 dataAppName, appId, seinfo); 16430 } else { 16431 move = null; 16432 } 16433 16434 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16435 16436 final Message msg = mHandler.obtainMessage(INIT_COPY); 16437 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16438 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16439 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16440 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16441 msg.obj = params; 16442 16443 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16444 System.identityHashCode(msg.obj)); 16445 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16446 System.identityHashCode(msg.obj)); 16447 16448 mHandler.sendMessage(msg); 16449 } 16450 16451 @Override 16452 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16453 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16454 16455 final int realMoveId = mNextMoveId.getAndIncrement(); 16456 final Bundle extras = new Bundle(); 16457 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16458 mMoveCallbacks.notifyCreated(realMoveId, extras); 16459 16460 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16461 @Override 16462 public void onCreated(int moveId, Bundle extras) { 16463 // Ignored 16464 } 16465 16466 @Override 16467 public void onStatusChanged(int moveId, int status, long estMillis) { 16468 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16469 } 16470 }; 16471 16472 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16473 storage.setPrimaryStorageUuid(volumeUuid, callback); 16474 return realMoveId; 16475 } 16476 16477 @Override 16478 public int getMoveStatus(int moveId) { 16479 mContext.enforceCallingOrSelfPermission( 16480 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16481 return mMoveCallbacks.mLastStatus.get(moveId); 16482 } 16483 16484 @Override 16485 public void registerMoveCallback(IPackageMoveObserver callback) { 16486 mContext.enforceCallingOrSelfPermission( 16487 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16488 mMoveCallbacks.register(callback); 16489 } 16490 16491 @Override 16492 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16493 mContext.enforceCallingOrSelfPermission( 16494 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16495 mMoveCallbacks.unregister(callback); 16496 } 16497 16498 @Override 16499 public boolean setInstallLocation(int loc) { 16500 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16501 null); 16502 if (getInstallLocation() == loc) { 16503 return true; 16504 } 16505 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16506 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16507 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16508 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16509 return true; 16510 } 16511 return false; 16512 } 16513 16514 @Override 16515 public int getInstallLocation() { 16516 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16517 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16518 PackageHelper.APP_INSTALL_AUTO); 16519 } 16520 16521 /** Called by UserManagerService */ 16522 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16523 mDirtyUsers.remove(userHandle); 16524 mSettings.removeUserLPw(userHandle); 16525 mPendingBroadcasts.remove(userHandle); 16526 if (mInstaller != null) { 16527 // Technically, we shouldn't be doing this with the package lock 16528 // held. However, this is very rare, and there is already so much 16529 // other disk I/O going on, that we'll let it slide for now. 16530 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16531 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16532 final String volumeUuid = vol.getFsUuid(); 16533 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16534 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16535 } 16536 } 16537 mUserNeedsBadging.delete(userHandle); 16538 removeUnusedPackagesLILPw(userManager, userHandle); 16539 } 16540 16541 /** 16542 * We're removing userHandle and would like to remove any downloaded packages 16543 * that are no longer in use by any other user. 16544 * @param userHandle the user being removed 16545 */ 16546 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16547 final boolean DEBUG_CLEAN_APKS = false; 16548 int [] users = userManager.getUserIds(); 16549 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16550 while (psit.hasNext()) { 16551 PackageSetting ps = psit.next(); 16552 if (ps.pkg == null) { 16553 continue; 16554 } 16555 final String packageName = ps.pkg.packageName; 16556 // Skip over if system app 16557 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16558 continue; 16559 } 16560 if (DEBUG_CLEAN_APKS) { 16561 Slog.i(TAG, "Checking package " + packageName); 16562 } 16563 boolean keep = false; 16564 for (int i = 0; i < users.length; i++) { 16565 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16566 keep = true; 16567 if (DEBUG_CLEAN_APKS) { 16568 Slog.i(TAG, " Keeping package " + packageName + " for user " 16569 + users[i]); 16570 } 16571 break; 16572 } 16573 } 16574 if (!keep) { 16575 if (DEBUG_CLEAN_APKS) { 16576 Slog.i(TAG, " Removing package " + packageName); 16577 } 16578 mHandler.post(new Runnable() { 16579 public void run() { 16580 deletePackageX(packageName, userHandle, 0); 16581 } //end run 16582 }); 16583 } 16584 } 16585 } 16586 16587 /** Called by UserManagerService */ 16588 void createNewUserLILPw(int userHandle) { 16589 if (mInstaller != null) { 16590 mInstaller.createUserConfig(userHandle); 16591 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16592 applyFactoryDefaultBrowserLPw(userHandle); 16593 primeDomainVerificationsLPw(userHandle); 16594 } 16595 } 16596 16597 void newUserCreated(final int userHandle) { 16598 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16599 } 16600 16601 @Override 16602 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16603 mContext.enforceCallingOrSelfPermission( 16604 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16605 "Only package verification agents can read the verifier device identity"); 16606 16607 synchronized (mPackages) { 16608 return mSettings.getVerifierDeviceIdentityLPw(); 16609 } 16610 } 16611 16612 @Override 16613 public void setPermissionEnforced(String permission, boolean enforced) { 16614 // TODO: Now that we no longer change GID for storage, this should to away. 16615 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16616 "setPermissionEnforced"); 16617 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16618 synchronized (mPackages) { 16619 if (mSettings.mReadExternalStorageEnforced == null 16620 || mSettings.mReadExternalStorageEnforced != enforced) { 16621 mSettings.mReadExternalStorageEnforced = enforced; 16622 mSettings.writeLPr(); 16623 } 16624 } 16625 // kill any non-foreground processes so we restart them and 16626 // grant/revoke the GID. 16627 final IActivityManager am = ActivityManagerNative.getDefault(); 16628 if (am != null) { 16629 final long token = Binder.clearCallingIdentity(); 16630 try { 16631 am.killProcessesBelowForeground("setPermissionEnforcement"); 16632 } catch (RemoteException e) { 16633 } finally { 16634 Binder.restoreCallingIdentity(token); 16635 } 16636 } 16637 } else { 16638 throw new IllegalArgumentException("No selective enforcement for " + permission); 16639 } 16640 } 16641 16642 @Override 16643 @Deprecated 16644 public boolean isPermissionEnforced(String permission) { 16645 return true; 16646 } 16647 16648 @Override 16649 public boolean isStorageLow() { 16650 final long token = Binder.clearCallingIdentity(); 16651 try { 16652 final DeviceStorageMonitorInternal 16653 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16654 if (dsm != null) { 16655 return dsm.isMemoryLow(); 16656 } else { 16657 return false; 16658 } 16659 } finally { 16660 Binder.restoreCallingIdentity(token); 16661 } 16662 } 16663 16664 @Override 16665 public IPackageInstaller getPackageInstaller() { 16666 return mInstallerService; 16667 } 16668 16669 private boolean userNeedsBadging(int userId) { 16670 int index = mUserNeedsBadging.indexOfKey(userId); 16671 if (index < 0) { 16672 final UserInfo userInfo; 16673 final long token = Binder.clearCallingIdentity(); 16674 try { 16675 userInfo = sUserManager.getUserInfo(userId); 16676 } finally { 16677 Binder.restoreCallingIdentity(token); 16678 } 16679 final boolean b; 16680 if (userInfo != null && userInfo.isManagedProfile()) { 16681 b = true; 16682 } else { 16683 b = false; 16684 } 16685 mUserNeedsBadging.put(userId, b); 16686 return b; 16687 } 16688 return mUserNeedsBadging.valueAt(index); 16689 } 16690 16691 @Override 16692 public KeySet getKeySetByAlias(String packageName, String alias) { 16693 if (packageName == null || alias == null) { 16694 return null; 16695 } 16696 synchronized(mPackages) { 16697 final PackageParser.Package pkg = mPackages.get(packageName); 16698 if (pkg == null) { 16699 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16700 throw new IllegalArgumentException("Unknown package: " + packageName); 16701 } 16702 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16703 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16704 } 16705 } 16706 16707 @Override 16708 public KeySet getSigningKeySet(String packageName) { 16709 if (packageName == null) { 16710 return null; 16711 } 16712 synchronized(mPackages) { 16713 final PackageParser.Package pkg = mPackages.get(packageName); 16714 if (pkg == null) { 16715 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16716 throw new IllegalArgumentException("Unknown package: " + packageName); 16717 } 16718 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16719 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16720 throw new SecurityException("May not access signing KeySet of other apps."); 16721 } 16722 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16723 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16724 } 16725 } 16726 16727 @Override 16728 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16729 if (packageName == null || ks == null) { 16730 return false; 16731 } 16732 synchronized(mPackages) { 16733 final PackageParser.Package pkg = mPackages.get(packageName); 16734 if (pkg == null) { 16735 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16736 throw new IllegalArgumentException("Unknown package: " + packageName); 16737 } 16738 IBinder ksh = ks.getToken(); 16739 if (ksh instanceof KeySetHandle) { 16740 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16741 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16742 } 16743 return false; 16744 } 16745 } 16746 16747 @Override 16748 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16749 if (packageName == null || ks == null) { 16750 return false; 16751 } 16752 synchronized(mPackages) { 16753 final PackageParser.Package pkg = mPackages.get(packageName); 16754 if (pkg == null) { 16755 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16756 throw new IllegalArgumentException("Unknown package: " + packageName); 16757 } 16758 IBinder ksh = ks.getToken(); 16759 if (ksh instanceof KeySetHandle) { 16760 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16761 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16762 } 16763 return false; 16764 } 16765 } 16766 16767 public void getUsageStatsIfNoPackageUsageInfo() { 16768 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16769 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16770 if (usm == null) { 16771 throw new IllegalStateException("UsageStatsManager must be initialized"); 16772 } 16773 long now = System.currentTimeMillis(); 16774 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16775 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16776 String packageName = entry.getKey(); 16777 PackageParser.Package pkg = mPackages.get(packageName); 16778 if (pkg == null) { 16779 continue; 16780 } 16781 UsageStats usage = entry.getValue(); 16782 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16783 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16784 } 16785 } 16786 } 16787 16788 /** 16789 * Check and throw if the given before/after packages would be considered a 16790 * downgrade. 16791 */ 16792 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16793 throws PackageManagerException { 16794 if (after.versionCode < before.mVersionCode) { 16795 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16796 "Update version code " + after.versionCode + " is older than current " 16797 + before.mVersionCode); 16798 } else if (after.versionCode == before.mVersionCode) { 16799 if (after.baseRevisionCode < before.baseRevisionCode) { 16800 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16801 "Update base revision code " + after.baseRevisionCode 16802 + " is older than current " + before.baseRevisionCode); 16803 } 16804 16805 if (!ArrayUtils.isEmpty(after.splitNames)) { 16806 for (int i = 0; i < after.splitNames.length; i++) { 16807 final String splitName = after.splitNames[i]; 16808 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16809 if (j != -1) { 16810 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16811 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16812 "Update split " + splitName + " revision code " 16813 + after.splitRevisionCodes[i] + " is older than current " 16814 + before.splitRevisionCodes[j]); 16815 } 16816 } 16817 } 16818 } 16819 } 16820 } 16821 16822 private static class MoveCallbacks extends Handler { 16823 private static final int MSG_CREATED = 1; 16824 private static final int MSG_STATUS_CHANGED = 2; 16825 16826 private final RemoteCallbackList<IPackageMoveObserver> 16827 mCallbacks = new RemoteCallbackList<>(); 16828 16829 private final SparseIntArray mLastStatus = new SparseIntArray(); 16830 16831 public MoveCallbacks(Looper looper) { 16832 super(looper); 16833 } 16834 16835 public void register(IPackageMoveObserver callback) { 16836 mCallbacks.register(callback); 16837 } 16838 16839 public void unregister(IPackageMoveObserver callback) { 16840 mCallbacks.unregister(callback); 16841 } 16842 16843 @Override 16844 public void handleMessage(Message msg) { 16845 final SomeArgs args = (SomeArgs) msg.obj; 16846 final int n = mCallbacks.beginBroadcast(); 16847 for (int i = 0; i < n; i++) { 16848 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16849 try { 16850 invokeCallback(callback, msg.what, args); 16851 } catch (RemoteException ignored) { 16852 } 16853 } 16854 mCallbacks.finishBroadcast(); 16855 args.recycle(); 16856 } 16857 16858 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16859 throws RemoteException { 16860 switch (what) { 16861 case MSG_CREATED: { 16862 callback.onCreated(args.argi1, (Bundle) args.arg2); 16863 break; 16864 } 16865 case MSG_STATUS_CHANGED: { 16866 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16867 break; 16868 } 16869 } 16870 } 16871 16872 private void notifyCreated(int moveId, Bundle extras) { 16873 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16874 16875 final SomeArgs args = SomeArgs.obtain(); 16876 args.argi1 = moveId; 16877 args.arg2 = extras; 16878 obtainMessage(MSG_CREATED, args).sendToTarget(); 16879 } 16880 16881 private void notifyStatusChanged(int moveId, int status) { 16882 notifyStatusChanged(moveId, status, -1); 16883 } 16884 16885 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16886 Slog.v(TAG, "Move " + moveId + " status " + status); 16887 16888 final SomeArgs args = SomeArgs.obtain(); 16889 args.argi1 = moveId; 16890 args.argi2 = status; 16891 args.arg3 = estMillis; 16892 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16893 16894 synchronized (mLastStatus) { 16895 mLastStatus.put(moveId, status); 16896 } 16897 } 16898 } 16899 16900 private final class OnPermissionChangeListeners extends Handler { 16901 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16902 16903 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16904 new RemoteCallbackList<>(); 16905 16906 public OnPermissionChangeListeners(Looper looper) { 16907 super(looper); 16908 } 16909 16910 @Override 16911 public void handleMessage(Message msg) { 16912 switch (msg.what) { 16913 case MSG_ON_PERMISSIONS_CHANGED: { 16914 final int uid = msg.arg1; 16915 handleOnPermissionsChanged(uid); 16916 } break; 16917 } 16918 } 16919 16920 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16921 mPermissionListeners.register(listener); 16922 16923 } 16924 16925 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16926 mPermissionListeners.unregister(listener); 16927 } 16928 16929 public void onPermissionsChanged(int uid) { 16930 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16931 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16932 } 16933 } 16934 16935 private void handleOnPermissionsChanged(int uid) { 16936 final int count = mPermissionListeners.beginBroadcast(); 16937 try { 16938 for (int i = 0; i < count; i++) { 16939 IOnPermissionsChangeListener callback = mPermissionListeners 16940 .getBroadcastItem(i); 16941 try { 16942 callback.onPermissionsChanged(uid); 16943 } catch (RemoteException e) { 16944 Log.e(TAG, "Permission listener is dead", e); 16945 } 16946 } 16947 } finally { 16948 mPermissionListeners.finishBroadcast(); 16949 } 16950 } 16951 } 16952 16953 private class PackageManagerInternalImpl extends PackageManagerInternal { 16954 @Override 16955 public void setLocationPackagesProvider(PackagesProvider provider) { 16956 synchronized (mPackages) { 16957 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16958 } 16959 } 16960 16961 @Override 16962 public void setImePackagesProvider(PackagesProvider provider) { 16963 synchronized (mPackages) { 16964 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16965 } 16966 } 16967 16968 @Override 16969 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16970 synchronized (mPackages) { 16971 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16972 } 16973 } 16974 16975 @Override 16976 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16977 synchronized (mPackages) { 16978 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16979 } 16980 } 16981 16982 @Override 16983 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16984 synchronized (mPackages) { 16985 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16986 } 16987 } 16988 16989 @Override 16990 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16991 synchronized (mPackages) { 16992 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 16993 } 16994 } 16995 16996 @Override 16997 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16998 synchronized (mPackages) { 16999 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17000 } 17001 } 17002 17003 @Override 17004 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17005 synchronized (mPackages) { 17006 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17007 packageName, userId); 17008 } 17009 } 17010 17011 @Override 17012 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17013 synchronized (mPackages) { 17014 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17015 packageName, userId); 17016 } 17017 } 17018 @Override 17019 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17020 synchronized (mPackages) { 17021 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17022 packageName, userId); 17023 } 17024 } 17025 } 17026 17027 @Override 17028 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17029 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17030 synchronized (mPackages) { 17031 final long identity = Binder.clearCallingIdentity(); 17032 try { 17033 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17034 packageNames, userId); 17035 } finally { 17036 Binder.restoreCallingIdentity(identity); 17037 } 17038 } 17039 } 17040 17041 private static void enforceSystemOrPhoneCaller(String tag) { 17042 int callingUid = Binder.getCallingUid(); 17043 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17044 throw new SecurityException( 17045 "Cannot call " + tag + " from UID " + callingUid); 17046 } 17047 } 17048} 17049