PackageManagerService.java revision 60459abb211a11caf71238a44f543fdc18289772
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 33import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 53import static android.content.pm.PackageManager.INSTALL_INTERNAL; 54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_DENIED; 66import static android.content.pm.PackageManager.PERMISSION_GRANTED; 67import static android.content.pm.PackageParser.isApkFile; 68import static android.os.Process.PACKAGE_INFO_GID; 69import static android.os.Process.SYSTEM_UID; 70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 71import static android.system.OsConstants.O_CREAT; 72import static android.system.OsConstants.O_RDWR; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 77import static com.android.internal.util.ArrayUtils.appendInt; 78import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 87 88import android.Manifest; 89import android.app.ActivityManager; 90import android.app.ActivityManagerNative; 91import android.app.AppGlobals; 92import android.app.IActivityManager; 93import android.app.admin.IDevicePolicyManager; 94import android.app.backup.IBackupManager; 95import android.app.usage.UsageStats; 96import android.app.usage.UsageStatsManager; 97import android.content.BroadcastReceiver; 98import android.content.ComponentName; 99import android.content.Context; 100import android.content.IIntentReceiver; 101import android.content.Intent; 102import android.content.IntentFilter; 103import android.content.IntentSender; 104import android.content.IntentSender.SendIntentException; 105import android.content.ServiceConnection; 106import android.content.pm.ActivityInfo; 107import android.content.pm.ApplicationInfo; 108import android.content.pm.FeatureInfo; 109import android.content.pm.IOnPermissionsChangeListener; 110import android.content.pm.IPackageDataObserver; 111import android.content.pm.IPackageDeleteObserver; 112import android.content.pm.IPackageDeleteObserver2; 113import android.content.pm.IPackageInstallObserver2; 114import android.content.pm.IPackageInstaller; 115import android.content.pm.IPackageManager; 116import android.content.pm.IPackageMoveObserver; 117import android.content.pm.IPackageStatsObserver; 118import android.content.pm.InstrumentationInfo; 119import android.content.pm.IntentFilterVerificationInfo; 120import android.content.pm.KeySet; 121import android.content.pm.ManifestDigest; 122import android.content.pm.PackageCleanItem; 123import android.content.pm.PackageInfo; 124import android.content.pm.PackageInfoLite; 125import android.content.pm.PackageInstaller; 126import android.content.pm.PackageManager; 127import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 128import android.content.pm.PackageManagerInternal; 129import android.content.pm.PackageParser; 130import android.content.pm.PackageParser.ActivityIntentInfo; 131import android.content.pm.PackageParser.PackageLite; 132import android.content.pm.PackageParser.PackageParserException; 133import android.content.pm.PackageStats; 134import android.content.pm.PackageUserState; 135import android.content.pm.ParceledListSlice; 136import android.content.pm.PermissionGroupInfo; 137import android.content.pm.PermissionInfo; 138import android.content.pm.ProviderInfo; 139import android.content.pm.ResolveInfo; 140import android.content.pm.ServiceInfo; 141import android.content.pm.Signature; 142import android.content.pm.UserInfo; 143import android.content.pm.VerificationParams; 144import android.content.pm.VerifierDeviceIdentity; 145import android.content.pm.VerifierInfo; 146import android.content.res.Resources; 147import android.hardware.display.DisplayManager; 148import android.net.Uri; 149import android.os.Debug; 150import android.os.Binder; 151import android.os.Build; 152import android.os.Bundle; 153import android.os.Environment; 154import android.os.Environment.UserEnvironment; 155import android.os.FileUtils; 156import android.os.Handler; 157import android.os.IBinder; 158import android.os.Looper; 159import android.os.Message; 160import android.os.Parcel; 161import android.os.ParcelFileDescriptor; 162import android.os.Process; 163import android.os.RemoteCallbackList; 164import android.os.RemoteException; 165import android.os.ResultReceiver; 166import android.os.SELinux; 167import android.os.ServiceManager; 168import android.os.SystemClock; 169import android.os.SystemProperties; 170import android.os.Trace; 171import android.os.UserHandle; 172import android.os.UserManager; 173import android.os.storage.IMountService; 174import android.os.storage.MountServiceInternal; 175import android.os.storage.StorageEventListener; 176import android.os.storage.StorageManager; 177import android.os.storage.VolumeInfo; 178import android.os.storage.VolumeRecord; 179import android.security.KeyStore; 180import android.security.SystemKeyStore; 181import android.system.ErrnoException; 182import android.system.Os; 183import android.system.StructStat; 184import android.text.TextUtils; 185import android.text.format.DateUtils; 186import android.util.ArrayMap; 187import android.util.ArraySet; 188import android.util.AtomicFile; 189import android.util.DisplayMetrics; 190import android.util.EventLog; 191import android.util.ExceptionUtils; 192import android.util.Log; 193import android.util.LogPrinter; 194import android.util.MathUtils; 195import android.util.PrintStreamPrinter; 196import android.util.Slog; 197import android.util.SparseArray; 198import android.util.SparseBooleanArray; 199import android.util.SparseIntArray; 200import android.util.Xml; 201import android.view.Display; 202 203import dalvik.system.DexFile; 204import dalvik.system.VMRuntime; 205 206import libcore.io.IoUtils; 207import libcore.util.EmptyArray; 208 209import com.android.internal.R; 210import com.android.internal.annotations.GuardedBy; 211import com.android.internal.app.IMediaContainerService; 212import com.android.internal.app.ResolverActivity; 213import com.android.internal.content.NativeLibraryHelper; 214import com.android.internal.content.PackageHelper; 215import com.android.internal.os.IParcelFileDescriptorFactory; 216import com.android.internal.os.SomeArgs; 217import com.android.internal.os.Zygote; 218import com.android.internal.util.ArrayUtils; 219import com.android.internal.util.FastPrintWriter; 220import com.android.internal.util.FastXmlSerializer; 221import com.android.internal.util.IndentingPrintWriter; 222import com.android.internal.util.Preconditions; 223import com.android.server.EventLogTags; 224import com.android.server.FgThread; 225import com.android.server.IntentResolver; 226import com.android.server.LocalServices; 227import com.android.server.ServiceThread; 228import com.android.server.SystemConfig; 229import com.android.server.Watchdog; 230import com.android.server.pm.PermissionsState.PermissionState; 231import com.android.server.pm.Settings.DatabaseVersion; 232import com.android.server.pm.Settings.VersionInfo; 233import com.android.server.storage.DeviceStorageMonitorInternal; 234 235import org.xmlpull.v1.XmlPullParser; 236import org.xmlpull.v1.XmlPullParserException; 237import org.xmlpull.v1.XmlSerializer; 238 239import java.io.BufferedInputStream; 240import java.io.BufferedOutputStream; 241import java.io.BufferedReader; 242import java.io.ByteArrayInputStream; 243import java.io.ByteArrayOutputStream; 244import java.io.File; 245import java.io.FileDescriptor; 246import java.io.FileNotFoundException; 247import java.io.FileOutputStream; 248import java.io.FileReader; 249import java.io.FilenameFilter; 250import java.io.IOException; 251import java.io.InputStream; 252import java.io.PrintWriter; 253import java.nio.charset.StandardCharsets; 254import java.security.NoSuchAlgorithmException; 255import java.security.PublicKey; 256import java.security.cert.CertificateEncodingException; 257import java.security.cert.CertificateException; 258import java.text.SimpleDateFormat; 259import java.util.ArrayList; 260import java.util.Arrays; 261import java.util.Collection; 262import java.util.Collections; 263import java.util.Comparator; 264import java.util.Date; 265import java.util.Iterator; 266import java.util.List; 267import java.util.Map; 268import java.util.Objects; 269import java.util.Set; 270import java.util.concurrent.CountDownLatch; 271import java.util.concurrent.TimeUnit; 272import java.util.concurrent.atomic.AtomicBoolean; 273import java.util.concurrent.atomic.AtomicInteger; 274import java.util.concurrent.atomic.AtomicLong; 275 276/** 277 * Keep track of all those .apks everywhere. 278 * 279 * This is very central to the platform's security; please run the unit 280 * tests whenever making modifications here: 281 * 282runtest -c android.content.pm.PackageManagerTests frameworks-core 283 * 284 * {@hide} 285 */ 286public class PackageManagerService extends IPackageManager.Stub { 287 static final String TAG = "PackageManager"; 288 static final boolean DEBUG_SETTINGS = false; 289 static final boolean DEBUG_PREFERRED = false; 290 static final boolean DEBUG_UPGRADE = false; 291 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 292 private static final boolean DEBUG_BACKUP = false; 293 private static final boolean DEBUG_INSTALL = false; 294 private static final boolean DEBUG_REMOVE = false; 295 private static final boolean DEBUG_BROADCASTS = false; 296 private static final boolean DEBUG_SHOW_INFO = false; 297 private static final boolean DEBUG_PACKAGE_INFO = false; 298 private static final boolean DEBUG_INTENT_MATCHING = false; 299 private static final boolean DEBUG_PACKAGE_SCANNING = false; 300 private static final boolean DEBUG_VERIFY = false; 301 private static final boolean DEBUG_DEXOPT = false; 302 private static final boolean DEBUG_ABI_SELECTION = false; 303 304 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 305 306 private static final int RADIO_UID = Process.PHONE_UID; 307 private static final int LOG_UID = Process.LOG_UID; 308 private static final int NFC_UID = Process.NFC_UID; 309 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 310 private static final int SHELL_UID = Process.SHELL_UID; 311 312 // Cap the size of permission trees that 3rd party apps can define 313 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 314 315 // Suffix used during package installation when copying/moving 316 // package apks to install directory. 317 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 318 319 static final int SCAN_NO_DEX = 1<<1; 320 static final int SCAN_FORCE_DEX = 1<<2; 321 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 322 static final int SCAN_NEW_INSTALL = 1<<4; 323 static final int SCAN_NO_PATHS = 1<<5; 324 static final int SCAN_UPDATE_TIME = 1<<6; 325 static final int SCAN_DEFER_DEX = 1<<7; 326 static final int SCAN_BOOTING = 1<<8; 327 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 328 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 329 static final int SCAN_REPLACING = 1<<11; 330 static final int SCAN_REQUIRE_KNOWN = 1<<12; 331 static final int SCAN_MOVE = 1<<13; 332 static final int SCAN_INITIAL = 1<<14; 333 334 static final int REMOVE_CHATTY = 1<<16; 335 336 private static final int[] EMPTY_INT_ARRAY = new int[0]; 337 338 /** 339 * Timeout (in milliseconds) after which the watchdog should declare that 340 * our handler thread is wedged. The usual default for such things is one 341 * minute but we sometimes do very lengthy I/O operations on this thread, 342 * such as installing multi-gigabyte applications, so ours needs to be longer. 343 */ 344 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 345 346 /** 347 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 348 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 349 * settings entry if available, otherwise we use the hardcoded default. If it's been 350 * more than this long since the last fstrim, we force one during the boot sequence. 351 * 352 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 353 * one gets run at the next available charging+idle time. This final mandatory 354 * no-fstrim check kicks in only of the other scheduling criteria is never met. 355 */ 356 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 357 358 /** 359 * Whether verification is enabled by default. 360 */ 361 private static final boolean DEFAULT_VERIFY_ENABLE = true; 362 363 /** 364 * The default maximum time to wait for the verification agent to return in 365 * milliseconds. 366 */ 367 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 368 369 /** 370 * The default response for package verification timeout. 371 * 372 * This can be either PackageManager.VERIFICATION_ALLOW or 373 * PackageManager.VERIFICATION_REJECT. 374 */ 375 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 376 377 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 378 379 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 380 DEFAULT_CONTAINER_PACKAGE, 381 "com.android.defcontainer.DefaultContainerService"); 382 383 private static final String KILL_APP_REASON_GIDS_CHANGED = 384 "permission grant or revoke changed gids"; 385 386 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 387 "permissions revoked"; 388 389 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 390 391 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 392 393 /** Permission grant: not grant the permission. */ 394 private static final int GRANT_DENIED = 1; 395 396 /** Permission grant: grant the permission as an install permission. */ 397 private static final int GRANT_INSTALL = 2; 398 399 /** Permission grant: grant the permission as an install permission for a legacy app. */ 400 private static final int GRANT_INSTALL_LEGACY = 3; 401 402 /** Permission grant: grant the permission as a runtime one. */ 403 private static final int GRANT_RUNTIME = 4; 404 405 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 406 private static final int GRANT_UPGRADE = 5; 407 408 /** Canonical intent used to identify what counts as a "web browser" app */ 409 private static final Intent sBrowserIntent; 410 static { 411 sBrowserIntent = new Intent(); 412 sBrowserIntent.setAction(Intent.ACTION_VIEW); 413 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 414 sBrowserIntent.setData(Uri.parse("http:")); 415 } 416 417 final ServiceThread mHandlerThread; 418 419 final PackageHandler mHandler; 420 421 /** 422 * Messages for {@link #mHandler} that need to wait for system ready before 423 * being dispatched. 424 */ 425 private ArrayList<Message> mPostSystemReadyMessages; 426 427 final int mSdkVersion = Build.VERSION.SDK_INT; 428 429 final Context mContext; 430 final boolean mFactoryTest; 431 final boolean mOnlyCore; 432 final boolean mLazyDexOpt; 433 final long mDexOptLRUThresholdInMills; 434 final DisplayMetrics mMetrics; 435 final int mDefParseFlags; 436 final String[] mSeparateProcesses; 437 final boolean mIsUpgrade; 438 439 // This is where all application persistent data goes. 440 final File mAppDataDir; 441 442 // This is where all application persistent data goes for secondary users. 443 final File mUserAppDataDir; 444 445 /** The location for ASEC container files on internal storage. */ 446 final String mAsecInternalPath; 447 448 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 449 // LOCK HELD. Can be called with mInstallLock held. 450 @GuardedBy("mInstallLock") 451 final Installer mInstaller; 452 453 /** Directory where installed third-party apps stored */ 454 final File mAppInstallDir; 455 456 /** 457 * Directory to which applications installed internally have their 458 * 32 bit native libraries copied. 459 */ 460 private File mAppLib32InstallDir; 461 462 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 463 // apps. 464 final File mDrmAppPrivateInstallDir; 465 466 // ---------------------------------------------------------------- 467 468 // Lock for state used when installing and doing other long running 469 // operations. Methods that must be called with this lock held have 470 // the suffix "LI". 471 final Object mInstallLock = new Object(); 472 473 // ---------------------------------------------------------------- 474 475 // Keys are String (package name), values are Package. This also serves 476 // as the lock for the global state. Methods that must be called with 477 // this lock held have the prefix "LP". 478 @GuardedBy("mPackages") 479 final ArrayMap<String, PackageParser.Package> mPackages = 480 new ArrayMap<String, PackageParser.Package>(); 481 482 // Tracks available target package names -> overlay package paths. 483 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 484 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 485 486 /** 487 * Tracks new system packages [received in an OTA] that we expect to 488 * find updated user-installed versions. Keys are package name, values 489 * are package location. 490 */ 491 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 492 493 /** 494 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 495 */ 496 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 497 /** 498 * Whether or not system app permissions should be promoted from install to runtime. 499 */ 500 boolean mPromoteSystemApps; 501 502 final Settings mSettings; 503 boolean mRestoredSettings; 504 505 // System configuration read by SystemConfig. 506 final int[] mGlobalGids; 507 final SparseArray<ArraySet<String>> mSystemPermissions; 508 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 509 510 // If mac_permissions.xml was found for seinfo labeling. 511 boolean mFoundPolicyFile; 512 513 // If a recursive restorecon of /data/data/<pkg> is needed. 514 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 515 516 public static final class SharedLibraryEntry { 517 public final String path; 518 public final String apk; 519 520 SharedLibraryEntry(String _path, String _apk) { 521 path = _path; 522 apk = _apk; 523 } 524 } 525 526 // Currently known shared libraries. 527 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 528 new ArrayMap<String, SharedLibraryEntry>(); 529 530 // All available activities, for your resolving pleasure. 531 final ActivityIntentResolver mActivities = 532 new ActivityIntentResolver(); 533 534 // All available receivers, for your resolving pleasure. 535 final ActivityIntentResolver mReceivers = 536 new ActivityIntentResolver(); 537 538 // All available services, for your resolving pleasure. 539 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 540 541 // All available providers, for your resolving pleasure. 542 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 543 544 // Mapping from provider base names (first directory in content URI codePath) 545 // to the provider information. 546 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 547 new ArrayMap<String, PackageParser.Provider>(); 548 549 // Mapping from instrumentation class names to info about them. 550 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 551 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 552 553 // Mapping from permission names to info about them. 554 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 555 new ArrayMap<String, PackageParser.PermissionGroup>(); 556 557 // Packages whose data we have transfered into another package, thus 558 // should no longer exist. 559 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 560 561 // Broadcast actions that are only available to the system. 562 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 563 564 /** List of packages waiting for verification. */ 565 final SparseArray<PackageVerificationState> mPendingVerification 566 = new SparseArray<PackageVerificationState>(); 567 568 /** Set of packages associated with each app op permission. */ 569 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 570 571 final PackageInstallerService mInstallerService; 572 573 private final PackageDexOptimizer mPackageDexOptimizer; 574 575 private AtomicInteger mNextMoveId = new AtomicInteger(); 576 private final MoveCallbacks mMoveCallbacks; 577 578 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 579 580 // Cache of users who need badging. 581 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 582 583 /** Token for keys in mPendingVerification. */ 584 private int mPendingVerificationToken = 0; 585 586 volatile boolean mSystemReady; 587 volatile boolean mSafeMode; 588 volatile boolean mHasSystemUidErrors; 589 590 ApplicationInfo mAndroidApplication; 591 final ActivityInfo mResolveActivity = new ActivityInfo(); 592 final ResolveInfo mResolveInfo = new ResolveInfo(); 593 ComponentName mResolveComponentName; 594 PackageParser.Package mPlatformPackage; 595 ComponentName mCustomResolverComponentName; 596 597 boolean mResolverReplaced = false; 598 599 private final ComponentName mIntentFilterVerifierComponent; 600 private int mIntentFilterVerificationToken = 0; 601 602 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 603 = new SparseArray<IntentFilterVerificationState>(); 604 605 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 606 new DefaultPermissionGrantPolicy(this); 607 608 private static class IFVerificationParams { 609 PackageParser.Package pkg; 610 boolean replacing; 611 int userId; 612 int verifierUid; 613 614 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 615 int _userId, int _verifierUid) { 616 pkg = _pkg; 617 replacing = _replacing; 618 userId = _userId; 619 replacing = _replacing; 620 verifierUid = _verifierUid; 621 } 622 } 623 624 private interface IntentFilterVerifier<T extends IntentFilter> { 625 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 626 T filter, String packageName); 627 void startVerifications(int userId); 628 void receiveVerificationResponse(int verificationId); 629 } 630 631 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 632 private Context mContext; 633 private ComponentName mIntentFilterVerifierComponent; 634 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 635 636 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 637 mContext = context; 638 mIntentFilterVerifierComponent = verifierComponent; 639 } 640 641 private String getDefaultScheme() { 642 return IntentFilter.SCHEME_HTTPS; 643 } 644 645 @Override 646 public void startVerifications(int userId) { 647 // Launch verifications requests 648 int count = mCurrentIntentFilterVerifications.size(); 649 for (int n=0; n<count; n++) { 650 int verificationId = mCurrentIntentFilterVerifications.get(n); 651 final IntentFilterVerificationState ivs = 652 mIntentFilterVerificationStates.get(verificationId); 653 654 String packageName = ivs.getPackageName(); 655 656 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 657 final int filterCount = filters.size(); 658 ArraySet<String> domainsSet = new ArraySet<>(); 659 for (int m=0; m<filterCount; m++) { 660 PackageParser.ActivityIntentInfo filter = filters.get(m); 661 domainsSet.addAll(filter.getHostsList()); 662 } 663 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 664 synchronized (mPackages) { 665 if (mSettings.createIntentFilterVerificationIfNeededLPw( 666 packageName, domainsList) != null) { 667 scheduleWriteSettingsLocked(); 668 } 669 } 670 sendVerificationRequest(userId, verificationId, ivs); 671 } 672 mCurrentIntentFilterVerifications.clear(); 673 } 674 675 private void sendVerificationRequest(int userId, int verificationId, 676 IntentFilterVerificationState ivs) { 677 678 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 679 verificationIntent.putExtra( 680 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 681 verificationId); 682 verificationIntent.putExtra( 683 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 684 getDefaultScheme()); 685 verificationIntent.putExtra( 686 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 687 ivs.getHostsString()); 688 verificationIntent.putExtra( 689 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 690 ivs.getPackageName()); 691 verificationIntent.setComponent(mIntentFilterVerifierComponent); 692 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 693 694 UserHandle user = new UserHandle(userId); 695 mContext.sendBroadcastAsUser(verificationIntent, user); 696 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 697 "Sending IntentFilter verification broadcast"); 698 } 699 700 public void receiveVerificationResponse(int verificationId) { 701 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 702 703 final boolean verified = ivs.isVerified(); 704 705 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 706 final int count = filters.size(); 707 if (DEBUG_DOMAIN_VERIFICATION) { 708 Slog.i(TAG, "Received verification response " + verificationId 709 + " for " + count + " filters, verified=" + verified); 710 } 711 for (int n=0; n<count; n++) { 712 PackageParser.ActivityIntentInfo filter = filters.get(n); 713 filter.setVerified(verified); 714 715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 716 + " verified with result:" + verified + " and hosts:" 717 + ivs.getHostsString()); 718 } 719 720 mIntentFilterVerificationStates.remove(verificationId); 721 722 final String packageName = ivs.getPackageName(); 723 IntentFilterVerificationInfo ivi = null; 724 725 synchronized (mPackages) { 726 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 727 } 728 if (ivi == null) { 729 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 730 + verificationId + " packageName:" + packageName); 731 return; 732 } 733 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 734 "Updating IntentFilterVerificationInfo for package " + packageName 735 +" verificationId:" + verificationId); 736 737 synchronized (mPackages) { 738 if (verified) { 739 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 740 } else { 741 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 742 } 743 scheduleWriteSettingsLocked(); 744 745 final int userId = ivs.getUserId(); 746 if (userId != UserHandle.USER_ALL) { 747 final int userStatus = 748 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 749 750 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 751 boolean needUpdate = false; 752 753 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 754 // already been set by the User thru the Disambiguation dialog 755 switch (userStatus) { 756 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 757 if (verified) { 758 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 759 } else { 760 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 761 } 762 needUpdate = true; 763 break; 764 765 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 766 if (verified) { 767 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 768 needUpdate = true; 769 } 770 break; 771 772 default: 773 // Nothing to do 774 } 775 776 if (needUpdate) { 777 mSettings.updateIntentFilterVerificationStatusLPw( 778 packageName, updatedStatus, userId); 779 scheduleWritePackageRestrictionsLocked(userId); 780 } 781 } 782 } 783 } 784 785 @Override 786 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 787 ActivityIntentInfo filter, String packageName) { 788 if (!hasValidDomains(filter)) { 789 return false; 790 } 791 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 792 if (ivs == null) { 793 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 794 packageName); 795 } 796 if (DEBUG_DOMAIN_VERIFICATION) { 797 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 798 } 799 ivs.addFilter(filter); 800 return true; 801 } 802 803 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 804 int userId, int verificationId, String packageName) { 805 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 806 verifierUid, userId, packageName); 807 ivs.setPendingState(); 808 synchronized (mPackages) { 809 mIntentFilterVerificationStates.append(verificationId, ivs); 810 mCurrentIntentFilterVerifications.add(verificationId); 811 } 812 return ivs; 813 } 814 } 815 816 private static boolean hasValidDomains(ActivityIntentInfo filter) { 817 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 818 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 819 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 820 } 821 822 private IntentFilterVerifier mIntentFilterVerifier; 823 824 // Set of pending broadcasts for aggregating enable/disable of components. 825 static class PendingPackageBroadcasts { 826 // for each user id, a map of <package name -> components within that package> 827 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 828 829 public PendingPackageBroadcasts() { 830 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 831 } 832 833 public ArrayList<String> get(int userId, String packageName) { 834 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 835 return packages.get(packageName); 836 } 837 838 public void put(int userId, String packageName, ArrayList<String> components) { 839 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 840 packages.put(packageName, components); 841 } 842 843 public void remove(int userId, String packageName) { 844 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 845 if (packages != null) { 846 packages.remove(packageName); 847 } 848 } 849 850 public void remove(int userId) { 851 mUidMap.remove(userId); 852 } 853 854 public int userIdCount() { 855 return mUidMap.size(); 856 } 857 858 public int userIdAt(int n) { 859 return mUidMap.keyAt(n); 860 } 861 862 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 863 return mUidMap.get(userId); 864 } 865 866 public int size() { 867 // total number of pending broadcast entries across all userIds 868 int num = 0; 869 for (int i = 0; i< mUidMap.size(); i++) { 870 num += mUidMap.valueAt(i).size(); 871 } 872 return num; 873 } 874 875 public void clear() { 876 mUidMap.clear(); 877 } 878 879 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 880 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 881 if (map == null) { 882 map = new ArrayMap<String, ArrayList<String>>(); 883 mUidMap.put(userId, map); 884 } 885 return map; 886 } 887 } 888 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 889 890 // Service Connection to remote media container service to copy 891 // package uri's from external media onto secure containers 892 // or internal storage. 893 private IMediaContainerService mContainerService = null; 894 895 static final int SEND_PENDING_BROADCAST = 1; 896 static final int MCS_BOUND = 3; 897 static final int END_COPY = 4; 898 static final int INIT_COPY = 5; 899 static final int MCS_UNBIND = 6; 900 static final int START_CLEANING_PACKAGE = 7; 901 static final int FIND_INSTALL_LOC = 8; 902 static final int POST_INSTALL = 9; 903 static final int MCS_RECONNECT = 10; 904 static final int MCS_GIVE_UP = 11; 905 static final int UPDATED_MEDIA_STATUS = 12; 906 static final int WRITE_SETTINGS = 13; 907 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 908 static final int PACKAGE_VERIFIED = 15; 909 static final int CHECK_PENDING_VERIFICATION = 16; 910 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 911 static final int INTENT_FILTER_VERIFIED = 18; 912 913 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 914 915 // Delay time in millisecs 916 static final int BROADCAST_DELAY = 10 * 1000; 917 918 static UserManagerService sUserManager; 919 920 // Stores a list of users whose package restrictions file needs to be updated 921 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 922 923 final private DefaultContainerConnection mDefContainerConn = 924 new DefaultContainerConnection(); 925 class DefaultContainerConnection implements ServiceConnection { 926 public void onServiceConnected(ComponentName name, IBinder service) { 927 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 928 IMediaContainerService imcs = 929 IMediaContainerService.Stub.asInterface(service); 930 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 931 } 932 933 public void onServiceDisconnected(ComponentName name) { 934 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 935 } 936 } 937 938 // Recordkeeping of restore-after-install operations that are currently in flight 939 // between the Package Manager and the Backup Manager 940 class PostInstallData { 941 public InstallArgs args; 942 public PackageInstalledInfo res; 943 944 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 945 args = _a; 946 res = _r; 947 } 948 } 949 950 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 951 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 952 953 // XML tags for backup/restore of various bits of state 954 private static final String TAG_PREFERRED_BACKUP = "pa"; 955 private static final String TAG_DEFAULT_APPS = "da"; 956 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 957 958 final String mRequiredVerifierPackage; 959 final String mRequiredInstallerPackage; 960 961 private final PackageUsage mPackageUsage = new PackageUsage(); 962 963 private class PackageUsage { 964 private static final int WRITE_INTERVAL 965 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 966 967 private final Object mFileLock = new Object(); 968 private final AtomicLong mLastWritten = new AtomicLong(0); 969 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 970 971 private boolean mIsHistoricalPackageUsageAvailable = true; 972 973 boolean isHistoricalPackageUsageAvailable() { 974 return mIsHistoricalPackageUsageAvailable; 975 } 976 977 void write(boolean force) { 978 if (force) { 979 writeInternal(); 980 return; 981 } 982 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 983 && !DEBUG_DEXOPT) { 984 return; 985 } 986 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 987 new Thread("PackageUsage_DiskWriter") { 988 @Override 989 public void run() { 990 try { 991 writeInternal(); 992 } finally { 993 mBackgroundWriteRunning.set(false); 994 } 995 } 996 }.start(); 997 } 998 } 999 1000 private void writeInternal() { 1001 synchronized (mPackages) { 1002 synchronized (mFileLock) { 1003 AtomicFile file = getFile(); 1004 FileOutputStream f = null; 1005 try { 1006 f = file.startWrite(); 1007 BufferedOutputStream out = new BufferedOutputStream(f); 1008 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1009 StringBuilder sb = new StringBuilder(); 1010 for (PackageParser.Package pkg : mPackages.values()) { 1011 if (pkg.mLastPackageUsageTimeInMills == 0) { 1012 continue; 1013 } 1014 sb.setLength(0); 1015 sb.append(pkg.packageName); 1016 sb.append(' '); 1017 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1018 sb.append('\n'); 1019 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1020 } 1021 out.flush(); 1022 file.finishWrite(f); 1023 } catch (IOException e) { 1024 if (f != null) { 1025 file.failWrite(f); 1026 } 1027 Log.e(TAG, "Failed to write package usage times", e); 1028 } 1029 } 1030 } 1031 mLastWritten.set(SystemClock.elapsedRealtime()); 1032 } 1033 1034 void readLP() { 1035 synchronized (mFileLock) { 1036 AtomicFile file = getFile(); 1037 BufferedInputStream in = null; 1038 try { 1039 in = new BufferedInputStream(file.openRead()); 1040 StringBuffer sb = new StringBuffer(); 1041 while (true) { 1042 String packageName = readToken(in, sb, ' '); 1043 if (packageName == null) { 1044 break; 1045 } 1046 String timeInMillisString = readToken(in, sb, '\n'); 1047 if (timeInMillisString == null) { 1048 throw new IOException("Failed to find last usage time for package " 1049 + packageName); 1050 } 1051 PackageParser.Package pkg = mPackages.get(packageName); 1052 if (pkg == null) { 1053 continue; 1054 } 1055 long timeInMillis; 1056 try { 1057 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1058 } catch (NumberFormatException e) { 1059 throw new IOException("Failed to parse " + timeInMillisString 1060 + " as a long.", e); 1061 } 1062 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1063 } 1064 } catch (FileNotFoundException expected) { 1065 mIsHistoricalPackageUsageAvailable = false; 1066 } catch (IOException e) { 1067 Log.w(TAG, "Failed to read package usage times", e); 1068 } finally { 1069 IoUtils.closeQuietly(in); 1070 } 1071 } 1072 mLastWritten.set(SystemClock.elapsedRealtime()); 1073 } 1074 1075 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1076 throws IOException { 1077 sb.setLength(0); 1078 while (true) { 1079 int ch = in.read(); 1080 if (ch == -1) { 1081 if (sb.length() == 0) { 1082 return null; 1083 } 1084 throw new IOException("Unexpected EOF"); 1085 } 1086 if (ch == endOfToken) { 1087 return sb.toString(); 1088 } 1089 sb.append((char)ch); 1090 } 1091 } 1092 1093 private AtomicFile getFile() { 1094 File dataDir = Environment.getDataDirectory(); 1095 File systemDir = new File(dataDir, "system"); 1096 File fname = new File(systemDir, "package-usage.list"); 1097 return new AtomicFile(fname); 1098 } 1099 } 1100 1101 class PackageHandler extends Handler { 1102 private boolean mBound = false; 1103 final ArrayList<HandlerParams> mPendingInstalls = 1104 new ArrayList<HandlerParams>(); 1105 1106 private boolean connectToService() { 1107 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1108 " DefaultContainerService"); 1109 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1111 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1112 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1113 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1114 mBound = true; 1115 return true; 1116 } 1117 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1118 return false; 1119 } 1120 1121 private void disconnectService() { 1122 mContainerService = null; 1123 mBound = false; 1124 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1125 mContext.unbindService(mDefContainerConn); 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1127 } 1128 1129 PackageHandler(Looper looper) { 1130 super(looper); 1131 } 1132 1133 public void handleMessage(Message msg) { 1134 try { 1135 doHandleMessage(msg); 1136 } finally { 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1138 } 1139 } 1140 1141 void doHandleMessage(Message msg) { 1142 switch (msg.what) { 1143 case INIT_COPY: { 1144 HandlerParams params = (HandlerParams) msg.obj; 1145 int idx = mPendingInstalls.size(); 1146 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1147 // If a bind was already initiated we dont really 1148 // need to do anything. The pending install 1149 // will be processed later on. 1150 if (!mBound) { 1151 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1152 System.identityHashCode(mHandler)); 1153 // If this is the only one pending we might 1154 // have to bind to the service again. 1155 if (!connectToService()) { 1156 Slog.e(TAG, "Failed to bind to media container service"); 1157 params.serviceError(); 1158 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1159 System.identityHashCode(mHandler)); 1160 if (params.traceMethod != null) { 1161 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1162 params.traceCookie); 1163 } 1164 return; 1165 } else { 1166 // Once we bind to the service, the first 1167 // pending request will be processed. 1168 mPendingInstalls.add(idx, params); 1169 } 1170 } else { 1171 mPendingInstalls.add(idx, params); 1172 // Already bound to the service. Just make 1173 // sure we trigger off processing the first request. 1174 if (idx == 0) { 1175 mHandler.sendEmptyMessage(MCS_BOUND); 1176 } 1177 } 1178 break; 1179 } 1180 case MCS_BOUND: { 1181 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1182 if (msg.obj != null) { 1183 mContainerService = (IMediaContainerService) msg.obj; 1184 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1185 System.identityHashCode(mHandler)); 1186 } 1187 if (mContainerService == null) { 1188 if (!mBound) { 1189 // Something seriously wrong since we are not bound and we are not 1190 // waiting for connection. Bail out. 1191 Slog.e(TAG, "Cannot bind to media container service"); 1192 for (HandlerParams params : mPendingInstalls) { 1193 // Indicate service bind error 1194 params.serviceError(); 1195 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1196 System.identityHashCode(params)); 1197 if (params.traceMethod != null) { 1198 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1199 params.traceMethod, params.traceCookie); 1200 } 1201 return; 1202 } 1203 mPendingInstalls.clear(); 1204 } else { 1205 Slog.w(TAG, "Waiting to connect to media container service"); 1206 } 1207 } else if (mPendingInstalls.size() > 0) { 1208 HandlerParams params = mPendingInstalls.get(0); 1209 if (params != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1211 System.identityHashCode(params)); 1212 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1213 if (params.startCopy()) { 1214 // We are done... look for more work or to 1215 // go idle. 1216 if (DEBUG_SD_INSTALL) Log.i(TAG, 1217 "Checking for more work or unbind..."); 1218 // Delete pending install 1219 if (mPendingInstalls.size() > 0) { 1220 mPendingInstalls.remove(0); 1221 } 1222 if (mPendingInstalls.size() == 0) { 1223 if (mBound) { 1224 if (DEBUG_SD_INSTALL) Log.i(TAG, 1225 "Posting delayed MCS_UNBIND"); 1226 removeMessages(MCS_UNBIND); 1227 Message ubmsg = obtainMessage(MCS_UNBIND); 1228 // Unbind after a little delay, to avoid 1229 // continual thrashing. 1230 sendMessageDelayed(ubmsg, 10000); 1231 } 1232 } else { 1233 // There are more pending requests in queue. 1234 // Just post MCS_BOUND message to trigger processing 1235 // of next pending install. 1236 if (DEBUG_SD_INSTALL) Log.i(TAG, 1237 "Posting MCS_BOUND for next work"); 1238 mHandler.sendEmptyMessage(MCS_BOUND); 1239 } 1240 } 1241 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1242 } 1243 } else { 1244 // Should never happen ideally. 1245 Slog.w(TAG, "Empty queue"); 1246 } 1247 break; 1248 } 1249 case MCS_RECONNECT: { 1250 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1251 if (mPendingInstalls.size() > 0) { 1252 if (mBound) { 1253 disconnectService(); 1254 } 1255 if (!connectToService()) { 1256 Slog.e(TAG, "Failed to bind to media container service"); 1257 for (HandlerParams params : mPendingInstalls) { 1258 // Indicate service bind error 1259 params.serviceError(); 1260 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1261 System.identityHashCode(params)); 1262 } 1263 mPendingInstalls.clear(); 1264 } 1265 } 1266 break; 1267 } 1268 case MCS_UNBIND: { 1269 // If there is no actual work left, then time to unbind. 1270 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1271 1272 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1273 if (mBound) { 1274 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1275 1276 disconnectService(); 1277 } 1278 } else if (mPendingInstalls.size() > 0) { 1279 // There are more pending requests in queue. 1280 // Just post MCS_BOUND message to trigger processing 1281 // of next pending install. 1282 mHandler.sendEmptyMessage(MCS_BOUND); 1283 } 1284 1285 break; 1286 } 1287 case MCS_GIVE_UP: { 1288 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1289 HandlerParams params = mPendingInstalls.remove(0); 1290 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1291 System.identityHashCode(params)); 1292 break; 1293 } 1294 case SEND_PENDING_BROADCAST: { 1295 String packages[]; 1296 ArrayList<String> components[]; 1297 int size = 0; 1298 int uids[]; 1299 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1300 synchronized (mPackages) { 1301 if (mPendingBroadcasts == null) { 1302 return; 1303 } 1304 size = mPendingBroadcasts.size(); 1305 if (size <= 0) { 1306 // Nothing to be done. Just return 1307 return; 1308 } 1309 packages = new String[size]; 1310 components = new ArrayList[size]; 1311 uids = new int[size]; 1312 int i = 0; // filling out the above arrays 1313 1314 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1315 int packageUserId = mPendingBroadcasts.userIdAt(n); 1316 Iterator<Map.Entry<String, ArrayList<String>>> it 1317 = mPendingBroadcasts.packagesForUserId(packageUserId) 1318 .entrySet().iterator(); 1319 while (it.hasNext() && i < size) { 1320 Map.Entry<String, ArrayList<String>> ent = it.next(); 1321 packages[i] = ent.getKey(); 1322 components[i] = ent.getValue(); 1323 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1324 uids[i] = (ps != null) 1325 ? UserHandle.getUid(packageUserId, ps.appId) 1326 : -1; 1327 i++; 1328 } 1329 } 1330 size = i; 1331 mPendingBroadcasts.clear(); 1332 } 1333 // Send broadcasts 1334 for (int i = 0; i < size; i++) { 1335 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1336 } 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1338 break; 1339 } 1340 case START_CLEANING_PACKAGE: { 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 final String packageName = (String)msg.obj; 1343 final int userId = msg.arg1; 1344 final boolean andCode = msg.arg2 != 0; 1345 synchronized (mPackages) { 1346 if (userId == UserHandle.USER_ALL) { 1347 int[] users = sUserManager.getUserIds(); 1348 for (int user : users) { 1349 mSettings.addPackageToCleanLPw( 1350 new PackageCleanItem(user, packageName, andCode)); 1351 } 1352 } else { 1353 mSettings.addPackageToCleanLPw( 1354 new PackageCleanItem(userId, packageName, andCode)); 1355 } 1356 } 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 startCleaningPackages(); 1359 } break; 1360 case POST_INSTALL: { 1361 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1362 PostInstallData data = mRunningInstalls.get(msg.arg1); 1363 mRunningInstalls.delete(msg.arg1); 1364 boolean deleteOld = false; 1365 1366 if (data != null) { 1367 InstallArgs args = data.args; 1368 PackageInstalledInfo res = data.res; 1369 1370 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1371 final String packageName = res.pkg.applicationInfo.packageName; 1372 res.removedInfo.sendBroadcast(false, true, false); 1373 Bundle extras = new Bundle(1); 1374 extras.putInt(Intent.EXTRA_UID, res.uid); 1375 1376 // Now that we successfully installed the package, grant runtime 1377 // permissions if requested before broadcasting the install. 1378 if ((args.installFlags 1379 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1380 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1381 args.installGrantPermissions); 1382 } 1383 1384 // Determine the set of users who are adding this 1385 // package for the first time vs. those who are seeing 1386 // an update. 1387 int[] firstUsers; 1388 int[] updateUsers = new int[0]; 1389 if (res.origUsers == null || res.origUsers.length == 0) { 1390 firstUsers = res.newUsers; 1391 } else { 1392 firstUsers = new int[0]; 1393 for (int i=0; i<res.newUsers.length; i++) { 1394 int user = res.newUsers[i]; 1395 boolean isNew = true; 1396 for (int j=0; j<res.origUsers.length; j++) { 1397 if (res.origUsers[j] == user) { 1398 isNew = false; 1399 break; 1400 } 1401 } 1402 if (isNew) { 1403 int[] newFirst = new int[firstUsers.length+1]; 1404 System.arraycopy(firstUsers, 0, newFirst, 0, 1405 firstUsers.length); 1406 newFirst[firstUsers.length] = user; 1407 firstUsers = newFirst; 1408 } else { 1409 int[] newUpdate = new int[updateUsers.length+1]; 1410 System.arraycopy(updateUsers, 0, newUpdate, 0, 1411 updateUsers.length); 1412 newUpdate[updateUsers.length] = user; 1413 updateUsers = newUpdate; 1414 } 1415 } 1416 } 1417 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1418 packageName, extras, null, null, firstUsers); 1419 final boolean update = res.removedInfo.removedPackage != null; 1420 if (update) { 1421 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1422 } 1423 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1424 packageName, extras, null, null, updateUsers); 1425 if (update) { 1426 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1427 packageName, extras, null, null, updateUsers); 1428 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1429 null, null, packageName, null, updateUsers); 1430 1431 // treat asec-hosted packages like removable media on upgrade 1432 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1433 if (DEBUG_INSTALL) { 1434 Slog.i(TAG, "upgrading pkg " + res.pkg 1435 + " is ASEC-hosted -> AVAILABLE"); 1436 } 1437 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1438 ArrayList<String> pkgList = new ArrayList<String>(1); 1439 pkgList.add(packageName); 1440 sendResourcesChangedBroadcast(true, true, 1441 pkgList,uidArray, null); 1442 } 1443 } 1444 if (res.removedInfo.args != null) { 1445 // Remove the replaced package's older resources safely now 1446 deleteOld = true; 1447 } 1448 1449 // If this app is a browser and it's newly-installed for some 1450 // users, clear any default-browser state in those users 1451 if (firstUsers.length > 0) { 1452 // the app's nature doesn't depend on the user, so we can just 1453 // check its browser nature in any user and generalize. 1454 if (packageIsBrowser(packageName, firstUsers[0])) { 1455 synchronized (mPackages) { 1456 for (int userId : firstUsers) { 1457 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1458 } 1459 } 1460 } 1461 } 1462 // Log current value of "unknown sources" setting 1463 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1464 getUnknownSourcesSettings()); 1465 } 1466 // Force a gc to clear up things 1467 Runtime.getRuntime().gc(); 1468 // We delete after a gc for applications on sdcard. 1469 if (deleteOld) { 1470 synchronized (mInstallLock) { 1471 res.removedInfo.args.doPostDeleteLI(true); 1472 } 1473 } 1474 if (args.observer != null) { 1475 try { 1476 Bundle extras = extrasForInstallResult(res); 1477 args.observer.onPackageInstalled(res.name, res.returnCode, 1478 res.returnMsg, extras); 1479 } catch (RemoteException e) { 1480 Slog.i(TAG, "Observer no longer exists."); 1481 } 1482 } 1483 if (args.traceMethod != null) { 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1485 args.traceCookie); 1486 } 1487 return; 1488 } else { 1489 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1490 } 1491 1492 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1493 } break; 1494 case UPDATED_MEDIA_STATUS: { 1495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1496 boolean reportStatus = msg.arg1 == 1; 1497 boolean doGc = msg.arg2 == 1; 1498 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1499 if (doGc) { 1500 // Force a gc to clear up stale containers. 1501 Runtime.getRuntime().gc(); 1502 } 1503 if (msg.obj != null) { 1504 @SuppressWarnings("unchecked") 1505 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1506 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1507 // Unload containers 1508 unloadAllContainers(args); 1509 } 1510 if (reportStatus) { 1511 try { 1512 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1513 PackageHelper.getMountService().finishMediaUpdate(); 1514 } catch (RemoteException e) { 1515 Log.e(TAG, "MountService not running?"); 1516 } 1517 } 1518 } break; 1519 case WRITE_SETTINGS: { 1520 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1521 synchronized (mPackages) { 1522 removeMessages(WRITE_SETTINGS); 1523 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1524 mSettings.writeLPr(); 1525 mDirtyUsers.clear(); 1526 } 1527 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1528 } break; 1529 case WRITE_PACKAGE_RESTRICTIONS: { 1530 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1531 synchronized (mPackages) { 1532 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1533 for (int userId : mDirtyUsers) { 1534 mSettings.writePackageRestrictionsLPr(userId); 1535 } 1536 mDirtyUsers.clear(); 1537 } 1538 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1539 } break; 1540 case CHECK_PENDING_VERIFICATION: { 1541 final int verificationId = msg.arg1; 1542 final PackageVerificationState state = mPendingVerification.get(verificationId); 1543 1544 if ((state != null) && !state.timeoutExtended()) { 1545 final InstallArgs args = state.getInstallArgs(); 1546 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1547 1548 Slog.i(TAG, "Verification timed out for " + originUri); 1549 mPendingVerification.remove(verificationId); 1550 1551 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1552 1553 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1554 Slog.i(TAG, "Continuing with installation of " + originUri); 1555 state.setVerifierResponse(Binder.getCallingUid(), 1556 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1557 broadcastPackageVerified(verificationId, originUri, 1558 PackageManager.VERIFICATION_ALLOW, 1559 state.getInstallArgs().getUser()); 1560 try { 1561 ret = args.copyApk(mContainerService, true); 1562 } catch (RemoteException e) { 1563 Slog.e(TAG, "Could not contact the ContainerService"); 1564 } 1565 } else { 1566 broadcastPackageVerified(verificationId, originUri, 1567 PackageManager.VERIFICATION_REJECT, 1568 state.getInstallArgs().getUser()); 1569 } 1570 1571 Trace.asyncTraceEnd( 1572 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1573 1574 processPendingInstall(args, ret); 1575 mHandler.sendEmptyMessage(MCS_UNBIND); 1576 } 1577 break; 1578 } 1579 case PACKAGE_VERIFIED: { 1580 final int verificationId = msg.arg1; 1581 1582 final PackageVerificationState state = mPendingVerification.get(verificationId); 1583 if (state == null) { 1584 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1585 break; 1586 } 1587 1588 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1589 1590 state.setVerifierResponse(response.callerUid, response.code); 1591 1592 if (state.isVerificationComplete()) { 1593 mPendingVerification.remove(verificationId); 1594 1595 final InstallArgs args = state.getInstallArgs(); 1596 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1597 1598 int ret; 1599 if (state.isInstallAllowed()) { 1600 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1601 broadcastPackageVerified(verificationId, originUri, 1602 response.code, state.getInstallArgs().getUser()); 1603 try { 1604 ret = args.copyApk(mContainerService, true); 1605 } catch (RemoteException e) { 1606 Slog.e(TAG, "Could not contact the ContainerService"); 1607 } 1608 } else { 1609 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1610 } 1611 1612 Trace.asyncTraceEnd( 1613 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1614 1615 processPendingInstall(args, ret); 1616 mHandler.sendEmptyMessage(MCS_UNBIND); 1617 } 1618 1619 break; 1620 } 1621 case START_INTENT_FILTER_VERIFICATIONS: { 1622 IFVerificationParams params = (IFVerificationParams) msg.obj; 1623 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1624 params.replacing, params.pkg); 1625 break; 1626 } 1627 case INTENT_FILTER_VERIFIED: { 1628 final int verificationId = msg.arg1; 1629 1630 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1631 verificationId); 1632 if (state == null) { 1633 Slog.w(TAG, "Invalid IntentFilter verification token " 1634 + verificationId + " received"); 1635 break; 1636 } 1637 1638 final int userId = state.getUserId(); 1639 1640 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1641 "Processing IntentFilter verification with token:" 1642 + verificationId + " and userId:" + userId); 1643 1644 final IntentFilterVerificationResponse response = 1645 (IntentFilterVerificationResponse) msg.obj; 1646 1647 state.setVerifierResponse(response.callerUid, response.code); 1648 1649 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1650 "IntentFilter verification with token:" + verificationId 1651 + " and userId:" + userId 1652 + " is settings verifier response with response code:" 1653 + response.code); 1654 1655 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1656 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1657 + response.getFailedDomainsString()); 1658 } 1659 1660 if (state.isVerificationComplete()) { 1661 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1662 } else { 1663 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1664 "IntentFilter verification with token:" + verificationId 1665 + " was not said to be complete"); 1666 } 1667 1668 break; 1669 } 1670 } 1671 } 1672 } 1673 1674 private StorageEventListener mStorageListener = new StorageEventListener() { 1675 @Override 1676 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1677 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1678 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1679 final String volumeUuid = vol.getFsUuid(); 1680 1681 // Clean up any users or apps that were removed or recreated 1682 // while this volume was missing 1683 reconcileUsers(volumeUuid); 1684 reconcileApps(volumeUuid); 1685 1686 // Clean up any install sessions that expired or were 1687 // cancelled while this volume was missing 1688 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1689 1690 loadPrivatePackages(vol); 1691 1692 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1693 unloadPrivatePackages(vol); 1694 } 1695 } 1696 1697 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1698 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1699 updateExternalMediaStatus(true, false); 1700 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1701 updateExternalMediaStatus(false, false); 1702 } 1703 } 1704 } 1705 1706 @Override 1707 public void onVolumeForgotten(String fsUuid) { 1708 if (TextUtils.isEmpty(fsUuid)) { 1709 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1710 return; 1711 } 1712 1713 // Remove any apps installed on the forgotten volume 1714 synchronized (mPackages) { 1715 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1716 for (PackageSetting ps : packages) { 1717 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1718 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1719 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1720 } 1721 1722 mSettings.onVolumeForgotten(fsUuid); 1723 mSettings.writeLPr(); 1724 } 1725 } 1726 }; 1727 1728 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1729 String[] grantedPermissions) { 1730 if (userId >= UserHandle.USER_SYSTEM) { 1731 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1732 } else if (userId == UserHandle.USER_ALL) { 1733 final int[] userIds; 1734 synchronized (mPackages) { 1735 userIds = UserManagerService.getInstance().getUserIds(); 1736 } 1737 for (int someUserId : userIds) { 1738 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1739 } 1740 } 1741 1742 // We could have touched GID membership, so flush out packages.list 1743 synchronized (mPackages) { 1744 mSettings.writePackageListLPr(); 1745 } 1746 } 1747 1748 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1749 String[] grantedPermissions) { 1750 SettingBase sb = (SettingBase) pkg.mExtras; 1751 if (sb == null) { 1752 return; 1753 } 1754 1755 PermissionsState permissionsState = sb.getPermissionsState(); 1756 1757 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1758 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1759 1760 synchronized (mPackages) { 1761 for (String permission : pkg.requestedPermissions) { 1762 BasePermission bp = mSettings.mPermissions.get(permission); 1763 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1764 && (grantedPermissions == null 1765 || ArrayUtils.contains(grantedPermissions, permission))) { 1766 final int flags = permissionsState.getPermissionFlags(permission, userId); 1767 // Installer cannot change immutable permissions. 1768 if ((flags & immutableFlags) == 0) { 1769 grantRuntimePermission(pkg.packageName, permission, userId); 1770 } 1771 } 1772 } 1773 } 1774 } 1775 1776 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1777 Bundle extras = null; 1778 switch (res.returnCode) { 1779 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1780 extras = new Bundle(); 1781 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1782 res.origPermission); 1783 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1784 res.origPackage); 1785 break; 1786 } 1787 case PackageManager.INSTALL_SUCCEEDED: { 1788 extras = new Bundle(); 1789 extras.putBoolean(Intent.EXTRA_REPLACING, 1790 res.removedInfo != null && res.removedInfo.removedPackage != null); 1791 break; 1792 } 1793 } 1794 return extras; 1795 } 1796 1797 void scheduleWriteSettingsLocked() { 1798 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1799 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1800 } 1801 } 1802 1803 void scheduleWritePackageRestrictionsLocked(int userId) { 1804 if (!sUserManager.exists(userId)) return; 1805 mDirtyUsers.add(userId); 1806 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1807 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1808 } 1809 } 1810 1811 public static PackageManagerService main(Context context, Installer installer, 1812 boolean factoryTest, boolean onlyCore) { 1813 PackageManagerService m = new PackageManagerService(context, installer, 1814 factoryTest, onlyCore); 1815 ServiceManager.addService("package", m); 1816 return m; 1817 } 1818 1819 static String[] splitString(String str, char sep) { 1820 int count = 1; 1821 int i = 0; 1822 while ((i=str.indexOf(sep, i)) >= 0) { 1823 count++; 1824 i++; 1825 } 1826 1827 String[] res = new String[count]; 1828 i=0; 1829 count = 0; 1830 int lastI=0; 1831 while ((i=str.indexOf(sep, i)) >= 0) { 1832 res[count] = str.substring(lastI, i); 1833 count++; 1834 i++; 1835 lastI = i; 1836 } 1837 res[count] = str.substring(lastI, str.length()); 1838 return res; 1839 } 1840 1841 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1842 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1843 Context.DISPLAY_SERVICE); 1844 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1845 } 1846 1847 public PackageManagerService(Context context, Installer installer, 1848 boolean factoryTest, boolean onlyCore) { 1849 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1850 SystemClock.uptimeMillis()); 1851 1852 if (mSdkVersion <= 0) { 1853 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1854 } 1855 1856 mContext = context; 1857 mFactoryTest = factoryTest; 1858 mOnlyCore = onlyCore; 1859 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1860 mMetrics = new DisplayMetrics(); 1861 mSettings = new Settings(mPackages); 1862 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1863 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1864 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1865 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1866 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1867 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1868 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1869 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1870 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1871 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1872 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1873 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1874 1875 // TODO: add a property to control this? 1876 long dexOptLRUThresholdInMinutes; 1877 if (mLazyDexOpt) { 1878 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1879 } else { 1880 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1881 } 1882 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1883 1884 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1885 if (separateProcesses != null && separateProcesses.length() > 0) { 1886 if ("*".equals(separateProcesses)) { 1887 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1888 mSeparateProcesses = null; 1889 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1890 } else { 1891 mDefParseFlags = 0; 1892 mSeparateProcesses = separateProcesses.split(","); 1893 Slog.w(TAG, "Running with debug.separate_processes: " 1894 + separateProcesses); 1895 } 1896 } else { 1897 mDefParseFlags = 0; 1898 mSeparateProcesses = null; 1899 } 1900 1901 mInstaller = installer; 1902 mPackageDexOptimizer = new PackageDexOptimizer(this); 1903 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1904 1905 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1906 FgThread.get().getLooper()); 1907 1908 getDefaultDisplayMetrics(context, mMetrics); 1909 1910 SystemConfig systemConfig = SystemConfig.getInstance(); 1911 mGlobalGids = systemConfig.getGlobalGids(); 1912 mSystemPermissions = systemConfig.getSystemPermissions(); 1913 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1914 1915 synchronized (mInstallLock) { 1916 // writer 1917 synchronized (mPackages) { 1918 mHandlerThread = new ServiceThread(TAG, 1919 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1920 mHandlerThread.start(); 1921 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1922 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1923 1924 File dataDir = Environment.getDataDirectory(); 1925 mAppDataDir = new File(dataDir, "data"); 1926 mAppInstallDir = new File(dataDir, "app"); 1927 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1928 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1929 mUserAppDataDir = new File(dataDir, "user"); 1930 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1931 1932 sUserManager = new UserManagerService(context, this, 1933 mInstallLock, mPackages); 1934 1935 // Propagate permission configuration in to package manager. 1936 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1937 = systemConfig.getPermissions(); 1938 for (int i=0; i<permConfig.size(); i++) { 1939 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1940 BasePermission bp = mSettings.mPermissions.get(perm.name); 1941 if (bp == null) { 1942 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1943 mSettings.mPermissions.put(perm.name, bp); 1944 } 1945 if (perm.gids != null) { 1946 bp.setGids(perm.gids, perm.perUser); 1947 } 1948 } 1949 1950 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1951 for (int i=0; i<libConfig.size(); i++) { 1952 mSharedLibraries.put(libConfig.keyAt(i), 1953 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1954 } 1955 1956 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1957 1958 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1959 1960 String customResolverActivity = Resources.getSystem().getString( 1961 R.string.config_customResolverActivity); 1962 if (TextUtils.isEmpty(customResolverActivity)) { 1963 customResolverActivity = null; 1964 } else { 1965 mCustomResolverComponentName = ComponentName.unflattenFromString( 1966 customResolverActivity); 1967 } 1968 1969 long startTime = SystemClock.uptimeMillis(); 1970 1971 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1972 startTime); 1973 1974 // Set flag to monitor and not change apk file paths when 1975 // scanning install directories. 1976 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1977 1978 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1979 1980 /** 1981 * Add everything in the in the boot class path to the 1982 * list of process files because dexopt will have been run 1983 * if necessary during zygote startup. 1984 */ 1985 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1986 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1987 1988 if (bootClassPath != null) { 1989 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1990 for (String element : bootClassPathElements) { 1991 alreadyDexOpted.add(element); 1992 } 1993 } else { 1994 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1995 } 1996 1997 if (systemServerClassPath != null) { 1998 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1999 for (String element : systemServerClassPathElements) { 2000 alreadyDexOpted.add(element); 2001 } 2002 } else { 2003 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2004 } 2005 2006 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2007 final String[] dexCodeInstructionSets = 2008 getDexCodeInstructionSets( 2009 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2010 2011 /** 2012 * Ensure all external libraries have had dexopt run on them. 2013 */ 2014 if (mSharedLibraries.size() > 0) { 2015 // NOTE: For now, we're compiling these system "shared libraries" 2016 // (and framework jars) into all available architectures. It's possible 2017 // to compile them only when we come across an app that uses them (there's 2018 // already logic for that in scanPackageLI) but that adds some complexity. 2019 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2020 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2021 final String lib = libEntry.path; 2022 if (lib == null) { 2023 continue; 2024 } 2025 2026 try { 2027 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2028 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2029 alreadyDexOpted.add(lib); 2030 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2031 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2032 } 2033 } catch (FileNotFoundException e) { 2034 Slog.w(TAG, "Library not found: " + lib); 2035 } catch (IOException e) { 2036 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2037 + e.getMessage()); 2038 } 2039 } 2040 } 2041 } 2042 2043 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2044 2045 // Gross hack for now: we know this file doesn't contain any 2046 // code, so don't dexopt it to avoid the resulting log spew. 2047 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 2048 2049 // Gross hack for now: we know this file is only part of 2050 // the boot class path for art, so don't dexopt it to 2051 // avoid the resulting log spew. 2052 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 2053 2054 /** 2055 * There are a number of commands implemented in Java, which 2056 * we currently need to do the dexopt on so that they can be 2057 * run from a non-root shell. 2058 */ 2059 String[] frameworkFiles = frameworkDir.list(); 2060 if (frameworkFiles != null) { 2061 // TODO: We could compile these only for the most preferred ABI. We should 2062 // first double check that the dex files for these commands are not referenced 2063 // by other system apps. 2064 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2065 for (int i=0; i<frameworkFiles.length; i++) { 2066 File libPath = new File(frameworkDir, frameworkFiles[i]); 2067 String path = libPath.getPath(); 2068 // Skip the file if we already did it. 2069 if (alreadyDexOpted.contains(path)) { 2070 continue; 2071 } 2072 // Skip the file if it is not a type we want to dexopt. 2073 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 2074 continue; 2075 } 2076 try { 2077 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2078 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2079 mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet, 2080 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2081 } 2082 } catch (FileNotFoundException e) { 2083 Slog.w(TAG, "Jar not found: " + path); 2084 } catch (IOException e) { 2085 Slog.w(TAG, "Exception reading jar: " + path, e); 2086 } 2087 } 2088 } 2089 } 2090 2091 final VersionInfo ver = mSettings.getInternalVersion(); 2092 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2093 // when upgrading from pre-M, promote system app permissions from install to runtime 2094 mPromoteSystemApps = 2095 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2096 2097 // save off the names of pre-existing system packages prior to scanning; we don't 2098 // want to automatically grant runtime permissions for new system apps 2099 if (mPromoteSystemApps) { 2100 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2101 while (pkgSettingIter.hasNext()) { 2102 PackageSetting ps = pkgSettingIter.next(); 2103 if (isSystemApp(ps)) { 2104 mExistingSystemPackages.add(ps.name); 2105 } 2106 } 2107 } 2108 2109 // Collect vendor overlay packages. 2110 // (Do this before scanning any apps.) 2111 // For security and version matching reason, only consider 2112 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2113 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2114 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2115 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2116 2117 // Find base frameworks (resource packages without code). 2118 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2119 | PackageParser.PARSE_IS_SYSTEM_DIR 2120 | PackageParser.PARSE_IS_PRIVILEGED, 2121 scanFlags | SCAN_NO_DEX, 0); 2122 2123 // Collected privileged system packages. 2124 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2125 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2126 | PackageParser.PARSE_IS_SYSTEM_DIR 2127 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2128 2129 // Collect ordinary system packages. 2130 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2131 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2132 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2133 2134 // Collect all vendor packages. 2135 File vendorAppDir = new File("/vendor/app"); 2136 try { 2137 vendorAppDir = vendorAppDir.getCanonicalFile(); 2138 } catch (IOException e) { 2139 // failed to look up canonical path, continue with original one 2140 } 2141 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2142 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2143 2144 // Collect all OEM packages. 2145 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2146 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2147 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2148 2149 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2150 mInstaller.moveFiles(); 2151 2152 // Prune any system packages that no longer exist. 2153 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2154 if (!mOnlyCore) { 2155 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2156 while (psit.hasNext()) { 2157 PackageSetting ps = psit.next(); 2158 2159 /* 2160 * If this is not a system app, it can't be a 2161 * disable system app. 2162 */ 2163 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2164 continue; 2165 } 2166 2167 /* 2168 * If the package is scanned, it's not erased. 2169 */ 2170 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2171 if (scannedPkg != null) { 2172 /* 2173 * If the system app is both scanned and in the 2174 * disabled packages list, then it must have been 2175 * added via OTA. Remove it from the currently 2176 * scanned package so the previously user-installed 2177 * application can be scanned. 2178 */ 2179 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2180 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2181 + ps.name + "; removing system app. Last known codePath=" 2182 + ps.codePathString + ", installStatus=" + ps.installStatus 2183 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2184 + scannedPkg.mVersionCode); 2185 removePackageLI(ps, true); 2186 mExpectingBetter.put(ps.name, ps.codePath); 2187 } 2188 2189 continue; 2190 } 2191 2192 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2193 psit.remove(); 2194 logCriticalInfo(Log.WARN, "System package " + ps.name 2195 + " no longer exists; wiping its data"); 2196 removeDataDirsLI(null, ps.name); 2197 } else { 2198 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2199 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2200 possiblyDeletedUpdatedSystemApps.add(ps.name); 2201 } 2202 } 2203 } 2204 } 2205 2206 //look for any incomplete package installations 2207 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2208 //clean up list 2209 for(int i = 0; i < deletePkgsList.size(); i++) { 2210 //clean up here 2211 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2212 } 2213 //delete tmp files 2214 deleteTempPackageFiles(); 2215 2216 // Remove any shared userIDs that have no associated packages 2217 mSettings.pruneSharedUsersLPw(); 2218 2219 if (!mOnlyCore) { 2220 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2221 SystemClock.uptimeMillis()); 2222 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2223 2224 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2225 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2226 2227 /** 2228 * Remove disable package settings for any updated system 2229 * apps that were removed via an OTA. If they're not a 2230 * previously-updated app, remove them completely. 2231 * Otherwise, just revoke their system-level permissions. 2232 */ 2233 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2234 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2235 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2236 2237 String msg; 2238 if (deletedPkg == null) { 2239 msg = "Updated system package " + deletedAppName 2240 + " no longer exists; wiping its data"; 2241 removeDataDirsLI(null, deletedAppName); 2242 } else { 2243 msg = "Updated system app + " + deletedAppName 2244 + " no longer present; removing system privileges for " 2245 + deletedAppName; 2246 2247 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2248 2249 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2250 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2251 } 2252 logCriticalInfo(Log.WARN, msg); 2253 } 2254 2255 /** 2256 * Make sure all system apps that we expected to appear on 2257 * the userdata partition actually showed up. If they never 2258 * appeared, crawl back and revive the system version. 2259 */ 2260 for (int i = 0; i < mExpectingBetter.size(); i++) { 2261 final String packageName = mExpectingBetter.keyAt(i); 2262 if (!mPackages.containsKey(packageName)) { 2263 final File scanFile = mExpectingBetter.valueAt(i); 2264 2265 logCriticalInfo(Log.WARN, "Expected better " + packageName 2266 + " but never showed up; reverting to system"); 2267 2268 final int reparseFlags; 2269 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2270 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2271 | PackageParser.PARSE_IS_SYSTEM_DIR 2272 | PackageParser.PARSE_IS_PRIVILEGED; 2273 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2274 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2275 | PackageParser.PARSE_IS_SYSTEM_DIR; 2276 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2277 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2278 | PackageParser.PARSE_IS_SYSTEM_DIR; 2279 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2280 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2281 | PackageParser.PARSE_IS_SYSTEM_DIR; 2282 } else { 2283 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2284 continue; 2285 } 2286 2287 mSettings.enableSystemPackageLPw(packageName); 2288 2289 try { 2290 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2291 } catch (PackageManagerException e) { 2292 Slog.e(TAG, "Failed to parse original system package: " 2293 + e.getMessage()); 2294 } 2295 } 2296 } 2297 } 2298 mExpectingBetter.clear(); 2299 2300 // Now that we know all of the shared libraries, update all clients to have 2301 // the correct library paths. 2302 updateAllSharedLibrariesLPw(); 2303 2304 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2305 // NOTE: We ignore potential failures here during a system scan (like 2306 // the rest of the commands above) because there's precious little we 2307 // can do about it. A settings error is reported, though. 2308 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2309 false /* force dexopt */, false /* defer dexopt */, 2310 false /* boot complete */); 2311 } 2312 2313 // Now that we know all the packages we are keeping, 2314 // read and update their last usage times. 2315 mPackageUsage.readLP(); 2316 2317 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2318 SystemClock.uptimeMillis()); 2319 Slog.i(TAG, "Time to scan packages: " 2320 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2321 + " seconds"); 2322 2323 // If the platform SDK has changed since the last time we booted, 2324 // we need to re-grant app permission to catch any new ones that 2325 // appear. This is really a hack, and means that apps can in some 2326 // cases get permissions that the user didn't initially explicitly 2327 // allow... it would be nice to have some better way to handle 2328 // this situation. 2329 int updateFlags = UPDATE_PERMISSIONS_ALL; 2330 if (ver.sdkVersion != mSdkVersion) { 2331 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2332 + mSdkVersion + "; regranting permissions for internal storage"); 2333 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2334 } 2335 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2336 ver.sdkVersion = mSdkVersion; 2337 2338 // If this is the first boot or an update from pre-M, and it is a normal 2339 // boot, then we need to initialize the default preferred apps across 2340 // all defined users. 2341 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2342 for (UserInfo user : sUserManager.getUsers(true)) { 2343 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2344 applyFactoryDefaultBrowserLPw(user.id); 2345 primeDomainVerificationsLPw(user.id); 2346 } 2347 } 2348 2349 // If this is first boot after an OTA, and a normal boot, then 2350 // we need to clear code cache directories. 2351 if (mIsUpgrade && !onlyCore) { 2352 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2353 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2354 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2355 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2356 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2357 } 2358 } 2359 ver.fingerprint = Build.FINGERPRINT; 2360 } 2361 2362 checkDefaultBrowser(); 2363 2364 // clear only after permissions and other defaults have been updated 2365 mExistingSystemPackages.clear(); 2366 mPromoteSystemApps = false; 2367 2368 // All the changes are done during package scanning. 2369 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2370 2371 // can downgrade to reader 2372 mSettings.writeLPr(); 2373 2374 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2375 SystemClock.uptimeMillis()); 2376 2377 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2378 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2379 2380 mInstallerService = new PackageInstallerService(context, this); 2381 2382 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2383 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2384 mIntentFilterVerifierComponent); 2385 2386 } // synchronized (mPackages) 2387 } // synchronized (mInstallLock) 2388 2389 // Now after opening every single application zip, make sure they 2390 // are all flushed. Not really needed, but keeps things nice and 2391 // tidy. 2392 Runtime.getRuntime().gc(); 2393 2394 // Expose private service for system components to use. 2395 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2396 } 2397 2398 @Override 2399 public boolean isFirstBoot() { 2400 return !mRestoredSettings; 2401 } 2402 2403 @Override 2404 public boolean isOnlyCoreApps() { 2405 return mOnlyCore; 2406 } 2407 2408 @Override 2409 public boolean isUpgrade() { 2410 return mIsUpgrade; 2411 } 2412 2413 private String getRequiredVerifierLPr() { 2414 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2415 // We only care about verifier that's installed under system user. 2416 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2417 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2418 2419 String requiredVerifier = null; 2420 2421 final int N = receivers.size(); 2422 for (int i = 0; i < N; i++) { 2423 final ResolveInfo info = receivers.get(i); 2424 2425 if (info.activityInfo == null) { 2426 continue; 2427 } 2428 2429 final String packageName = info.activityInfo.packageName; 2430 2431 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2432 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2433 continue; 2434 } 2435 2436 if (requiredVerifier != null) { 2437 throw new RuntimeException("There can be only one required verifier"); 2438 } 2439 2440 requiredVerifier = packageName; 2441 } 2442 2443 return requiredVerifier; 2444 } 2445 2446 private String getRequiredInstallerLPr() { 2447 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2448 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2449 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2450 2451 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2452 PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM); 2453 2454 String requiredInstaller = null; 2455 2456 final int N = installers.size(); 2457 for (int i = 0; i < N; i++) { 2458 final ResolveInfo info = installers.get(i); 2459 final String packageName = info.activityInfo.packageName; 2460 2461 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2462 continue; 2463 } 2464 2465 if (requiredInstaller != null) { 2466 throw new RuntimeException("There must be one required installer"); 2467 } 2468 2469 requiredInstaller = packageName; 2470 } 2471 2472 if (requiredInstaller == null) { 2473 throw new RuntimeException("There must be one required installer"); 2474 } 2475 2476 return requiredInstaller; 2477 } 2478 2479 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2480 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2481 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2482 PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM); 2483 2484 ComponentName verifierComponentName = null; 2485 2486 int priority = -1000; 2487 final int N = receivers.size(); 2488 for (int i = 0; i < N; i++) { 2489 final ResolveInfo info = receivers.get(i); 2490 2491 if (info.activityInfo == null) { 2492 continue; 2493 } 2494 2495 final String packageName = info.activityInfo.packageName; 2496 2497 final PackageSetting ps = mSettings.mPackages.get(packageName); 2498 if (ps == null) { 2499 continue; 2500 } 2501 2502 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2503 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2504 continue; 2505 } 2506 2507 // Select the IntentFilterVerifier with the highest priority 2508 if (priority < info.priority) { 2509 priority = info.priority; 2510 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2511 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2512 + verifierComponentName + " with priority: " + info.priority); 2513 } 2514 } 2515 2516 return verifierComponentName; 2517 } 2518 2519 private void primeDomainVerificationsLPw(int userId) { 2520 if (DEBUG_DOMAIN_VERIFICATION) { 2521 Slog.d(TAG, "Priming domain verifications in user " + userId); 2522 } 2523 2524 SystemConfig systemConfig = SystemConfig.getInstance(); 2525 ArraySet<String> packages = systemConfig.getLinkedApps(); 2526 ArraySet<String> domains = new ArraySet<String>(); 2527 2528 for (String packageName : packages) { 2529 PackageParser.Package pkg = mPackages.get(packageName); 2530 if (pkg != null) { 2531 if (!pkg.isSystemApp()) { 2532 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2533 continue; 2534 } 2535 2536 domains.clear(); 2537 for (PackageParser.Activity a : pkg.activities) { 2538 for (ActivityIntentInfo filter : a.intents) { 2539 if (hasValidDomains(filter)) { 2540 domains.addAll(filter.getHostsList()); 2541 } 2542 } 2543 } 2544 2545 if (domains.size() > 0) { 2546 if (DEBUG_DOMAIN_VERIFICATION) { 2547 Slog.v(TAG, " + " + packageName); 2548 } 2549 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2550 // state w.r.t. the formal app-linkage "no verification attempted" state; 2551 // and then 'always' in the per-user state actually used for intent resolution. 2552 final IntentFilterVerificationInfo ivi; 2553 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2554 new ArrayList<String>(domains)); 2555 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2556 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2557 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2558 } else { 2559 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2560 + "' does not handle web links"); 2561 } 2562 } else { 2563 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2564 } 2565 } 2566 2567 scheduleWritePackageRestrictionsLocked(userId); 2568 scheduleWriteSettingsLocked(); 2569 } 2570 2571 private void applyFactoryDefaultBrowserLPw(int userId) { 2572 // The default browser app's package name is stored in a string resource, 2573 // with a product-specific overlay used for vendor customization. 2574 String browserPkg = mContext.getResources().getString( 2575 com.android.internal.R.string.default_browser); 2576 if (!TextUtils.isEmpty(browserPkg)) { 2577 // non-empty string => required to be a known package 2578 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2579 if (ps == null) { 2580 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2581 browserPkg = null; 2582 } else { 2583 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2584 } 2585 } 2586 2587 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2588 // default. If there's more than one, just leave everything alone. 2589 if (browserPkg == null) { 2590 calculateDefaultBrowserLPw(userId); 2591 } 2592 } 2593 2594 private void calculateDefaultBrowserLPw(int userId) { 2595 List<String> allBrowsers = resolveAllBrowserApps(userId); 2596 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2597 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2598 } 2599 2600 private List<String> resolveAllBrowserApps(int userId) { 2601 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2602 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2603 PackageManager.MATCH_ALL, userId); 2604 2605 final int count = list.size(); 2606 List<String> result = new ArrayList<String>(count); 2607 for (int i=0; i<count; i++) { 2608 ResolveInfo info = list.get(i); 2609 if (info.activityInfo == null 2610 || !info.handleAllWebDataURI 2611 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2612 || result.contains(info.activityInfo.packageName)) { 2613 continue; 2614 } 2615 result.add(info.activityInfo.packageName); 2616 } 2617 2618 return result; 2619 } 2620 2621 private boolean packageIsBrowser(String packageName, int userId) { 2622 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2623 PackageManager.MATCH_ALL, userId); 2624 final int N = list.size(); 2625 for (int i = 0; i < N; i++) { 2626 ResolveInfo info = list.get(i); 2627 if (packageName.equals(info.activityInfo.packageName)) { 2628 return true; 2629 } 2630 } 2631 return false; 2632 } 2633 2634 private void checkDefaultBrowser() { 2635 final int myUserId = UserHandle.myUserId(); 2636 final String packageName = getDefaultBrowserPackageName(myUserId); 2637 if (packageName != null) { 2638 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2639 if (info == null) { 2640 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2641 synchronized (mPackages) { 2642 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2643 } 2644 } 2645 } 2646 } 2647 2648 @Override 2649 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2650 throws RemoteException { 2651 try { 2652 return super.onTransact(code, data, reply, flags); 2653 } catch (RuntimeException e) { 2654 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2655 Slog.wtf(TAG, "Package Manager Crash", e); 2656 } 2657 throw e; 2658 } 2659 } 2660 2661 void cleanupInstallFailedPackage(PackageSetting ps) { 2662 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2663 2664 removeDataDirsLI(ps.volumeUuid, ps.name); 2665 if (ps.codePath != null) { 2666 if (ps.codePath.isDirectory()) { 2667 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2668 } else { 2669 ps.codePath.delete(); 2670 } 2671 } 2672 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2673 if (ps.resourcePath.isDirectory()) { 2674 FileUtils.deleteContents(ps.resourcePath); 2675 } 2676 ps.resourcePath.delete(); 2677 } 2678 mSettings.removePackageLPw(ps.name); 2679 } 2680 2681 static int[] appendInts(int[] cur, int[] add) { 2682 if (add == null) return cur; 2683 if (cur == null) return add; 2684 final int N = add.length; 2685 for (int i=0; i<N; i++) { 2686 cur = appendInt(cur, add[i]); 2687 } 2688 return cur; 2689 } 2690 2691 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2692 if (!sUserManager.exists(userId)) return null; 2693 final PackageSetting ps = (PackageSetting) p.mExtras; 2694 if (ps == null) { 2695 return null; 2696 } 2697 2698 final PermissionsState permissionsState = ps.getPermissionsState(); 2699 2700 final int[] gids = permissionsState.computeGids(userId); 2701 final Set<String> permissions = permissionsState.getPermissions(userId); 2702 final PackageUserState state = ps.readUserState(userId); 2703 2704 return PackageParser.generatePackageInfo(p, gids, flags, 2705 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2706 } 2707 2708 @Override 2709 public boolean isPackageFrozen(String packageName) { 2710 synchronized (mPackages) { 2711 final PackageSetting ps = mSettings.mPackages.get(packageName); 2712 if (ps != null) { 2713 return ps.frozen; 2714 } 2715 } 2716 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2717 return true; 2718 } 2719 2720 @Override 2721 public boolean isPackageAvailable(String packageName, int userId) { 2722 if (!sUserManager.exists(userId)) return false; 2723 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2724 synchronized (mPackages) { 2725 PackageParser.Package p = mPackages.get(packageName); 2726 if (p != null) { 2727 final PackageSetting ps = (PackageSetting) p.mExtras; 2728 if (ps != null) { 2729 final PackageUserState state = ps.readUserState(userId); 2730 if (state != null) { 2731 return PackageParser.isAvailable(state); 2732 } 2733 } 2734 } 2735 } 2736 return false; 2737 } 2738 2739 @Override 2740 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2741 if (!sUserManager.exists(userId)) return null; 2742 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2743 // reader 2744 synchronized (mPackages) { 2745 PackageParser.Package p = mPackages.get(packageName); 2746 if (DEBUG_PACKAGE_INFO) 2747 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2748 if (p != null) { 2749 return generatePackageInfo(p, flags, userId); 2750 } 2751 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2752 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2753 } 2754 } 2755 return null; 2756 } 2757 2758 @Override 2759 public String[] currentToCanonicalPackageNames(String[] names) { 2760 String[] out = new String[names.length]; 2761 // reader 2762 synchronized (mPackages) { 2763 for (int i=names.length-1; i>=0; i--) { 2764 PackageSetting ps = mSettings.mPackages.get(names[i]); 2765 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2766 } 2767 } 2768 return out; 2769 } 2770 2771 @Override 2772 public String[] canonicalToCurrentPackageNames(String[] names) { 2773 String[] out = new String[names.length]; 2774 // reader 2775 synchronized (mPackages) { 2776 for (int i=names.length-1; i>=0; i--) { 2777 String cur = mSettings.mRenamedPackages.get(names[i]); 2778 out[i] = cur != null ? cur : names[i]; 2779 } 2780 } 2781 return out; 2782 } 2783 2784 @Override 2785 public int getPackageUid(String packageName, int userId) { 2786 return getPackageUidEtc(packageName, 0, userId); 2787 } 2788 2789 @Override 2790 public int getPackageUidEtc(String packageName, int flags, int userId) { 2791 if (!sUserManager.exists(userId)) return -1; 2792 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2793 2794 // reader 2795 synchronized (mPackages) { 2796 final PackageParser.Package p = mPackages.get(packageName); 2797 if (p != null) { 2798 return UserHandle.getUid(userId, p.applicationInfo.uid); 2799 } 2800 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2801 final PackageSetting ps = mSettings.mPackages.get(packageName); 2802 if (ps != null) { 2803 return UserHandle.getUid(userId, ps.appId); 2804 } 2805 } 2806 } 2807 2808 return -1; 2809 } 2810 2811 @Override 2812 public int[] getPackageGids(String packageName, int userId) { 2813 return getPackageGidsEtc(packageName, 0, userId); 2814 } 2815 2816 @Override 2817 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2818 if (!sUserManager.exists(userId)) { 2819 return null; 2820 } 2821 2822 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2823 "getPackageGids"); 2824 2825 // reader 2826 synchronized (mPackages) { 2827 final PackageParser.Package p = mPackages.get(packageName); 2828 if (p != null) { 2829 PackageSetting ps = (PackageSetting) p.mExtras; 2830 return ps.getPermissionsState().computeGids(userId); 2831 } 2832 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2833 final PackageSetting ps = mSettings.mPackages.get(packageName); 2834 if (ps != null) { 2835 return ps.getPermissionsState().computeGids(userId); 2836 } 2837 } 2838 } 2839 2840 return null; 2841 } 2842 2843 static PermissionInfo generatePermissionInfo( 2844 BasePermission bp, int flags) { 2845 if (bp.perm != null) { 2846 return PackageParser.generatePermissionInfo(bp.perm, flags); 2847 } 2848 PermissionInfo pi = new PermissionInfo(); 2849 pi.name = bp.name; 2850 pi.packageName = bp.sourcePackage; 2851 pi.nonLocalizedLabel = bp.name; 2852 pi.protectionLevel = bp.protectionLevel; 2853 return pi; 2854 } 2855 2856 @Override 2857 public PermissionInfo getPermissionInfo(String name, int flags) { 2858 // reader 2859 synchronized (mPackages) { 2860 final BasePermission p = mSettings.mPermissions.get(name); 2861 if (p != null) { 2862 return generatePermissionInfo(p, flags); 2863 } 2864 return null; 2865 } 2866 } 2867 2868 @Override 2869 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2870 // reader 2871 synchronized (mPackages) { 2872 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2873 for (BasePermission p : mSettings.mPermissions.values()) { 2874 if (group == null) { 2875 if (p.perm == null || p.perm.info.group == null) { 2876 out.add(generatePermissionInfo(p, flags)); 2877 } 2878 } else { 2879 if (p.perm != null && group.equals(p.perm.info.group)) { 2880 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2881 } 2882 } 2883 } 2884 2885 if (out.size() > 0) { 2886 return out; 2887 } 2888 return mPermissionGroups.containsKey(group) ? out : null; 2889 } 2890 } 2891 2892 @Override 2893 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2894 // reader 2895 synchronized (mPackages) { 2896 return PackageParser.generatePermissionGroupInfo( 2897 mPermissionGroups.get(name), flags); 2898 } 2899 } 2900 2901 @Override 2902 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2903 // reader 2904 synchronized (mPackages) { 2905 final int N = mPermissionGroups.size(); 2906 ArrayList<PermissionGroupInfo> out 2907 = new ArrayList<PermissionGroupInfo>(N); 2908 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2909 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2910 } 2911 return out; 2912 } 2913 } 2914 2915 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2916 int userId) { 2917 if (!sUserManager.exists(userId)) return null; 2918 PackageSetting ps = mSettings.mPackages.get(packageName); 2919 if (ps != null) { 2920 if (ps.pkg == null) { 2921 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2922 flags, userId); 2923 if (pInfo != null) { 2924 return pInfo.applicationInfo; 2925 } 2926 return null; 2927 } 2928 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2929 ps.readUserState(userId), userId); 2930 } 2931 return null; 2932 } 2933 2934 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2935 int userId) { 2936 if (!sUserManager.exists(userId)) return null; 2937 PackageSetting ps = mSettings.mPackages.get(packageName); 2938 if (ps != null) { 2939 PackageParser.Package pkg = ps.pkg; 2940 if (pkg == null) { 2941 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2942 return null; 2943 } 2944 // Only data remains, so we aren't worried about code paths 2945 pkg = new PackageParser.Package(packageName); 2946 pkg.applicationInfo.packageName = packageName; 2947 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2948 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2949 pkg.applicationInfo.dataDir = Environment 2950 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2951 .getAbsolutePath(); 2952 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2953 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2954 } 2955 return generatePackageInfo(pkg, flags, userId); 2956 } 2957 return null; 2958 } 2959 2960 @Override 2961 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2962 if (!sUserManager.exists(userId)) return null; 2963 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2964 // writer 2965 synchronized (mPackages) { 2966 PackageParser.Package p = mPackages.get(packageName); 2967 if (DEBUG_PACKAGE_INFO) Log.v( 2968 TAG, "getApplicationInfo " + packageName 2969 + ": " + p); 2970 if (p != null) { 2971 PackageSetting ps = mSettings.mPackages.get(packageName); 2972 if (ps == null) return null; 2973 // Note: isEnabledLP() does not apply here - always return info 2974 return PackageParser.generateApplicationInfo( 2975 p, flags, ps.readUserState(userId), userId); 2976 } 2977 if ("android".equals(packageName)||"system".equals(packageName)) { 2978 return mAndroidApplication; 2979 } 2980 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2981 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2982 } 2983 } 2984 return null; 2985 } 2986 2987 @Override 2988 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2989 final IPackageDataObserver observer) { 2990 mContext.enforceCallingOrSelfPermission( 2991 android.Manifest.permission.CLEAR_APP_CACHE, null); 2992 // Queue up an async operation since clearing cache may take a little while. 2993 mHandler.post(new Runnable() { 2994 public void run() { 2995 mHandler.removeCallbacks(this); 2996 int retCode = -1; 2997 synchronized (mInstallLock) { 2998 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2999 if (retCode < 0) { 3000 Slog.w(TAG, "Couldn't clear application caches"); 3001 } 3002 } 3003 if (observer != null) { 3004 try { 3005 observer.onRemoveCompleted(null, (retCode >= 0)); 3006 } catch (RemoteException e) { 3007 Slog.w(TAG, "RemoveException when invoking call back"); 3008 } 3009 } 3010 } 3011 }); 3012 } 3013 3014 @Override 3015 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3016 final IntentSender pi) { 3017 mContext.enforceCallingOrSelfPermission( 3018 android.Manifest.permission.CLEAR_APP_CACHE, null); 3019 // Queue up an async operation since clearing cache may take a little while. 3020 mHandler.post(new Runnable() { 3021 public void run() { 3022 mHandler.removeCallbacks(this); 3023 int retCode = -1; 3024 synchronized (mInstallLock) { 3025 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3026 if (retCode < 0) { 3027 Slog.w(TAG, "Couldn't clear application caches"); 3028 } 3029 } 3030 if(pi != null) { 3031 try { 3032 // Callback via pending intent 3033 int code = (retCode >= 0) ? 1 : 0; 3034 pi.sendIntent(null, code, null, 3035 null, null); 3036 } catch (SendIntentException e1) { 3037 Slog.i(TAG, "Failed to send pending intent"); 3038 } 3039 } 3040 } 3041 }); 3042 } 3043 3044 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3045 synchronized (mInstallLock) { 3046 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3047 throw new IOException("Failed to free enough space"); 3048 } 3049 } 3050 } 3051 3052 @Override 3053 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3054 if (!sUserManager.exists(userId)) return null; 3055 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3056 synchronized (mPackages) { 3057 PackageParser.Activity a = mActivities.mActivities.get(component); 3058 3059 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3060 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3061 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3062 if (ps == null) return null; 3063 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3064 userId); 3065 } 3066 if (mResolveComponentName.equals(component)) { 3067 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3068 new PackageUserState(), userId); 3069 } 3070 } 3071 return null; 3072 } 3073 3074 @Override 3075 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3076 String resolvedType) { 3077 synchronized (mPackages) { 3078 if (component.equals(mResolveComponentName)) { 3079 // The resolver supports EVERYTHING! 3080 return true; 3081 } 3082 PackageParser.Activity a = mActivities.mActivities.get(component); 3083 if (a == null) { 3084 return false; 3085 } 3086 for (int i=0; i<a.intents.size(); i++) { 3087 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3088 intent.getData(), intent.getCategories(), TAG) >= 0) { 3089 return true; 3090 } 3091 } 3092 return false; 3093 } 3094 } 3095 3096 @Override 3097 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3098 if (!sUserManager.exists(userId)) return null; 3099 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3100 synchronized (mPackages) { 3101 PackageParser.Activity a = mReceivers.mActivities.get(component); 3102 if (DEBUG_PACKAGE_INFO) Log.v( 3103 TAG, "getReceiverInfo " + component + ": " + a); 3104 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3105 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3106 if (ps == null) return null; 3107 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3108 userId); 3109 } 3110 } 3111 return null; 3112 } 3113 3114 @Override 3115 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3116 if (!sUserManager.exists(userId)) return null; 3117 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3118 synchronized (mPackages) { 3119 PackageParser.Service s = mServices.mServices.get(component); 3120 if (DEBUG_PACKAGE_INFO) Log.v( 3121 TAG, "getServiceInfo " + component + ": " + s); 3122 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3123 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3124 if (ps == null) return null; 3125 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3126 userId); 3127 } 3128 } 3129 return null; 3130 } 3131 3132 @Override 3133 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3134 if (!sUserManager.exists(userId)) return null; 3135 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3136 synchronized (mPackages) { 3137 PackageParser.Provider p = mProviders.mProviders.get(component); 3138 if (DEBUG_PACKAGE_INFO) Log.v( 3139 TAG, "getProviderInfo " + component + ": " + p); 3140 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3141 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3142 if (ps == null) return null; 3143 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3144 userId); 3145 } 3146 } 3147 return null; 3148 } 3149 3150 @Override 3151 public String[] getSystemSharedLibraryNames() { 3152 Set<String> libSet; 3153 synchronized (mPackages) { 3154 libSet = mSharedLibraries.keySet(); 3155 int size = libSet.size(); 3156 if (size > 0) { 3157 String[] libs = new String[size]; 3158 libSet.toArray(libs); 3159 return libs; 3160 } 3161 } 3162 return null; 3163 } 3164 3165 /** 3166 * @hide 3167 */ 3168 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3169 synchronized (mPackages) { 3170 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3171 if (lib != null && lib.apk != null) { 3172 return mPackages.get(lib.apk); 3173 } 3174 } 3175 return null; 3176 } 3177 3178 @Override 3179 public FeatureInfo[] getSystemAvailableFeatures() { 3180 Collection<FeatureInfo> featSet; 3181 synchronized (mPackages) { 3182 featSet = mAvailableFeatures.values(); 3183 int size = featSet.size(); 3184 if (size > 0) { 3185 FeatureInfo[] features = new FeatureInfo[size+1]; 3186 featSet.toArray(features); 3187 FeatureInfo fi = new FeatureInfo(); 3188 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3189 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3190 features[size] = fi; 3191 return features; 3192 } 3193 } 3194 return null; 3195 } 3196 3197 @Override 3198 public boolean hasSystemFeature(String name) { 3199 synchronized (mPackages) { 3200 return mAvailableFeatures.containsKey(name); 3201 } 3202 } 3203 3204 private void checkValidCaller(int uid, int userId) { 3205 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3206 return; 3207 3208 throw new SecurityException("Caller uid=" + uid 3209 + " is not privileged to communicate with user=" + userId); 3210 } 3211 3212 @Override 3213 public int checkPermission(String permName, String pkgName, int userId) { 3214 if (!sUserManager.exists(userId)) { 3215 return PackageManager.PERMISSION_DENIED; 3216 } 3217 3218 synchronized (mPackages) { 3219 final PackageParser.Package p = mPackages.get(pkgName); 3220 if (p != null && p.mExtras != null) { 3221 final PackageSetting ps = (PackageSetting) p.mExtras; 3222 final PermissionsState permissionsState = ps.getPermissionsState(); 3223 if (permissionsState.hasPermission(permName, userId)) { 3224 return PackageManager.PERMISSION_GRANTED; 3225 } 3226 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3227 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3228 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3229 return PackageManager.PERMISSION_GRANTED; 3230 } 3231 } 3232 } 3233 3234 return PackageManager.PERMISSION_DENIED; 3235 } 3236 3237 @Override 3238 public int checkUidPermission(String permName, int uid) { 3239 final int userId = UserHandle.getUserId(uid); 3240 3241 if (!sUserManager.exists(userId)) { 3242 return PackageManager.PERMISSION_DENIED; 3243 } 3244 3245 synchronized (mPackages) { 3246 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3247 if (obj != null) { 3248 final SettingBase ps = (SettingBase) obj; 3249 final PermissionsState permissionsState = ps.getPermissionsState(); 3250 if (permissionsState.hasPermission(permName, userId)) { 3251 return PackageManager.PERMISSION_GRANTED; 3252 } 3253 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3254 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3255 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3256 return PackageManager.PERMISSION_GRANTED; 3257 } 3258 } else { 3259 ArraySet<String> perms = mSystemPermissions.get(uid); 3260 if (perms != null) { 3261 if (perms.contains(permName)) { 3262 return PackageManager.PERMISSION_GRANTED; 3263 } 3264 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3265 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3266 return PackageManager.PERMISSION_GRANTED; 3267 } 3268 } 3269 } 3270 } 3271 3272 return PackageManager.PERMISSION_DENIED; 3273 } 3274 3275 @Override 3276 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3277 if (UserHandle.getCallingUserId() != userId) { 3278 mContext.enforceCallingPermission( 3279 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3280 "isPermissionRevokedByPolicy for user " + userId); 3281 } 3282 3283 if (checkPermission(permission, packageName, userId) 3284 == PackageManager.PERMISSION_GRANTED) { 3285 return false; 3286 } 3287 3288 final long identity = Binder.clearCallingIdentity(); 3289 try { 3290 final int flags = getPermissionFlags(permission, packageName, userId); 3291 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3292 } finally { 3293 Binder.restoreCallingIdentity(identity); 3294 } 3295 } 3296 3297 @Override 3298 public String getPermissionControllerPackageName() { 3299 synchronized (mPackages) { 3300 return mRequiredInstallerPackage; 3301 } 3302 } 3303 3304 /** 3305 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3306 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3307 * @param checkShell TODO(yamasani): 3308 * @param message the message to log on security exception 3309 */ 3310 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3311 boolean checkShell, String message) { 3312 if (userId < 0) { 3313 throw new IllegalArgumentException("Invalid userId " + userId); 3314 } 3315 if (checkShell) { 3316 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3317 } 3318 if (userId == UserHandle.getUserId(callingUid)) return; 3319 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3320 if (requireFullPermission) { 3321 mContext.enforceCallingOrSelfPermission( 3322 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3323 } else { 3324 try { 3325 mContext.enforceCallingOrSelfPermission( 3326 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3327 } catch (SecurityException se) { 3328 mContext.enforceCallingOrSelfPermission( 3329 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3330 } 3331 } 3332 } 3333 } 3334 3335 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3336 if (callingUid == Process.SHELL_UID) { 3337 if (userHandle >= 0 3338 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3339 throw new SecurityException("Shell does not have permission to access user " 3340 + userHandle); 3341 } else if (userHandle < 0) { 3342 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3343 + Debug.getCallers(3)); 3344 } 3345 } 3346 } 3347 3348 private BasePermission findPermissionTreeLP(String permName) { 3349 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3350 if (permName.startsWith(bp.name) && 3351 permName.length() > bp.name.length() && 3352 permName.charAt(bp.name.length()) == '.') { 3353 return bp; 3354 } 3355 } 3356 return null; 3357 } 3358 3359 private BasePermission checkPermissionTreeLP(String permName) { 3360 if (permName != null) { 3361 BasePermission bp = findPermissionTreeLP(permName); 3362 if (bp != null) { 3363 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3364 return bp; 3365 } 3366 throw new SecurityException("Calling uid " 3367 + Binder.getCallingUid() 3368 + " is not allowed to add to permission tree " 3369 + bp.name + " owned by uid " + bp.uid); 3370 } 3371 } 3372 throw new SecurityException("No permission tree found for " + permName); 3373 } 3374 3375 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3376 if (s1 == null) { 3377 return s2 == null; 3378 } 3379 if (s2 == null) { 3380 return false; 3381 } 3382 if (s1.getClass() != s2.getClass()) { 3383 return false; 3384 } 3385 return s1.equals(s2); 3386 } 3387 3388 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3389 if (pi1.icon != pi2.icon) return false; 3390 if (pi1.logo != pi2.logo) return false; 3391 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3392 if (!compareStrings(pi1.name, pi2.name)) return false; 3393 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3394 // We'll take care of setting this one. 3395 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3396 // These are not currently stored in settings. 3397 //if (!compareStrings(pi1.group, pi2.group)) return false; 3398 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3399 //if (pi1.labelRes != pi2.labelRes) return false; 3400 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3401 return true; 3402 } 3403 3404 int permissionInfoFootprint(PermissionInfo info) { 3405 int size = info.name.length(); 3406 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3407 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3408 return size; 3409 } 3410 3411 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3412 int size = 0; 3413 for (BasePermission perm : mSettings.mPermissions.values()) { 3414 if (perm.uid == tree.uid) { 3415 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3416 } 3417 } 3418 return size; 3419 } 3420 3421 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3422 // We calculate the max size of permissions defined by this uid and throw 3423 // if that plus the size of 'info' would exceed our stated maximum. 3424 if (tree.uid != Process.SYSTEM_UID) { 3425 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3426 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3427 throw new SecurityException("Permission tree size cap exceeded"); 3428 } 3429 } 3430 } 3431 3432 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3433 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3434 throw new SecurityException("Label must be specified in permission"); 3435 } 3436 BasePermission tree = checkPermissionTreeLP(info.name); 3437 BasePermission bp = mSettings.mPermissions.get(info.name); 3438 boolean added = bp == null; 3439 boolean changed = true; 3440 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3441 if (added) { 3442 enforcePermissionCapLocked(info, tree); 3443 bp = new BasePermission(info.name, tree.sourcePackage, 3444 BasePermission.TYPE_DYNAMIC); 3445 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3446 throw new SecurityException( 3447 "Not allowed to modify non-dynamic permission " 3448 + info.name); 3449 } else { 3450 if (bp.protectionLevel == fixedLevel 3451 && bp.perm.owner.equals(tree.perm.owner) 3452 && bp.uid == tree.uid 3453 && comparePermissionInfos(bp.perm.info, info)) { 3454 changed = false; 3455 } 3456 } 3457 bp.protectionLevel = fixedLevel; 3458 info = new PermissionInfo(info); 3459 info.protectionLevel = fixedLevel; 3460 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3461 bp.perm.info.packageName = tree.perm.info.packageName; 3462 bp.uid = tree.uid; 3463 if (added) { 3464 mSettings.mPermissions.put(info.name, bp); 3465 } 3466 if (changed) { 3467 if (!async) { 3468 mSettings.writeLPr(); 3469 } else { 3470 scheduleWriteSettingsLocked(); 3471 } 3472 } 3473 return added; 3474 } 3475 3476 @Override 3477 public boolean addPermission(PermissionInfo info) { 3478 synchronized (mPackages) { 3479 return addPermissionLocked(info, false); 3480 } 3481 } 3482 3483 @Override 3484 public boolean addPermissionAsync(PermissionInfo info) { 3485 synchronized (mPackages) { 3486 return addPermissionLocked(info, true); 3487 } 3488 } 3489 3490 @Override 3491 public void removePermission(String name) { 3492 synchronized (mPackages) { 3493 checkPermissionTreeLP(name); 3494 BasePermission bp = mSettings.mPermissions.get(name); 3495 if (bp != null) { 3496 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3497 throw new SecurityException( 3498 "Not allowed to modify non-dynamic permission " 3499 + name); 3500 } 3501 mSettings.mPermissions.remove(name); 3502 mSettings.writeLPr(); 3503 } 3504 } 3505 } 3506 3507 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3508 BasePermission bp) { 3509 int index = pkg.requestedPermissions.indexOf(bp.name); 3510 if (index == -1) { 3511 throw new SecurityException("Package " + pkg.packageName 3512 + " has not requested permission " + bp.name); 3513 } 3514 if (!bp.isRuntime() && !bp.isDevelopment()) { 3515 throw new SecurityException("Permission " + bp.name 3516 + " is not a changeable permission type"); 3517 } 3518 } 3519 3520 @Override 3521 public void grantRuntimePermission(String packageName, String name, final int userId) { 3522 if (!sUserManager.exists(userId)) { 3523 Log.e(TAG, "No such user:" + userId); 3524 return; 3525 } 3526 3527 mContext.enforceCallingOrSelfPermission( 3528 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3529 "grantRuntimePermission"); 3530 3531 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3532 "grantRuntimePermission"); 3533 3534 final int uid; 3535 final SettingBase sb; 3536 3537 synchronized (mPackages) { 3538 final PackageParser.Package pkg = mPackages.get(packageName); 3539 if (pkg == null) { 3540 throw new IllegalArgumentException("Unknown package: " + packageName); 3541 } 3542 3543 final BasePermission bp = mSettings.mPermissions.get(name); 3544 if (bp == null) { 3545 throw new IllegalArgumentException("Unknown permission: " + name); 3546 } 3547 3548 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3549 3550 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3551 sb = (SettingBase) pkg.mExtras; 3552 if (sb == null) { 3553 throw new IllegalArgumentException("Unknown package: " + packageName); 3554 } 3555 3556 final PermissionsState permissionsState = sb.getPermissionsState(); 3557 3558 final int flags = permissionsState.getPermissionFlags(name, userId); 3559 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3560 throw new SecurityException("Cannot grant system fixed permission: " 3561 + name + " for package: " + packageName); 3562 } 3563 3564 if (bp.isDevelopment()) { 3565 // Development permissions must be handled specially, since they are not 3566 // normal runtime permissions. For now they apply to all users. 3567 if (permissionsState.grantInstallPermission(bp) != 3568 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3569 scheduleWriteSettingsLocked(); 3570 } 3571 return; 3572 } 3573 3574 final int result = permissionsState.grantRuntimePermission(bp, userId); 3575 switch (result) { 3576 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3577 return; 3578 } 3579 3580 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3581 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3582 mHandler.post(new Runnable() { 3583 @Override 3584 public void run() { 3585 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3586 } 3587 }); 3588 } 3589 break; 3590 } 3591 3592 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3593 3594 // Not critical if that is lost - app has to request again. 3595 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3596 } 3597 3598 // Only need to do this if user is initialized. Otherwise it's a new user 3599 // and there are no processes running as the user yet and there's no need 3600 // to make an expensive call to remount processes for the changed permissions. 3601 if (READ_EXTERNAL_STORAGE.equals(name) 3602 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3603 final long token = Binder.clearCallingIdentity(); 3604 try { 3605 if (sUserManager.isInitialized(userId)) { 3606 MountServiceInternal mountServiceInternal = LocalServices.getService( 3607 MountServiceInternal.class); 3608 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3609 } 3610 } finally { 3611 Binder.restoreCallingIdentity(token); 3612 } 3613 } 3614 } 3615 3616 @Override 3617 public void revokeRuntimePermission(String packageName, String name, int userId) { 3618 if (!sUserManager.exists(userId)) { 3619 Log.e(TAG, "No such user:" + userId); 3620 return; 3621 } 3622 3623 mContext.enforceCallingOrSelfPermission( 3624 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3625 "revokeRuntimePermission"); 3626 3627 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3628 "revokeRuntimePermission"); 3629 3630 final int appId; 3631 3632 synchronized (mPackages) { 3633 final PackageParser.Package pkg = mPackages.get(packageName); 3634 if (pkg == null) { 3635 throw new IllegalArgumentException("Unknown package: " + packageName); 3636 } 3637 3638 final BasePermission bp = mSettings.mPermissions.get(name); 3639 if (bp == null) { 3640 throw new IllegalArgumentException("Unknown permission: " + name); 3641 } 3642 3643 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3644 3645 SettingBase sb = (SettingBase) pkg.mExtras; 3646 if (sb == null) { 3647 throw new IllegalArgumentException("Unknown package: " + packageName); 3648 } 3649 3650 final PermissionsState permissionsState = sb.getPermissionsState(); 3651 3652 final int flags = permissionsState.getPermissionFlags(name, userId); 3653 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3654 throw new SecurityException("Cannot revoke system fixed permission: " 3655 + name + " for package: " + packageName); 3656 } 3657 3658 if (bp.isDevelopment()) { 3659 // Development permissions must be handled specially, since they are not 3660 // normal runtime permissions. For now they apply to all users. 3661 if (permissionsState.revokeInstallPermission(bp) != 3662 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3663 scheduleWriteSettingsLocked(); 3664 } 3665 return; 3666 } 3667 3668 if (permissionsState.revokeRuntimePermission(bp, userId) == 3669 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3670 return; 3671 } 3672 3673 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3674 3675 // Critical, after this call app should never have the permission. 3676 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3677 3678 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3679 } 3680 3681 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3682 } 3683 3684 @Override 3685 public void resetRuntimePermissions() { 3686 mContext.enforceCallingOrSelfPermission( 3687 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3688 "revokeRuntimePermission"); 3689 3690 int callingUid = Binder.getCallingUid(); 3691 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3692 mContext.enforceCallingOrSelfPermission( 3693 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3694 "resetRuntimePermissions"); 3695 } 3696 3697 synchronized (mPackages) { 3698 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3699 for (int userId : UserManagerService.getInstance().getUserIds()) { 3700 final int packageCount = mPackages.size(); 3701 for (int i = 0; i < packageCount; i++) { 3702 PackageParser.Package pkg = mPackages.valueAt(i); 3703 if (!(pkg.mExtras instanceof PackageSetting)) { 3704 continue; 3705 } 3706 PackageSetting ps = (PackageSetting) pkg.mExtras; 3707 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3708 } 3709 } 3710 } 3711 } 3712 3713 @Override 3714 public int getPermissionFlags(String name, String packageName, int userId) { 3715 if (!sUserManager.exists(userId)) { 3716 return 0; 3717 } 3718 3719 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3720 3721 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3722 "getPermissionFlags"); 3723 3724 synchronized (mPackages) { 3725 final PackageParser.Package pkg = mPackages.get(packageName); 3726 if (pkg == null) { 3727 throw new IllegalArgumentException("Unknown package: " + packageName); 3728 } 3729 3730 final BasePermission bp = mSettings.mPermissions.get(name); 3731 if (bp == null) { 3732 throw new IllegalArgumentException("Unknown permission: " + name); 3733 } 3734 3735 SettingBase sb = (SettingBase) pkg.mExtras; 3736 if (sb == null) { 3737 throw new IllegalArgumentException("Unknown package: " + packageName); 3738 } 3739 3740 PermissionsState permissionsState = sb.getPermissionsState(); 3741 return permissionsState.getPermissionFlags(name, userId); 3742 } 3743 } 3744 3745 @Override 3746 public void updatePermissionFlags(String name, String packageName, int flagMask, 3747 int flagValues, int userId) { 3748 if (!sUserManager.exists(userId)) { 3749 return; 3750 } 3751 3752 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3753 3754 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3755 "updatePermissionFlags"); 3756 3757 // Only the system can change these flags and nothing else. 3758 if (getCallingUid() != Process.SYSTEM_UID) { 3759 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3760 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3761 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3762 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3763 } 3764 3765 synchronized (mPackages) { 3766 final PackageParser.Package pkg = mPackages.get(packageName); 3767 if (pkg == null) { 3768 throw new IllegalArgumentException("Unknown package: " + packageName); 3769 } 3770 3771 final BasePermission bp = mSettings.mPermissions.get(name); 3772 if (bp == null) { 3773 throw new IllegalArgumentException("Unknown permission: " + name); 3774 } 3775 3776 SettingBase sb = (SettingBase) pkg.mExtras; 3777 if (sb == null) { 3778 throw new IllegalArgumentException("Unknown package: " + packageName); 3779 } 3780 3781 PermissionsState permissionsState = sb.getPermissionsState(); 3782 3783 // Only the package manager can change flags for system component permissions. 3784 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3785 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3786 return; 3787 } 3788 3789 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3790 3791 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3792 // Install and runtime permissions are stored in different places, 3793 // so figure out what permission changed and persist the change. 3794 if (permissionsState.getInstallPermissionState(name) != null) { 3795 scheduleWriteSettingsLocked(); 3796 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3797 || hadState) { 3798 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3799 } 3800 } 3801 } 3802 } 3803 3804 /** 3805 * Update the permission flags for all packages and runtime permissions of a user in order 3806 * to allow device or profile owner to remove POLICY_FIXED. 3807 */ 3808 @Override 3809 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3810 if (!sUserManager.exists(userId)) { 3811 return; 3812 } 3813 3814 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3815 3816 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3817 "updatePermissionFlagsForAllApps"); 3818 3819 // Only the system can change system fixed flags. 3820 if (getCallingUid() != Process.SYSTEM_UID) { 3821 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3822 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3823 } 3824 3825 synchronized (mPackages) { 3826 boolean changed = false; 3827 final int packageCount = mPackages.size(); 3828 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3829 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3830 SettingBase sb = (SettingBase) pkg.mExtras; 3831 if (sb == null) { 3832 continue; 3833 } 3834 PermissionsState permissionsState = sb.getPermissionsState(); 3835 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3836 userId, flagMask, flagValues); 3837 } 3838 if (changed) { 3839 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3840 } 3841 } 3842 } 3843 3844 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 3845 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 3846 != PackageManager.PERMISSION_GRANTED 3847 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 3848 != PackageManager.PERMISSION_GRANTED) { 3849 throw new SecurityException(message + " requires " 3850 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 3851 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 3852 } 3853 } 3854 3855 @Override 3856 public boolean shouldShowRequestPermissionRationale(String permissionName, 3857 String packageName, int userId) { 3858 if (UserHandle.getCallingUserId() != userId) { 3859 mContext.enforceCallingPermission( 3860 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3861 "canShowRequestPermissionRationale for user " + userId); 3862 } 3863 3864 final int uid = getPackageUid(packageName, userId); 3865 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3866 return false; 3867 } 3868 3869 if (checkPermission(permissionName, packageName, userId) 3870 == PackageManager.PERMISSION_GRANTED) { 3871 return false; 3872 } 3873 3874 final int flags; 3875 3876 final long identity = Binder.clearCallingIdentity(); 3877 try { 3878 flags = getPermissionFlags(permissionName, 3879 packageName, userId); 3880 } finally { 3881 Binder.restoreCallingIdentity(identity); 3882 } 3883 3884 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3885 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3886 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3887 3888 if ((flags & fixedFlags) != 0) { 3889 return false; 3890 } 3891 3892 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3893 } 3894 3895 @Override 3896 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3897 mContext.enforceCallingOrSelfPermission( 3898 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3899 "addOnPermissionsChangeListener"); 3900 3901 synchronized (mPackages) { 3902 mOnPermissionChangeListeners.addListenerLocked(listener); 3903 } 3904 } 3905 3906 @Override 3907 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3908 synchronized (mPackages) { 3909 mOnPermissionChangeListeners.removeListenerLocked(listener); 3910 } 3911 } 3912 3913 @Override 3914 public boolean isProtectedBroadcast(String actionName) { 3915 synchronized (mPackages) { 3916 return mProtectedBroadcasts.contains(actionName); 3917 } 3918 } 3919 3920 @Override 3921 public int checkSignatures(String pkg1, String pkg2) { 3922 synchronized (mPackages) { 3923 final PackageParser.Package p1 = mPackages.get(pkg1); 3924 final PackageParser.Package p2 = mPackages.get(pkg2); 3925 if (p1 == null || p1.mExtras == null 3926 || p2 == null || p2.mExtras == null) { 3927 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3928 } 3929 return compareSignatures(p1.mSignatures, p2.mSignatures); 3930 } 3931 } 3932 3933 @Override 3934 public int checkUidSignatures(int uid1, int uid2) { 3935 // Map to base uids. 3936 uid1 = UserHandle.getAppId(uid1); 3937 uid2 = UserHandle.getAppId(uid2); 3938 // reader 3939 synchronized (mPackages) { 3940 Signature[] s1; 3941 Signature[] s2; 3942 Object obj = mSettings.getUserIdLPr(uid1); 3943 if (obj != null) { 3944 if (obj instanceof SharedUserSetting) { 3945 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3946 } else if (obj instanceof PackageSetting) { 3947 s1 = ((PackageSetting)obj).signatures.mSignatures; 3948 } else { 3949 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3950 } 3951 } else { 3952 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3953 } 3954 obj = mSettings.getUserIdLPr(uid2); 3955 if (obj != null) { 3956 if (obj instanceof SharedUserSetting) { 3957 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3958 } else if (obj instanceof PackageSetting) { 3959 s2 = ((PackageSetting)obj).signatures.mSignatures; 3960 } else { 3961 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3962 } 3963 } else { 3964 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3965 } 3966 return compareSignatures(s1, s2); 3967 } 3968 } 3969 3970 private void killUid(int appId, int userId, String reason) { 3971 final long identity = Binder.clearCallingIdentity(); 3972 try { 3973 IActivityManager am = ActivityManagerNative.getDefault(); 3974 if (am != null) { 3975 try { 3976 am.killUid(appId, userId, reason); 3977 } catch (RemoteException e) { 3978 /* ignore - same process */ 3979 } 3980 } 3981 } finally { 3982 Binder.restoreCallingIdentity(identity); 3983 } 3984 } 3985 3986 /** 3987 * Compares two sets of signatures. Returns: 3988 * <br /> 3989 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3990 * <br /> 3991 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3992 * <br /> 3993 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3994 * <br /> 3995 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3996 * <br /> 3997 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3998 */ 3999 static int compareSignatures(Signature[] s1, Signature[] s2) { 4000 if (s1 == null) { 4001 return s2 == null 4002 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4003 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4004 } 4005 4006 if (s2 == null) { 4007 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4008 } 4009 4010 if (s1.length != s2.length) { 4011 return PackageManager.SIGNATURE_NO_MATCH; 4012 } 4013 4014 // Since both signature sets are of size 1, we can compare without HashSets. 4015 if (s1.length == 1) { 4016 return s1[0].equals(s2[0]) ? 4017 PackageManager.SIGNATURE_MATCH : 4018 PackageManager.SIGNATURE_NO_MATCH; 4019 } 4020 4021 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4022 for (Signature sig : s1) { 4023 set1.add(sig); 4024 } 4025 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4026 for (Signature sig : s2) { 4027 set2.add(sig); 4028 } 4029 // Make sure s2 contains all signatures in s1. 4030 if (set1.equals(set2)) { 4031 return PackageManager.SIGNATURE_MATCH; 4032 } 4033 return PackageManager.SIGNATURE_NO_MATCH; 4034 } 4035 4036 /** 4037 * If the database version for this type of package (internal storage or 4038 * external storage) is less than the version where package signatures 4039 * were updated, return true. 4040 */ 4041 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4042 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4043 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4044 } 4045 4046 /** 4047 * Used for backward compatibility to make sure any packages with 4048 * certificate chains get upgraded to the new style. {@code existingSigs} 4049 * will be in the old format (since they were stored on disk from before the 4050 * system upgrade) and {@code scannedSigs} will be in the newer format. 4051 */ 4052 private int compareSignaturesCompat(PackageSignatures existingSigs, 4053 PackageParser.Package scannedPkg) { 4054 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4055 return PackageManager.SIGNATURE_NO_MATCH; 4056 } 4057 4058 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4059 for (Signature sig : existingSigs.mSignatures) { 4060 existingSet.add(sig); 4061 } 4062 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4063 for (Signature sig : scannedPkg.mSignatures) { 4064 try { 4065 Signature[] chainSignatures = sig.getChainSignatures(); 4066 for (Signature chainSig : chainSignatures) { 4067 scannedCompatSet.add(chainSig); 4068 } 4069 } catch (CertificateEncodingException e) { 4070 scannedCompatSet.add(sig); 4071 } 4072 } 4073 /* 4074 * Make sure the expanded scanned set contains all signatures in the 4075 * existing one. 4076 */ 4077 if (scannedCompatSet.equals(existingSet)) { 4078 // Migrate the old signatures to the new scheme. 4079 existingSigs.assignSignatures(scannedPkg.mSignatures); 4080 // The new KeySets will be re-added later in the scanning process. 4081 synchronized (mPackages) { 4082 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4083 } 4084 return PackageManager.SIGNATURE_MATCH; 4085 } 4086 return PackageManager.SIGNATURE_NO_MATCH; 4087 } 4088 4089 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4090 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4091 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4092 } 4093 4094 private int compareSignaturesRecover(PackageSignatures existingSigs, 4095 PackageParser.Package scannedPkg) { 4096 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4097 return PackageManager.SIGNATURE_NO_MATCH; 4098 } 4099 4100 String msg = null; 4101 try { 4102 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4103 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4104 + scannedPkg.packageName); 4105 return PackageManager.SIGNATURE_MATCH; 4106 } 4107 } catch (CertificateException e) { 4108 msg = e.getMessage(); 4109 } 4110 4111 logCriticalInfo(Log.INFO, 4112 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4113 return PackageManager.SIGNATURE_NO_MATCH; 4114 } 4115 4116 @Override 4117 public String[] getPackagesForUid(int uid) { 4118 uid = UserHandle.getAppId(uid); 4119 // reader 4120 synchronized (mPackages) { 4121 Object obj = mSettings.getUserIdLPr(uid); 4122 if (obj instanceof SharedUserSetting) { 4123 final SharedUserSetting sus = (SharedUserSetting) obj; 4124 final int N = sus.packages.size(); 4125 final String[] res = new String[N]; 4126 final Iterator<PackageSetting> it = sus.packages.iterator(); 4127 int i = 0; 4128 while (it.hasNext()) { 4129 res[i++] = it.next().name; 4130 } 4131 return res; 4132 } else if (obj instanceof PackageSetting) { 4133 final PackageSetting ps = (PackageSetting) obj; 4134 return new String[] { ps.name }; 4135 } 4136 } 4137 return null; 4138 } 4139 4140 @Override 4141 public String getNameForUid(int uid) { 4142 // reader 4143 synchronized (mPackages) { 4144 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4145 if (obj instanceof SharedUserSetting) { 4146 final SharedUserSetting sus = (SharedUserSetting) obj; 4147 return sus.name + ":" + sus.userId; 4148 } else if (obj instanceof PackageSetting) { 4149 final PackageSetting ps = (PackageSetting) obj; 4150 return ps.name; 4151 } 4152 } 4153 return null; 4154 } 4155 4156 @Override 4157 public int getUidForSharedUser(String sharedUserName) { 4158 if(sharedUserName == null) { 4159 return -1; 4160 } 4161 // reader 4162 synchronized (mPackages) { 4163 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4164 if (suid == null) { 4165 return -1; 4166 } 4167 return suid.userId; 4168 } 4169 } 4170 4171 @Override 4172 public int getFlagsForUid(int uid) { 4173 synchronized (mPackages) { 4174 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4175 if (obj instanceof SharedUserSetting) { 4176 final SharedUserSetting sus = (SharedUserSetting) obj; 4177 return sus.pkgFlags; 4178 } else if (obj instanceof PackageSetting) { 4179 final PackageSetting ps = (PackageSetting) obj; 4180 return ps.pkgFlags; 4181 } 4182 } 4183 return 0; 4184 } 4185 4186 @Override 4187 public int getPrivateFlagsForUid(int uid) { 4188 synchronized (mPackages) { 4189 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4190 if (obj instanceof SharedUserSetting) { 4191 final SharedUserSetting sus = (SharedUserSetting) obj; 4192 return sus.pkgPrivateFlags; 4193 } else if (obj instanceof PackageSetting) { 4194 final PackageSetting ps = (PackageSetting) obj; 4195 return ps.pkgPrivateFlags; 4196 } 4197 } 4198 return 0; 4199 } 4200 4201 @Override 4202 public boolean isUidPrivileged(int uid) { 4203 uid = UserHandle.getAppId(uid); 4204 // reader 4205 synchronized (mPackages) { 4206 Object obj = mSettings.getUserIdLPr(uid); 4207 if (obj instanceof SharedUserSetting) { 4208 final SharedUserSetting sus = (SharedUserSetting) obj; 4209 final Iterator<PackageSetting> it = sus.packages.iterator(); 4210 while (it.hasNext()) { 4211 if (it.next().isPrivileged()) { 4212 return true; 4213 } 4214 } 4215 } else if (obj instanceof PackageSetting) { 4216 final PackageSetting ps = (PackageSetting) obj; 4217 return ps.isPrivileged(); 4218 } 4219 } 4220 return false; 4221 } 4222 4223 @Override 4224 public String[] getAppOpPermissionPackages(String permissionName) { 4225 synchronized (mPackages) { 4226 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4227 if (pkgs == null) { 4228 return null; 4229 } 4230 return pkgs.toArray(new String[pkgs.size()]); 4231 } 4232 } 4233 4234 @Override 4235 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4236 int flags, int userId) { 4237 if (!sUserManager.exists(userId)) return null; 4238 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4239 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4240 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4241 } 4242 4243 @Override 4244 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4245 IntentFilter filter, int match, ComponentName activity) { 4246 final int userId = UserHandle.getCallingUserId(); 4247 if (DEBUG_PREFERRED) { 4248 Log.v(TAG, "setLastChosenActivity intent=" + intent 4249 + " resolvedType=" + resolvedType 4250 + " flags=" + flags 4251 + " filter=" + filter 4252 + " match=" + match 4253 + " activity=" + activity); 4254 filter.dump(new PrintStreamPrinter(System.out), " "); 4255 } 4256 intent.setComponent(null); 4257 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4258 // Find any earlier preferred or last chosen entries and nuke them 4259 findPreferredActivity(intent, resolvedType, 4260 flags, query, 0, false, true, false, userId); 4261 // Add the new activity as the last chosen for this filter 4262 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4263 "Setting last chosen"); 4264 } 4265 4266 @Override 4267 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4268 final int userId = UserHandle.getCallingUserId(); 4269 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4270 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4271 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4272 false, false, false, userId); 4273 } 4274 4275 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4276 int flags, List<ResolveInfo> query, int userId) { 4277 if (query != null) { 4278 final int N = query.size(); 4279 if (N == 1) { 4280 return query.get(0); 4281 } else if (N > 1) { 4282 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4283 // If there is more than one activity with the same priority, 4284 // then let the user decide between them. 4285 ResolveInfo r0 = query.get(0); 4286 ResolveInfo r1 = query.get(1); 4287 if (DEBUG_INTENT_MATCHING || debug) { 4288 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4289 + r1.activityInfo.name + "=" + r1.priority); 4290 } 4291 // If the first activity has a higher priority, or a different 4292 // default, then it is always desireable to pick it. 4293 if (r0.priority != r1.priority 4294 || r0.preferredOrder != r1.preferredOrder 4295 || r0.isDefault != r1.isDefault) { 4296 return query.get(0); 4297 } 4298 // If we have saved a preference for a preferred activity for 4299 // this Intent, use that. 4300 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4301 flags, query, r0.priority, true, false, debug, userId); 4302 if (ri != null) { 4303 return ri; 4304 } 4305 ri = new ResolveInfo(mResolveInfo); 4306 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4307 ri.activityInfo.applicationInfo = new ApplicationInfo( 4308 ri.activityInfo.applicationInfo); 4309 if (userId != 0) { 4310 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4311 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4312 } 4313 // Make sure that the resolver is displayable in car mode 4314 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4315 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4316 return ri; 4317 } 4318 } 4319 return null; 4320 } 4321 4322 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4323 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4324 final int N = query.size(); 4325 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4326 .get(userId); 4327 // Get the list of persistent preferred activities that handle the intent 4328 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4329 List<PersistentPreferredActivity> pprefs = ppir != null 4330 ? ppir.queryIntent(intent, resolvedType, 4331 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4332 : null; 4333 if (pprefs != null && pprefs.size() > 0) { 4334 final int M = pprefs.size(); 4335 for (int i=0; i<M; i++) { 4336 final PersistentPreferredActivity ppa = pprefs.get(i); 4337 if (DEBUG_PREFERRED || debug) { 4338 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4339 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4340 + "\n component=" + ppa.mComponent); 4341 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4342 } 4343 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4344 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4345 if (DEBUG_PREFERRED || debug) { 4346 Slog.v(TAG, "Found persistent preferred activity:"); 4347 if (ai != null) { 4348 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4349 } else { 4350 Slog.v(TAG, " null"); 4351 } 4352 } 4353 if (ai == null) { 4354 // This previously registered persistent preferred activity 4355 // component is no longer known. Ignore it and do NOT remove it. 4356 continue; 4357 } 4358 for (int j=0; j<N; j++) { 4359 final ResolveInfo ri = query.get(j); 4360 if (!ri.activityInfo.applicationInfo.packageName 4361 .equals(ai.applicationInfo.packageName)) { 4362 continue; 4363 } 4364 if (!ri.activityInfo.name.equals(ai.name)) { 4365 continue; 4366 } 4367 // Found a persistent preference that can handle the intent. 4368 if (DEBUG_PREFERRED || debug) { 4369 Slog.v(TAG, "Returning persistent preferred activity: " + 4370 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4371 } 4372 return ri; 4373 } 4374 } 4375 } 4376 return null; 4377 } 4378 4379 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4380 List<ResolveInfo> query, int priority, boolean always, 4381 boolean removeMatches, boolean debug, int userId) { 4382 if (!sUserManager.exists(userId)) return null; 4383 // writer 4384 synchronized (mPackages) { 4385 if (intent.getSelector() != null) { 4386 intent = intent.getSelector(); 4387 } 4388 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4389 4390 // Try to find a matching persistent preferred activity. 4391 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4392 debug, userId); 4393 4394 // If a persistent preferred activity matched, use it. 4395 if (pri != null) { 4396 return pri; 4397 } 4398 4399 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4400 // Get the list of preferred activities that handle the intent 4401 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4402 List<PreferredActivity> prefs = pir != null 4403 ? pir.queryIntent(intent, resolvedType, 4404 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4405 : null; 4406 if (prefs != null && prefs.size() > 0) { 4407 boolean changed = false; 4408 try { 4409 // First figure out how good the original match set is. 4410 // We will only allow preferred activities that came 4411 // from the same match quality. 4412 int match = 0; 4413 4414 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4415 4416 final int N = query.size(); 4417 for (int j=0; j<N; j++) { 4418 final ResolveInfo ri = query.get(j); 4419 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4420 + ": 0x" + Integer.toHexString(match)); 4421 if (ri.match > match) { 4422 match = ri.match; 4423 } 4424 } 4425 4426 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4427 + Integer.toHexString(match)); 4428 4429 match &= IntentFilter.MATCH_CATEGORY_MASK; 4430 final int M = prefs.size(); 4431 for (int i=0; i<M; i++) { 4432 final PreferredActivity pa = prefs.get(i); 4433 if (DEBUG_PREFERRED || debug) { 4434 Slog.v(TAG, "Checking PreferredActivity ds=" 4435 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4436 + "\n component=" + pa.mPref.mComponent); 4437 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4438 } 4439 if (pa.mPref.mMatch != match) { 4440 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4441 + Integer.toHexString(pa.mPref.mMatch)); 4442 continue; 4443 } 4444 // If it's not an "always" type preferred activity and that's what we're 4445 // looking for, skip it. 4446 if (always && !pa.mPref.mAlways) { 4447 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4448 continue; 4449 } 4450 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4451 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4452 if (DEBUG_PREFERRED || debug) { 4453 Slog.v(TAG, "Found preferred activity:"); 4454 if (ai != null) { 4455 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4456 } else { 4457 Slog.v(TAG, " null"); 4458 } 4459 } 4460 if (ai == null) { 4461 // This previously registered preferred activity 4462 // component is no longer known. Most likely an update 4463 // to the app was installed and in the new version this 4464 // component no longer exists. Clean it up by removing 4465 // it from the preferred activities list, and skip it. 4466 Slog.w(TAG, "Removing dangling preferred activity: " 4467 + pa.mPref.mComponent); 4468 pir.removeFilter(pa); 4469 changed = true; 4470 continue; 4471 } 4472 for (int j=0; j<N; j++) { 4473 final ResolveInfo ri = query.get(j); 4474 if (!ri.activityInfo.applicationInfo.packageName 4475 .equals(ai.applicationInfo.packageName)) { 4476 continue; 4477 } 4478 if (!ri.activityInfo.name.equals(ai.name)) { 4479 continue; 4480 } 4481 4482 if (removeMatches) { 4483 pir.removeFilter(pa); 4484 changed = true; 4485 if (DEBUG_PREFERRED) { 4486 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4487 } 4488 break; 4489 } 4490 4491 // Okay we found a previously set preferred or last chosen app. 4492 // If the result set is different from when this 4493 // was created, we need to clear it and re-ask the 4494 // user their preference, if we're looking for an "always" type entry. 4495 if (always && !pa.mPref.sameSet(query)) { 4496 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4497 + intent + " type " + resolvedType); 4498 if (DEBUG_PREFERRED) { 4499 Slog.v(TAG, "Removing preferred activity since set changed " 4500 + pa.mPref.mComponent); 4501 } 4502 pir.removeFilter(pa); 4503 // Re-add the filter as a "last chosen" entry (!always) 4504 PreferredActivity lastChosen = new PreferredActivity( 4505 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4506 pir.addFilter(lastChosen); 4507 changed = true; 4508 return null; 4509 } 4510 4511 // Yay! Either the set matched or we're looking for the last chosen 4512 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4513 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4514 return ri; 4515 } 4516 } 4517 } finally { 4518 if (changed) { 4519 if (DEBUG_PREFERRED) { 4520 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4521 } 4522 scheduleWritePackageRestrictionsLocked(userId); 4523 } 4524 } 4525 } 4526 } 4527 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4528 return null; 4529 } 4530 4531 /* 4532 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4533 */ 4534 @Override 4535 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4536 int targetUserId) { 4537 mContext.enforceCallingOrSelfPermission( 4538 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4539 List<CrossProfileIntentFilter> matches = 4540 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4541 if (matches != null) { 4542 int size = matches.size(); 4543 for (int i = 0; i < size; i++) { 4544 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4545 } 4546 } 4547 if (hasWebURI(intent)) { 4548 // cross-profile app linking works only towards the parent. 4549 final UserInfo parent = getProfileParent(sourceUserId); 4550 synchronized(mPackages) { 4551 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4552 intent, resolvedType, 0, sourceUserId, parent.id); 4553 return xpDomainInfo != null; 4554 } 4555 } 4556 return false; 4557 } 4558 4559 private UserInfo getProfileParent(int userId) { 4560 final long identity = Binder.clearCallingIdentity(); 4561 try { 4562 return sUserManager.getProfileParent(userId); 4563 } finally { 4564 Binder.restoreCallingIdentity(identity); 4565 } 4566 } 4567 4568 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4569 String resolvedType, int userId) { 4570 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4571 if (resolver != null) { 4572 return resolver.queryIntent(intent, resolvedType, false, userId); 4573 } 4574 return null; 4575 } 4576 4577 @Override 4578 public List<ResolveInfo> queryIntentActivities(Intent intent, 4579 String resolvedType, int flags, int userId) { 4580 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4581 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4582 ComponentName comp = intent.getComponent(); 4583 if (comp == null) { 4584 if (intent.getSelector() != null) { 4585 intent = intent.getSelector(); 4586 comp = intent.getComponent(); 4587 } 4588 } 4589 4590 if (comp != null) { 4591 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4592 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4593 if (ai != null) { 4594 final ResolveInfo ri = new ResolveInfo(); 4595 ri.activityInfo = ai; 4596 list.add(ri); 4597 } 4598 return list; 4599 } 4600 4601 // reader 4602 synchronized (mPackages) { 4603 final String pkgName = intent.getPackage(); 4604 if (pkgName == null) { 4605 List<CrossProfileIntentFilter> matchingFilters = 4606 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4607 // Check for results that need to skip the current profile. 4608 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4609 resolvedType, flags, userId); 4610 if (xpResolveInfo != null) { 4611 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4612 result.add(xpResolveInfo); 4613 return filterIfNotSystemUser(result, userId); 4614 } 4615 4616 // Check for results in the current profile. 4617 List<ResolveInfo> result = mActivities.queryIntent( 4618 intent, resolvedType, flags, userId); 4619 4620 // Check for cross profile results. 4621 xpResolveInfo = queryCrossProfileIntents( 4622 matchingFilters, intent, resolvedType, flags, userId); 4623 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4624 result.add(xpResolveInfo); 4625 Collections.sort(result, mResolvePrioritySorter); 4626 } 4627 result = filterIfNotSystemUser(result, userId); 4628 if (hasWebURI(intent)) { 4629 CrossProfileDomainInfo xpDomainInfo = null; 4630 final UserInfo parent = getProfileParent(userId); 4631 if (parent != null) { 4632 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4633 flags, userId, parent.id); 4634 } 4635 if (xpDomainInfo != null) { 4636 if (xpResolveInfo != null) { 4637 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4638 // in the result. 4639 result.remove(xpResolveInfo); 4640 } 4641 if (result.size() == 0) { 4642 result.add(xpDomainInfo.resolveInfo); 4643 return result; 4644 } 4645 } else if (result.size() <= 1) { 4646 return result; 4647 } 4648 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4649 xpDomainInfo, userId); 4650 Collections.sort(result, mResolvePrioritySorter); 4651 } 4652 return result; 4653 } 4654 final PackageParser.Package pkg = mPackages.get(pkgName); 4655 if (pkg != null) { 4656 return filterIfNotSystemUser( 4657 mActivities.queryIntentForPackage( 4658 intent, resolvedType, flags, pkg.activities, userId), 4659 userId); 4660 } 4661 return new ArrayList<ResolveInfo>(); 4662 } 4663 } 4664 4665 private static class CrossProfileDomainInfo { 4666 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4667 ResolveInfo resolveInfo; 4668 /* Best domain verification status of the activities found in the other profile */ 4669 int bestDomainVerificationStatus; 4670 } 4671 4672 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4673 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4674 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4675 sourceUserId)) { 4676 return null; 4677 } 4678 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4679 resolvedType, flags, parentUserId); 4680 4681 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4682 return null; 4683 } 4684 CrossProfileDomainInfo result = null; 4685 int size = resultTargetUser.size(); 4686 for (int i = 0; i < size; i++) { 4687 ResolveInfo riTargetUser = resultTargetUser.get(i); 4688 // Intent filter verification is only for filters that specify a host. So don't return 4689 // those that handle all web uris. 4690 if (riTargetUser.handleAllWebDataURI) { 4691 continue; 4692 } 4693 String packageName = riTargetUser.activityInfo.packageName; 4694 PackageSetting ps = mSettings.mPackages.get(packageName); 4695 if (ps == null) { 4696 continue; 4697 } 4698 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4699 int status = (int)(verificationState >> 32); 4700 if (result == null) { 4701 result = new CrossProfileDomainInfo(); 4702 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 4703 sourceUserId, parentUserId); 4704 result.bestDomainVerificationStatus = status; 4705 } else { 4706 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4707 result.bestDomainVerificationStatus); 4708 } 4709 } 4710 // Don't consider matches with status NEVER across profiles. 4711 if (result != null && result.bestDomainVerificationStatus 4712 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4713 return null; 4714 } 4715 return result; 4716 } 4717 4718 /** 4719 * Verification statuses are ordered from the worse to the best, except for 4720 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4721 */ 4722 private int bestDomainVerificationStatus(int status1, int status2) { 4723 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4724 return status2; 4725 } 4726 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4727 return status1; 4728 } 4729 return (int) MathUtils.max(status1, status2); 4730 } 4731 4732 private boolean isUserEnabled(int userId) { 4733 long callingId = Binder.clearCallingIdentity(); 4734 try { 4735 UserInfo userInfo = sUserManager.getUserInfo(userId); 4736 return userInfo != null && userInfo.isEnabled(); 4737 } finally { 4738 Binder.restoreCallingIdentity(callingId); 4739 } 4740 } 4741 4742 /** 4743 * Filter out activities with systemUserOnly flag set, when current user is not System. 4744 * 4745 * @return filtered list 4746 */ 4747 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 4748 if (userId == UserHandle.USER_SYSTEM) { 4749 return resolveInfos; 4750 } 4751 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4752 ResolveInfo info = resolveInfos.get(i); 4753 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 4754 resolveInfos.remove(i); 4755 } 4756 } 4757 return resolveInfos; 4758 } 4759 4760 private static boolean hasWebURI(Intent intent) { 4761 if (intent.getData() == null) { 4762 return false; 4763 } 4764 final String scheme = intent.getScheme(); 4765 if (TextUtils.isEmpty(scheme)) { 4766 return false; 4767 } 4768 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4769 } 4770 4771 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4772 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4773 int userId) { 4774 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4775 4776 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4777 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4778 candidates.size()); 4779 } 4780 4781 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4782 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4783 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4784 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 4785 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4786 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4787 4788 synchronized (mPackages) { 4789 final int count = candidates.size(); 4790 // First, try to use linked apps. Partition the candidates into four lists: 4791 // one for the final results, one for the "do not use ever", one for "undefined status" 4792 // and finally one for "browser app type". 4793 for (int n=0; n<count; n++) { 4794 ResolveInfo info = candidates.get(n); 4795 String packageName = info.activityInfo.packageName; 4796 PackageSetting ps = mSettings.mPackages.get(packageName); 4797 if (ps != null) { 4798 // Add to the special match all list (Browser use case) 4799 if (info.handleAllWebDataURI) { 4800 matchAllList.add(info); 4801 continue; 4802 } 4803 // Try to get the status from User settings first 4804 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4805 int status = (int)(packedStatus >> 32); 4806 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4807 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4808 if (DEBUG_DOMAIN_VERIFICATION) { 4809 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4810 + " : linkgen=" + linkGeneration); 4811 } 4812 // Use link-enabled generation as preferredOrder, i.e. 4813 // prefer newly-enabled over earlier-enabled. 4814 info.preferredOrder = linkGeneration; 4815 alwaysList.add(info); 4816 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4817 if (DEBUG_DOMAIN_VERIFICATION) { 4818 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4819 } 4820 neverList.add(info); 4821 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4822 if (DEBUG_DOMAIN_VERIFICATION) { 4823 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 4824 } 4825 alwaysAskList.add(info); 4826 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4827 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4828 if (DEBUG_DOMAIN_VERIFICATION) { 4829 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4830 } 4831 undefinedList.add(info); 4832 } 4833 } 4834 } 4835 4836 // We'll want to include browser possibilities in a few cases 4837 boolean includeBrowser = false; 4838 4839 // First try to add the "always" resolution(s) for the current user, if any 4840 if (alwaysList.size() > 0) { 4841 result.addAll(alwaysList); 4842 } else { 4843 // Add all undefined apps as we want them to appear in the disambiguation dialog. 4844 result.addAll(undefinedList); 4845 // Maybe add one for the other profile. 4846 if (xpDomainInfo != null && ( 4847 xpDomainInfo.bestDomainVerificationStatus 4848 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 4849 result.add(xpDomainInfo.resolveInfo); 4850 } 4851 includeBrowser = true; 4852 } 4853 4854 // The presence of any 'always ask' alternatives means we'll also offer browsers. 4855 // If there were 'always' entries their preferred order has been set, so we also 4856 // back that off to make the alternatives equivalent 4857 if (alwaysAskList.size() > 0) { 4858 for (ResolveInfo i : result) { 4859 i.preferredOrder = 0; 4860 } 4861 result.addAll(alwaysAskList); 4862 includeBrowser = true; 4863 } 4864 4865 if (includeBrowser) { 4866 // Also add browsers (all of them or only the default one) 4867 if (DEBUG_DOMAIN_VERIFICATION) { 4868 Slog.v(TAG, " ...including browsers in candidate set"); 4869 } 4870 if ((matchFlags & MATCH_ALL) != 0) { 4871 result.addAll(matchAllList); 4872 } else { 4873 // Browser/generic handling case. If there's a default browser, go straight 4874 // to that (but only if there is no other higher-priority match). 4875 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4876 int maxMatchPrio = 0; 4877 ResolveInfo defaultBrowserMatch = null; 4878 final int numCandidates = matchAllList.size(); 4879 for (int n = 0; n < numCandidates; n++) { 4880 ResolveInfo info = matchAllList.get(n); 4881 // track the highest overall match priority... 4882 if (info.priority > maxMatchPrio) { 4883 maxMatchPrio = info.priority; 4884 } 4885 // ...and the highest-priority default browser match 4886 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4887 if (defaultBrowserMatch == null 4888 || (defaultBrowserMatch.priority < info.priority)) { 4889 if (debug) { 4890 Slog.v(TAG, "Considering default browser match " + info); 4891 } 4892 defaultBrowserMatch = info; 4893 } 4894 } 4895 } 4896 if (defaultBrowserMatch != null 4897 && defaultBrowserMatch.priority >= maxMatchPrio 4898 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4899 { 4900 if (debug) { 4901 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4902 } 4903 result.add(defaultBrowserMatch); 4904 } else { 4905 result.addAll(matchAllList); 4906 } 4907 } 4908 4909 // If there is nothing selected, add all candidates and remove the ones that the user 4910 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4911 if (result.size() == 0) { 4912 result.addAll(candidates); 4913 result.removeAll(neverList); 4914 } 4915 } 4916 } 4917 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4918 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4919 result.size()); 4920 for (ResolveInfo info : result) { 4921 Slog.v(TAG, " + " + info.activityInfo); 4922 } 4923 } 4924 return result; 4925 } 4926 4927 // Returns a packed value as a long: 4928 // 4929 // high 'int'-sized word: link status: undefined/ask/never/always. 4930 // low 'int'-sized word: relative priority among 'always' results. 4931 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4932 long result = ps.getDomainVerificationStatusForUser(userId); 4933 // if none available, get the master status 4934 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4935 if (ps.getIntentFilterVerificationInfo() != null) { 4936 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4937 } 4938 } 4939 return result; 4940 } 4941 4942 private ResolveInfo querySkipCurrentProfileIntents( 4943 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4944 int flags, int sourceUserId) { 4945 if (matchingFilters != null) { 4946 int size = matchingFilters.size(); 4947 for (int i = 0; i < size; i ++) { 4948 CrossProfileIntentFilter filter = matchingFilters.get(i); 4949 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4950 // Checking if there are activities in the target user that can handle the 4951 // intent. 4952 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4953 resolvedType, flags, sourceUserId); 4954 if (resolveInfo != null) { 4955 return resolveInfo; 4956 } 4957 } 4958 } 4959 } 4960 return null; 4961 } 4962 4963 // Return matching ResolveInfo if any for skip current profile intent filters. 4964 private ResolveInfo queryCrossProfileIntents( 4965 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4966 int flags, int sourceUserId) { 4967 if (matchingFilters != null) { 4968 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4969 // match the same intent. For performance reasons, it is better not to 4970 // run queryIntent twice for the same userId 4971 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4972 int size = matchingFilters.size(); 4973 for (int i = 0; i < size; i++) { 4974 CrossProfileIntentFilter filter = matchingFilters.get(i); 4975 int targetUserId = filter.getTargetUserId(); 4976 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4977 && !alreadyTriedUserIds.get(targetUserId)) { 4978 // Checking if there are activities in the target user that can handle the 4979 // intent. 4980 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 4981 resolvedType, flags, sourceUserId); 4982 if (resolveInfo != null) return resolveInfo; 4983 alreadyTriedUserIds.put(targetUserId, true); 4984 } 4985 } 4986 } 4987 return null; 4988 } 4989 4990 /** 4991 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 4992 * will forward the intent to the filter's target user. 4993 * Otherwise, returns null. 4994 */ 4995 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 4996 String resolvedType, int flags, int sourceUserId) { 4997 int targetUserId = filter.getTargetUserId(); 4998 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4999 resolvedType, flags, targetUserId); 5000 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5001 && isUserEnabled(targetUserId)) { 5002 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5003 } 5004 return null; 5005 } 5006 5007 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5008 int sourceUserId, int targetUserId) { 5009 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5010 long ident = Binder.clearCallingIdentity(); 5011 boolean targetIsProfile; 5012 try { 5013 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5014 } finally { 5015 Binder.restoreCallingIdentity(ident); 5016 } 5017 String className; 5018 if (targetIsProfile) { 5019 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5020 } else { 5021 className = FORWARD_INTENT_TO_PARENT; 5022 } 5023 ComponentName forwardingActivityComponentName = new ComponentName( 5024 mAndroidApplication.packageName, className); 5025 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5026 sourceUserId); 5027 if (!targetIsProfile) { 5028 forwardingActivityInfo.showUserIcon = targetUserId; 5029 forwardingResolveInfo.noResourceId = true; 5030 } 5031 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5032 forwardingResolveInfo.priority = 0; 5033 forwardingResolveInfo.preferredOrder = 0; 5034 forwardingResolveInfo.match = 0; 5035 forwardingResolveInfo.isDefault = true; 5036 forwardingResolveInfo.filter = filter; 5037 forwardingResolveInfo.targetUserId = targetUserId; 5038 return forwardingResolveInfo; 5039 } 5040 5041 @Override 5042 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5043 Intent[] specifics, String[] specificTypes, Intent intent, 5044 String resolvedType, int flags, int userId) { 5045 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5046 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5047 false, "query intent activity options"); 5048 final String resultsAction = intent.getAction(); 5049 5050 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5051 | PackageManager.GET_RESOLVED_FILTER, userId); 5052 5053 if (DEBUG_INTENT_MATCHING) { 5054 Log.v(TAG, "Query " + intent + ": " + results); 5055 } 5056 5057 int specificsPos = 0; 5058 int N; 5059 5060 // todo: note that the algorithm used here is O(N^2). This 5061 // isn't a problem in our current environment, but if we start running 5062 // into situations where we have more than 5 or 10 matches then this 5063 // should probably be changed to something smarter... 5064 5065 // First we go through and resolve each of the specific items 5066 // that were supplied, taking care of removing any corresponding 5067 // duplicate items in the generic resolve list. 5068 if (specifics != null) { 5069 for (int i=0; i<specifics.length; i++) { 5070 final Intent sintent = specifics[i]; 5071 if (sintent == null) { 5072 continue; 5073 } 5074 5075 if (DEBUG_INTENT_MATCHING) { 5076 Log.v(TAG, "Specific #" + i + ": " + sintent); 5077 } 5078 5079 String action = sintent.getAction(); 5080 if (resultsAction != null && resultsAction.equals(action)) { 5081 // If this action was explicitly requested, then don't 5082 // remove things that have it. 5083 action = null; 5084 } 5085 5086 ResolveInfo ri = null; 5087 ActivityInfo ai = null; 5088 5089 ComponentName comp = sintent.getComponent(); 5090 if (comp == null) { 5091 ri = resolveIntent( 5092 sintent, 5093 specificTypes != null ? specificTypes[i] : null, 5094 flags, userId); 5095 if (ri == null) { 5096 continue; 5097 } 5098 if (ri == mResolveInfo) { 5099 // ACK! Must do something better with this. 5100 } 5101 ai = ri.activityInfo; 5102 comp = new ComponentName(ai.applicationInfo.packageName, 5103 ai.name); 5104 } else { 5105 ai = getActivityInfo(comp, flags, userId); 5106 if (ai == null) { 5107 continue; 5108 } 5109 } 5110 5111 // Look for any generic query activities that are duplicates 5112 // of this specific one, and remove them from the results. 5113 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5114 N = results.size(); 5115 int j; 5116 for (j=specificsPos; j<N; j++) { 5117 ResolveInfo sri = results.get(j); 5118 if ((sri.activityInfo.name.equals(comp.getClassName()) 5119 && sri.activityInfo.applicationInfo.packageName.equals( 5120 comp.getPackageName())) 5121 || (action != null && sri.filter.matchAction(action))) { 5122 results.remove(j); 5123 if (DEBUG_INTENT_MATCHING) Log.v( 5124 TAG, "Removing duplicate item from " + j 5125 + " due to specific " + specificsPos); 5126 if (ri == null) { 5127 ri = sri; 5128 } 5129 j--; 5130 N--; 5131 } 5132 } 5133 5134 // Add this specific item to its proper place. 5135 if (ri == null) { 5136 ri = new ResolveInfo(); 5137 ri.activityInfo = ai; 5138 } 5139 results.add(specificsPos, ri); 5140 ri.specificIndex = i; 5141 specificsPos++; 5142 } 5143 } 5144 5145 // Now we go through the remaining generic results and remove any 5146 // duplicate actions that are found here. 5147 N = results.size(); 5148 for (int i=specificsPos; i<N-1; i++) { 5149 final ResolveInfo rii = results.get(i); 5150 if (rii.filter == null) { 5151 continue; 5152 } 5153 5154 // Iterate over all of the actions of this result's intent 5155 // filter... typically this should be just one. 5156 final Iterator<String> it = rii.filter.actionsIterator(); 5157 if (it == null) { 5158 continue; 5159 } 5160 while (it.hasNext()) { 5161 final String action = it.next(); 5162 if (resultsAction != null && resultsAction.equals(action)) { 5163 // If this action was explicitly requested, then don't 5164 // remove things that have it. 5165 continue; 5166 } 5167 for (int j=i+1; j<N; j++) { 5168 final ResolveInfo rij = results.get(j); 5169 if (rij.filter != null && rij.filter.hasAction(action)) { 5170 results.remove(j); 5171 if (DEBUG_INTENT_MATCHING) Log.v( 5172 TAG, "Removing duplicate item from " + j 5173 + " due to action " + action + " at " + i); 5174 j--; 5175 N--; 5176 } 5177 } 5178 } 5179 5180 // If the caller didn't request filter information, drop it now 5181 // so we don't have to marshall/unmarshall it. 5182 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5183 rii.filter = null; 5184 } 5185 } 5186 5187 // Filter out the caller activity if so requested. 5188 if (caller != null) { 5189 N = results.size(); 5190 for (int i=0; i<N; i++) { 5191 ActivityInfo ainfo = results.get(i).activityInfo; 5192 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5193 && caller.getClassName().equals(ainfo.name)) { 5194 results.remove(i); 5195 break; 5196 } 5197 } 5198 } 5199 5200 // If the caller didn't request filter information, 5201 // drop them now so we don't have to 5202 // marshall/unmarshall it. 5203 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5204 N = results.size(); 5205 for (int i=0; i<N; i++) { 5206 results.get(i).filter = null; 5207 } 5208 } 5209 5210 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5211 return results; 5212 } 5213 5214 @Override 5215 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5216 int userId) { 5217 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5218 ComponentName comp = intent.getComponent(); 5219 if (comp == null) { 5220 if (intent.getSelector() != null) { 5221 intent = intent.getSelector(); 5222 comp = intent.getComponent(); 5223 } 5224 } 5225 if (comp != null) { 5226 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5227 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5228 if (ai != null) { 5229 ResolveInfo ri = new ResolveInfo(); 5230 ri.activityInfo = ai; 5231 list.add(ri); 5232 } 5233 return list; 5234 } 5235 5236 // reader 5237 synchronized (mPackages) { 5238 String pkgName = intent.getPackage(); 5239 if (pkgName == null) { 5240 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5241 } 5242 final PackageParser.Package pkg = mPackages.get(pkgName); 5243 if (pkg != null) { 5244 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5245 userId); 5246 } 5247 return null; 5248 } 5249 } 5250 5251 @Override 5252 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5253 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5254 if (!sUserManager.exists(userId)) return null; 5255 if (query != null) { 5256 if (query.size() >= 1) { 5257 // If there is more than one service with the same priority, 5258 // just arbitrarily pick the first one. 5259 return query.get(0); 5260 } 5261 } 5262 return null; 5263 } 5264 5265 @Override 5266 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5267 int userId) { 5268 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5269 ComponentName comp = intent.getComponent(); 5270 if (comp == null) { 5271 if (intent.getSelector() != null) { 5272 intent = intent.getSelector(); 5273 comp = intent.getComponent(); 5274 } 5275 } 5276 if (comp != null) { 5277 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5278 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5279 if (si != null) { 5280 final ResolveInfo ri = new ResolveInfo(); 5281 ri.serviceInfo = si; 5282 list.add(ri); 5283 } 5284 return list; 5285 } 5286 5287 // reader 5288 synchronized (mPackages) { 5289 String pkgName = intent.getPackage(); 5290 if (pkgName == null) { 5291 return mServices.queryIntent(intent, resolvedType, flags, userId); 5292 } 5293 final PackageParser.Package pkg = mPackages.get(pkgName); 5294 if (pkg != null) { 5295 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5296 userId); 5297 } 5298 return null; 5299 } 5300 } 5301 5302 @Override 5303 public List<ResolveInfo> queryIntentContentProviders( 5304 Intent intent, String resolvedType, int flags, int userId) { 5305 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5306 ComponentName comp = intent.getComponent(); 5307 if (comp == null) { 5308 if (intent.getSelector() != null) { 5309 intent = intent.getSelector(); 5310 comp = intent.getComponent(); 5311 } 5312 } 5313 if (comp != null) { 5314 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5315 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5316 if (pi != null) { 5317 final ResolveInfo ri = new ResolveInfo(); 5318 ri.providerInfo = pi; 5319 list.add(ri); 5320 } 5321 return list; 5322 } 5323 5324 // reader 5325 synchronized (mPackages) { 5326 String pkgName = intent.getPackage(); 5327 if (pkgName == null) { 5328 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5329 } 5330 final PackageParser.Package pkg = mPackages.get(pkgName); 5331 if (pkg != null) { 5332 return mProviders.queryIntentForPackage( 5333 intent, resolvedType, flags, pkg.providers, userId); 5334 } 5335 return null; 5336 } 5337 } 5338 5339 @Override 5340 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5341 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5342 5343 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5344 5345 // writer 5346 synchronized (mPackages) { 5347 ArrayList<PackageInfo> list; 5348 if (listUninstalled) { 5349 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5350 for (PackageSetting ps : mSettings.mPackages.values()) { 5351 PackageInfo pi; 5352 if (ps.pkg != null) { 5353 pi = generatePackageInfo(ps.pkg, flags, userId); 5354 } else { 5355 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5356 } 5357 if (pi != null) { 5358 list.add(pi); 5359 } 5360 } 5361 } else { 5362 list = new ArrayList<PackageInfo>(mPackages.size()); 5363 for (PackageParser.Package p : mPackages.values()) { 5364 PackageInfo pi = generatePackageInfo(p, flags, userId); 5365 if (pi != null) { 5366 list.add(pi); 5367 } 5368 } 5369 } 5370 5371 return new ParceledListSlice<PackageInfo>(list); 5372 } 5373 } 5374 5375 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5376 String[] permissions, boolean[] tmp, int flags, int userId) { 5377 int numMatch = 0; 5378 final PermissionsState permissionsState = ps.getPermissionsState(); 5379 for (int i=0; i<permissions.length; i++) { 5380 final String permission = permissions[i]; 5381 if (permissionsState.hasPermission(permission, userId)) { 5382 tmp[i] = true; 5383 numMatch++; 5384 } else { 5385 tmp[i] = false; 5386 } 5387 } 5388 if (numMatch == 0) { 5389 return; 5390 } 5391 PackageInfo pi; 5392 if (ps.pkg != null) { 5393 pi = generatePackageInfo(ps.pkg, flags, userId); 5394 } else { 5395 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5396 } 5397 // The above might return null in cases of uninstalled apps or install-state 5398 // skew across users/profiles. 5399 if (pi != null) { 5400 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5401 if (numMatch == permissions.length) { 5402 pi.requestedPermissions = permissions; 5403 } else { 5404 pi.requestedPermissions = new String[numMatch]; 5405 numMatch = 0; 5406 for (int i=0; i<permissions.length; i++) { 5407 if (tmp[i]) { 5408 pi.requestedPermissions[numMatch] = permissions[i]; 5409 numMatch++; 5410 } 5411 } 5412 } 5413 } 5414 list.add(pi); 5415 } 5416 } 5417 5418 @Override 5419 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5420 String[] permissions, int flags, int userId) { 5421 if (!sUserManager.exists(userId)) return null; 5422 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5423 5424 // writer 5425 synchronized (mPackages) { 5426 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5427 boolean[] tmpBools = new boolean[permissions.length]; 5428 if (listUninstalled) { 5429 for (PackageSetting ps : mSettings.mPackages.values()) { 5430 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5431 } 5432 } else { 5433 for (PackageParser.Package pkg : mPackages.values()) { 5434 PackageSetting ps = (PackageSetting)pkg.mExtras; 5435 if (ps != null) { 5436 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5437 userId); 5438 } 5439 } 5440 } 5441 5442 return new ParceledListSlice<PackageInfo>(list); 5443 } 5444 } 5445 5446 @Override 5447 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5448 if (!sUserManager.exists(userId)) return null; 5449 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5450 5451 // writer 5452 synchronized (mPackages) { 5453 ArrayList<ApplicationInfo> list; 5454 if (listUninstalled) { 5455 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5456 for (PackageSetting ps : mSettings.mPackages.values()) { 5457 ApplicationInfo ai; 5458 if (ps.pkg != null) { 5459 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5460 ps.readUserState(userId), userId); 5461 } else { 5462 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5463 } 5464 if (ai != null) { 5465 list.add(ai); 5466 } 5467 } 5468 } else { 5469 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5470 for (PackageParser.Package p : mPackages.values()) { 5471 if (p.mExtras != null) { 5472 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5473 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5474 if (ai != null) { 5475 list.add(ai); 5476 } 5477 } 5478 } 5479 } 5480 5481 return new ParceledListSlice<ApplicationInfo>(list); 5482 } 5483 } 5484 5485 public List<ApplicationInfo> getPersistentApplications(int flags) { 5486 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5487 5488 // reader 5489 synchronized (mPackages) { 5490 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5491 final int userId = UserHandle.getCallingUserId(); 5492 while (i.hasNext()) { 5493 final PackageParser.Package p = i.next(); 5494 if (p.applicationInfo != null 5495 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5496 && (!mSafeMode || isSystemApp(p))) { 5497 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5498 if (ps != null) { 5499 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5500 ps.readUserState(userId), userId); 5501 if (ai != null) { 5502 finalList.add(ai); 5503 } 5504 } 5505 } 5506 } 5507 } 5508 5509 return finalList; 5510 } 5511 5512 @Override 5513 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5514 if (!sUserManager.exists(userId)) return null; 5515 // reader 5516 synchronized (mPackages) { 5517 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5518 PackageSetting ps = provider != null 5519 ? mSettings.mPackages.get(provider.owner.packageName) 5520 : null; 5521 return ps != null 5522 && mSettings.isEnabledLPr(provider.info, flags, userId) 5523 && (!mSafeMode || (provider.info.applicationInfo.flags 5524 &ApplicationInfo.FLAG_SYSTEM) != 0) 5525 ? PackageParser.generateProviderInfo(provider, flags, 5526 ps.readUserState(userId), userId) 5527 : null; 5528 } 5529 } 5530 5531 /** 5532 * @deprecated 5533 */ 5534 @Deprecated 5535 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5536 // reader 5537 synchronized (mPackages) { 5538 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5539 .entrySet().iterator(); 5540 final int userId = UserHandle.getCallingUserId(); 5541 while (i.hasNext()) { 5542 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5543 PackageParser.Provider p = entry.getValue(); 5544 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5545 5546 if (ps != null && p.syncable 5547 && (!mSafeMode || (p.info.applicationInfo.flags 5548 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5549 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5550 ps.readUserState(userId), userId); 5551 if (info != null) { 5552 outNames.add(entry.getKey()); 5553 outInfo.add(info); 5554 } 5555 } 5556 } 5557 } 5558 } 5559 5560 @Override 5561 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5562 int uid, int flags) { 5563 ArrayList<ProviderInfo> finalList = null; 5564 // reader 5565 synchronized (mPackages) { 5566 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5567 final int userId = processName != null ? 5568 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5569 while (i.hasNext()) { 5570 final PackageParser.Provider p = i.next(); 5571 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5572 if (ps != null && p.info.authority != null 5573 && (processName == null 5574 || (p.info.processName.equals(processName) 5575 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5576 && mSettings.isEnabledLPr(p.info, flags, userId) 5577 && (!mSafeMode 5578 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5579 if (finalList == null) { 5580 finalList = new ArrayList<ProviderInfo>(3); 5581 } 5582 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5583 ps.readUserState(userId), userId); 5584 if (info != null) { 5585 finalList.add(info); 5586 } 5587 } 5588 } 5589 } 5590 5591 if (finalList != null) { 5592 Collections.sort(finalList, mProviderInitOrderSorter); 5593 return new ParceledListSlice<ProviderInfo>(finalList); 5594 } 5595 5596 return null; 5597 } 5598 5599 @Override 5600 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5601 int flags) { 5602 // reader 5603 synchronized (mPackages) { 5604 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5605 return PackageParser.generateInstrumentationInfo(i, flags); 5606 } 5607 } 5608 5609 @Override 5610 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5611 int flags) { 5612 ArrayList<InstrumentationInfo> finalList = 5613 new ArrayList<InstrumentationInfo>(); 5614 5615 // reader 5616 synchronized (mPackages) { 5617 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5618 while (i.hasNext()) { 5619 final PackageParser.Instrumentation p = i.next(); 5620 if (targetPackage == null 5621 || targetPackage.equals(p.info.targetPackage)) { 5622 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5623 flags); 5624 if (ii != null) { 5625 finalList.add(ii); 5626 } 5627 } 5628 } 5629 } 5630 5631 return finalList; 5632 } 5633 5634 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5635 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5636 if (overlays == null) { 5637 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5638 return; 5639 } 5640 for (PackageParser.Package opkg : overlays.values()) { 5641 // Not much to do if idmap fails: we already logged the error 5642 // and we certainly don't want to abort installation of pkg simply 5643 // because an overlay didn't fit properly. For these reasons, 5644 // ignore the return value of createIdmapForPackagePairLI. 5645 createIdmapForPackagePairLI(pkg, opkg); 5646 } 5647 } 5648 5649 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5650 PackageParser.Package opkg) { 5651 if (!opkg.mTrustedOverlay) { 5652 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5653 opkg.baseCodePath + ": overlay not trusted"); 5654 return false; 5655 } 5656 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5657 if (overlaySet == null) { 5658 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5659 opkg.baseCodePath + " but target package has no known overlays"); 5660 return false; 5661 } 5662 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5663 // TODO: generate idmap for split APKs 5664 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5665 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5666 + opkg.baseCodePath); 5667 return false; 5668 } 5669 PackageParser.Package[] overlayArray = 5670 overlaySet.values().toArray(new PackageParser.Package[0]); 5671 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5672 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5673 return p1.mOverlayPriority - p2.mOverlayPriority; 5674 } 5675 }; 5676 Arrays.sort(overlayArray, cmp); 5677 5678 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5679 int i = 0; 5680 for (PackageParser.Package p : overlayArray) { 5681 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5682 } 5683 return true; 5684 } 5685 5686 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5687 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 5688 try { 5689 scanDirLI(dir, parseFlags, scanFlags, currentTime); 5690 } finally { 5691 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5692 } 5693 } 5694 5695 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5696 final File[] files = dir.listFiles(); 5697 if (ArrayUtils.isEmpty(files)) { 5698 Log.d(TAG, "No files in app dir " + dir); 5699 return; 5700 } 5701 5702 if (DEBUG_PACKAGE_SCANNING) { 5703 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5704 + " flags=0x" + Integer.toHexString(parseFlags)); 5705 } 5706 5707 for (File file : files) { 5708 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5709 && !PackageInstallerService.isStageName(file.getName()); 5710 if (!isPackage) { 5711 // Ignore entries which are not packages 5712 continue; 5713 } 5714 try { 5715 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5716 scanFlags, currentTime, null); 5717 } catch (PackageManagerException e) { 5718 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5719 5720 // Delete invalid userdata apps 5721 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5722 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5723 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5724 if (file.isDirectory()) { 5725 mInstaller.rmPackageDir(file.getAbsolutePath()); 5726 } else { 5727 file.delete(); 5728 } 5729 } 5730 } 5731 } 5732 } 5733 5734 private static File getSettingsProblemFile() { 5735 File dataDir = Environment.getDataDirectory(); 5736 File systemDir = new File(dataDir, "system"); 5737 File fname = new File(systemDir, "uiderrors.txt"); 5738 return fname; 5739 } 5740 5741 static void reportSettingsProblem(int priority, String msg) { 5742 logCriticalInfo(priority, msg); 5743 } 5744 5745 static void logCriticalInfo(int priority, String msg) { 5746 Slog.println(priority, TAG, msg); 5747 EventLogTags.writePmCriticalInfo(msg); 5748 try { 5749 File fname = getSettingsProblemFile(); 5750 FileOutputStream out = new FileOutputStream(fname, true); 5751 PrintWriter pw = new FastPrintWriter(out); 5752 SimpleDateFormat formatter = new SimpleDateFormat(); 5753 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5754 pw.println(dateString + ": " + msg); 5755 pw.close(); 5756 FileUtils.setPermissions( 5757 fname.toString(), 5758 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5759 -1, -1); 5760 } catch (java.io.IOException e) { 5761 } 5762 } 5763 5764 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5765 PackageParser.Package pkg, File srcFile, int parseFlags) 5766 throws PackageManagerException { 5767 if (ps != null 5768 && ps.codePath.equals(srcFile) 5769 && ps.timeStamp == srcFile.lastModified() 5770 && !isCompatSignatureUpdateNeeded(pkg) 5771 && !isRecoverSignatureUpdateNeeded(pkg)) { 5772 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5773 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5774 ArraySet<PublicKey> signingKs; 5775 synchronized (mPackages) { 5776 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5777 } 5778 if (ps.signatures.mSignatures != null 5779 && ps.signatures.mSignatures.length != 0 5780 && signingKs != null) { 5781 // Optimization: reuse the existing cached certificates 5782 // if the package appears to be unchanged. 5783 pkg.mSignatures = ps.signatures.mSignatures; 5784 pkg.mSigningKeys = signingKs; 5785 return; 5786 } 5787 5788 Slog.w(TAG, "PackageSetting for " + ps.name 5789 + " is missing signatures. Collecting certs again to recover them."); 5790 } else { 5791 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5792 } 5793 5794 try { 5795 pp.collectCertificates(pkg, parseFlags); 5796 pp.collectManifestDigest(pkg); 5797 } catch (PackageParserException e) { 5798 throw PackageManagerException.from(e); 5799 } 5800 } 5801 5802 /** 5803 * Traces a package scan. 5804 * @see #scanPackageLI(File, int, int, long, UserHandle) 5805 */ 5806 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 5807 long currentTime, UserHandle user) throws PackageManagerException { 5808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 5809 try { 5810 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 5811 } finally { 5812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5813 } 5814 } 5815 5816 /** 5817 * Scans a package and returns the newly parsed package. 5818 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 5819 */ 5820 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5821 long currentTime, UserHandle user) throws PackageManagerException { 5822 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5823 parseFlags |= mDefParseFlags; 5824 PackageParser pp = new PackageParser(); 5825 pp.setSeparateProcesses(mSeparateProcesses); 5826 pp.setOnlyCoreApps(mOnlyCore); 5827 pp.setDisplayMetrics(mMetrics); 5828 5829 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5830 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5831 } 5832 5833 final PackageParser.Package pkg; 5834 try { 5835 pkg = pp.parsePackage(scanFile, parseFlags); 5836 } catch (PackageParserException e) { 5837 throw PackageManagerException.from(e); 5838 } 5839 5840 PackageSetting ps = null; 5841 PackageSetting updatedPkg; 5842 // reader 5843 synchronized (mPackages) { 5844 // Look to see if we already know about this package. 5845 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5846 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5847 // This package has been renamed to its original name. Let's 5848 // use that. 5849 ps = mSettings.peekPackageLPr(oldName); 5850 } 5851 // If there was no original package, see one for the real package name. 5852 if (ps == null) { 5853 ps = mSettings.peekPackageLPr(pkg.packageName); 5854 } 5855 // Check to see if this package could be hiding/updating a system 5856 // package. Must look for it either under the original or real 5857 // package name depending on our state. 5858 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5859 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5860 } 5861 boolean updatedPkgBetter = false; 5862 // First check if this is a system package that may involve an update 5863 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 5864 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5865 // it needs to drop FLAG_PRIVILEGED. 5866 if (locationIsPrivileged(scanFile)) { 5867 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5868 } else { 5869 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5870 } 5871 5872 if (ps != null && !ps.codePath.equals(scanFile)) { 5873 // The path has changed from what was last scanned... check the 5874 // version of the new path against what we have stored to determine 5875 // what to do. 5876 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5877 if (pkg.mVersionCode <= ps.versionCode) { 5878 // The system package has been updated and the code path does not match 5879 // Ignore entry. Skip it. 5880 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5881 + " ignored: updated version " + ps.versionCode 5882 + " better than this " + pkg.mVersionCode); 5883 if (!updatedPkg.codePath.equals(scanFile)) { 5884 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5885 + ps.name + " changing from " + updatedPkg.codePathString 5886 + " to " + scanFile); 5887 updatedPkg.codePath = scanFile; 5888 updatedPkg.codePathString = scanFile.toString(); 5889 updatedPkg.resourcePath = scanFile; 5890 updatedPkg.resourcePathString = scanFile.toString(); 5891 } 5892 updatedPkg.pkg = pkg; 5893 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5894 "Package " + ps.name + " at " + scanFile 5895 + " ignored: updated version " + ps.versionCode 5896 + " better than this " + pkg.mVersionCode); 5897 } else { 5898 // The current app on the system partition is better than 5899 // what we have updated to on the data partition; switch 5900 // back to the system partition version. 5901 // At this point, its safely assumed that package installation for 5902 // apps in system partition will go through. If not there won't be a working 5903 // version of the app 5904 // writer 5905 synchronized (mPackages) { 5906 // Just remove the loaded entries from package lists. 5907 mPackages.remove(ps.name); 5908 } 5909 5910 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5911 + " reverting from " + ps.codePathString 5912 + ": new version " + pkg.mVersionCode 5913 + " better than installed " + ps.versionCode); 5914 5915 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5916 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5917 synchronized (mInstallLock) { 5918 args.cleanUpResourcesLI(); 5919 } 5920 synchronized (mPackages) { 5921 mSettings.enableSystemPackageLPw(ps.name); 5922 } 5923 updatedPkgBetter = true; 5924 } 5925 } 5926 } 5927 5928 if (updatedPkg != null) { 5929 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5930 // initially 5931 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5932 5933 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5934 // flag set initially 5935 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5936 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5937 } 5938 } 5939 5940 // Verify certificates against what was last scanned 5941 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5942 5943 /* 5944 * A new system app appeared, but we already had a non-system one of the 5945 * same name installed earlier. 5946 */ 5947 boolean shouldHideSystemApp = false; 5948 if (updatedPkg == null && ps != null 5949 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5950 /* 5951 * Check to make sure the signatures match first. If they don't, 5952 * wipe the installed application and its data. 5953 */ 5954 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5955 != PackageManager.SIGNATURE_MATCH) { 5956 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5957 + " signatures don't match existing userdata copy; removing"); 5958 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5959 ps = null; 5960 } else { 5961 /* 5962 * If the newly-added system app is an older version than the 5963 * already installed version, hide it. It will be scanned later 5964 * and re-added like an update. 5965 */ 5966 if (pkg.mVersionCode <= ps.versionCode) { 5967 shouldHideSystemApp = true; 5968 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5969 + " but new version " + pkg.mVersionCode + " better than installed " 5970 + ps.versionCode + "; hiding system"); 5971 } else { 5972 /* 5973 * The newly found system app is a newer version that the 5974 * one previously installed. Simply remove the 5975 * already-installed application and replace it with our own 5976 * while keeping the application data. 5977 */ 5978 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5979 + " reverting from " + ps.codePathString + ": new version " 5980 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5981 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5982 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5983 synchronized (mInstallLock) { 5984 args.cleanUpResourcesLI(); 5985 } 5986 } 5987 } 5988 } 5989 5990 // The apk is forward locked (not public) if its code and resources 5991 // are kept in different files. (except for app in either system or 5992 // vendor path). 5993 // TODO grab this value from PackageSettings 5994 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5995 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5996 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5997 } 5998 } 5999 6000 // TODO: extend to support forward-locked splits 6001 String resourcePath = null; 6002 String baseResourcePath = null; 6003 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6004 if (ps != null && ps.resourcePathString != null) { 6005 resourcePath = ps.resourcePathString; 6006 baseResourcePath = ps.resourcePathString; 6007 } else { 6008 // Should not happen at all. Just log an error. 6009 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 6010 } 6011 } else { 6012 resourcePath = pkg.codePath; 6013 baseResourcePath = pkg.baseCodePath; 6014 } 6015 6016 // Set application objects path explicitly. 6017 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6018 pkg.applicationInfo.setCodePath(pkg.codePath); 6019 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6020 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6021 pkg.applicationInfo.setResourcePath(resourcePath); 6022 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6023 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6024 6025 // Note that we invoke the following method only if we are about to unpack an application 6026 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6027 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6028 6029 /* 6030 * If the system app should be overridden by a previously installed 6031 * data, hide the system app now and let the /data/app scan pick it up 6032 * again. 6033 */ 6034 if (shouldHideSystemApp) { 6035 synchronized (mPackages) { 6036 mSettings.disableSystemPackageLPw(pkg.packageName); 6037 } 6038 } 6039 6040 return scannedPkg; 6041 } 6042 6043 private static String fixProcessName(String defProcessName, 6044 String processName, int uid) { 6045 if (processName == null) { 6046 return defProcessName; 6047 } 6048 return processName; 6049 } 6050 6051 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6052 throws PackageManagerException { 6053 if (pkgSetting.signatures.mSignatures != null) { 6054 // Already existing package. Make sure signatures match 6055 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6056 == PackageManager.SIGNATURE_MATCH; 6057 if (!match) { 6058 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6059 == PackageManager.SIGNATURE_MATCH; 6060 } 6061 if (!match) { 6062 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6063 == PackageManager.SIGNATURE_MATCH; 6064 } 6065 if (!match) { 6066 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6067 + pkg.packageName + " signatures do not match the " 6068 + "previously installed version; ignoring!"); 6069 } 6070 } 6071 6072 // Check for shared user signatures 6073 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6074 // Already existing package. Make sure signatures match 6075 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6076 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6077 if (!match) { 6078 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6079 == PackageManager.SIGNATURE_MATCH; 6080 } 6081 if (!match) { 6082 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6083 == PackageManager.SIGNATURE_MATCH; 6084 } 6085 if (!match) { 6086 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6087 "Package " + pkg.packageName 6088 + " has no signatures that match those in shared user " 6089 + pkgSetting.sharedUser.name + "; ignoring!"); 6090 } 6091 } 6092 } 6093 6094 /** 6095 * Enforces that only the system UID or root's UID can call a method exposed 6096 * via Binder. 6097 * 6098 * @param message used as message if SecurityException is thrown 6099 * @throws SecurityException if the caller is not system or root 6100 */ 6101 private static final void enforceSystemOrRoot(String message) { 6102 final int uid = Binder.getCallingUid(); 6103 if (uid != Process.SYSTEM_UID && uid != 0) { 6104 throw new SecurityException(message); 6105 } 6106 } 6107 6108 @Override 6109 public void performBootDexOpt() { 6110 enforceSystemOrRoot("Only the system can request dexopt be performed"); 6111 6112 // Before everything else, see whether we need to fstrim. 6113 try { 6114 IMountService ms = PackageHelper.getMountService(); 6115 if (ms != null) { 6116 final boolean isUpgrade = isUpgrade(); 6117 boolean doTrim = isUpgrade; 6118 if (doTrim) { 6119 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6120 } else { 6121 final long interval = android.provider.Settings.Global.getLong( 6122 mContext.getContentResolver(), 6123 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6124 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6125 if (interval > 0) { 6126 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6127 if (timeSinceLast > interval) { 6128 doTrim = true; 6129 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6130 + "; running immediately"); 6131 } 6132 } 6133 } 6134 if (doTrim) { 6135 if (!isFirstBoot()) { 6136 try { 6137 ActivityManagerNative.getDefault().showBootMessage( 6138 mContext.getResources().getString( 6139 R.string.android_upgrading_fstrim), true); 6140 } catch (RemoteException e) { 6141 } 6142 } 6143 ms.runMaintenance(); 6144 } 6145 } else { 6146 Slog.e(TAG, "Mount service unavailable!"); 6147 } 6148 } catch (RemoteException e) { 6149 // Can't happen; MountService is local 6150 } 6151 6152 final ArraySet<PackageParser.Package> pkgs; 6153 synchronized (mPackages) { 6154 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 6155 } 6156 6157 if (pkgs != null) { 6158 // Sort apps by importance for dexopt ordering. Important apps are given more priority 6159 // in case the device runs out of space. 6160 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 6161 // Give priority to core apps. 6162 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6163 PackageParser.Package pkg = it.next(); 6164 if (pkg.coreApp) { 6165 if (DEBUG_DEXOPT) { 6166 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 6167 } 6168 sortedPkgs.add(pkg); 6169 it.remove(); 6170 } 6171 } 6172 // Give priority to system apps that listen for pre boot complete. 6173 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 6174 ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM); 6175 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6176 PackageParser.Package pkg = it.next(); 6177 if (pkgNames.contains(pkg.packageName)) { 6178 if (DEBUG_DEXOPT) { 6179 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 6180 } 6181 sortedPkgs.add(pkg); 6182 it.remove(); 6183 } 6184 } 6185 // Filter out packages that aren't recently used. 6186 filterRecentlyUsedApps(pkgs); 6187 // Add all remaining apps. 6188 for (PackageParser.Package pkg : pkgs) { 6189 if (DEBUG_DEXOPT) { 6190 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6191 } 6192 sortedPkgs.add(pkg); 6193 } 6194 6195 // If we want to be lazy, filter everything that wasn't recently used. 6196 if (mLazyDexOpt) { 6197 filterRecentlyUsedApps(sortedPkgs); 6198 } 6199 6200 int i = 0; 6201 int total = sortedPkgs.size(); 6202 File dataDir = Environment.getDataDirectory(); 6203 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6204 if (lowThreshold == 0) { 6205 throw new IllegalStateException("Invalid low memory threshold"); 6206 } 6207 for (PackageParser.Package pkg : sortedPkgs) { 6208 long usableSpace = dataDir.getUsableSpace(); 6209 if (usableSpace < lowThreshold) { 6210 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6211 break; 6212 } 6213 performBootDexOpt(pkg, ++i, total); 6214 } 6215 } 6216 } 6217 6218 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6219 // Filter out packages that aren't recently used. 6220 // 6221 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6222 // should do a full dexopt. 6223 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6224 int total = pkgs.size(); 6225 int skipped = 0; 6226 long now = System.currentTimeMillis(); 6227 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6228 PackageParser.Package pkg = i.next(); 6229 long then = pkg.mLastPackageUsageTimeInMills; 6230 if (then + mDexOptLRUThresholdInMills < now) { 6231 if (DEBUG_DEXOPT) { 6232 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6233 ((then == 0) ? "never" : new Date(then))); 6234 } 6235 i.remove(); 6236 skipped++; 6237 } 6238 } 6239 if (DEBUG_DEXOPT) { 6240 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6241 } 6242 } 6243 } 6244 6245 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6246 List<ResolveInfo> ris = null; 6247 try { 6248 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6249 intent, null, 0, userId); 6250 } catch (RemoteException e) { 6251 } 6252 ArraySet<String> pkgNames = new ArraySet<String>(); 6253 if (ris != null) { 6254 for (ResolveInfo ri : ris) { 6255 pkgNames.add(ri.activityInfo.packageName); 6256 } 6257 } 6258 return pkgNames; 6259 } 6260 6261 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6262 if (DEBUG_DEXOPT) { 6263 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6264 } 6265 if (!isFirstBoot()) { 6266 try { 6267 ActivityManagerNative.getDefault().showBootMessage( 6268 mContext.getResources().getString(R.string.android_upgrading_apk, 6269 curr, total), true); 6270 } catch (RemoteException e) { 6271 } 6272 } 6273 PackageParser.Package p = pkg; 6274 synchronized (mInstallLock) { 6275 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6276 false /* force dex */, false /* defer */, true /* include dependencies */, 6277 false /* boot complete */, false /*useJit*/); 6278 } 6279 } 6280 6281 @Override 6282 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6283 return performDexOptTraced(packageName, instructionSet, false); 6284 } 6285 6286 public boolean performDexOpt( 6287 String packageName, String instructionSet, boolean backgroundDexopt) { 6288 return performDexOptTraced(packageName, instructionSet, backgroundDexopt); 6289 } 6290 6291 private boolean performDexOptTraced( 6292 String packageName, String instructionSet, boolean backgroundDexopt) { 6293 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6294 try { 6295 return performDexOptInternal(packageName, instructionSet, backgroundDexopt); 6296 } finally { 6297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6298 } 6299 } 6300 6301 private boolean performDexOptInternal( 6302 String packageName, String instructionSet, boolean backgroundDexopt) { 6303 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6304 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6305 if (!dexopt && !updateUsage) { 6306 // We aren't going to dexopt or update usage, so bail early. 6307 return false; 6308 } 6309 PackageParser.Package p; 6310 final String targetInstructionSet; 6311 synchronized (mPackages) { 6312 p = mPackages.get(packageName); 6313 if (p == null) { 6314 return false; 6315 } 6316 if (updateUsage) { 6317 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6318 } 6319 mPackageUsage.write(false); 6320 if (!dexopt) { 6321 // We aren't going to dexopt, so bail early. 6322 return false; 6323 } 6324 6325 targetInstructionSet = instructionSet != null ? instructionSet : 6326 getPrimaryInstructionSet(p.applicationInfo); 6327 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6328 return false; 6329 } 6330 } 6331 long callingId = Binder.clearCallingIdentity(); 6332 try { 6333 synchronized (mInstallLock) { 6334 final String[] instructionSets = new String[] { targetInstructionSet }; 6335 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6336 false /* forceDex */, false /* defer */, true /* inclDependencies */, 6337 true /* boot complete */, false /*useJit*/); 6338 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6339 } 6340 } finally { 6341 Binder.restoreCallingIdentity(callingId); 6342 } 6343 } 6344 6345 public ArraySet<String> getPackagesThatNeedDexOpt() { 6346 ArraySet<String> pkgs = null; 6347 synchronized (mPackages) { 6348 for (PackageParser.Package p : mPackages.values()) { 6349 if (DEBUG_DEXOPT) { 6350 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6351 } 6352 if (!p.mDexOptPerformed.isEmpty()) { 6353 continue; 6354 } 6355 if (pkgs == null) { 6356 pkgs = new ArraySet<String>(); 6357 } 6358 pkgs.add(p.packageName); 6359 } 6360 } 6361 return pkgs; 6362 } 6363 6364 public void shutdown() { 6365 mPackageUsage.write(true); 6366 } 6367 6368 @Override 6369 public void forceDexOpt(String packageName) { 6370 enforceSystemOrRoot("forceDexOpt"); 6371 6372 PackageParser.Package pkg; 6373 synchronized (mPackages) { 6374 pkg = mPackages.get(packageName); 6375 if (pkg == null) { 6376 throw new IllegalArgumentException("Missing package: " + packageName); 6377 } 6378 } 6379 6380 synchronized (mInstallLock) { 6381 final String[] instructionSets = new String[] { 6382 getPrimaryInstructionSet(pkg.applicationInfo) }; 6383 6384 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6385 6386 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6387 true /*forceDex*/, false /* defer */, true /* inclDependencies */, 6388 true /* boot complete */, false /*useJit*/); 6389 6390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6391 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6392 throw new IllegalStateException("Failed to dexopt: " + res); 6393 } 6394 } 6395 } 6396 6397 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6398 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6399 Slog.w(TAG, "Unable to update from " + oldPkg.name 6400 + " to " + newPkg.packageName 6401 + ": old package not in system partition"); 6402 return false; 6403 } else if (mPackages.get(oldPkg.name) != null) { 6404 Slog.w(TAG, "Unable to update from " + oldPkg.name 6405 + " to " + newPkg.packageName 6406 + ": old package still exists"); 6407 return false; 6408 } 6409 return true; 6410 } 6411 6412 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6413 int[] users = sUserManager.getUserIds(); 6414 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6415 if (res < 0) { 6416 return res; 6417 } 6418 for (int user : users) { 6419 if (user != 0) { 6420 res = mInstaller.createUserData(volumeUuid, packageName, 6421 UserHandle.getUid(user, uid), user, seinfo); 6422 if (res < 0) { 6423 return res; 6424 } 6425 } 6426 } 6427 return res; 6428 } 6429 6430 private int removeDataDirsLI(String volumeUuid, String packageName) { 6431 int[] users = sUserManager.getUserIds(); 6432 int res = 0; 6433 for (int user : users) { 6434 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6435 if (resInner < 0) { 6436 res = resInner; 6437 } 6438 } 6439 6440 return res; 6441 } 6442 6443 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6444 int[] users = sUserManager.getUserIds(); 6445 int res = 0; 6446 for (int user : users) { 6447 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6448 if (resInner < 0) { 6449 res = resInner; 6450 } 6451 } 6452 return res; 6453 } 6454 6455 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6456 PackageParser.Package changingLib) { 6457 if (file.path != null) { 6458 usesLibraryFiles.add(file.path); 6459 return; 6460 } 6461 PackageParser.Package p = mPackages.get(file.apk); 6462 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6463 // If we are doing this while in the middle of updating a library apk, 6464 // then we need to make sure to use that new apk for determining the 6465 // dependencies here. (We haven't yet finished committing the new apk 6466 // to the package manager state.) 6467 if (p == null || p.packageName.equals(changingLib.packageName)) { 6468 p = changingLib; 6469 } 6470 } 6471 if (p != null) { 6472 usesLibraryFiles.addAll(p.getAllCodePaths()); 6473 } 6474 } 6475 6476 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6477 PackageParser.Package changingLib) throws PackageManagerException { 6478 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6479 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6480 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6481 for (int i=0; i<N; i++) { 6482 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6483 if (file == null) { 6484 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6485 "Package " + pkg.packageName + " requires unavailable shared library " 6486 + pkg.usesLibraries.get(i) + "; failing!"); 6487 } 6488 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6489 } 6490 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6491 for (int i=0; i<N; i++) { 6492 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6493 if (file == null) { 6494 Slog.w(TAG, "Package " + pkg.packageName 6495 + " desires unavailable shared library " 6496 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6497 } else { 6498 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6499 } 6500 } 6501 N = usesLibraryFiles.size(); 6502 if (N > 0) { 6503 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6504 } else { 6505 pkg.usesLibraryFiles = null; 6506 } 6507 } 6508 } 6509 6510 private static boolean hasString(List<String> list, List<String> which) { 6511 if (list == null) { 6512 return false; 6513 } 6514 for (int i=list.size()-1; i>=0; i--) { 6515 for (int j=which.size()-1; j>=0; j--) { 6516 if (which.get(j).equals(list.get(i))) { 6517 return true; 6518 } 6519 } 6520 } 6521 return false; 6522 } 6523 6524 private void updateAllSharedLibrariesLPw() { 6525 for (PackageParser.Package pkg : mPackages.values()) { 6526 try { 6527 updateSharedLibrariesLPw(pkg, null); 6528 } catch (PackageManagerException e) { 6529 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6530 } 6531 } 6532 } 6533 6534 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6535 PackageParser.Package changingPkg) { 6536 ArrayList<PackageParser.Package> res = null; 6537 for (PackageParser.Package pkg : mPackages.values()) { 6538 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6539 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6540 if (res == null) { 6541 res = new ArrayList<PackageParser.Package>(); 6542 } 6543 res.add(pkg); 6544 try { 6545 updateSharedLibrariesLPw(pkg, changingPkg); 6546 } catch (PackageManagerException e) { 6547 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6548 } 6549 } 6550 } 6551 return res; 6552 } 6553 6554 /** 6555 * Derive the value of the {@code cpuAbiOverride} based on the provided 6556 * value and an optional stored value from the package settings. 6557 */ 6558 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6559 String cpuAbiOverride = null; 6560 6561 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6562 cpuAbiOverride = null; 6563 } else if (abiOverride != null) { 6564 cpuAbiOverride = abiOverride; 6565 } else if (settings != null) { 6566 cpuAbiOverride = settings.cpuAbiOverrideString; 6567 } 6568 6569 return cpuAbiOverride; 6570 } 6571 6572 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6573 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6574 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6575 try { 6576 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6577 } finally { 6578 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6579 } 6580 } 6581 6582 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6583 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6584 boolean success = false; 6585 try { 6586 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6587 currentTime, user); 6588 success = true; 6589 return res; 6590 } finally { 6591 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6592 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6593 } 6594 } 6595 } 6596 6597 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6598 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6599 final File scanFile = new File(pkg.codePath); 6600 if (pkg.applicationInfo.getCodePath() == null || 6601 pkg.applicationInfo.getResourcePath() == null) { 6602 // Bail out. The resource and code paths haven't been set. 6603 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6604 "Code and resource paths haven't been set correctly"); 6605 } 6606 6607 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6608 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6609 } else { 6610 // Only allow system apps to be flagged as core apps. 6611 pkg.coreApp = false; 6612 } 6613 6614 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6615 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6616 } 6617 6618 if (mCustomResolverComponentName != null && 6619 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6620 setUpCustomResolverActivity(pkg); 6621 } 6622 6623 if (pkg.packageName.equals("android")) { 6624 synchronized (mPackages) { 6625 if (mAndroidApplication != null) { 6626 Slog.w(TAG, "*************************************************"); 6627 Slog.w(TAG, "Core android package being redefined. Skipping."); 6628 Slog.w(TAG, " file=" + scanFile); 6629 Slog.w(TAG, "*************************************************"); 6630 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6631 "Core android package being redefined. Skipping."); 6632 } 6633 6634 // Set up information for our fall-back user intent resolution activity. 6635 mPlatformPackage = pkg; 6636 pkg.mVersionCode = mSdkVersion; 6637 mAndroidApplication = pkg.applicationInfo; 6638 6639 if (!mResolverReplaced) { 6640 mResolveActivity.applicationInfo = mAndroidApplication; 6641 mResolveActivity.name = ResolverActivity.class.getName(); 6642 mResolveActivity.packageName = mAndroidApplication.packageName; 6643 mResolveActivity.processName = "system:ui"; 6644 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6645 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6646 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6647 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6648 mResolveActivity.exported = true; 6649 mResolveActivity.enabled = true; 6650 mResolveInfo.activityInfo = mResolveActivity; 6651 mResolveInfo.priority = 0; 6652 mResolveInfo.preferredOrder = 0; 6653 mResolveInfo.match = 0; 6654 mResolveComponentName = new ComponentName( 6655 mAndroidApplication.packageName, mResolveActivity.name); 6656 } 6657 } 6658 } 6659 6660 if (DEBUG_PACKAGE_SCANNING) { 6661 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6662 Log.d(TAG, "Scanning package " + pkg.packageName); 6663 } 6664 6665 if (mPackages.containsKey(pkg.packageName) 6666 || mSharedLibraries.containsKey(pkg.packageName)) { 6667 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6668 "Application package " + pkg.packageName 6669 + " already installed. Skipping duplicate."); 6670 } 6671 6672 // If we're only installing presumed-existing packages, require that the 6673 // scanned APK is both already known and at the path previously established 6674 // for it. Previously unknown packages we pick up normally, but if we have an 6675 // a priori expectation about this package's install presence, enforce it. 6676 // With a singular exception for new system packages. When an OTA contains 6677 // a new system package, we allow the codepath to change from a system location 6678 // to the user-installed location. If we don't allow this change, any newer, 6679 // user-installed version of the application will be ignored. 6680 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6681 if (mExpectingBetter.containsKey(pkg.packageName)) { 6682 logCriticalInfo(Log.WARN, 6683 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6684 } else { 6685 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6686 if (known != null) { 6687 if (DEBUG_PACKAGE_SCANNING) { 6688 Log.d(TAG, "Examining " + pkg.codePath 6689 + " and requiring known paths " + known.codePathString 6690 + " & " + known.resourcePathString); 6691 } 6692 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6693 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6694 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6695 "Application package " + pkg.packageName 6696 + " found at " + pkg.applicationInfo.getCodePath() 6697 + " but expected at " + known.codePathString + "; ignoring."); 6698 } 6699 } 6700 } 6701 } 6702 6703 // Initialize package source and resource directories 6704 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6705 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6706 6707 SharedUserSetting suid = null; 6708 PackageSetting pkgSetting = null; 6709 6710 if (!isSystemApp(pkg)) { 6711 // Only system apps can use these features. 6712 pkg.mOriginalPackages = null; 6713 pkg.mRealPackage = null; 6714 pkg.mAdoptPermissions = null; 6715 } 6716 6717 // writer 6718 synchronized (mPackages) { 6719 if (pkg.mSharedUserId != null) { 6720 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6721 if (suid == null) { 6722 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6723 "Creating application package " + pkg.packageName 6724 + " for shared user failed"); 6725 } 6726 if (DEBUG_PACKAGE_SCANNING) { 6727 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6728 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6729 + "): packages=" + suid.packages); 6730 } 6731 } 6732 6733 // Check if we are renaming from an original package name. 6734 PackageSetting origPackage = null; 6735 String realName = null; 6736 if (pkg.mOriginalPackages != null) { 6737 // This package may need to be renamed to a previously 6738 // installed name. Let's check on that... 6739 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6740 if (pkg.mOriginalPackages.contains(renamed)) { 6741 // This package had originally been installed as the 6742 // original name, and we have already taken care of 6743 // transitioning to the new one. Just update the new 6744 // one to continue using the old name. 6745 realName = pkg.mRealPackage; 6746 if (!pkg.packageName.equals(renamed)) { 6747 // Callers into this function may have already taken 6748 // care of renaming the package; only do it here if 6749 // it is not already done. 6750 pkg.setPackageName(renamed); 6751 } 6752 6753 } else { 6754 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6755 if ((origPackage = mSettings.peekPackageLPr( 6756 pkg.mOriginalPackages.get(i))) != null) { 6757 // We do have the package already installed under its 6758 // original name... should we use it? 6759 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6760 // New package is not compatible with original. 6761 origPackage = null; 6762 continue; 6763 } else if (origPackage.sharedUser != null) { 6764 // Make sure uid is compatible between packages. 6765 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6766 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6767 + " to " + pkg.packageName + ": old uid " 6768 + origPackage.sharedUser.name 6769 + " differs from " + pkg.mSharedUserId); 6770 origPackage = null; 6771 continue; 6772 } 6773 } else { 6774 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6775 + pkg.packageName + " to old name " + origPackage.name); 6776 } 6777 break; 6778 } 6779 } 6780 } 6781 } 6782 6783 if (mTransferedPackages.contains(pkg.packageName)) { 6784 Slog.w(TAG, "Package " + pkg.packageName 6785 + " was transferred to another, but its .apk remains"); 6786 } 6787 6788 // Just create the setting, don't add it yet. For already existing packages 6789 // the PkgSetting exists already and doesn't have to be created. 6790 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6791 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6792 pkg.applicationInfo.primaryCpuAbi, 6793 pkg.applicationInfo.secondaryCpuAbi, 6794 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6795 user, false); 6796 if (pkgSetting == null) { 6797 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6798 "Creating application package " + pkg.packageName + " failed"); 6799 } 6800 6801 if (pkgSetting.origPackage != null) { 6802 // If we are first transitioning from an original package, 6803 // fix up the new package's name now. We need to do this after 6804 // looking up the package under its new name, so getPackageLP 6805 // can take care of fiddling things correctly. 6806 pkg.setPackageName(origPackage.name); 6807 6808 // File a report about this. 6809 String msg = "New package " + pkgSetting.realName 6810 + " renamed to replace old package " + pkgSetting.name; 6811 reportSettingsProblem(Log.WARN, msg); 6812 6813 // Make a note of it. 6814 mTransferedPackages.add(origPackage.name); 6815 6816 // No longer need to retain this. 6817 pkgSetting.origPackage = null; 6818 } 6819 6820 if (realName != null) { 6821 // Make a note of it. 6822 mTransferedPackages.add(pkg.packageName); 6823 } 6824 6825 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6826 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6827 } 6828 6829 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6830 // Check all shared libraries and map to their actual file path. 6831 // We only do this here for apps not on a system dir, because those 6832 // are the only ones that can fail an install due to this. We 6833 // will take care of the system apps by updating all of their 6834 // library paths after the scan is done. 6835 updateSharedLibrariesLPw(pkg, null); 6836 } 6837 6838 if (mFoundPolicyFile) { 6839 SELinuxMMAC.assignSeinfoValue(pkg); 6840 } 6841 6842 pkg.applicationInfo.uid = pkgSetting.appId; 6843 pkg.mExtras = pkgSetting; 6844 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6845 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6846 // We just determined the app is signed correctly, so bring 6847 // over the latest parsed certs. 6848 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6849 } else { 6850 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6851 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6852 "Package " + pkg.packageName + " upgrade keys do not match the " 6853 + "previously installed version"); 6854 } else { 6855 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6856 String msg = "System package " + pkg.packageName 6857 + " signature changed; retaining data."; 6858 reportSettingsProblem(Log.WARN, msg); 6859 } 6860 } 6861 } else { 6862 try { 6863 verifySignaturesLP(pkgSetting, pkg); 6864 // We just determined the app is signed correctly, so bring 6865 // over the latest parsed certs. 6866 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6867 } catch (PackageManagerException e) { 6868 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6869 throw e; 6870 } 6871 // The signature has changed, but this package is in the system 6872 // image... let's recover! 6873 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6874 // However... if this package is part of a shared user, but it 6875 // doesn't match the signature of the shared user, let's fail. 6876 // What this means is that you can't change the signatures 6877 // associated with an overall shared user, which doesn't seem all 6878 // that unreasonable. 6879 if (pkgSetting.sharedUser != null) { 6880 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6881 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6882 throw new PackageManagerException( 6883 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6884 "Signature mismatch for shared user : " 6885 + pkgSetting.sharedUser); 6886 } 6887 } 6888 // File a report about this. 6889 String msg = "System package " + pkg.packageName 6890 + " signature changed; retaining data."; 6891 reportSettingsProblem(Log.WARN, msg); 6892 } 6893 } 6894 // Verify that this new package doesn't have any content providers 6895 // that conflict with existing packages. Only do this if the 6896 // package isn't already installed, since we don't want to break 6897 // things that are installed. 6898 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6899 final int N = pkg.providers.size(); 6900 int i; 6901 for (i=0; i<N; i++) { 6902 PackageParser.Provider p = pkg.providers.get(i); 6903 if (p.info.authority != null) { 6904 String names[] = p.info.authority.split(";"); 6905 for (int j = 0; j < names.length; j++) { 6906 if (mProvidersByAuthority.containsKey(names[j])) { 6907 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6908 final String otherPackageName = 6909 ((other != null && other.getComponentName() != null) ? 6910 other.getComponentName().getPackageName() : "?"); 6911 throw new PackageManagerException( 6912 INSTALL_FAILED_CONFLICTING_PROVIDER, 6913 "Can't install because provider name " + names[j] 6914 + " (in package " + pkg.applicationInfo.packageName 6915 + ") is already used by " + otherPackageName); 6916 } 6917 } 6918 } 6919 } 6920 } 6921 6922 if (pkg.mAdoptPermissions != null) { 6923 // This package wants to adopt ownership of permissions from 6924 // another package. 6925 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6926 final String origName = pkg.mAdoptPermissions.get(i); 6927 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6928 if (orig != null) { 6929 if (verifyPackageUpdateLPr(orig, pkg)) { 6930 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6931 + pkg.packageName); 6932 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6933 } 6934 } 6935 } 6936 } 6937 } 6938 6939 final String pkgName = pkg.packageName; 6940 6941 final long scanFileTime = scanFile.lastModified(); 6942 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6943 pkg.applicationInfo.processName = fixProcessName( 6944 pkg.applicationInfo.packageName, 6945 pkg.applicationInfo.processName, 6946 pkg.applicationInfo.uid); 6947 6948 File dataPath; 6949 if (mPlatformPackage == pkg) { 6950 // The system package is special. 6951 dataPath = new File(Environment.getDataDirectory(), "system"); 6952 6953 pkg.applicationInfo.dataDir = dataPath.getPath(); 6954 6955 } else { 6956 // This is a normal package, need to make its data directory. 6957 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6958 UserHandle.USER_SYSTEM, pkg.packageName); 6959 6960 boolean uidError = false; 6961 if (dataPath.exists()) { 6962 int currentUid = 0; 6963 try { 6964 StructStat stat = Os.stat(dataPath.getPath()); 6965 currentUid = stat.st_uid; 6966 } catch (ErrnoException e) { 6967 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6968 } 6969 6970 // If we have mismatched owners for the data path, we have a problem. 6971 if (currentUid != pkg.applicationInfo.uid) { 6972 boolean recovered = false; 6973 if (currentUid == 0) { 6974 // The directory somehow became owned by root. Wow. 6975 // This is probably because the system was stopped while 6976 // installd was in the middle of messing with its libs 6977 // directory. Ask installd to fix that. 6978 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6979 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6980 if (ret >= 0) { 6981 recovered = true; 6982 String msg = "Package " + pkg.packageName 6983 + " unexpectedly changed to uid 0; recovered to " + 6984 + pkg.applicationInfo.uid; 6985 reportSettingsProblem(Log.WARN, msg); 6986 } 6987 } 6988 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6989 || (scanFlags&SCAN_BOOTING) != 0)) { 6990 // If this is a system app, we can at least delete its 6991 // current data so the application will still work. 6992 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6993 if (ret >= 0) { 6994 // TODO: Kill the processes first 6995 // Old data gone! 6996 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6997 ? "System package " : "Third party package "; 6998 String msg = prefix + pkg.packageName 6999 + " has changed from uid: " 7000 + currentUid + " to " 7001 + pkg.applicationInfo.uid + "; old data erased"; 7002 reportSettingsProblem(Log.WARN, msg); 7003 recovered = true; 7004 7005 // And now re-install the app. 7006 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7007 pkg.applicationInfo.seinfo); 7008 if (ret == -1) { 7009 // Ack should not happen! 7010 msg = prefix + pkg.packageName 7011 + " could not have data directory re-created after delete."; 7012 reportSettingsProblem(Log.WARN, msg); 7013 throw new PackageManagerException( 7014 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 7015 } 7016 } 7017 if (!recovered) { 7018 mHasSystemUidErrors = true; 7019 } 7020 } else if (!recovered) { 7021 // If we allow this install to proceed, we will be broken. 7022 // Abort, abort! 7023 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7024 "scanPackageLI"); 7025 } 7026 if (!recovered) { 7027 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7028 + pkg.applicationInfo.uid + "/fs_" 7029 + currentUid; 7030 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7031 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7032 String msg = "Package " + pkg.packageName 7033 + " has mismatched uid: " 7034 + currentUid + " on disk, " 7035 + pkg.applicationInfo.uid + " in settings"; 7036 // writer 7037 synchronized (mPackages) { 7038 mSettings.mReadMessages.append(msg); 7039 mSettings.mReadMessages.append('\n'); 7040 uidError = true; 7041 if (!pkgSetting.uidError) { 7042 reportSettingsProblem(Log.ERROR, msg); 7043 } 7044 } 7045 } 7046 } 7047 pkg.applicationInfo.dataDir = dataPath.getPath(); 7048 if (mShouldRestoreconData) { 7049 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7050 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7051 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7052 } 7053 } else { 7054 if (DEBUG_PACKAGE_SCANNING) { 7055 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7056 Log.v(TAG, "Want this data dir: " + dataPath); 7057 } 7058 //invoke installer to do the actual installation 7059 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7060 pkg.applicationInfo.seinfo); 7061 if (ret < 0) { 7062 // Error from installer 7063 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7064 "Unable to create data dirs [errorCode=" + ret + "]"); 7065 } 7066 7067 if (dataPath.exists()) { 7068 pkg.applicationInfo.dataDir = dataPath.getPath(); 7069 } else { 7070 Slog.w(TAG, "Unable to create data directory: " + dataPath); 7071 pkg.applicationInfo.dataDir = null; 7072 } 7073 } 7074 7075 pkgSetting.uidError = uidError; 7076 } 7077 7078 final String path = scanFile.getPath(); 7079 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7080 7081 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7082 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7083 7084 // Some system apps still use directory structure for native libraries 7085 // in which case we might end up not detecting abi solely based on apk 7086 // structure. Try to detect abi based on directory structure. 7087 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7088 pkg.applicationInfo.primaryCpuAbi == null) { 7089 setBundledAppAbisAndRoots(pkg, pkgSetting); 7090 setNativeLibraryPaths(pkg); 7091 } 7092 7093 } else { 7094 if ((scanFlags & SCAN_MOVE) != 0) { 7095 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7096 // but we already have this packages package info in the PackageSetting. We just 7097 // use that and derive the native library path based on the new codepath. 7098 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7099 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7100 } 7101 7102 // Set native library paths again. For moves, the path will be updated based on the 7103 // ABIs we've determined above. For non-moves, the path will be updated based on the 7104 // ABIs we determined during compilation, but the path will depend on the final 7105 // package path (after the rename away from the stage path). 7106 setNativeLibraryPaths(pkg); 7107 } 7108 7109 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7110 final int[] userIds = sUserManager.getUserIds(); 7111 synchronized (mInstallLock) { 7112 // Make sure all user data directories are ready to roll; we're okay 7113 // if they already exist 7114 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7115 for (int userId : userIds) { 7116 if (userId != UserHandle.USER_SYSTEM) { 7117 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7118 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7119 pkg.applicationInfo.seinfo); 7120 } 7121 } 7122 } 7123 7124 // Create a native library symlink only if we have native libraries 7125 // and if the native libraries are 32 bit libraries. We do not provide 7126 // this symlink for 64 bit libraries. 7127 if (pkg.applicationInfo.primaryCpuAbi != null && 7128 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7129 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7130 try { 7131 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7132 for (int userId : userIds) { 7133 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7134 nativeLibPath, userId) < 0) { 7135 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7136 "Failed linking native library dir (user=" + userId + ")"); 7137 } 7138 } 7139 } finally { 7140 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7141 } 7142 } 7143 } 7144 7145 // This is a special case for the "system" package, where the ABI is 7146 // dictated by the zygote configuration (and init.rc). We should keep track 7147 // of this ABI so that we can deal with "normal" applications that run under 7148 // the same UID correctly. 7149 if (mPlatformPackage == pkg) { 7150 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7151 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7152 } 7153 7154 // If there's a mismatch between the abi-override in the package setting 7155 // and the abiOverride specified for the install. Warn about this because we 7156 // would've already compiled the app without taking the package setting into 7157 // account. 7158 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7159 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7160 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7161 " for package: " + pkg.packageName); 7162 } 7163 } 7164 7165 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7166 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7167 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7168 7169 // Copy the derived override back to the parsed package, so that we can 7170 // update the package settings accordingly. 7171 pkg.cpuAbiOverride = cpuAbiOverride; 7172 7173 if (DEBUG_ABI_SELECTION) { 7174 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7175 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7176 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7177 } 7178 7179 // Push the derived path down into PackageSettings so we know what to 7180 // clean up at uninstall time. 7181 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7182 7183 if (DEBUG_ABI_SELECTION) { 7184 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7185 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7186 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7187 } 7188 7189 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7190 // We don't do this here during boot because we can do it all 7191 // at once after scanning all existing packages. 7192 // 7193 // We also do this *before* we perform dexopt on this package, so that 7194 // we can avoid redundant dexopts, and also to make sure we've got the 7195 // code and package path correct. 7196 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7197 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */); 7198 } 7199 7200 if ((scanFlags & SCAN_NO_DEX) == 0) { 7201 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7202 7203 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7204 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */, 7205 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7206 7207 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7208 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7209 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7210 } 7211 } 7212 if (mFactoryTest && pkg.requestedPermissions.contains( 7213 android.Manifest.permission.FACTORY_TEST)) { 7214 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7215 } 7216 7217 ArrayList<PackageParser.Package> clientLibPkgs = null; 7218 7219 // writer 7220 synchronized (mPackages) { 7221 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7222 // Only system apps can add new shared libraries. 7223 if (pkg.libraryNames != null) { 7224 for (int i=0; i<pkg.libraryNames.size(); i++) { 7225 String name = pkg.libraryNames.get(i); 7226 boolean allowed = false; 7227 if (pkg.isUpdatedSystemApp()) { 7228 // New library entries can only be added through the 7229 // system image. This is important to get rid of a lot 7230 // of nasty edge cases: for example if we allowed a non- 7231 // system update of the app to add a library, then uninstalling 7232 // the update would make the library go away, and assumptions 7233 // we made such as through app install filtering would now 7234 // have allowed apps on the device which aren't compatible 7235 // with it. Better to just have the restriction here, be 7236 // conservative, and create many fewer cases that can negatively 7237 // impact the user experience. 7238 final PackageSetting sysPs = mSettings 7239 .getDisabledSystemPkgLPr(pkg.packageName); 7240 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7241 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7242 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7243 allowed = true; 7244 break; 7245 } 7246 } 7247 } 7248 } else { 7249 allowed = true; 7250 } 7251 if (allowed) { 7252 if (!mSharedLibraries.containsKey(name)) { 7253 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7254 } else if (!name.equals(pkg.packageName)) { 7255 Slog.w(TAG, "Package " + pkg.packageName + " library " 7256 + name + " already exists; skipping"); 7257 } 7258 } else { 7259 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7260 + name + " that is not declared on system image; skipping"); 7261 } 7262 } 7263 if ((scanFlags&SCAN_BOOTING) == 0) { 7264 // If we are not booting, we need to update any applications 7265 // that are clients of our shared library. If we are booting, 7266 // this will all be done once the scan is complete. 7267 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7268 } 7269 } 7270 } 7271 } 7272 7273 // We also need to dexopt any apps that are dependent on this library. Note that 7274 // if these fail, we should abort the install since installing the library will 7275 // result in some apps being broken. 7276 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7277 try { 7278 if (clientLibPkgs != null) { 7279 if ((scanFlags & SCAN_NO_DEX) == 0) { 7280 for (int i = 0; i < clientLibPkgs.size(); i++) { 7281 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7282 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7283 null /* instruction sets */, forceDex, 7284 (scanFlags & SCAN_DEFER_DEX) != 0, false, 7285 (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/); 7286 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7287 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7288 "scanPackageLI failed to dexopt clientLibPkgs"); 7289 } 7290 } 7291 } 7292 } 7293 } finally { 7294 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7295 } 7296 7297 // Request the ActivityManager to kill the process(only for existing packages) 7298 // so that we do not end up in a confused state while the user is still using the older 7299 // version of the application while the new one gets installed. 7300 if ((scanFlags & SCAN_REPLACING) != 0) { 7301 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7302 7303 killApplication(pkg.applicationInfo.packageName, 7304 pkg.applicationInfo.uid, "replace pkg"); 7305 7306 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7307 } 7308 7309 // Also need to kill any apps that are dependent on the library. 7310 if (clientLibPkgs != null) { 7311 for (int i=0; i<clientLibPkgs.size(); i++) { 7312 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7313 killApplication(clientPkg.applicationInfo.packageName, 7314 clientPkg.applicationInfo.uid, "update lib"); 7315 } 7316 } 7317 7318 // Make sure we're not adding any bogus keyset info 7319 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7320 ksms.assertScannedPackageValid(pkg); 7321 7322 // writer 7323 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7324 7325 boolean createIdmapFailed = false; 7326 synchronized (mPackages) { 7327 // We don't expect installation to fail beyond this point 7328 7329 // Add the new setting to mSettings 7330 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7331 // Add the new setting to mPackages 7332 mPackages.put(pkg.applicationInfo.packageName, pkg); 7333 // Make sure we don't accidentally delete its data. 7334 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7335 while (iter.hasNext()) { 7336 PackageCleanItem item = iter.next(); 7337 if (pkgName.equals(item.packageName)) { 7338 iter.remove(); 7339 } 7340 } 7341 7342 // Take care of first install / last update times. 7343 if (currentTime != 0) { 7344 if (pkgSetting.firstInstallTime == 0) { 7345 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7346 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7347 pkgSetting.lastUpdateTime = currentTime; 7348 } 7349 } else if (pkgSetting.firstInstallTime == 0) { 7350 // We need *something*. Take time time stamp of the file. 7351 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7352 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7353 if (scanFileTime != pkgSetting.timeStamp) { 7354 // A package on the system image has changed; consider this 7355 // to be an update. 7356 pkgSetting.lastUpdateTime = scanFileTime; 7357 } 7358 } 7359 7360 // Add the package's KeySets to the global KeySetManagerService 7361 ksms.addScannedPackageLPw(pkg); 7362 7363 int N = pkg.providers.size(); 7364 StringBuilder r = null; 7365 int i; 7366 for (i=0; i<N; i++) { 7367 PackageParser.Provider p = pkg.providers.get(i); 7368 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7369 p.info.processName, pkg.applicationInfo.uid); 7370 mProviders.addProvider(p); 7371 p.syncable = p.info.isSyncable; 7372 if (p.info.authority != null) { 7373 String names[] = p.info.authority.split(";"); 7374 p.info.authority = null; 7375 for (int j = 0; j < names.length; j++) { 7376 if (j == 1 && p.syncable) { 7377 // We only want the first authority for a provider to possibly be 7378 // syncable, so if we already added this provider using a different 7379 // authority clear the syncable flag. We copy the provider before 7380 // changing it because the mProviders object contains a reference 7381 // to a provider that we don't want to change. 7382 // Only do this for the second authority since the resulting provider 7383 // object can be the same for all future authorities for this provider. 7384 p = new PackageParser.Provider(p); 7385 p.syncable = false; 7386 } 7387 if (!mProvidersByAuthority.containsKey(names[j])) { 7388 mProvidersByAuthority.put(names[j], p); 7389 if (p.info.authority == null) { 7390 p.info.authority = names[j]; 7391 } else { 7392 p.info.authority = p.info.authority + ";" + names[j]; 7393 } 7394 if (DEBUG_PACKAGE_SCANNING) { 7395 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7396 Log.d(TAG, "Registered content provider: " + names[j] 7397 + ", className = " + p.info.name + ", isSyncable = " 7398 + p.info.isSyncable); 7399 } 7400 } else { 7401 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7402 Slog.w(TAG, "Skipping provider name " + names[j] + 7403 " (in package " + pkg.applicationInfo.packageName + 7404 "): name already used by " 7405 + ((other != null && other.getComponentName() != null) 7406 ? other.getComponentName().getPackageName() : "?")); 7407 } 7408 } 7409 } 7410 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7411 if (r == null) { 7412 r = new StringBuilder(256); 7413 } else { 7414 r.append(' '); 7415 } 7416 r.append(p.info.name); 7417 } 7418 } 7419 if (r != null) { 7420 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7421 } 7422 7423 N = pkg.services.size(); 7424 r = null; 7425 for (i=0; i<N; i++) { 7426 PackageParser.Service s = pkg.services.get(i); 7427 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7428 s.info.processName, pkg.applicationInfo.uid); 7429 mServices.addService(s); 7430 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7431 if (r == null) { 7432 r = new StringBuilder(256); 7433 } else { 7434 r.append(' '); 7435 } 7436 r.append(s.info.name); 7437 } 7438 } 7439 if (r != null) { 7440 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7441 } 7442 7443 N = pkg.receivers.size(); 7444 r = null; 7445 for (i=0; i<N; i++) { 7446 PackageParser.Activity a = pkg.receivers.get(i); 7447 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7448 a.info.processName, pkg.applicationInfo.uid); 7449 mReceivers.addActivity(a, "receiver"); 7450 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7451 if (r == null) { 7452 r = new StringBuilder(256); 7453 } else { 7454 r.append(' '); 7455 } 7456 r.append(a.info.name); 7457 } 7458 } 7459 if (r != null) { 7460 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7461 } 7462 7463 N = pkg.activities.size(); 7464 r = null; 7465 for (i=0; i<N; i++) { 7466 PackageParser.Activity a = pkg.activities.get(i); 7467 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7468 a.info.processName, pkg.applicationInfo.uid); 7469 mActivities.addActivity(a, "activity"); 7470 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7471 if (r == null) { 7472 r = new StringBuilder(256); 7473 } else { 7474 r.append(' '); 7475 } 7476 r.append(a.info.name); 7477 } 7478 } 7479 if (r != null) { 7480 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7481 } 7482 7483 N = pkg.permissionGroups.size(); 7484 r = null; 7485 for (i=0; i<N; i++) { 7486 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7487 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7488 if (cur == null) { 7489 mPermissionGroups.put(pg.info.name, pg); 7490 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7491 if (r == null) { 7492 r = new StringBuilder(256); 7493 } else { 7494 r.append(' '); 7495 } 7496 r.append(pg.info.name); 7497 } 7498 } else { 7499 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7500 + pg.info.packageName + " ignored: original from " 7501 + cur.info.packageName); 7502 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7503 if (r == null) { 7504 r = new StringBuilder(256); 7505 } else { 7506 r.append(' '); 7507 } 7508 r.append("DUP:"); 7509 r.append(pg.info.name); 7510 } 7511 } 7512 } 7513 if (r != null) { 7514 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7515 } 7516 7517 N = pkg.permissions.size(); 7518 r = null; 7519 for (i=0; i<N; i++) { 7520 PackageParser.Permission p = pkg.permissions.get(i); 7521 7522 // Assume by default that we did not install this permission into the system. 7523 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7524 7525 // Now that permission groups have a special meaning, we ignore permission 7526 // groups for legacy apps to prevent unexpected behavior. In particular, 7527 // permissions for one app being granted to someone just becuase they happen 7528 // to be in a group defined by another app (before this had no implications). 7529 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7530 p.group = mPermissionGroups.get(p.info.group); 7531 // Warn for a permission in an unknown group. 7532 if (p.info.group != null && p.group == null) { 7533 Slog.w(TAG, "Permission " + p.info.name + " from package " 7534 + p.info.packageName + " in an unknown group " + p.info.group); 7535 } 7536 } 7537 7538 ArrayMap<String, BasePermission> permissionMap = 7539 p.tree ? mSettings.mPermissionTrees 7540 : mSettings.mPermissions; 7541 BasePermission bp = permissionMap.get(p.info.name); 7542 7543 // Allow system apps to redefine non-system permissions 7544 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7545 final boolean currentOwnerIsSystem = (bp.perm != null 7546 && isSystemApp(bp.perm.owner)); 7547 if (isSystemApp(p.owner)) { 7548 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7549 // It's a built-in permission and no owner, take ownership now 7550 bp.packageSetting = pkgSetting; 7551 bp.perm = p; 7552 bp.uid = pkg.applicationInfo.uid; 7553 bp.sourcePackage = p.info.packageName; 7554 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7555 } else if (!currentOwnerIsSystem) { 7556 String msg = "New decl " + p.owner + " of permission " 7557 + p.info.name + " is system; overriding " + bp.sourcePackage; 7558 reportSettingsProblem(Log.WARN, msg); 7559 bp = null; 7560 } 7561 } 7562 } 7563 7564 if (bp == null) { 7565 bp = new BasePermission(p.info.name, p.info.packageName, 7566 BasePermission.TYPE_NORMAL); 7567 permissionMap.put(p.info.name, bp); 7568 } 7569 7570 if (bp.perm == null) { 7571 if (bp.sourcePackage == null 7572 || bp.sourcePackage.equals(p.info.packageName)) { 7573 BasePermission tree = findPermissionTreeLP(p.info.name); 7574 if (tree == null 7575 || tree.sourcePackage.equals(p.info.packageName)) { 7576 bp.packageSetting = pkgSetting; 7577 bp.perm = p; 7578 bp.uid = pkg.applicationInfo.uid; 7579 bp.sourcePackage = p.info.packageName; 7580 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7581 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7582 if (r == null) { 7583 r = new StringBuilder(256); 7584 } else { 7585 r.append(' '); 7586 } 7587 r.append(p.info.name); 7588 } 7589 } else { 7590 Slog.w(TAG, "Permission " + p.info.name + " from package " 7591 + p.info.packageName + " ignored: base tree " 7592 + tree.name + " is from package " 7593 + tree.sourcePackage); 7594 } 7595 } else { 7596 Slog.w(TAG, "Permission " + p.info.name + " from package " 7597 + p.info.packageName + " ignored: original from " 7598 + bp.sourcePackage); 7599 } 7600 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7601 if (r == null) { 7602 r = new StringBuilder(256); 7603 } else { 7604 r.append(' '); 7605 } 7606 r.append("DUP:"); 7607 r.append(p.info.name); 7608 } 7609 if (bp.perm == p) { 7610 bp.protectionLevel = p.info.protectionLevel; 7611 } 7612 } 7613 7614 if (r != null) { 7615 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7616 } 7617 7618 N = pkg.instrumentation.size(); 7619 r = null; 7620 for (i=0; i<N; i++) { 7621 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7622 a.info.packageName = pkg.applicationInfo.packageName; 7623 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7624 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7625 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7626 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7627 a.info.dataDir = pkg.applicationInfo.dataDir; 7628 7629 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7630 // need other information about the application, like the ABI and what not ? 7631 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7632 mInstrumentation.put(a.getComponentName(), a); 7633 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7634 if (r == null) { 7635 r = new StringBuilder(256); 7636 } else { 7637 r.append(' '); 7638 } 7639 r.append(a.info.name); 7640 } 7641 } 7642 if (r != null) { 7643 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7644 } 7645 7646 if (pkg.protectedBroadcasts != null) { 7647 N = pkg.protectedBroadcasts.size(); 7648 for (i=0; i<N; i++) { 7649 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7650 } 7651 } 7652 7653 pkgSetting.setTimeStamp(scanFileTime); 7654 7655 // Create idmap files for pairs of (packages, overlay packages). 7656 // Note: "android", ie framework-res.apk, is handled by native layers. 7657 if (pkg.mOverlayTarget != null) { 7658 // This is an overlay package. 7659 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7660 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7661 mOverlays.put(pkg.mOverlayTarget, 7662 new ArrayMap<String, PackageParser.Package>()); 7663 } 7664 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7665 map.put(pkg.packageName, pkg); 7666 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7667 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7668 createIdmapFailed = true; 7669 } 7670 } 7671 } else if (mOverlays.containsKey(pkg.packageName) && 7672 !pkg.packageName.equals("android")) { 7673 // This is a regular package, with one or more known overlay packages. 7674 createIdmapsForPackageLI(pkg); 7675 } 7676 } 7677 7678 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7679 7680 if (createIdmapFailed) { 7681 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7682 "scanPackageLI failed to createIdmap"); 7683 } 7684 return pkg; 7685 } 7686 7687 /** 7688 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7689 * is derived purely on the basis of the contents of {@code scanFile} and 7690 * {@code cpuAbiOverride}. 7691 * 7692 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7693 */ 7694 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7695 String cpuAbiOverride, boolean extractLibs) 7696 throws PackageManagerException { 7697 // TODO: We can probably be smarter about this stuff. For installed apps, 7698 // we can calculate this information at install time once and for all. For 7699 // system apps, we can probably assume that this information doesn't change 7700 // after the first boot scan. As things stand, we do lots of unnecessary work. 7701 7702 // Give ourselves some initial paths; we'll come back for another 7703 // pass once we've determined ABI below. 7704 setNativeLibraryPaths(pkg); 7705 7706 // We would never need to extract libs for forward-locked and external packages, 7707 // since the container service will do it for us. We shouldn't attempt to 7708 // extract libs from system app when it was not updated. 7709 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7710 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7711 extractLibs = false; 7712 } 7713 7714 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7715 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7716 7717 NativeLibraryHelper.Handle handle = null; 7718 try { 7719 handle = NativeLibraryHelper.Handle.create(pkg); 7720 // TODO(multiArch): This can be null for apps that didn't go through the 7721 // usual installation process. We can calculate it again, like we 7722 // do during install time. 7723 // 7724 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7725 // unnecessary. 7726 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7727 7728 // Null out the abis so that they can be recalculated. 7729 pkg.applicationInfo.primaryCpuAbi = null; 7730 pkg.applicationInfo.secondaryCpuAbi = null; 7731 if (isMultiArch(pkg.applicationInfo)) { 7732 // Warn if we've set an abiOverride for multi-lib packages.. 7733 // By definition, we need to copy both 32 and 64 bit libraries for 7734 // such packages. 7735 if (pkg.cpuAbiOverride != null 7736 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7737 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7738 } 7739 7740 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7741 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7742 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7743 if (extractLibs) { 7744 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7745 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7746 useIsaSpecificSubdirs); 7747 } else { 7748 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7749 } 7750 } 7751 7752 maybeThrowExceptionForMultiArchCopy( 7753 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7754 7755 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7756 if (extractLibs) { 7757 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7758 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7759 useIsaSpecificSubdirs); 7760 } else { 7761 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7762 } 7763 } 7764 7765 maybeThrowExceptionForMultiArchCopy( 7766 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7767 7768 if (abi64 >= 0) { 7769 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7770 } 7771 7772 if (abi32 >= 0) { 7773 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7774 if (abi64 >= 0) { 7775 pkg.applicationInfo.secondaryCpuAbi = abi; 7776 } else { 7777 pkg.applicationInfo.primaryCpuAbi = abi; 7778 } 7779 } 7780 } else { 7781 String[] abiList = (cpuAbiOverride != null) ? 7782 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7783 7784 // Enable gross and lame hacks for apps that are built with old 7785 // SDK tools. We must scan their APKs for renderscript bitcode and 7786 // not launch them if it's present. Don't bother checking on devices 7787 // that don't have 64 bit support. 7788 boolean needsRenderScriptOverride = false; 7789 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7790 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7791 abiList = Build.SUPPORTED_32_BIT_ABIS; 7792 needsRenderScriptOverride = true; 7793 } 7794 7795 final int copyRet; 7796 if (extractLibs) { 7797 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7798 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7799 } else { 7800 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7801 } 7802 7803 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7804 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7805 "Error unpackaging native libs for app, errorCode=" + copyRet); 7806 } 7807 7808 if (copyRet >= 0) { 7809 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7810 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7811 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7812 } else if (needsRenderScriptOverride) { 7813 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7814 } 7815 } 7816 } catch (IOException ioe) { 7817 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7818 } finally { 7819 IoUtils.closeQuietly(handle); 7820 } 7821 7822 // Now that we've calculated the ABIs and determined if it's an internal app, 7823 // we will go ahead and populate the nativeLibraryPath. 7824 setNativeLibraryPaths(pkg); 7825 } 7826 7827 /** 7828 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7829 * i.e, so that all packages can be run inside a single process if required. 7830 * 7831 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7832 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7833 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7834 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7835 * updating a package that belongs to a shared user. 7836 * 7837 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7838 * adds unnecessary complexity. 7839 */ 7840 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7841 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt, 7842 boolean bootComplete) { 7843 String requiredInstructionSet = null; 7844 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7845 requiredInstructionSet = VMRuntime.getInstructionSet( 7846 scannedPackage.applicationInfo.primaryCpuAbi); 7847 } 7848 7849 PackageSetting requirer = null; 7850 for (PackageSetting ps : packagesForUser) { 7851 // If packagesForUser contains scannedPackage, we skip it. This will happen 7852 // when scannedPackage is an update of an existing package. Without this check, 7853 // we will never be able to change the ABI of any package belonging to a shared 7854 // user, even if it's compatible with other packages. 7855 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7856 if (ps.primaryCpuAbiString == null) { 7857 continue; 7858 } 7859 7860 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7861 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7862 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7863 // this but there's not much we can do. 7864 String errorMessage = "Instruction set mismatch, " 7865 + ((requirer == null) ? "[caller]" : requirer) 7866 + " requires " + requiredInstructionSet + " whereas " + ps 7867 + " requires " + instructionSet; 7868 Slog.w(TAG, errorMessage); 7869 } 7870 7871 if (requiredInstructionSet == null) { 7872 requiredInstructionSet = instructionSet; 7873 requirer = ps; 7874 } 7875 } 7876 } 7877 7878 if (requiredInstructionSet != null) { 7879 String adjustedAbi; 7880 if (requirer != null) { 7881 // requirer != null implies that either scannedPackage was null or that scannedPackage 7882 // did not require an ABI, in which case we have to adjust scannedPackage to match 7883 // the ABI of the set (which is the same as requirer's ABI) 7884 adjustedAbi = requirer.primaryCpuAbiString; 7885 if (scannedPackage != null) { 7886 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7887 } 7888 } else { 7889 // requirer == null implies that we're updating all ABIs in the set to 7890 // match scannedPackage. 7891 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7892 } 7893 7894 for (PackageSetting ps : packagesForUser) { 7895 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7896 if (ps.primaryCpuAbiString != null) { 7897 continue; 7898 } 7899 7900 ps.primaryCpuAbiString = adjustedAbi; 7901 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7902 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7903 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7904 7905 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7906 7907 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7908 null /* instruction sets */, forceDexOpt, deferDexOpt, true, 7909 bootComplete, false /*useJit*/); 7910 7911 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7912 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7913 ps.primaryCpuAbiString = null; 7914 ps.pkg.applicationInfo.primaryCpuAbi = null; 7915 return; 7916 } else { 7917 mInstaller.rmdex(ps.codePathString, 7918 getDexCodeInstructionSet(getPreferredInstructionSet())); 7919 } 7920 } 7921 } 7922 } 7923 } 7924 } 7925 7926 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7927 synchronized (mPackages) { 7928 mResolverReplaced = true; 7929 // Set up information for custom user intent resolution activity. 7930 mResolveActivity.applicationInfo = pkg.applicationInfo; 7931 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7932 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7933 mResolveActivity.processName = pkg.applicationInfo.packageName; 7934 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7935 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7936 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7937 mResolveActivity.theme = 0; 7938 mResolveActivity.exported = true; 7939 mResolveActivity.enabled = true; 7940 mResolveInfo.activityInfo = mResolveActivity; 7941 mResolveInfo.priority = 0; 7942 mResolveInfo.preferredOrder = 0; 7943 mResolveInfo.match = 0; 7944 mResolveComponentName = mCustomResolverComponentName; 7945 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7946 mResolveComponentName); 7947 } 7948 } 7949 7950 private static String calculateBundledApkRoot(final String codePathString) { 7951 final File codePath = new File(codePathString); 7952 final File codeRoot; 7953 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7954 codeRoot = Environment.getRootDirectory(); 7955 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7956 codeRoot = Environment.getOemDirectory(); 7957 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7958 codeRoot = Environment.getVendorDirectory(); 7959 } else { 7960 // Unrecognized code path; take its top real segment as the apk root: 7961 // e.g. /something/app/blah.apk => /something 7962 try { 7963 File f = codePath.getCanonicalFile(); 7964 File parent = f.getParentFile(); // non-null because codePath is a file 7965 File tmp; 7966 while ((tmp = parent.getParentFile()) != null) { 7967 f = parent; 7968 parent = tmp; 7969 } 7970 codeRoot = f; 7971 Slog.w(TAG, "Unrecognized code path " 7972 + codePath + " - using " + codeRoot); 7973 } catch (IOException e) { 7974 // Can't canonicalize the code path -- shenanigans? 7975 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7976 return Environment.getRootDirectory().getPath(); 7977 } 7978 } 7979 return codeRoot.getPath(); 7980 } 7981 7982 /** 7983 * Derive and set the location of native libraries for the given package, 7984 * which varies depending on where and how the package was installed. 7985 */ 7986 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7987 final ApplicationInfo info = pkg.applicationInfo; 7988 final String codePath = pkg.codePath; 7989 final File codeFile = new File(codePath); 7990 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7991 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 7992 7993 info.nativeLibraryRootDir = null; 7994 info.nativeLibraryRootRequiresIsa = false; 7995 info.nativeLibraryDir = null; 7996 info.secondaryNativeLibraryDir = null; 7997 7998 if (isApkFile(codeFile)) { 7999 // Monolithic install 8000 if (bundledApp) { 8001 // If "/system/lib64/apkname" exists, assume that is the per-package 8002 // native library directory to use; otherwise use "/system/lib/apkname". 8003 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8004 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8005 getPrimaryInstructionSet(info)); 8006 8007 // This is a bundled system app so choose the path based on the ABI. 8008 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8009 // is just the default path. 8010 final String apkName = deriveCodePathName(codePath); 8011 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8012 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8013 apkName).getAbsolutePath(); 8014 8015 if (info.secondaryCpuAbi != null) { 8016 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8017 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8018 secondaryLibDir, apkName).getAbsolutePath(); 8019 } 8020 } else if (asecApp) { 8021 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8022 .getAbsolutePath(); 8023 } else { 8024 final String apkName = deriveCodePathName(codePath); 8025 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8026 .getAbsolutePath(); 8027 } 8028 8029 info.nativeLibraryRootRequiresIsa = false; 8030 info.nativeLibraryDir = info.nativeLibraryRootDir; 8031 } else { 8032 // Cluster install 8033 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8034 info.nativeLibraryRootRequiresIsa = true; 8035 8036 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8037 getPrimaryInstructionSet(info)).getAbsolutePath(); 8038 8039 if (info.secondaryCpuAbi != null) { 8040 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8041 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8042 } 8043 } 8044 } 8045 8046 /** 8047 * Calculate the abis and roots for a bundled app. These can uniquely 8048 * be determined from the contents of the system partition, i.e whether 8049 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8050 * of this information, and instead assume that the system was built 8051 * sensibly. 8052 */ 8053 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8054 PackageSetting pkgSetting) { 8055 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8056 8057 // If "/system/lib64/apkname" exists, assume that is the per-package 8058 // native library directory to use; otherwise use "/system/lib/apkname". 8059 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8060 setBundledAppAbi(pkg, apkRoot, apkName); 8061 // pkgSetting might be null during rescan following uninstall of updates 8062 // to a bundled app, so accommodate that possibility. The settings in 8063 // that case will be established later from the parsed package. 8064 // 8065 // If the settings aren't null, sync them up with what we've just derived. 8066 // note that apkRoot isn't stored in the package settings. 8067 if (pkgSetting != null) { 8068 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8069 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8070 } 8071 } 8072 8073 /** 8074 * Deduces the ABI of a bundled app and sets the relevant fields on the 8075 * parsed pkg object. 8076 * 8077 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8078 * under which system libraries are installed. 8079 * @param apkName the name of the installed package. 8080 */ 8081 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8082 final File codeFile = new File(pkg.codePath); 8083 8084 final boolean has64BitLibs; 8085 final boolean has32BitLibs; 8086 if (isApkFile(codeFile)) { 8087 // Monolithic install 8088 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8089 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8090 } else { 8091 // Cluster install 8092 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8093 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8094 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8095 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8096 has64BitLibs = (new File(rootDir, isa)).exists(); 8097 } else { 8098 has64BitLibs = false; 8099 } 8100 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8101 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8102 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8103 has32BitLibs = (new File(rootDir, isa)).exists(); 8104 } else { 8105 has32BitLibs = false; 8106 } 8107 } 8108 8109 if (has64BitLibs && !has32BitLibs) { 8110 // The package has 64 bit libs, but not 32 bit libs. Its primary 8111 // ABI should be 64 bit. We can safely assume here that the bundled 8112 // native libraries correspond to the most preferred ABI in the list. 8113 8114 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8115 pkg.applicationInfo.secondaryCpuAbi = null; 8116 } else if (has32BitLibs && !has64BitLibs) { 8117 // The package has 32 bit libs but not 64 bit libs. Its primary 8118 // ABI should be 32 bit. 8119 8120 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8121 pkg.applicationInfo.secondaryCpuAbi = null; 8122 } else if (has32BitLibs && has64BitLibs) { 8123 // The application has both 64 and 32 bit bundled libraries. We check 8124 // here that the app declares multiArch support, and warn if it doesn't. 8125 // 8126 // We will be lenient here and record both ABIs. The primary will be the 8127 // ABI that's higher on the list, i.e, a device that's configured to prefer 8128 // 64 bit apps will see a 64 bit primary ABI, 8129 8130 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8131 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 8132 } 8133 8134 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8135 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8136 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8137 } else { 8138 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8139 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8140 } 8141 } else { 8142 pkg.applicationInfo.primaryCpuAbi = null; 8143 pkg.applicationInfo.secondaryCpuAbi = null; 8144 } 8145 } 8146 8147 private void killApplication(String pkgName, int appId, String reason) { 8148 // Request the ActivityManager to kill the process(only for existing packages) 8149 // so that we do not end up in a confused state while the user is still using the older 8150 // version of the application while the new one gets installed. 8151 IActivityManager am = ActivityManagerNative.getDefault(); 8152 if (am != null) { 8153 try { 8154 am.killApplicationWithAppId(pkgName, appId, reason); 8155 } catch (RemoteException e) { 8156 } 8157 } 8158 } 8159 8160 void removePackageLI(PackageSetting ps, boolean chatty) { 8161 if (DEBUG_INSTALL) { 8162 if (chatty) 8163 Log.d(TAG, "Removing package " + ps.name); 8164 } 8165 8166 // writer 8167 synchronized (mPackages) { 8168 mPackages.remove(ps.name); 8169 final PackageParser.Package pkg = ps.pkg; 8170 if (pkg != null) { 8171 cleanPackageDataStructuresLILPw(pkg, chatty); 8172 } 8173 } 8174 } 8175 8176 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8177 if (DEBUG_INSTALL) { 8178 if (chatty) 8179 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8180 } 8181 8182 // writer 8183 synchronized (mPackages) { 8184 mPackages.remove(pkg.applicationInfo.packageName); 8185 cleanPackageDataStructuresLILPw(pkg, chatty); 8186 } 8187 } 8188 8189 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8190 int N = pkg.providers.size(); 8191 StringBuilder r = null; 8192 int i; 8193 for (i=0; i<N; i++) { 8194 PackageParser.Provider p = pkg.providers.get(i); 8195 mProviders.removeProvider(p); 8196 if (p.info.authority == null) { 8197 8198 /* There was another ContentProvider with this authority when 8199 * this app was installed so this authority is null, 8200 * Ignore it as we don't have to unregister the provider. 8201 */ 8202 continue; 8203 } 8204 String names[] = p.info.authority.split(";"); 8205 for (int j = 0; j < names.length; j++) { 8206 if (mProvidersByAuthority.get(names[j]) == p) { 8207 mProvidersByAuthority.remove(names[j]); 8208 if (DEBUG_REMOVE) { 8209 if (chatty) 8210 Log.d(TAG, "Unregistered content provider: " + names[j] 8211 + ", className = " + p.info.name + ", isSyncable = " 8212 + p.info.isSyncable); 8213 } 8214 } 8215 } 8216 if (DEBUG_REMOVE && chatty) { 8217 if (r == null) { 8218 r = new StringBuilder(256); 8219 } else { 8220 r.append(' '); 8221 } 8222 r.append(p.info.name); 8223 } 8224 } 8225 if (r != null) { 8226 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8227 } 8228 8229 N = pkg.services.size(); 8230 r = null; 8231 for (i=0; i<N; i++) { 8232 PackageParser.Service s = pkg.services.get(i); 8233 mServices.removeService(s); 8234 if (chatty) { 8235 if (r == null) { 8236 r = new StringBuilder(256); 8237 } else { 8238 r.append(' '); 8239 } 8240 r.append(s.info.name); 8241 } 8242 } 8243 if (r != null) { 8244 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8245 } 8246 8247 N = pkg.receivers.size(); 8248 r = null; 8249 for (i=0; i<N; i++) { 8250 PackageParser.Activity a = pkg.receivers.get(i); 8251 mReceivers.removeActivity(a, "receiver"); 8252 if (DEBUG_REMOVE && chatty) { 8253 if (r == null) { 8254 r = new StringBuilder(256); 8255 } else { 8256 r.append(' '); 8257 } 8258 r.append(a.info.name); 8259 } 8260 } 8261 if (r != null) { 8262 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8263 } 8264 8265 N = pkg.activities.size(); 8266 r = null; 8267 for (i=0; i<N; i++) { 8268 PackageParser.Activity a = pkg.activities.get(i); 8269 mActivities.removeActivity(a, "activity"); 8270 if (DEBUG_REMOVE && chatty) { 8271 if (r == null) { 8272 r = new StringBuilder(256); 8273 } else { 8274 r.append(' '); 8275 } 8276 r.append(a.info.name); 8277 } 8278 } 8279 if (r != null) { 8280 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8281 } 8282 8283 N = pkg.permissions.size(); 8284 r = null; 8285 for (i=0; i<N; i++) { 8286 PackageParser.Permission p = pkg.permissions.get(i); 8287 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8288 if (bp == null) { 8289 bp = mSettings.mPermissionTrees.get(p.info.name); 8290 } 8291 if (bp != null && bp.perm == p) { 8292 bp.perm = null; 8293 if (DEBUG_REMOVE && chatty) { 8294 if (r == null) { 8295 r = new StringBuilder(256); 8296 } else { 8297 r.append(' '); 8298 } 8299 r.append(p.info.name); 8300 } 8301 } 8302 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8303 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8304 if (appOpPerms != null) { 8305 appOpPerms.remove(pkg.packageName); 8306 } 8307 } 8308 } 8309 if (r != null) { 8310 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8311 } 8312 8313 N = pkg.requestedPermissions.size(); 8314 r = null; 8315 for (i=0; i<N; i++) { 8316 String perm = pkg.requestedPermissions.get(i); 8317 BasePermission bp = mSettings.mPermissions.get(perm); 8318 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8319 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8320 if (appOpPerms != null) { 8321 appOpPerms.remove(pkg.packageName); 8322 if (appOpPerms.isEmpty()) { 8323 mAppOpPermissionPackages.remove(perm); 8324 } 8325 } 8326 } 8327 } 8328 if (r != null) { 8329 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8330 } 8331 8332 N = pkg.instrumentation.size(); 8333 r = null; 8334 for (i=0; i<N; i++) { 8335 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8336 mInstrumentation.remove(a.getComponentName()); 8337 if (DEBUG_REMOVE && chatty) { 8338 if (r == null) { 8339 r = new StringBuilder(256); 8340 } else { 8341 r.append(' '); 8342 } 8343 r.append(a.info.name); 8344 } 8345 } 8346 if (r != null) { 8347 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8348 } 8349 8350 r = null; 8351 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8352 // Only system apps can hold shared libraries. 8353 if (pkg.libraryNames != null) { 8354 for (i=0; i<pkg.libraryNames.size(); i++) { 8355 String name = pkg.libraryNames.get(i); 8356 SharedLibraryEntry cur = mSharedLibraries.get(name); 8357 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8358 mSharedLibraries.remove(name); 8359 if (DEBUG_REMOVE && chatty) { 8360 if (r == null) { 8361 r = new StringBuilder(256); 8362 } else { 8363 r.append(' '); 8364 } 8365 r.append(name); 8366 } 8367 } 8368 } 8369 } 8370 } 8371 if (r != null) { 8372 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8373 } 8374 } 8375 8376 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8377 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8378 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8379 return true; 8380 } 8381 } 8382 return false; 8383 } 8384 8385 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8386 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8387 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8388 8389 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8390 int flags) { 8391 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8392 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8393 } 8394 8395 private void updatePermissionsLPw(String changingPkg, 8396 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8397 // Make sure there are no dangling permission trees. 8398 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8399 while (it.hasNext()) { 8400 final BasePermission bp = it.next(); 8401 if (bp.packageSetting == null) { 8402 // We may not yet have parsed the package, so just see if 8403 // we still know about its settings. 8404 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8405 } 8406 if (bp.packageSetting == null) { 8407 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8408 + " from package " + bp.sourcePackage); 8409 it.remove(); 8410 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8411 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8412 Slog.i(TAG, "Removing old permission tree: " + bp.name 8413 + " from package " + bp.sourcePackage); 8414 flags |= UPDATE_PERMISSIONS_ALL; 8415 it.remove(); 8416 } 8417 } 8418 } 8419 8420 // Make sure all dynamic permissions have been assigned to a package, 8421 // and make sure there are no dangling permissions. 8422 it = mSettings.mPermissions.values().iterator(); 8423 while (it.hasNext()) { 8424 final BasePermission bp = it.next(); 8425 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8426 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8427 + bp.name + " pkg=" + bp.sourcePackage 8428 + " info=" + bp.pendingInfo); 8429 if (bp.packageSetting == null && bp.pendingInfo != null) { 8430 final BasePermission tree = findPermissionTreeLP(bp.name); 8431 if (tree != null && tree.perm != null) { 8432 bp.packageSetting = tree.packageSetting; 8433 bp.perm = new PackageParser.Permission(tree.perm.owner, 8434 new PermissionInfo(bp.pendingInfo)); 8435 bp.perm.info.packageName = tree.perm.info.packageName; 8436 bp.perm.info.name = bp.name; 8437 bp.uid = tree.uid; 8438 } 8439 } 8440 } 8441 if (bp.packageSetting == null) { 8442 // We may not yet have parsed the package, so just see if 8443 // we still know about its settings. 8444 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8445 } 8446 if (bp.packageSetting == null) { 8447 Slog.w(TAG, "Removing dangling permission: " + bp.name 8448 + " from package " + bp.sourcePackage); 8449 it.remove(); 8450 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8451 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8452 Slog.i(TAG, "Removing old permission: " + bp.name 8453 + " from package " + bp.sourcePackage); 8454 flags |= UPDATE_PERMISSIONS_ALL; 8455 it.remove(); 8456 } 8457 } 8458 } 8459 8460 // Now update the permissions for all packages, in particular 8461 // replace the granted permissions of the system packages. 8462 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8463 for (PackageParser.Package pkg : mPackages.values()) { 8464 if (pkg != pkgInfo) { 8465 // Only replace for packages on requested volume 8466 final String volumeUuid = getVolumeUuidForPackage(pkg); 8467 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8468 && Objects.equals(replaceVolumeUuid, volumeUuid); 8469 grantPermissionsLPw(pkg, replace, changingPkg); 8470 } 8471 } 8472 } 8473 8474 if (pkgInfo != null) { 8475 // Only replace for packages on requested volume 8476 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8477 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8478 && Objects.equals(replaceVolumeUuid, volumeUuid); 8479 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8480 } 8481 } 8482 8483 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8484 String packageOfInterest) { 8485 // IMPORTANT: There are two types of permissions: install and runtime. 8486 // Install time permissions are granted when the app is installed to 8487 // all device users and users added in the future. Runtime permissions 8488 // are granted at runtime explicitly to specific users. Normal and signature 8489 // protected permissions are install time permissions. Dangerous permissions 8490 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8491 // otherwise they are runtime permissions. This function does not manage 8492 // runtime permissions except for the case an app targeting Lollipop MR1 8493 // being upgraded to target a newer SDK, in which case dangerous permissions 8494 // are transformed from install time to runtime ones. 8495 8496 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8497 if (ps == null) { 8498 return; 8499 } 8500 8501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8502 8503 PermissionsState permissionsState = ps.getPermissionsState(); 8504 PermissionsState origPermissions = permissionsState; 8505 8506 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8507 8508 boolean runtimePermissionsRevoked = false; 8509 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8510 8511 boolean changedInstallPermission = false; 8512 8513 if (replace) { 8514 ps.installPermissionsFixed = false; 8515 if (!ps.isSharedUser()) { 8516 origPermissions = new PermissionsState(permissionsState); 8517 permissionsState.reset(); 8518 } else { 8519 // We need to know only about runtime permission changes since the 8520 // calling code always writes the install permissions state but 8521 // the runtime ones are written only if changed. The only cases of 8522 // changed runtime permissions here are promotion of an install to 8523 // runtime and revocation of a runtime from a shared user. 8524 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8525 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8526 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8527 runtimePermissionsRevoked = true; 8528 } 8529 } 8530 } 8531 8532 permissionsState.setGlobalGids(mGlobalGids); 8533 8534 final int N = pkg.requestedPermissions.size(); 8535 for (int i=0; i<N; i++) { 8536 final String name = pkg.requestedPermissions.get(i); 8537 final BasePermission bp = mSettings.mPermissions.get(name); 8538 8539 if (DEBUG_INSTALL) { 8540 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8541 } 8542 8543 if (bp == null || bp.packageSetting == null) { 8544 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8545 Slog.w(TAG, "Unknown permission " + name 8546 + " in package " + pkg.packageName); 8547 } 8548 continue; 8549 } 8550 8551 final String perm = bp.name; 8552 boolean allowedSig = false; 8553 int grant = GRANT_DENIED; 8554 8555 // Keep track of app op permissions. 8556 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8557 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8558 if (pkgs == null) { 8559 pkgs = new ArraySet<>(); 8560 mAppOpPermissionPackages.put(bp.name, pkgs); 8561 } 8562 pkgs.add(pkg.packageName); 8563 } 8564 8565 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8566 switch (level) { 8567 case PermissionInfo.PROTECTION_NORMAL: { 8568 // For all apps normal permissions are install time ones. 8569 grant = GRANT_INSTALL; 8570 } break; 8571 8572 case PermissionInfo.PROTECTION_DANGEROUS: { 8573 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8574 // For legacy apps dangerous permissions are install time ones. 8575 grant = GRANT_INSTALL_LEGACY; 8576 } else if (origPermissions.hasInstallPermission(bp.name)) { 8577 // For legacy apps that became modern, install becomes runtime. 8578 grant = GRANT_UPGRADE; 8579 } else if (mPromoteSystemApps 8580 && isSystemApp(ps) 8581 && mExistingSystemPackages.contains(ps.name)) { 8582 // For legacy system apps, install becomes runtime. 8583 // We cannot check hasInstallPermission() for system apps since those 8584 // permissions were granted implicitly and not persisted pre-M. 8585 grant = GRANT_UPGRADE; 8586 } else { 8587 // For modern apps keep runtime permissions unchanged. 8588 grant = GRANT_RUNTIME; 8589 } 8590 } break; 8591 8592 case PermissionInfo.PROTECTION_SIGNATURE: { 8593 // For all apps signature permissions are install time ones. 8594 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8595 if (allowedSig) { 8596 grant = GRANT_INSTALL; 8597 } 8598 } break; 8599 } 8600 8601 if (DEBUG_INSTALL) { 8602 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8603 } 8604 8605 if (grant != GRANT_DENIED) { 8606 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8607 // If this is an existing, non-system package, then 8608 // we can't add any new permissions to it. 8609 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8610 // Except... if this is a permission that was added 8611 // to the platform (note: need to only do this when 8612 // updating the platform). 8613 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8614 grant = GRANT_DENIED; 8615 } 8616 } 8617 } 8618 8619 switch (grant) { 8620 case GRANT_INSTALL: { 8621 // Revoke this as runtime permission to handle the case of 8622 // a runtime permission being downgraded to an install one. 8623 for (int userId : UserManagerService.getInstance().getUserIds()) { 8624 if (origPermissions.getRuntimePermissionState( 8625 bp.name, userId) != null) { 8626 // Revoke the runtime permission and clear the flags. 8627 origPermissions.revokeRuntimePermission(bp, userId); 8628 origPermissions.updatePermissionFlags(bp, userId, 8629 PackageManager.MASK_PERMISSION_FLAGS, 0); 8630 // If we revoked a permission permission, we have to write. 8631 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8632 changedRuntimePermissionUserIds, userId); 8633 } 8634 } 8635 // Grant an install permission. 8636 if (permissionsState.grantInstallPermission(bp) != 8637 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8638 changedInstallPermission = true; 8639 } 8640 } break; 8641 8642 case GRANT_INSTALL_LEGACY: { 8643 // Grant an install permission. 8644 if (permissionsState.grantInstallPermission(bp) != 8645 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8646 changedInstallPermission = true; 8647 } 8648 } break; 8649 8650 case GRANT_RUNTIME: { 8651 // Grant previously granted runtime permissions. 8652 for (int userId : UserManagerService.getInstance().getUserIds()) { 8653 PermissionState permissionState = origPermissions 8654 .getRuntimePermissionState(bp.name, userId); 8655 final int flags = permissionState != null 8656 ? permissionState.getFlags() : 0; 8657 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8658 if (permissionsState.grantRuntimePermission(bp, userId) == 8659 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8660 // If we cannot put the permission as it was, we have to write. 8661 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8662 changedRuntimePermissionUserIds, userId); 8663 } 8664 } 8665 // Propagate the permission flags. 8666 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8667 } 8668 } break; 8669 8670 case GRANT_UPGRADE: { 8671 // Grant runtime permissions for a previously held install permission. 8672 PermissionState permissionState = origPermissions 8673 .getInstallPermissionState(bp.name); 8674 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8675 8676 if (origPermissions.revokeInstallPermission(bp) 8677 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8678 // We will be transferring the permission flags, so clear them. 8679 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8680 PackageManager.MASK_PERMISSION_FLAGS, 0); 8681 changedInstallPermission = true; 8682 } 8683 8684 // If the permission is not to be promoted to runtime we ignore it and 8685 // also its other flags as they are not applicable to install permissions. 8686 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8687 for (int userId : currentUserIds) { 8688 if (permissionsState.grantRuntimePermission(bp, userId) != 8689 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8690 // Transfer the permission flags. 8691 permissionsState.updatePermissionFlags(bp, userId, 8692 flags, flags); 8693 // If we granted the permission, we have to write. 8694 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8695 changedRuntimePermissionUserIds, userId); 8696 } 8697 } 8698 } 8699 } break; 8700 8701 default: { 8702 if (packageOfInterest == null 8703 || packageOfInterest.equals(pkg.packageName)) { 8704 Slog.w(TAG, "Not granting permission " + perm 8705 + " to package " + pkg.packageName 8706 + " because it was previously installed without"); 8707 } 8708 } break; 8709 } 8710 } else { 8711 if (permissionsState.revokeInstallPermission(bp) != 8712 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8713 // Also drop the permission flags. 8714 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8715 PackageManager.MASK_PERMISSION_FLAGS, 0); 8716 changedInstallPermission = true; 8717 Slog.i(TAG, "Un-granting permission " + perm 8718 + " from package " + pkg.packageName 8719 + " (protectionLevel=" + bp.protectionLevel 8720 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8721 + ")"); 8722 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8723 // Don't print warning for app op permissions, since it is fine for them 8724 // not to be granted, there is a UI for the user to decide. 8725 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8726 Slog.w(TAG, "Not granting permission " + perm 8727 + " to package " + pkg.packageName 8728 + " (protectionLevel=" + bp.protectionLevel 8729 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8730 + ")"); 8731 } 8732 } 8733 } 8734 } 8735 8736 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8737 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8738 // This is the first that we have heard about this package, so the 8739 // permissions we have now selected are fixed until explicitly 8740 // changed. 8741 ps.installPermissionsFixed = true; 8742 } 8743 8744 // Persist the runtime permissions state for users with changes. If permissions 8745 // were revoked because no app in the shared user declares them we have to 8746 // write synchronously to avoid losing runtime permissions state. 8747 for (int userId : changedRuntimePermissionUserIds) { 8748 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8749 } 8750 8751 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8752 } 8753 8754 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8755 boolean allowed = false; 8756 final int NP = PackageParser.NEW_PERMISSIONS.length; 8757 for (int ip=0; ip<NP; ip++) { 8758 final PackageParser.NewPermissionInfo npi 8759 = PackageParser.NEW_PERMISSIONS[ip]; 8760 if (npi.name.equals(perm) 8761 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8762 allowed = true; 8763 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8764 + pkg.packageName); 8765 break; 8766 } 8767 } 8768 return allowed; 8769 } 8770 8771 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8772 BasePermission bp, PermissionsState origPermissions) { 8773 boolean allowed; 8774 allowed = (compareSignatures( 8775 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8776 == PackageManager.SIGNATURE_MATCH) 8777 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8778 == PackageManager.SIGNATURE_MATCH); 8779 if (!allowed && (bp.protectionLevel 8780 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8781 if (isSystemApp(pkg)) { 8782 // For updated system applications, a system permission 8783 // is granted only if it had been defined by the original application. 8784 if (pkg.isUpdatedSystemApp()) { 8785 final PackageSetting sysPs = mSettings 8786 .getDisabledSystemPkgLPr(pkg.packageName); 8787 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8788 // If the original was granted this permission, we take 8789 // that grant decision as read and propagate it to the 8790 // update. 8791 if (sysPs.isPrivileged()) { 8792 allowed = true; 8793 } 8794 } else { 8795 // The system apk may have been updated with an older 8796 // version of the one on the data partition, but which 8797 // granted a new system permission that it didn't have 8798 // before. In this case we do want to allow the app to 8799 // now get the new permission if the ancestral apk is 8800 // privileged to get it. 8801 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8802 for (int j=0; 8803 j<sysPs.pkg.requestedPermissions.size(); j++) { 8804 if (perm.equals( 8805 sysPs.pkg.requestedPermissions.get(j))) { 8806 allowed = true; 8807 break; 8808 } 8809 } 8810 } 8811 } 8812 } else { 8813 allowed = isPrivilegedApp(pkg); 8814 } 8815 } 8816 } 8817 if (!allowed) { 8818 if (!allowed && (bp.protectionLevel 8819 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8820 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 8821 // If this was a previously normal/dangerous permission that got moved 8822 // to a system permission as part of the runtime permission redesign, then 8823 // we still want to blindly grant it to old apps. 8824 allowed = true; 8825 } 8826 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8827 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8828 // If this permission is to be granted to the system installer and 8829 // this app is an installer, then it gets the permission. 8830 allowed = true; 8831 } 8832 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8833 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8834 // If this permission is to be granted to the system verifier and 8835 // this app is a verifier, then it gets the permission. 8836 allowed = true; 8837 } 8838 if (!allowed && (bp.protectionLevel 8839 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8840 && isSystemApp(pkg)) { 8841 // Any pre-installed system app is allowed to get this permission. 8842 allowed = true; 8843 } 8844 if (!allowed && (bp.protectionLevel 8845 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8846 // For development permissions, a development permission 8847 // is granted only if it was already granted. 8848 allowed = origPermissions.hasInstallPermission(perm); 8849 } 8850 } 8851 return allowed; 8852 } 8853 8854 final class ActivityIntentResolver 8855 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8856 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8857 boolean defaultOnly, int userId) { 8858 if (!sUserManager.exists(userId)) return null; 8859 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8860 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8861 } 8862 8863 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8864 int userId) { 8865 if (!sUserManager.exists(userId)) return null; 8866 mFlags = flags; 8867 return super.queryIntent(intent, resolvedType, 8868 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8869 } 8870 8871 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8872 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8873 if (!sUserManager.exists(userId)) return null; 8874 if (packageActivities == null) { 8875 return null; 8876 } 8877 mFlags = flags; 8878 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8879 final int N = packageActivities.size(); 8880 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8881 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8882 8883 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8884 for (int i = 0; i < N; ++i) { 8885 intentFilters = packageActivities.get(i).intents; 8886 if (intentFilters != null && intentFilters.size() > 0) { 8887 PackageParser.ActivityIntentInfo[] array = 8888 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8889 intentFilters.toArray(array); 8890 listCut.add(array); 8891 } 8892 } 8893 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8894 } 8895 8896 public final void addActivity(PackageParser.Activity a, String type) { 8897 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8898 mActivities.put(a.getComponentName(), a); 8899 if (DEBUG_SHOW_INFO) 8900 Log.v( 8901 TAG, " " + type + " " + 8902 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8903 if (DEBUG_SHOW_INFO) 8904 Log.v(TAG, " Class=" + a.info.name); 8905 final int NI = a.intents.size(); 8906 for (int j=0; j<NI; j++) { 8907 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8908 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8909 intent.setPriority(0); 8910 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8911 + a.className + " with priority > 0, forcing to 0"); 8912 } 8913 if (DEBUG_SHOW_INFO) { 8914 Log.v(TAG, " IntentFilter:"); 8915 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8916 } 8917 if (!intent.debugCheck()) { 8918 Log.w(TAG, "==> For Activity " + a.info.name); 8919 } 8920 addFilter(intent); 8921 } 8922 } 8923 8924 public final void removeActivity(PackageParser.Activity a, String type) { 8925 mActivities.remove(a.getComponentName()); 8926 if (DEBUG_SHOW_INFO) { 8927 Log.v(TAG, " " + type + " " 8928 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8929 : a.info.name) + ":"); 8930 Log.v(TAG, " Class=" + a.info.name); 8931 } 8932 final int NI = a.intents.size(); 8933 for (int j=0; j<NI; j++) { 8934 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8935 if (DEBUG_SHOW_INFO) { 8936 Log.v(TAG, " IntentFilter:"); 8937 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8938 } 8939 removeFilter(intent); 8940 } 8941 } 8942 8943 @Override 8944 protected boolean allowFilterResult( 8945 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8946 ActivityInfo filterAi = filter.activity.info; 8947 for (int i=dest.size()-1; i>=0; i--) { 8948 ActivityInfo destAi = dest.get(i).activityInfo; 8949 if (destAi.name == filterAi.name 8950 && destAi.packageName == filterAi.packageName) { 8951 return false; 8952 } 8953 } 8954 return true; 8955 } 8956 8957 @Override 8958 protected ActivityIntentInfo[] newArray(int size) { 8959 return new ActivityIntentInfo[size]; 8960 } 8961 8962 @Override 8963 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8964 if (!sUserManager.exists(userId)) return true; 8965 PackageParser.Package p = filter.activity.owner; 8966 if (p != null) { 8967 PackageSetting ps = (PackageSetting)p.mExtras; 8968 if (ps != null) { 8969 // System apps are never considered stopped for purposes of 8970 // filtering, because there may be no way for the user to 8971 // actually re-launch them. 8972 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8973 && ps.getStopped(userId); 8974 } 8975 } 8976 return false; 8977 } 8978 8979 @Override 8980 protected boolean isPackageForFilter(String packageName, 8981 PackageParser.ActivityIntentInfo info) { 8982 return packageName.equals(info.activity.owner.packageName); 8983 } 8984 8985 @Override 8986 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8987 int match, int userId) { 8988 if (!sUserManager.exists(userId)) return null; 8989 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8990 return null; 8991 } 8992 final PackageParser.Activity activity = info.activity; 8993 if (mSafeMode && (activity.info.applicationInfo.flags 8994 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8995 return null; 8996 } 8997 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8998 if (ps == null) { 8999 return null; 9000 } 9001 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9002 ps.readUserState(userId), userId); 9003 if (ai == null) { 9004 return null; 9005 } 9006 final ResolveInfo res = new ResolveInfo(); 9007 res.activityInfo = ai; 9008 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9009 res.filter = info; 9010 } 9011 if (info != null) { 9012 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9013 } 9014 res.priority = info.getPriority(); 9015 res.preferredOrder = activity.owner.mPreferredOrder; 9016 //System.out.println("Result: " + res.activityInfo.className + 9017 // " = " + res.priority); 9018 res.match = match; 9019 res.isDefault = info.hasDefault; 9020 res.labelRes = info.labelRes; 9021 res.nonLocalizedLabel = info.nonLocalizedLabel; 9022 if (userNeedsBadging(userId)) { 9023 res.noResourceId = true; 9024 } else { 9025 res.icon = info.icon; 9026 } 9027 res.iconResourceId = info.icon; 9028 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9029 return res; 9030 } 9031 9032 @Override 9033 protected void sortResults(List<ResolveInfo> results) { 9034 Collections.sort(results, mResolvePrioritySorter); 9035 } 9036 9037 @Override 9038 protected void dumpFilter(PrintWriter out, String prefix, 9039 PackageParser.ActivityIntentInfo filter) { 9040 out.print(prefix); out.print( 9041 Integer.toHexString(System.identityHashCode(filter.activity))); 9042 out.print(' '); 9043 filter.activity.printComponentShortName(out); 9044 out.print(" filter "); 9045 out.println(Integer.toHexString(System.identityHashCode(filter))); 9046 } 9047 9048 @Override 9049 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9050 return filter.activity; 9051 } 9052 9053 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9054 PackageParser.Activity activity = (PackageParser.Activity)label; 9055 out.print(prefix); out.print( 9056 Integer.toHexString(System.identityHashCode(activity))); 9057 out.print(' '); 9058 activity.printComponentShortName(out); 9059 if (count > 1) { 9060 out.print(" ("); out.print(count); out.print(" filters)"); 9061 } 9062 out.println(); 9063 } 9064 9065// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9066// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9067// final List<ResolveInfo> retList = Lists.newArrayList(); 9068// while (i.hasNext()) { 9069// final ResolveInfo resolveInfo = i.next(); 9070// if (isEnabledLP(resolveInfo.activityInfo)) { 9071// retList.add(resolveInfo); 9072// } 9073// } 9074// return retList; 9075// } 9076 9077 // Keys are String (activity class name), values are Activity. 9078 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9079 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9080 private int mFlags; 9081 } 9082 9083 private final class ServiceIntentResolver 9084 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9085 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9086 boolean defaultOnly, int userId) { 9087 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9088 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9089 } 9090 9091 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9092 int userId) { 9093 if (!sUserManager.exists(userId)) return null; 9094 mFlags = flags; 9095 return super.queryIntent(intent, resolvedType, 9096 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9097 } 9098 9099 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9100 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9101 if (!sUserManager.exists(userId)) return null; 9102 if (packageServices == null) { 9103 return null; 9104 } 9105 mFlags = flags; 9106 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9107 final int N = packageServices.size(); 9108 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9109 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9110 9111 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9112 for (int i = 0; i < N; ++i) { 9113 intentFilters = packageServices.get(i).intents; 9114 if (intentFilters != null && intentFilters.size() > 0) { 9115 PackageParser.ServiceIntentInfo[] array = 9116 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9117 intentFilters.toArray(array); 9118 listCut.add(array); 9119 } 9120 } 9121 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9122 } 9123 9124 public final void addService(PackageParser.Service s) { 9125 mServices.put(s.getComponentName(), s); 9126 if (DEBUG_SHOW_INFO) { 9127 Log.v(TAG, " " 9128 + (s.info.nonLocalizedLabel != null 9129 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9130 Log.v(TAG, " Class=" + s.info.name); 9131 } 9132 final int NI = s.intents.size(); 9133 int j; 9134 for (j=0; j<NI; j++) { 9135 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9136 if (DEBUG_SHOW_INFO) { 9137 Log.v(TAG, " IntentFilter:"); 9138 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9139 } 9140 if (!intent.debugCheck()) { 9141 Log.w(TAG, "==> For Service " + s.info.name); 9142 } 9143 addFilter(intent); 9144 } 9145 } 9146 9147 public final void removeService(PackageParser.Service s) { 9148 mServices.remove(s.getComponentName()); 9149 if (DEBUG_SHOW_INFO) { 9150 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9151 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9152 Log.v(TAG, " Class=" + s.info.name); 9153 } 9154 final int NI = s.intents.size(); 9155 int j; 9156 for (j=0; j<NI; j++) { 9157 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9158 if (DEBUG_SHOW_INFO) { 9159 Log.v(TAG, " IntentFilter:"); 9160 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9161 } 9162 removeFilter(intent); 9163 } 9164 } 9165 9166 @Override 9167 protected boolean allowFilterResult( 9168 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9169 ServiceInfo filterSi = filter.service.info; 9170 for (int i=dest.size()-1; i>=0; i--) { 9171 ServiceInfo destAi = dest.get(i).serviceInfo; 9172 if (destAi.name == filterSi.name 9173 && destAi.packageName == filterSi.packageName) { 9174 return false; 9175 } 9176 } 9177 return true; 9178 } 9179 9180 @Override 9181 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9182 return new PackageParser.ServiceIntentInfo[size]; 9183 } 9184 9185 @Override 9186 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9187 if (!sUserManager.exists(userId)) return true; 9188 PackageParser.Package p = filter.service.owner; 9189 if (p != null) { 9190 PackageSetting ps = (PackageSetting)p.mExtras; 9191 if (ps != null) { 9192 // System apps are never considered stopped for purposes of 9193 // filtering, because there may be no way for the user to 9194 // actually re-launch them. 9195 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9196 && ps.getStopped(userId); 9197 } 9198 } 9199 return false; 9200 } 9201 9202 @Override 9203 protected boolean isPackageForFilter(String packageName, 9204 PackageParser.ServiceIntentInfo info) { 9205 return packageName.equals(info.service.owner.packageName); 9206 } 9207 9208 @Override 9209 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9210 int match, int userId) { 9211 if (!sUserManager.exists(userId)) return null; 9212 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9213 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 9214 return null; 9215 } 9216 final PackageParser.Service service = info.service; 9217 if (mSafeMode && (service.info.applicationInfo.flags 9218 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9219 return null; 9220 } 9221 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9222 if (ps == null) { 9223 return null; 9224 } 9225 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9226 ps.readUserState(userId), userId); 9227 if (si == null) { 9228 return null; 9229 } 9230 final ResolveInfo res = new ResolveInfo(); 9231 res.serviceInfo = si; 9232 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9233 res.filter = filter; 9234 } 9235 res.priority = info.getPriority(); 9236 res.preferredOrder = service.owner.mPreferredOrder; 9237 res.match = match; 9238 res.isDefault = info.hasDefault; 9239 res.labelRes = info.labelRes; 9240 res.nonLocalizedLabel = info.nonLocalizedLabel; 9241 res.icon = info.icon; 9242 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9243 return res; 9244 } 9245 9246 @Override 9247 protected void sortResults(List<ResolveInfo> results) { 9248 Collections.sort(results, mResolvePrioritySorter); 9249 } 9250 9251 @Override 9252 protected void dumpFilter(PrintWriter out, String prefix, 9253 PackageParser.ServiceIntentInfo filter) { 9254 out.print(prefix); out.print( 9255 Integer.toHexString(System.identityHashCode(filter.service))); 9256 out.print(' '); 9257 filter.service.printComponentShortName(out); 9258 out.print(" filter "); 9259 out.println(Integer.toHexString(System.identityHashCode(filter))); 9260 } 9261 9262 @Override 9263 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9264 return filter.service; 9265 } 9266 9267 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9268 PackageParser.Service service = (PackageParser.Service)label; 9269 out.print(prefix); out.print( 9270 Integer.toHexString(System.identityHashCode(service))); 9271 out.print(' '); 9272 service.printComponentShortName(out); 9273 if (count > 1) { 9274 out.print(" ("); out.print(count); out.print(" filters)"); 9275 } 9276 out.println(); 9277 } 9278 9279// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9280// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9281// final List<ResolveInfo> retList = Lists.newArrayList(); 9282// while (i.hasNext()) { 9283// final ResolveInfo resolveInfo = (ResolveInfo) i; 9284// if (isEnabledLP(resolveInfo.serviceInfo)) { 9285// retList.add(resolveInfo); 9286// } 9287// } 9288// return retList; 9289// } 9290 9291 // Keys are String (activity class name), values are Activity. 9292 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9293 = new ArrayMap<ComponentName, PackageParser.Service>(); 9294 private int mFlags; 9295 }; 9296 9297 private final class ProviderIntentResolver 9298 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9299 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9300 boolean defaultOnly, int userId) { 9301 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9302 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9303 } 9304 9305 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9306 int userId) { 9307 if (!sUserManager.exists(userId)) 9308 return null; 9309 mFlags = flags; 9310 return super.queryIntent(intent, resolvedType, 9311 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9312 } 9313 9314 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9315 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9316 if (!sUserManager.exists(userId)) 9317 return null; 9318 if (packageProviders == null) { 9319 return null; 9320 } 9321 mFlags = flags; 9322 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9323 final int N = packageProviders.size(); 9324 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9325 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9326 9327 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9328 for (int i = 0; i < N; ++i) { 9329 intentFilters = packageProviders.get(i).intents; 9330 if (intentFilters != null && intentFilters.size() > 0) { 9331 PackageParser.ProviderIntentInfo[] array = 9332 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9333 intentFilters.toArray(array); 9334 listCut.add(array); 9335 } 9336 } 9337 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9338 } 9339 9340 public final void addProvider(PackageParser.Provider p) { 9341 if (mProviders.containsKey(p.getComponentName())) { 9342 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9343 return; 9344 } 9345 9346 mProviders.put(p.getComponentName(), p); 9347 if (DEBUG_SHOW_INFO) { 9348 Log.v(TAG, " " 9349 + (p.info.nonLocalizedLabel != null 9350 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9351 Log.v(TAG, " Class=" + p.info.name); 9352 } 9353 final int NI = p.intents.size(); 9354 int j; 9355 for (j = 0; j < NI; j++) { 9356 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9357 if (DEBUG_SHOW_INFO) { 9358 Log.v(TAG, " IntentFilter:"); 9359 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9360 } 9361 if (!intent.debugCheck()) { 9362 Log.w(TAG, "==> For Provider " + p.info.name); 9363 } 9364 addFilter(intent); 9365 } 9366 } 9367 9368 public final void removeProvider(PackageParser.Provider p) { 9369 mProviders.remove(p.getComponentName()); 9370 if (DEBUG_SHOW_INFO) { 9371 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9372 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9373 Log.v(TAG, " Class=" + p.info.name); 9374 } 9375 final int NI = p.intents.size(); 9376 int j; 9377 for (j = 0; j < NI; j++) { 9378 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9379 if (DEBUG_SHOW_INFO) { 9380 Log.v(TAG, " IntentFilter:"); 9381 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9382 } 9383 removeFilter(intent); 9384 } 9385 } 9386 9387 @Override 9388 protected boolean allowFilterResult( 9389 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9390 ProviderInfo filterPi = filter.provider.info; 9391 for (int i = dest.size() - 1; i >= 0; i--) { 9392 ProviderInfo destPi = dest.get(i).providerInfo; 9393 if (destPi.name == filterPi.name 9394 && destPi.packageName == filterPi.packageName) { 9395 return false; 9396 } 9397 } 9398 return true; 9399 } 9400 9401 @Override 9402 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9403 return new PackageParser.ProviderIntentInfo[size]; 9404 } 9405 9406 @Override 9407 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9408 if (!sUserManager.exists(userId)) 9409 return true; 9410 PackageParser.Package p = filter.provider.owner; 9411 if (p != null) { 9412 PackageSetting ps = (PackageSetting) p.mExtras; 9413 if (ps != null) { 9414 // System apps are never considered stopped for purposes of 9415 // filtering, because there may be no way for the user to 9416 // actually re-launch them. 9417 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9418 && ps.getStopped(userId); 9419 } 9420 } 9421 return false; 9422 } 9423 9424 @Override 9425 protected boolean isPackageForFilter(String packageName, 9426 PackageParser.ProviderIntentInfo info) { 9427 return packageName.equals(info.provider.owner.packageName); 9428 } 9429 9430 @Override 9431 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9432 int match, int userId) { 9433 if (!sUserManager.exists(userId)) 9434 return null; 9435 final PackageParser.ProviderIntentInfo info = filter; 9436 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9437 return null; 9438 } 9439 final PackageParser.Provider provider = info.provider; 9440 if (mSafeMode && (provider.info.applicationInfo.flags 9441 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9442 return null; 9443 } 9444 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9445 if (ps == null) { 9446 return null; 9447 } 9448 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9449 ps.readUserState(userId), userId); 9450 if (pi == null) { 9451 return null; 9452 } 9453 final ResolveInfo res = new ResolveInfo(); 9454 res.providerInfo = pi; 9455 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9456 res.filter = filter; 9457 } 9458 res.priority = info.getPriority(); 9459 res.preferredOrder = provider.owner.mPreferredOrder; 9460 res.match = match; 9461 res.isDefault = info.hasDefault; 9462 res.labelRes = info.labelRes; 9463 res.nonLocalizedLabel = info.nonLocalizedLabel; 9464 res.icon = info.icon; 9465 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9466 return res; 9467 } 9468 9469 @Override 9470 protected void sortResults(List<ResolveInfo> results) { 9471 Collections.sort(results, mResolvePrioritySorter); 9472 } 9473 9474 @Override 9475 protected void dumpFilter(PrintWriter out, String prefix, 9476 PackageParser.ProviderIntentInfo filter) { 9477 out.print(prefix); 9478 out.print( 9479 Integer.toHexString(System.identityHashCode(filter.provider))); 9480 out.print(' '); 9481 filter.provider.printComponentShortName(out); 9482 out.print(" filter "); 9483 out.println(Integer.toHexString(System.identityHashCode(filter))); 9484 } 9485 9486 @Override 9487 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9488 return filter.provider; 9489 } 9490 9491 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9492 PackageParser.Provider provider = (PackageParser.Provider)label; 9493 out.print(prefix); out.print( 9494 Integer.toHexString(System.identityHashCode(provider))); 9495 out.print(' '); 9496 provider.printComponentShortName(out); 9497 if (count > 1) { 9498 out.print(" ("); out.print(count); out.print(" filters)"); 9499 } 9500 out.println(); 9501 } 9502 9503 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9504 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9505 private int mFlags; 9506 }; 9507 9508 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9509 new Comparator<ResolveInfo>() { 9510 public int compare(ResolveInfo r1, ResolveInfo r2) { 9511 int v1 = r1.priority; 9512 int v2 = r2.priority; 9513 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9514 if (v1 != v2) { 9515 return (v1 > v2) ? -1 : 1; 9516 } 9517 v1 = r1.preferredOrder; 9518 v2 = r2.preferredOrder; 9519 if (v1 != v2) { 9520 return (v1 > v2) ? -1 : 1; 9521 } 9522 if (r1.isDefault != r2.isDefault) { 9523 return r1.isDefault ? -1 : 1; 9524 } 9525 v1 = r1.match; 9526 v2 = r2.match; 9527 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9528 if (v1 != v2) { 9529 return (v1 > v2) ? -1 : 1; 9530 } 9531 if (r1.system != r2.system) { 9532 return r1.system ? -1 : 1; 9533 } 9534 return 0; 9535 } 9536 }; 9537 9538 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9539 new Comparator<ProviderInfo>() { 9540 public int compare(ProviderInfo p1, ProviderInfo p2) { 9541 final int v1 = p1.initOrder; 9542 final int v2 = p2.initOrder; 9543 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9544 } 9545 }; 9546 9547 final void sendPackageBroadcast(final String action, final String pkg, 9548 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9549 final int[] userIds) { 9550 mHandler.post(new Runnable() { 9551 @Override 9552 public void run() { 9553 try { 9554 final IActivityManager am = ActivityManagerNative.getDefault(); 9555 if (am == null) return; 9556 final int[] resolvedUserIds; 9557 if (userIds == null) { 9558 resolvedUserIds = am.getRunningUserIds(); 9559 } else { 9560 resolvedUserIds = userIds; 9561 } 9562 for (int id : resolvedUserIds) { 9563 final Intent intent = new Intent(action, 9564 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9565 if (extras != null) { 9566 intent.putExtras(extras); 9567 } 9568 if (targetPkg != null) { 9569 intent.setPackage(targetPkg); 9570 } 9571 // Modify the UID when posting to other users 9572 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9573 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9574 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9575 intent.putExtra(Intent.EXTRA_UID, uid); 9576 } 9577 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9578 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9579 if (DEBUG_BROADCASTS) { 9580 RuntimeException here = new RuntimeException("here"); 9581 here.fillInStackTrace(); 9582 Slog.d(TAG, "Sending to user " + id + ": " 9583 + intent.toShortString(false, true, false, false) 9584 + " " + intent.getExtras(), here); 9585 } 9586 am.broadcastIntent(null, intent, null, finishedReceiver, 9587 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9588 null, finishedReceiver != null, false, id); 9589 } 9590 } catch (RemoteException ex) { 9591 } 9592 } 9593 }); 9594 } 9595 9596 /** 9597 * Check if the external storage media is available. This is true if there 9598 * is a mounted external storage medium or if the external storage is 9599 * emulated. 9600 */ 9601 private boolean isExternalMediaAvailable() { 9602 return mMediaMounted || Environment.isExternalStorageEmulated(); 9603 } 9604 9605 @Override 9606 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9607 // writer 9608 synchronized (mPackages) { 9609 if (!isExternalMediaAvailable()) { 9610 // If the external storage is no longer mounted at this point, 9611 // the caller may not have been able to delete all of this 9612 // packages files and can not delete any more. Bail. 9613 return null; 9614 } 9615 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9616 if (lastPackage != null) { 9617 pkgs.remove(lastPackage); 9618 } 9619 if (pkgs.size() > 0) { 9620 return pkgs.get(0); 9621 } 9622 } 9623 return null; 9624 } 9625 9626 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9627 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9628 userId, andCode ? 1 : 0, packageName); 9629 if (mSystemReady) { 9630 msg.sendToTarget(); 9631 } else { 9632 if (mPostSystemReadyMessages == null) { 9633 mPostSystemReadyMessages = new ArrayList<>(); 9634 } 9635 mPostSystemReadyMessages.add(msg); 9636 } 9637 } 9638 9639 void startCleaningPackages() { 9640 // reader 9641 synchronized (mPackages) { 9642 if (!isExternalMediaAvailable()) { 9643 return; 9644 } 9645 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9646 return; 9647 } 9648 } 9649 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9650 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9651 IActivityManager am = ActivityManagerNative.getDefault(); 9652 if (am != null) { 9653 try { 9654 am.startService(null, intent, null, mContext.getOpPackageName(), 9655 UserHandle.USER_SYSTEM); 9656 } catch (RemoteException e) { 9657 } 9658 } 9659 } 9660 9661 @Override 9662 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9663 int installFlags, String installerPackageName, VerificationParams verificationParams, 9664 String packageAbiOverride) { 9665 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9666 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9667 } 9668 9669 @Override 9670 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9671 int installFlags, String installerPackageName, VerificationParams verificationParams, 9672 String packageAbiOverride, int userId) { 9673 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9674 9675 final int callingUid = Binder.getCallingUid(); 9676 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9677 9678 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9679 try { 9680 if (observer != null) { 9681 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9682 } 9683 } catch (RemoteException re) { 9684 } 9685 return; 9686 } 9687 9688 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9689 installFlags |= PackageManager.INSTALL_FROM_ADB; 9690 9691 } else { 9692 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9693 // about installerPackageName. 9694 9695 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9696 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9697 } 9698 9699 UserHandle user; 9700 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9701 user = UserHandle.ALL; 9702 } else { 9703 user = new UserHandle(userId); 9704 } 9705 9706 // Only system components can circumvent runtime permissions when installing. 9707 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9708 && mContext.checkCallingOrSelfPermission(Manifest.permission 9709 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9710 throw new SecurityException("You need the " 9711 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9712 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9713 } 9714 9715 verificationParams.setInstallerUid(callingUid); 9716 9717 final File originFile = new File(originPath); 9718 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9719 9720 final Message msg = mHandler.obtainMessage(INIT_COPY); 9721 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9722 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9723 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9724 msg.obj = params; 9725 9726 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9727 System.identityHashCode(msg.obj)); 9728 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9729 System.identityHashCode(msg.obj)); 9730 9731 mHandler.sendMessage(msg); 9732 } 9733 9734 void installStage(String packageName, File stagedDir, String stagedCid, 9735 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 9736 String installerPackageName, int installerUid, UserHandle user) { 9737 final VerificationParams verifParams = new VerificationParams( 9738 null, sessionParams.originatingUri, sessionParams.referrerUri, 9739 sessionParams.originatingUid, null); 9740 verifParams.setInstallerUid(installerUid); 9741 9742 final OriginInfo origin; 9743 if (stagedDir != null) { 9744 origin = OriginInfo.fromStagedFile(stagedDir); 9745 } else { 9746 origin = OriginInfo.fromStagedContainer(stagedCid); 9747 } 9748 9749 final Message msg = mHandler.obtainMessage(INIT_COPY); 9750 final InstallParams params = new InstallParams(origin, null, observer, 9751 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 9752 verifParams, user, sessionParams.abiOverride, 9753 sessionParams.grantedRuntimePermissions); 9754 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 9755 msg.obj = params; 9756 9757 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 9758 System.identityHashCode(msg.obj)); 9759 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9760 System.identityHashCode(msg.obj)); 9761 9762 mHandler.sendMessage(msg); 9763 } 9764 9765 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9766 Bundle extras = new Bundle(1); 9767 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9768 9769 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9770 packageName, extras, null, null, new int[] {userId}); 9771 try { 9772 IActivityManager am = ActivityManagerNative.getDefault(); 9773 final boolean isSystem = 9774 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9775 if (isSystem && am.isUserRunning(userId, false)) { 9776 // The just-installed/enabled app is bundled on the system, so presumed 9777 // to be able to run automatically without needing an explicit launch. 9778 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9779 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9780 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9781 .setPackage(packageName); 9782 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9783 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9784 } 9785 } catch (RemoteException e) { 9786 // shouldn't happen 9787 Slog.w(TAG, "Unable to bootstrap installed package", e); 9788 } 9789 } 9790 9791 @Override 9792 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9793 int userId) { 9794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9795 PackageSetting pkgSetting; 9796 final int uid = Binder.getCallingUid(); 9797 enforceCrossUserPermission(uid, userId, true, true, 9798 "setApplicationHiddenSetting for user " + userId); 9799 9800 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9801 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9802 return false; 9803 } 9804 9805 long callingId = Binder.clearCallingIdentity(); 9806 try { 9807 boolean sendAdded = false; 9808 boolean sendRemoved = false; 9809 // writer 9810 synchronized (mPackages) { 9811 pkgSetting = mSettings.mPackages.get(packageName); 9812 if (pkgSetting == null) { 9813 return false; 9814 } 9815 if (pkgSetting.getHidden(userId) != hidden) { 9816 pkgSetting.setHidden(hidden, userId); 9817 mSettings.writePackageRestrictionsLPr(userId); 9818 if (hidden) { 9819 sendRemoved = true; 9820 } else { 9821 sendAdded = true; 9822 } 9823 } 9824 } 9825 if (sendAdded) { 9826 sendPackageAddedForUser(packageName, pkgSetting, userId); 9827 return true; 9828 } 9829 if (sendRemoved) { 9830 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9831 "hiding pkg"); 9832 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9833 return true; 9834 } 9835 } finally { 9836 Binder.restoreCallingIdentity(callingId); 9837 } 9838 return false; 9839 } 9840 9841 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9842 int userId) { 9843 final PackageRemovedInfo info = new PackageRemovedInfo(); 9844 info.removedPackage = packageName; 9845 info.removedUsers = new int[] {userId}; 9846 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9847 info.sendBroadcast(false, false, false); 9848 } 9849 9850 /** 9851 * Returns true if application is not found or there was an error. Otherwise it returns 9852 * the hidden state of the package for the given user. 9853 */ 9854 @Override 9855 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9856 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9857 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9858 false, "getApplicationHidden for user " + userId); 9859 PackageSetting pkgSetting; 9860 long callingId = Binder.clearCallingIdentity(); 9861 try { 9862 // writer 9863 synchronized (mPackages) { 9864 pkgSetting = mSettings.mPackages.get(packageName); 9865 if (pkgSetting == null) { 9866 return true; 9867 } 9868 return pkgSetting.getHidden(userId); 9869 } 9870 } finally { 9871 Binder.restoreCallingIdentity(callingId); 9872 } 9873 } 9874 9875 /** 9876 * @hide 9877 */ 9878 @Override 9879 public int installExistingPackageAsUser(String packageName, int userId) { 9880 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9881 null); 9882 PackageSetting pkgSetting; 9883 final int uid = Binder.getCallingUid(); 9884 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9885 + userId); 9886 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9887 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9888 } 9889 9890 long callingId = Binder.clearCallingIdentity(); 9891 try { 9892 boolean sendAdded = false; 9893 9894 // writer 9895 synchronized (mPackages) { 9896 pkgSetting = mSettings.mPackages.get(packageName); 9897 if (pkgSetting == null) { 9898 return PackageManager.INSTALL_FAILED_INVALID_URI; 9899 } 9900 if (!pkgSetting.getInstalled(userId)) { 9901 pkgSetting.setInstalled(true, userId); 9902 pkgSetting.setHidden(false, userId); 9903 mSettings.writePackageRestrictionsLPr(userId); 9904 sendAdded = true; 9905 } 9906 } 9907 9908 if (sendAdded) { 9909 sendPackageAddedForUser(packageName, pkgSetting, userId); 9910 } 9911 } finally { 9912 Binder.restoreCallingIdentity(callingId); 9913 } 9914 9915 return PackageManager.INSTALL_SUCCEEDED; 9916 } 9917 9918 boolean isUserRestricted(int userId, String restrictionKey) { 9919 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9920 if (restrictions.getBoolean(restrictionKey, false)) { 9921 Log.w(TAG, "User is restricted: " + restrictionKey); 9922 return true; 9923 } 9924 return false; 9925 } 9926 9927 @Override 9928 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9929 mContext.enforceCallingOrSelfPermission( 9930 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9931 "Only package verification agents can verify applications"); 9932 9933 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9934 final PackageVerificationResponse response = new PackageVerificationResponse( 9935 verificationCode, Binder.getCallingUid()); 9936 msg.arg1 = id; 9937 msg.obj = response; 9938 mHandler.sendMessage(msg); 9939 } 9940 9941 @Override 9942 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9943 long millisecondsToDelay) { 9944 mContext.enforceCallingOrSelfPermission( 9945 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9946 "Only package verification agents can extend verification timeouts"); 9947 9948 final PackageVerificationState state = mPendingVerification.get(id); 9949 final PackageVerificationResponse response = new PackageVerificationResponse( 9950 verificationCodeAtTimeout, Binder.getCallingUid()); 9951 9952 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9953 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9954 } 9955 if (millisecondsToDelay < 0) { 9956 millisecondsToDelay = 0; 9957 } 9958 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9959 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9960 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9961 } 9962 9963 if ((state != null) && !state.timeoutExtended()) { 9964 state.extendTimeout(); 9965 9966 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9967 msg.arg1 = id; 9968 msg.obj = response; 9969 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9970 } 9971 } 9972 9973 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9974 int verificationCode, UserHandle user) { 9975 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9976 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9977 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9978 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9979 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9980 9981 mContext.sendBroadcastAsUser(intent, user, 9982 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9983 } 9984 9985 private ComponentName matchComponentForVerifier(String packageName, 9986 List<ResolveInfo> receivers) { 9987 ActivityInfo targetReceiver = null; 9988 9989 final int NR = receivers.size(); 9990 for (int i = 0; i < NR; i++) { 9991 final ResolveInfo info = receivers.get(i); 9992 if (info.activityInfo == null) { 9993 continue; 9994 } 9995 9996 if (packageName.equals(info.activityInfo.packageName)) { 9997 targetReceiver = info.activityInfo; 9998 break; 9999 } 10000 } 10001 10002 if (targetReceiver == null) { 10003 return null; 10004 } 10005 10006 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10007 } 10008 10009 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10010 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10011 if (pkgInfo.verifiers.length == 0) { 10012 return null; 10013 } 10014 10015 final int N = pkgInfo.verifiers.length; 10016 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10017 for (int i = 0; i < N; i++) { 10018 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10019 10020 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10021 receivers); 10022 if (comp == null) { 10023 continue; 10024 } 10025 10026 final int verifierUid = getUidForVerifier(verifierInfo); 10027 if (verifierUid == -1) { 10028 continue; 10029 } 10030 10031 if (DEBUG_VERIFY) { 10032 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10033 + " with the correct signature"); 10034 } 10035 sufficientVerifiers.add(comp); 10036 verificationState.addSufficientVerifier(verifierUid); 10037 } 10038 10039 return sufficientVerifiers; 10040 } 10041 10042 private int getUidForVerifier(VerifierInfo verifierInfo) { 10043 synchronized (mPackages) { 10044 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10045 if (pkg == null) { 10046 return -1; 10047 } else if (pkg.mSignatures.length != 1) { 10048 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10049 + " has more than one signature; ignoring"); 10050 return -1; 10051 } 10052 10053 /* 10054 * If the public key of the package's signature does not match 10055 * our expected public key, then this is a different package and 10056 * we should skip. 10057 */ 10058 10059 final byte[] expectedPublicKey; 10060 try { 10061 final Signature verifierSig = pkg.mSignatures[0]; 10062 final PublicKey publicKey = verifierSig.getPublicKey(); 10063 expectedPublicKey = publicKey.getEncoded(); 10064 } catch (CertificateException e) { 10065 return -1; 10066 } 10067 10068 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10069 10070 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10071 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10072 + " does not have the expected public key; ignoring"); 10073 return -1; 10074 } 10075 10076 return pkg.applicationInfo.uid; 10077 } 10078 } 10079 10080 @Override 10081 public void finishPackageInstall(int token) { 10082 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10083 10084 if (DEBUG_INSTALL) { 10085 Slog.v(TAG, "BM finishing package install for " + token); 10086 } 10087 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10088 10089 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10090 mHandler.sendMessage(msg); 10091 } 10092 10093 /** 10094 * Get the verification agent timeout. 10095 * 10096 * @return verification timeout in milliseconds 10097 */ 10098 private long getVerificationTimeout() { 10099 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10100 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10101 DEFAULT_VERIFICATION_TIMEOUT); 10102 } 10103 10104 /** 10105 * Get the default verification agent response code. 10106 * 10107 * @return default verification response code 10108 */ 10109 private int getDefaultVerificationResponse() { 10110 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10111 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10112 DEFAULT_VERIFICATION_RESPONSE); 10113 } 10114 10115 /** 10116 * Check whether or not package verification has been enabled. 10117 * 10118 * @return true if verification should be performed 10119 */ 10120 private boolean isVerificationEnabled(int userId, int installFlags) { 10121 if (!DEFAULT_VERIFY_ENABLE) { 10122 return false; 10123 } 10124 // TODO: fix b/25118622; don't bypass verification 10125 if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) { 10126 return false; 10127 } 10128 10129 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10130 10131 // Check if installing from ADB 10132 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10133 // Do not run verification in a test harness environment 10134 if (ActivityManager.isRunningInTestHarness()) { 10135 return false; 10136 } 10137 if (ensureVerifyAppsEnabled) { 10138 return true; 10139 } 10140 // Check if the developer does not want package verification for ADB installs 10141 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10142 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10143 return false; 10144 } 10145 } 10146 10147 if (ensureVerifyAppsEnabled) { 10148 return true; 10149 } 10150 10151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10152 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10153 } 10154 10155 @Override 10156 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10157 throws RemoteException { 10158 mContext.enforceCallingOrSelfPermission( 10159 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10160 "Only intentfilter verification agents can verify applications"); 10161 10162 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10163 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10164 Binder.getCallingUid(), verificationCode, failedDomains); 10165 msg.arg1 = id; 10166 msg.obj = response; 10167 mHandler.sendMessage(msg); 10168 } 10169 10170 @Override 10171 public int getIntentVerificationStatus(String packageName, int userId) { 10172 synchronized (mPackages) { 10173 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10174 } 10175 } 10176 10177 @Override 10178 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10179 mContext.enforceCallingOrSelfPermission( 10180 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10181 10182 boolean result = false; 10183 synchronized (mPackages) { 10184 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10185 } 10186 if (result) { 10187 scheduleWritePackageRestrictionsLocked(userId); 10188 } 10189 return result; 10190 } 10191 10192 @Override 10193 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10194 synchronized (mPackages) { 10195 return mSettings.getIntentFilterVerificationsLPr(packageName); 10196 } 10197 } 10198 10199 @Override 10200 public List<IntentFilter> getAllIntentFilters(String packageName) { 10201 if (TextUtils.isEmpty(packageName)) { 10202 return Collections.<IntentFilter>emptyList(); 10203 } 10204 synchronized (mPackages) { 10205 PackageParser.Package pkg = mPackages.get(packageName); 10206 if (pkg == null || pkg.activities == null) { 10207 return Collections.<IntentFilter>emptyList(); 10208 } 10209 final int count = pkg.activities.size(); 10210 ArrayList<IntentFilter> result = new ArrayList<>(); 10211 for (int n=0; n<count; n++) { 10212 PackageParser.Activity activity = pkg.activities.get(n); 10213 if (activity.intents != null || activity.intents.size() > 0) { 10214 result.addAll(activity.intents); 10215 } 10216 } 10217 return result; 10218 } 10219 } 10220 10221 @Override 10222 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10223 mContext.enforceCallingOrSelfPermission( 10224 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10225 10226 synchronized (mPackages) { 10227 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10228 if (packageName != null) { 10229 result |= updateIntentVerificationStatus(packageName, 10230 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10231 userId); 10232 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10233 packageName, userId); 10234 } 10235 return result; 10236 } 10237 } 10238 10239 @Override 10240 public String getDefaultBrowserPackageName(int userId) { 10241 synchronized (mPackages) { 10242 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10243 } 10244 } 10245 10246 /** 10247 * Get the "allow unknown sources" setting. 10248 * 10249 * @return the current "allow unknown sources" setting 10250 */ 10251 private int getUnknownSourcesSettings() { 10252 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10253 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10254 -1); 10255 } 10256 10257 @Override 10258 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10259 final int uid = Binder.getCallingUid(); 10260 // writer 10261 synchronized (mPackages) { 10262 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10263 if (targetPackageSetting == null) { 10264 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10265 } 10266 10267 PackageSetting installerPackageSetting; 10268 if (installerPackageName != null) { 10269 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10270 if (installerPackageSetting == null) { 10271 throw new IllegalArgumentException("Unknown installer package: " 10272 + installerPackageName); 10273 } 10274 } else { 10275 installerPackageSetting = null; 10276 } 10277 10278 Signature[] callerSignature; 10279 Object obj = mSettings.getUserIdLPr(uid); 10280 if (obj != null) { 10281 if (obj instanceof SharedUserSetting) { 10282 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10283 } else if (obj instanceof PackageSetting) { 10284 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10285 } else { 10286 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10287 } 10288 } else { 10289 throw new SecurityException("Unknown calling uid " + uid); 10290 } 10291 10292 // Verify: can't set installerPackageName to a package that is 10293 // not signed with the same cert as the caller. 10294 if (installerPackageSetting != null) { 10295 if (compareSignatures(callerSignature, 10296 installerPackageSetting.signatures.mSignatures) 10297 != PackageManager.SIGNATURE_MATCH) { 10298 throw new SecurityException( 10299 "Caller does not have same cert as new installer package " 10300 + installerPackageName); 10301 } 10302 } 10303 10304 // Verify: if target already has an installer package, it must 10305 // be signed with the same cert as the caller. 10306 if (targetPackageSetting.installerPackageName != null) { 10307 PackageSetting setting = mSettings.mPackages.get( 10308 targetPackageSetting.installerPackageName); 10309 // If the currently set package isn't valid, then it's always 10310 // okay to change it. 10311 if (setting != null) { 10312 if (compareSignatures(callerSignature, 10313 setting.signatures.mSignatures) 10314 != PackageManager.SIGNATURE_MATCH) { 10315 throw new SecurityException( 10316 "Caller does not have same cert as old installer package " 10317 + targetPackageSetting.installerPackageName); 10318 } 10319 } 10320 } 10321 10322 // Okay! 10323 targetPackageSetting.installerPackageName = installerPackageName; 10324 scheduleWriteSettingsLocked(); 10325 } 10326 } 10327 10328 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10329 // Queue up an async operation since the package installation may take a little while. 10330 mHandler.post(new Runnable() { 10331 public void run() { 10332 mHandler.removeCallbacks(this); 10333 // Result object to be returned 10334 PackageInstalledInfo res = new PackageInstalledInfo(); 10335 res.returnCode = currentStatus; 10336 res.uid = -1; 10337 res.pkg = null; 10338 res.removedInfo = new PackageRemovedInfo(); 10339 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10340 args.doPreInstall(res.returnCode); 10341 synchronized (mInstallLock) { 10342 installPackageTracedLI(args, res); 10343 } 10344 args.doPostInstall(res.returnCode, res.uid); 10345 } 10346 10347 // A restore should be performed at this point if (a) the install 10348 // succeeded, (b) the operation is not an update, and (c) the new 10349 // package has not opted out of backup participation. 10350 final boolean update = res.removedInfo.removedPackage != null; 10351 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10352 boolean doRestore = !update 10353 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10354 10355 // Set up the post-install work request bookkeeping. This will be used 10356 // and cleaned up by the post-install event handling regardless of whether 10357 // there's a restore pass performed. Token values are >= 1. 10358 int token; 10359 if (mNextInstallToken < 0) mNextInstallToken = 1; 10360 token = mNextInstallToken++; 10361 10362 PostInstallData data = new PostInstallData(args, res); 10363 mRunningInstalls.put(token, data); 10364 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10365 10366 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10367 // Pass responsibility to the Backup Manager. It will perform a 10368 // restore if appropriate, then pass responsibility back to the 10369 // Package Manager to run the post-install observer callbacks 10370 // and broadcasts. 10371 IBackupManager bm = IBackupManager.Stub.asInterface( 10372 ServiceManager.getService(Context.BACKUP_SERVICE)); 10373 if (bm != null) { 10374 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10375 + " to BM for possible restore"); 10376 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10377 try { 10378 // TODO: http://b/22388012 10379 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10380 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10381 } else { 10382 doRestore = false; 10383 } 10384 } catch (RemoteException e) { 10385 // can't happen; the backup manager is local 10386 } catch (Exception e) { 10387 Slog.e(TAG, "Exception trying to enqueue restore", e); 10388 doRestore = false; 10389 } 10390 } else { 10391 Slog.e(TAG, "Backup Manager not found!"); 10392 doRestore = false; 10393 } 10394 } 10395 10396 if (!doRestore) { 10397 // No restore possible, or the Backup Manager was mysteriously not 10398 // available -- just fire the post-install work request directly. 10399 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10400 10401 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10402 10403 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10404 mHandler.sendMessage(msg); 10405 } 10406 } 10407 }); 10408 } 10409 10410 private abstract class HandlerParams { 10411 private static final int MAX_RETRIES = 4; 10412 10413 /** 10414 * Number of times startCopy() has been attempted and had a non-fatal 10415 * error. 10416 */ 10417 private int mRetries = 0; 10418 10419 /** User handle for the user requesting the information or installation. */ 10420 private final UserHandle mUser; 10421 String traceMethod; 10422 int traceCookie; 10423 10424 HandlerParams(UserHandle user) { 10425 mUser = user; 10426 } 10427 10428 UserHandle getUser() { 10429 return mUser; 10430 } 10431 10432 HandlerParams setTraceMethod(String traceMethod) { 10433 this.traceMethod = traceMethod; 10434 return this; 10435 } 10436 10437 HandlerParams setTraceCookie(int traceCookie) { 10438 this.traceCookie = traceCookie; 10439 return this; 10440 } 10441 10442 final boolean startCopy() { 10443 boolean res; 10444 try { 10445 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10446 10447 if (++mRetries > MAX_RETRIES) { 10448 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10449 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10450 handleServiceError(); 10451 return false; 10452 } else { 10453 handleStartCopy(); 10454 res = true; 10455 } 10456 } catch (RemoteException e) { 10457 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10458 mHandler.sendEmptyMessage(MCS_RECONNECT); 10459 res = false; 10460 } 10461 handleReturnCode(); 10462 return res; 10463 } 10464 10465 final void serviceError() { 10466 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10467 handleServiceError(); 10468 handleReturnCode(); 10469 } 10470 10471 abstract void handleStartCopy() throws RemoteException; 10472 abstract void handleServiceError(); 10473 abstract void handleReturnCode(); 10474 } 10475 10476 class MeasureParams extends HandlerParams { 10477 private final PackageStats mStats; 10478 private boolean mSuccess; 10479 10480 private final IPackageStatsObserver mObserver; 10481 10482 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10483 super(new UserHandle(stats.userHandle)); 10484 mObserver = observer; 10485 mStats = stats; 10486 } 10487 10488 @Override 10489 public String toString() { 10490 return "MeasureParams{" 10491 + Integer.toHexString(System.identityHashCode(this)) 10492 + " " + mStats.packageName + "}"; 10493 } 10494 10495 @Override 10496 void handleStartCopy() throws RemoteException { 10497 synchronized (mInstallLock) { 10498 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10499 } 10500 10501 if (mSuccess) { 10502 final boolean mounted; 10503 if (Environment.isExternalStorageEmulated()) { 10504 mounted = true; 10505 } else { 10506 final String status = Environment.getExternalStorageState(); 10507 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10508 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10509 } 10510 10511 if (mounted) { 10512 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10513 10514 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10515 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10516 10517 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10518 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10519 10520 // Always subtract cache size, since it's a subdirectory 10521 mStats.externalDataSize -= mStats.externalCacheSize; 10522 10523 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10524 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10525 10526 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10527 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10528 } 10529 } 10530 } 10531 10532 @Override 10533 void handleReturnCode() { 10534 if (mObserver != null) { 10535 try { 10536 mObserver.onGetStatsCompleted(mStats, mSuccess); 10537 } catch (RemoteException e) { 10538 Slog.i(TAG, "Observer no longer exists."); 10539 } 10540 } 10541 } 10542 10543 @Override 10544 void handleServiceError() { 10545 Slog.e(TAG, "Could not measure application " + mStats.packageName 10546 + " external storage"); 10547 } 10548 } 10549 10550 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10551 throws RemoteException { 10552 long result = 0; 10553 for (File path : paths) { 10554 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10555 } 10556 return result; 10557 } 10558 10559 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10560 for (File path : paths) { 10561 try { 10562 mcs.clearDirectory(path.getAbsolutePath()); 10563 } catch (RemoteException e) { 10564 } 10565 } 10566 } 10567 10568 static class OriginInfo { 10569 /** 10570 * Location where install is coming from, before it has been 10571 * copied/renamed into place. This could be a single monolithic APK 10572 * file, or a cluster directory. This location may be untrusted. 10573 */ 10574 final File file; 10575 final String cid; 10576 10577 /** 10578 * Flag indicating that {@link #file} or {@link #cid} has already been 10579 * staged, meaning downstream users don't need to defensively copy the 10580 * contents. 10581 */ 10582 final boolean staged; 10583 10584 /** 10585 * Flag indicating that {@link #file} or {@link #cid} is an already 10586 * installed app that is being moved. 10587 */ 10588 final boolean existing; 10589 10590 final String resolvedPath; 10591 final File resolvedFile; 10592 10593 static OriginInfo fromNothing() { 10594 return new OriginInfo(null, null, false, false); 10595 } 10596 10597 static OriginInfo fromUntrustedFile(File file) { 10598 return new OriginInfo(file, null, false, false); 10599 } 10600 10601 static OriginInfo fromExistingFile(File file) { 10602 return new OriginInfo(file, null, false, true); 10603 } 10604 10605 static OriginInfo fromStagedFile(File file) { 10606 return new OriginInfo(file, null, true, false); 10607 } 10608 10609 static OriginInfo fromStagedContainer(String cid) { 10610 return new OriginInfo(null, cid, true, false); 10611 } 10612 10613 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10614 this.file = file; 10615 this.cid = cid; 10616 this.staged = staged; 10617 this.existing = existing; 10618 10619 if (cid != null) { 10620 resolvedPath = PackageHelper.getSdDir(cid); 10621 resolvedFile = new File(resolvedPath); 10622 } else if (file != null) { 10623 resolvedPath = file.getAbsolutePath(); 10624 resolvedFile = file; 10625 } else { 10626 resolvedPath = null; 10627 resolvedFile = null; 10628 } 10629 } 10630 } 10631 10632 class MoveInfo { 10633 final int moveId; 10634 final String fromUuid; 10635 final String toUuid; 10636 final String packageName; 10637 final String dataAppName; 10638 final int appId; 10639 final String seinfo; 10640 10641 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10642 String dataAppName, int appId, String seinfo) { 10643 this.moveId = moveId; 10644 this.fromUuid = fromUuid; 10645 this.toUuid = toUuid; 10646 this.packageName = packageName; 10647 this.dataAppName = dataAppName; 10648 this.appId = appId; 10649 this.seinfo = seinfo; 10650 } 10651 } 10652 10653 class InstallParams extends HandlerParams { 10654 final OriginInfo origin; 10655 final MoveInfo move; 10656 final IPackageInstallObserver2 observer; 10657 int installFlags; 10658 final String installerPackageName; 10659 final String volumeUuid; 10660 final VerificationParams verificationParams; 10661 private InstallArgs mArgs; 10662 private int mRet; 10663 final String packageAbiOverride; 10664 final String[] grantedRuntimePermissions; 10665 10666 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10667 int installFlags, String installerPackageName, String volumeUuid, 10668 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10669 String[] grantedPermissions) { 10670 super(user); 10671 this.origin = origin; 10672 this.move = move; 10673 this.observer = observer; 10674 this.installFlags = installFlags; 10675 this.installerPackageName = installerPackageName; 10676 this.volumeUuid = volumeUuid; 10677 this.verificationParams = verificationParams; 10678 this.packageAbiOverride = packageAbiOverride; 10679 this.grantedRuntimePermissions = grantedPermissions; 10680 } 10681 10682 @Override 10683 public String toString() { 10684 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10685 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10686 } 10687 10688 public ManifestDigest getManifestDigest() { 10689 if (verificationParams == null) { 10690 return null; 10691 } 10692 return verificationParams.getManifestDigest(); 10693 } 10694 10695 private int installLocationPolicy(PackageInfoLite pkgLite) { 10696 String packageName = pkgLite.packageName; 10697 int installLocation = pkgLite.installLocation; 10698 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10699 // reader 10700 synchronized (mPackages) { 10701 PackageParser.Package pkg = mPackages.get(packageName); 10702 if (pkg != null) { 10703 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10704 // Check for downgrading. 10705 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10706 try { 10707 checkDowngrade(pkg, pkgLite); 10708 } catch (PackageManagerException e) { 10709 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10710 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10711 } 10712 } 10713 // Check for updated system application. 10714 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10715 if (onSd) { 10716 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10717 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10718 } 10719 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10720 } else { 10721 if (onSd) { 10722 // Install flag overrides everything. 10723 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10724 } 10725 // If current upgrade specifies particular preference 10726 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10727 // Application explicitly specified internal. 10728 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10729 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10730 // App explictly prefers external. Let policy decide 10731 } else { 10732 // Prefer previous location 10733 if (isExternal(pkg)) { 10734 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10735 } 10736 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10737 } 10738 } 10739 } else { 10740 // Invalid install. Return error code 10741 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10742 } 10743 } 10744 } 10745 // All the special cases have been taken care of. 10746 // Return result based on recommended install location. 10747 if (onSd) { 10748 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10749 } 10750 return pkgLite.recommendedInstallLocation; 10751 } 10752 10753 /* 10754 * Invoke remote method to get package information and install 10755 * location values. Override install location based on default 10756 * policy if needed and then create install arguments based 10757 * on the install location. 10758 */ 10759 public void handleStartCopy() throws RemoteException { 10760 int ret = PackageManager.INSTALL_SUCCEEDED; 10761 10762 // If we're already staged, we've firmly committed to an install location 10763 if (origin.staged) { 10764 if (origin.file != null) { 10765 installFlags |= PackageManager.INSTALL_INTERNAL; 10766 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10767 } else if (origin.cid != null) { 10768 installFlags |= PackageManager.INSTALL_EXTERNAL; 10769 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10770 } else { 10771 throw new IllegalStateException("Invalid stage location"); 10772 } 10773 } 10774 10775 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10776 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10777 PackageInfoLite pkgLite = null; 10778 10779 if (onInt && onSd) { 10780 // Check if both bits are set. 10781 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10782 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10783 } else { 10784 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10785 packageAbiOverride); 10786 10787 /* 10788 * If we have too little free space, try to free cache 10789 * before giving up. 10790 */ 10791 if (!origin.staged && pkgLite.recommendedInstallLocation 10792 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10793 // TODO: focus freeing disk space on the target device 10794 final StorageManager storage = StorageManager.from(mContext); 10795 final long lowThreshold = storage.getStorageLowBytes( 10796 Environment.getDataDirectory()); 10797 10798 final long sizeBytes = mContainerService.calculateInstalledSize( 10799 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10800 10801 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10802 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10803 installFlags, packageAbiOverride); 10804 } 10805 10806 /* 10807 * The cache free must have deleted the file we 10808 * downloaded to install. 10809 * 10810 * TODO: fix the "freeCache" call to not delete 10811 * the file we care about. 10812 */ 10813 if (pkgLite.recommendedInstallLocation 10814 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10815 pkgLite.recommendedInstallLocation 10816 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10817 } 10818 } 10819 } 10820 10821 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10822 int loc = pkgLite.recommendedInstallLocation; 10823 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10824 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10825 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10826 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10827 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10828 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10829 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10830 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10831 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10832 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10833 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10834 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10835 } else { 10836 // Override with defaults if needed. 10837 loc = installLocationPolicy(pkgLite); 10838 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10839 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10840 } else if (!onSd && !onInt) { 10841 // Override install location with flags 10842 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10843 // Set the flag to install on external media. 10844 installFlags |= PackageManager.INSTALL_EXTERNAL; 10845 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10846 } else { 10847 // Make sure the flag for installing on external 10848 // media is unset 10849 installFlags |= PackageManager.INSTALL_INTERNAL; 10850 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10851 } 10852 } 10853 } 10854 } 10855 10856 final InstallArgs args = createInstallArgs(this); 10857 mArgs = args; 10858 10859 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10860 // TODO: http://b/22976637 10861 // Apps installed for "all" users use the device owner to verify the app 10862 UserHandle verifierUser = getUser(); 10863 if (verifierUser == UserHandle.ALL) { 10864 verifierUser = UserHandle.SYSTEM; 10865 } 10866 10867 /* 10868 * Determine if we have any installed package verifiers. If we 10869 * do, then we'll defer to them to verify the packages. 10870 */ 10871 final int requiredUid = mRequiredVerifierPackage == null ? -1 10872 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 10873 if (!origin.existing && requiredUid != -1 10874 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 10875 final Intent verification = new Intent( 10876 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10877 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10878 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10879 PACKAGE_MIME_TYPE); 10880 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10881 10882 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10883 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10884 verifierUser.getIdentifier()); 10885 10886 if (DEBUG_VERIFY) { 10887 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10888 + verification.toString() + " with " + pkgLite.verifiers.length 10889 + " optional verifiers"); 10890 } 10891 10892 final int verificationId = mPendingVerificationToken++; 10893 10894 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10895 10896 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10897 installerPackageName); 10898 10899 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10900 installFlags); 10901 10902 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10903 pkgLite.packageName); 10904 10905 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10906 pkgLite.versionCode); 10907 10908 if (verificationParams != null) { 10909 if (verificationParams.getVerificationURI() != null) { 10910 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10911 verificationParams.getVerificationURI()); 10912 } 10913 if (verificationParams.getOriginatingURI() != null) { 10914 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10915 verificationParams.getOriginatingURI()); 10916 } 10917 if (verificationParams.getReferrer() != null) { 10918 verification.putExtra(Intent.EXTRA_REFERRER, 10919 verificationParams.getReferrer()); 10920 } 10921 if (verificationParams.getOriginatingUid() >= 0) { 10922 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10923 verificationParams.getOriginatingUid()); 10924 } 10925 if (verificationParams.getInstallerUid() >= 0) { 10926 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10927 verificationParams.getInstallerUid()); 10928 } 10929 } 10930 10931 final PackageVerificationState verificationState = new PackageVerificationState( 10932 requiredUid, args); 10933 10934 mPendingVerification.append(verificationId, verificationState); 10935 10936 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10937 receivers, verificationState); 10938 10939 /* 10940 * If any sufficient verifiers were listed in the package 10941 * manifest, attempt to ask them. 10942 */ 10943 if (sufficientVerifiers != null) { 10944 final int N = sufficientVerifiers.size(); 10945 if (N == 0) { 10946 Slog.i(TAG, "Additional verifiers required, but none installed."); 10947 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10948 } else { 10949 for (int i = 0; i < N; i++) { 10950 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10951 10952 final Intent sufficientIntent = new Intent(verification); 10953 sufficientIntent.setComponent(verifierComponent); 10954 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10955 } 10956 } 10957 } 10958 10959 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10960 mRequiredVerifierPackage, receivers); 10961 if (ret == PackageManager.INSTALL_SUCCEEDED 10962 && mRequiredVerifierPackage != null) { 10963 Trace.asyncTraceBegin( 10964 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 10965 /* 10966 * Send the intent to the required verification agent, 10967 * but only start the verification timeout after the 10968 * target BroadcastReceivers have run. 10969 */ 10970 verification.setComponent(requiredVerifierComponent); 10971 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10973 new BroadcastReceiver() { 10974 @Override 10975 public void onReceive(Context context, Intent intent) { 10976 final Message msg = mHandler 10977 .obtainMessage(CHECK_PENDING_VERIFICATION); 10978 msg.arg1 = verificationId; 10979 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10980 } 10981 }, null, 0, null, null); 10982 10983 /* 10984 * We don't want the copy to proceed until verification 10985 * succeeds, so null out this field. 10986 */ 10987 mArgs = null; 10988 } 10989 } else { 10990 /* 10991 * No package verification is enabled, so immediately start 10992 * the remote call to initiate copy using temporary file. 10993 */ 10994 ret = args.copyApk(mContainerService, true); 10995 } 10996 } 10997 10998 mRet = ret; 10999 } 11000 11001 @Override 11002 void handleReturnCode() { 11003 // If mArgs is null, then MCS couldn't be reached. When it 11004 // reconnects, it will try again to install. At that point, this 11005 // will succeed. 11006 if (mArgs != null) { 11007 processPendingInstall(mArgs, mRet); 11008 } 11009 } 11010 11011 @Override 11012 void handleServiceError() { 11013 mArgs = createInstallArgs(this); 11014 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11015 } 11016 11017 public boolean isForwardLocked() { 11018 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11019 } 11020 } 11021 11022 /** 11023 * Used during creation of InstallArgs 11024 * 11025 * @param installFlags package installation flags 11026 * @return true if should be installed on external storage 11027 */ 11028 private static boolean installOnExternalAsec(int installFlags) { 11029 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11030 return false; 11031 } 11032 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11033 return true; 11034 } 11035 return false; 11036 } 11037 11038 /** 11039 * Used during creation of InstallArgs 11040 * 11041 * @param installFlags package installation flags 11042 * @return true if should be installed as forward locked 11043 */ 11044 private static boolean installForwardLocked(int installFlags) { 11045 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11046 } 11047 11048 private InstallArgs createInstallArgs(InstallParams params) { 11049 if (params.move != null) { 11050 return new MoveInstallArgs(params); 11051 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11052 return new AsecInstallArgs(params); 11053 } else { 11054 return new FileInstallArgs(params); 11055 } 11056 } 11057 11058 /** 11059 * Create args that describe an existing installed package. Typically used 11060 * when cleaning up old installs, or used as a move source. 11061 */ 11062 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11063 String resourcePath, String[] instructionSets) { 11064 final boolean isInAsec; 11065 if (installOnExternalAsec(installFlags)) { 11066 /* Apps on SD card are always in ASEC containers. */ 11067 isInAsec = true; 11068 } else if (installForwardLocked(installFlags) 11069 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11070 /* 11071 * Forward-locked apps are only in ASEC containers if they're the 11072 * new style 11073 */ 11074 isInAsec = true; 11075 } else { 11076 isInAsec = false; 11077 } 11078 11079 if (isInAsec) { 11080 return new AsecInstallArgs(codePath, instructionSets, 11081 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11082 } else { 11083 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11084 } 11085 } 11086 11087 static abstract class InstallArgs { 11088 /** @see InstallParams#origin */ 11089 final OriginInfo origin; 11090 /** @see InstallParams#move */ 11091 final MoveInfo move; 11092 11093 final IPackageInstallObserver2 observer; 11094 // Always refers to PackageManager flags only 11095 final int installFlags; 11096 final String installerPackageName; 11097 final String volumeUuid; 11098 final ManifestDigest manifestDigest; 11099 final UserHandle user; 11100 final String abiOverride; 11101 final String[] installGrantPermissions; 11102 /** If non-null, drop an async trace when the install completes */ 11103 final String traceMethod; 11104 final int traceCookie; 11105 11106 // The list of instruction sets supported by this app. This is currently 11107 // only used during the rmdex() phase to clean up resources. We can get rid of this 11108 // if we move dex files under the common app path. 11109 /* nullable */ String[] instructionSets; 11110 11111 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11112 int installFlags, String installerPackageName, String volumeUuid, 11113 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 11114 String abiOverride, String[] installGrantPermissions, 11115 String traceMethod, int traceCookie) { 11116 this.origin = origin; 11117 this.move = move; 11118 this.installFlags = installFlags; 11119 this.observer = observer; 11120 this.installerPackageName = installerPackageName; 11121 this.volumeUuid = volumeUuid; 11122 this.manifestDigest = manifestDigest; 11123 this.user = user; 11124 this.instructionSets = instructionSets; 11125 this.abiOverride = abiOverride; 11126 this.installGrantPermissions = installGrantPermissions; 11127 this.traceMethod = traceMethod; 11128 this.traceCookie = traceCookie; 11129 } 11130 11131 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11132 abstract int doPreInstall(int status); 11133 11134 /** 11135 * Rename package into final resting place. All paths on the given 11136 * scanned package should be updated to reflect the rename. 11137 */ 11138 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11139 abstract int doPostInstall(int status, int uid); 11140 11141 /** @see PackageSettingBase#codePathString */ 11142 abstract String getCodePath(); 11143 /** @see PackageSettingBase#resourcePathString */ 11144 abstract String getResourcePath(); 11145 11146 // Need installer lock especially for dex file removal. 11147 abstract void cleanUpResourcesLI(); 11148 abstract boolean doPostDeleteLI(boolean delete); 11149 11150 /** 11151 * Called before the source arguments are copied. This is used mostly 11152 * for MoveParams when it needs to read the source file to put it in the 11153 * destination. 11154 */ 11155 int doPreCopy() { 11156 return PackageManager.INSTALL_SUCCEEDED; 11157 } 11158 11159 /** 11160 * Called after the source arguments are copied. This is used mostly for 11161 * MoveParams when it needs to read the source file to put it in the 11162 * destination. 11163 * 11164 * @return 11165 */ 11166 int doPostCopy(int uid) { 11167 return PackageManager.INSTALL_SUCCEEDED; 11168 } 11169 11170 protected boolean isFwdLocked() { 11171 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11172 } 11173 11174 protected boolean isExternalAsec() { 11175 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11176 } 11177 11178 UserHandle getUser() { 11179 return user; 11180 } 11181 } 11182 11183 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11184 if (!allCodePaths.isEmpty()) { 11185 if (instructionSets == null) { 11186 throw new IllegalStateException("instructionSet == null"); 11187 } 11188 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11189 for (String codePath : allCodePaths) { 11190 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11191 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11192 if (retCode < 0) { 11193 Slog.w(TAG, "Couldn't remove dex file for package: " 11194 + " at location " + codePath + ", retcode=" + retCode); 11195 // we don't consider this to be a failure of the core package deletion 11196 } 11197 } 11198 } 11199 } 11200 } 11201 11202 /** 11203 * Logic to handle installation of non-ASEC applications, including copying 11204 * and renaming logic. 11205 */ 11206 class FileInstallArgs extends InstallArgs { 11207 private File codeFile; 11208 private File resourceFile; 11209 11210 // Example topology: 11211 // /data/app/com.example/base.apk 11212 // /data/app/com.example/split_foo.apk 11213 // /data/app/com.example/lib/arm/libfoo.so 11214 // /data/app/com.example/lib/arm64/libfoo.so 11215 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11216 11217 /** New install */ 11218 FileInstallArgs(InstallParams params) { 11219 super(params.origin, params.move, params.observer, params.installFlags, 11220 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11221 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11222 params.grantedRuntimePermissions, 11223 params.traceMethod, params.traceCookie); 11224 if (isFwdLocked()) { 11225 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11226 } 11227 } 11228 11229 /** Existing install */ 11230 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11231 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 11232 null, null, null, 0); 11233 this.codeFile = (codePath != null) ? new File(codePath) : null; 11234 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11235 } 11236 11237 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11238 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11239 try { 11240 return doCopyApk(imcs, temp); 11241 } finally { 11242 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11243 } 11244 } 11245 11246 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11247 if (origin.staged) { 11248 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11249 codeFile = origin.file; 11250 resourceFile = origin.file; 11251 return PackageManager.INSTALL_SUCCEEDED; 11252 } 11253 11254 try { 11255 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 11256 codeFile = tempDir; 11257 resourceFile = tempDir; 11258 } catch (IOException e) { 11259 Slog.w(TAG, "Failed to create copy file: " + e); 11260 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11261 } 11262 11263 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11264 @Override 11265 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11266 if (!FileUtils.isValidExtFilename(name)) { 11267 throw new IllegalArgumentException("Invalid filename: " + name); 11268 } 11269 try { 11270 final File file = new File(codeFile, name); 11271 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11272 O_RDWR | O_CREAT, 0644); 11273 Os.chmod(file.getAbsolutePath(), 0644); 11274 return new ParcelFileDescriptor(fd); 11275 } catch (ErrnoException e) { 11276 throw new RemoteException("Failed to open: " + e.getMessage()); 11277 } 11278 } 11279 }; 11280 11281 int ret = PackageManager.INSTALL_SUCCEEDED; 11282 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11283 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11284 Slog.e(TAG, "Failed to copy package"); 11285 return ret; 11286 } 11287 11288 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11289 NativeLibraryHelper.Handle handle = null; 11290 try { 11291 handle = NativeLibraryHelper.Handle.create(codeFile); 11292 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11293 abiOverride); 11294 } catch (IOException e) { 11295 Slog.e(TAG, "Copying native libraries failed", e); 11296 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11297 } finally { 11298 IoUtils.closeQuietly(handle); 11299 } 11300 11301 return ret; 11302 } 11303 11304 int doPreInstall(int status) { 11305 if (status != PackageManager.INSTALL_SUCCEEDED) { 11306 cleanUp(); 11307 } 11308 return status; 11309 } 11310 11311 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11312 if (status != PackageManager.INSTALL_SUCCEEDED) { 11313 cleanUp(); 11314 return false; 11315 } 11316 11317 final File targetDir = codeFile.getParentFile(); 11318 final File beforeCodeFile = codeFile; 11319 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11320 11321 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11322 try { 11323 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11324 } catch (ErrnoException e) { 11325 Slog.w(TAG, "Failed to rename", e); 11326 return false; 11327 } 11328 11329 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11330 Slog.w(TAG, "Failed to restorecon"); 11331 return false; 11332 } 11333 11334 // Reflect the rename internally 11335 codeFile = afterCodeFile; 11336 resourceFile = afterCodeFile; 11337 11338 // Reflect the rename in scanned details 11339 pkg.codePath = afterCodeFile.getAbsolutePath(); 11340 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11341 pkg.baseCodePath); 11342 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11343 pkg.splitCodePaths); 11344 11345 // Reflect the rename in app info 11346 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11347 pkg.applicationInfo.setCodePath(pkg.codePath); 11348 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11349 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11350 pkg.applicationInfo.setResourcePath(pkg.codePath); 11351 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11352 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11353 11354 return true; 11355 } 11356 11357 int doPostInstall(int status, int uid) { 11358 if (status != PackageManager.INSTALL_SUCCEEDED) { 11359 cleanUp(); 11360 } 11361 return status; 11362 } 11363 11364 @Override 11365 String getCodePath() { 11366 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11367 } 11368 11369 @Override 11370 String getResourcePath() { 11371 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11372 } 11373 11374 private boolean cleanUp() { 11375 if (codeFile == null || !codeFile.exists()) { 11376 return false; 11377 } 11378 11379 if (codeFile.isDirectory()) { 11380 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11381 } else { 11382 codeFile.delete(); 11383 } 11384 11385 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11386 resourceFile.delete(); 11387 } 11388 11389 return true; 11390 } 11391 11392 void cleanUpResourcesLI() { 11393 // Try enumerating all code paths before deleting 11394 List<String> allCodePaths = Collections.EMPTY_LIST; 11395 if (codeFile != null && codeFile.exists()) { 11396 try { 11397 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11398 allCodePaths = pkg.getAllCodePaths(); 11399 } catch (PackageParserException e) { 11400 // Ignored; we tried our best 11401 } 11402 } 11403 11404 cleanUp(); 11405 removeDexFiles(allCodePaths, instructionSets); 11406 } 11407 11408 boolean doPostDeleteLI(boolean delete) { 11409 // XXX err, shouldn't we respect the delete flag? 11410 cleanUpResourcesLI(); 11411 return true; 11412 } 11413 } 11414 11415 private boolean isAsecExternal(String cid) { 11416 final String asecPath = PackageHelper.getSdFilesystem(cid); 11417 return !asecPath.startsWith(mAsecInternalPath); 11418 } 11419 11420 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11421 PackageManagerException { 11422 if (copyRet < 0) { 11423 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11424 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11425 throw new PackageManagerException(copyRet, message); 11426 } 11427 } 11428 } 11429 11430 /** 11431 * Extract the MountService "container ID" from the full code path of an 11432 * .apk. 11433 */ 11434 static String cidFromCodePath(String fullCodePath) { 11435 int eidx = fullCodePath.lastIndexOf("/"); 11436 String subStr1 = fullCodePath.substring(0, eidx); 11437 int sidx = subStr1.lastIndexOf("/"); 11438 return subStr1.substring(sidx+1, eidx); 11439 } 11440 11441 /** 11442 * Logic to handle installation of ASEC applications, including copying and 11443 * renaming logic. 11444 */ 11445 class AsecInstallArgs extends InstallArgs { 11446 static final String RES_FILE_NAME = "pkg.apk"; 11447 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11448 11449 String cid; 11450 String packagePath; 11451 String resourcePath; 11452 11453 /** New install */ 11454 AsecInstallArgs(InstallParams params) { 11455 super(params.origin, params.move, params.observer, params.installFlags, 11456 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11457 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11458 params.grantedRuntimePermissions, 11459 params.traceMethod, params.traceCookie); 11460 } 11461 11462 /** Existing install */ 11463 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11464 boolean isExternal, boolean isForwardLocked) { 11465 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11466 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11467 instructionSets, null, null, null, 0); 11468 // Hackily pretend we're still looking at a full code path 11469 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11470 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11471 } 11472 11473 // Extract cid from fullCodePath 11474 int eidx = fullCodePath.lastIndexOf("/"); 11475 String subStr1 = fullCodePath.substring(0, eidx); 11476 int sidx = subStr1.lastIndexOf("/"); 11477 cid = subStr1.substring(sidx+1, eidx); 11478 setMountPath(subStr1); 11479 } 11480 11481 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11482 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11483 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11484 instructionSets, null, null, null, 0); 11485 this.cid = cid; 11486 setMountPath(PackageHelper.getSdDir(cid)); 11487 } 11488 11489 void createCopyFile() { 11490 cid = mInstallerService.allocateExternalStageCidLegacy(); 11491 } 11492 11493 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11494 if (origin.staged) { 11495 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11496 cid = origin.cid; 11497 setMountPath(PackageHelper.getSdDir(cid)); 11498 return PackageManager.INSTALL_SUCCEEDED; 11499 } 11500 11501 if (temp) { 11502 createCopyFile(); 11503 } else { 11504 /* 11505 * Pre-emptively destroy the container since it's destroyed if 11506 * copying fails due to it existing anyway. 11507 */ 11508 PackageHelper.destroySdDir(cid); 11509 } 11510 11511 final String newMountPath = imcs.copyPackageToContainer( 11512 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11513 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11514 11515 if (newMountPath != null) { 11516 setMountPath(newMountPath); 11517 return PackageManager.INSTALL_SUCCEEDED; 11518 } else { 11519 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11520 } 11521 } 11522 11523 @Override 11524 String getCodePath() { 11525 return packagePath; 11526 } 11527 11528 @Override 11529 String getResourcePath() { 11530 return resourcePath; 11531 } 11532 11533 int doPreInstall(int status) { 11534 if (status != PackageManager.INSTALL_SUCCEEDED) { 11535 // Destroy container 11536 PackageHelper.destroySdDir(cid); 11537 } else { 11538 boolean mounted = PackageHelper.isContainerMounted(cid); 11539 if (!mounted) { 11540 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11541 Process.SYSTEM_UID); 11542 if (newMountPath != null) { 11543 setMountPath(newMountPath); 11544 } else { 11545 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11546 } 11547 } 11548 } 11549 return status; 11550 } 11551 11552 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11553 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11554 String newMountPath = null; 11555 if (PackageHelper.isContainerMounted(cid)) { 11556 // Unmount the container 11557 if (!PackageHelper.unMountSdDir(cid)) { 11558 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11559 return false; 11560 } 11561 } 11562 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11563 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11564 " which might be stale. Will try to clean up."); 11565 // Clean up the stale container and proceed to recreate. 11566 if (!PackageHelper.destroySdDir(newCacheId)) { 11567 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11568 return false; 11569 } 11570 // Successfully cleaned up stale container. Try to rename again. 11571 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11572 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11573 + " inspite of cleaning it up."); 11574 return false; 11575 } 11576 } 11577 if (!PackageHelper.isContainerMounted(newCacheId)) { 11578 Slog.w(TAG, "Mounting container " + newCacheId); 11579 newMountPath = PackageHelper.mountSdDir(newCacheId, 11580 getEncryptKey(), Process.SYSTEM_UID); 11581 } else { 11582 newMountPath = PackageHelper.getSdDir(newCacheId); 11583 } 11584 if (newMountPath == null) { 11585 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11586 return false; 11587 } 11588 Log.i(TAG, "Succesfully renamed " + cid + 11589 " to " + newCacheId + 11590 " at new path: " + newMountPath); 11591 cid = newCacheId; 11592 11593 final File beforeCodeFile = new File(packagePath); 11594 setMountPath(newMountPath); 11595 final File afterCodeFile = new File(packagePath); 11596 11597 // Reflect the rename in scanned details 11598 pkg.codePath = afterCodeFile.getAbsolutePath(); 11599 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11600 pkg.baseCodePath); 11601 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11602 pkg.splitCodePaths); 11603 11604 // Reflect the rename in app info 11605 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11606 pkg.applicationInfo.setCodePath(pkg.codePath); 11607 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11608 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11609 pkg.applicationInfo.setResourcePath(pkg.codePath); 11610 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11611 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11612 11613 return true; 11614 } 11615 11616 private void setMountPath(String mountPath) { 11617 final File mountFile = new File(mountPath); 11618 11619 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11620 if (monolithicFile.exists()) { 11621 packagePath = monolithicFile.getAbsolutePath(); 11622 if (isFwdLocked()) { 11623 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11624 } else { 11625 resourcePath = packagePath; 11626 } 11627 } else { 11628 packagePath = mountFile.getAbsolutePath(); 11629 resourcePath = packagePath; 11630 } 11631 } 11632 11633 int doPostInstall(int status, int uid) { 11634 if (status != PackageManager.INSTALL_SUCCEEDED) { 11635 cleanUp(); 11636 } else { 11637 final int groupOwner; 11638 final String protectedFile; 11639 if (isFwdLocked()) { 11640 groupOwner = UserHandle.getSharedAppGid(uid); 11641 protectedFile = RES_FILE_NAME; 11642 } else { 11643 groupOwner = -1; 11644 protectedFile = null; 11645 } 11646 11647 if (uid < Process.FIRST_APPLICATION_UID 11648 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11649 Slog.e(TAG, "Failed to finalize " + cid); 11650 PackageHelper.destroySdDir(cid); 11651 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11652 } 11653 11654 boolean mounted = PackageHelper.isContainerMounted(cid); 11655 if (!mounted) { 11656 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11657 } 11658 } 11659 return status; 11660 } 11661 11662 private void cleanUp() { 11663 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11664 11665 // Destroy secure container 11666 PackageHelper.destroySdDir(cid); 11667 } 11668 11669 private List<String> getAllCodePaths() { 11670 final File codeFile = new File(getCodePath()); 11671 if (codeFile != null && codeFile.exists()) { 11672 try { 11673 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11674 return pkg.getAllCodePaths(); 11675 } catch (PackageParserException e) { 11676 // Ignored; we tried our best 11677 } 11678 } 11679 return Collections.EMPTY_LIST; 11680 } 11681 11682 void cleanUpResourcesLI() { 11683 // Enumerate all code paths before deleting 11684 cleanUpResourcesLI(getAllCodePaths()); 11685 } 11686 11687 private void cleanUpResourcesLI(List<String> allCodePaths) { 11688 cleanUp(); 11689 removeDexFiles(allCodePaths, instructionSets); 11690 } 11691 11692 String getPackageName() { 11693 return getAsecPackageName(cid); 11694 } 11695 11696 boolean doPostDeleteLI(boolean delete) { 11697 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11698 final List<String> allCodePaths = getAllCodePaths(); 11699 boolean mounted = PackageHelper.isContainerMounted(cid); 11700 if (mounted) { 11701 // Unmount first 11702 if (PackageHelper.unMountSdDir(cid)) { 11703 mounted = false; 11704 } 11705 } 11706 if (!mounted && delete) { 11707 cleanUpResourcesLI(allCodePaths); 11708 } 11709 return !mounted; 11710 } 11711 11712 @Override 11713 int doPreCopy() { 11714 if (isFwdLocked()) { 11715 if (!PackageHelper.fixSdPermissions(cid, 11716 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11717 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11718 } 11719 } 11720 11721 return PackageManager.INSTALL_SUCCEEDED; 11722 } 11723 11724 @Override 11725 int doPostCopy(int uid) { 11726 if (isFwdLocked()) { 11727 if (uid < Process.FIRST_APPLICATION_UID 11728 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11729 RES_FILE_NAME)) { 11730 Slog.e(TAG, "Failed to finalize " + cid); 11731 PackageHelper.destroySdDir(cid); 11732 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11733 } 11734 } 11735 11736 return PackageManager.INSTALL_SUCCEEDED; 11737 } 11738 } 11739 11740 /** 11741 * Logic to handle movement of existing installed applications. 11742 */ 11743 class MoveInstallArgs extends InstallArgs { 11744 private File codeFile; 11745 private File resourceFile; 11746 11747 /** New install */ 11748 MoveInstallArgs(InstallParams params) { 11749 super(params.origin, params.move, params.observer, params.installFlags, 11750 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11751 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11752 params.grantedRuntimePermissions, 11753 params.traceMethod, params.traceCookie); 11754 } 11755 11756 int copyApk(IMediaContainerService imcs, boolean temp) { 11757 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11758 + move.fromUuid + " to " + move.toUuid); 11759 synchronized (mInstaller) { 11760 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11761 move.dataAppName, move.appId, move.seinfo) != 0) { 11762 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11763 } 11764 } 11765 11766 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11767 resourceFile = codeFile; 11768 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11769 11770 return PackageManager.INSTALL_SUCCEEDED; 11771 } 11772 11773 int doPreInstall(int status) { 11774 if (status != PackageManager.INSTALL_SUCCEEDED) { 11775 cleanUp(move.toUuid); 11776 } 11777 return status; 11778 } 11779 11780 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11781 if (status != PackageManager.INSTALL_SUCCEEDED) { 11782 cleanUp(move.toUuid); 11783 return false; 11784 } 11785 11786 // Reflect the move in app info 11787 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11788 pkg.applicationInfo.setCodePath(pkg.codePath); 11789 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11790 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11791 pkg.applicationInfo.setResourcePath(pkg.codePath); 11792 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11793 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11794 11795 return true; 11796 } 11797 11798 int doPostInstall(int status, int uid) { 11799 if (status == PackageManager.INSTALL_SUCCEEDED) { 11800 cleanUp(move.fromUuid); 11801 } else { 11802 cleanUp(move.toUuid); 11803 } 11804 return status; 11805 } 11806 11807 @Override 11808 String getCodePath() { 11809 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11810 } 11811 11812 @Override 11813 String getResourcePath() { 11814 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11815 } 11816 11817 private boolean cleanUp(String volumeUuid) { 11818 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11819 move.dataAppName); 11820 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11821 synchronized (mInstallLock) { 11822 // Clean up both app data and code 11823 removeDataDirsLI(volumeUuid, move.packageName); 11824 if (codeFile.isDirectory()) { 11825 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11826 } else { 11827 codeFile.delete(); 11828 } 11829 } 11830 return true; 11831 } 11832 11833 void cleanUpResourcesLI() { 11834 throw new UnsupportedOperationException(); 11835 } 11836 11837 boolean doPostDeleteLI(boolean delete) { 11838 throw new UnsupportedOperationException(); 11839 } 11840 } 11841 11842 static String getAsecPackageName(String packageCid) { 11843 int idx = packageCid.lastIndexOf("-"); 11844 if (idx == -1) { 11845 return packageCid; 11846 } 11847 return packageCid.substring(0, idx); 11848 } 11849 11850 // Utility method used to create code paths based on package name and available index. 11851 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11852 String idxStr = ""; 11853 int idx = 1; 11854 // Fall back to default value of idx=1 if prefix is not 11855 // part of oldCodePath 11856 if (oldCodePath != null) { 11857 String subStr = oldCodePath; 11858 // Drop the suffix right away 11859 if (suffix != null && subStr.endsWith(suffix)) { 11860 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11861 } 11862 // If oldCodePath already contains prefix find out the 11863 // ending index to either increment or decrement. 11864 int sidx = subStr.lastIndexOf(prefix); 11865 if (sidx != -1) { 11866 subStr = subStr.substring(sidx + prefix.length()); 11867 if (subStr != null) { 11868 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11869 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11870 } 11871 try { 11872 idx = Integer.parseInt(subStr); 11873 if (idx <= 1) { 11874 idx++; 11875 } else { 11876 idx--; 11877 } 11878 } catch(NumberFormatException e) { 11879 } 11880 } 11881 } 11882 } 11883 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11884 return prefix + idxStr; 11885 } 11886 11887 private File getNextCodePath(File targetDir, String packageName) { 11888 int suffix = 1; 11889 File result; 11890 do { 11891 result = new File(targetDir, packageName + "-" + suffix); 11892 suffix++; 11893 } while (result.exists()); 11894 return result; 11895 } 11896 11897 // Utility method that returns the relative package path with respect 11898 // to the installation directory. Like say for /data/data/com.test-1.apk 11899 // string com.test-1 is returned. 11900 static String deriveCodePathName(String codePath) { 11901 if (codePath == null) { 11902 return null; 11903 } 11904 final File codeFile = new File(codePath); 11905 final String name = codeFile.getName(); 11906 if (codeFile.isDirectory()) { 11907 return name; 11908 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11909 final int lastDot = name.lastIndexOf('.'); 11910 return name.substring(0, lastDot); 11911 } else { 11912 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11913 return null; 11914 } 11915 } 11916 11917 class PackageInstalledInfo { 11918 String name; 11919 int uid; 11920 // The set of users that originally had this package installed. 11921 int[] origUsers; 11922 // The set of users that now have this package installed. 11923 int[] newUsers; 11924 PackageParser.Package pkg; 11925 int returnCode; 11926 String returnMsg; 11927 PackageRemovedInfo removedInfo; 11928 11929 public void setError(int code, String msg) { 11930 returnCode = code; 11931 returnMsg = msg; 11932 Slog.w(TAG, msg); 11933 } 11934 11935 public void setError(String msg, PackageParserException e) { 11936 returnCode = e.error; 11937 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11938 Slog.w(TAG, msg, e); 11939 } 11940 11941 public void setError(String msg, PackageManagerException e) { 11942 returnCode = e.error; 11943 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11944 Slog.w(TAG, msg, e); 11945 } 11946 11947 // In some error cases we want to convey more info back to the observer 11948 String origPackage; 11949 String origPermission; 11950 } 11951 11952 /* 11953 * Install a non-existing package. 11954 */ 11955 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11956 UserHandle user, String installerPackageName, String volumeUuid, 11957 PackageInstalledInfo res) { 11958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 11959 11960 // Remember this for later, in case we need to rollback this install 11961 String pkgName = pkg.packageName; 11962 11963 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11964 // TODO: b/23350563 11965 final boolean dataDirExists = Environment 11966 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 11967 11968 synchronized(mPackages) { 11969 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11970 // A package with the same name is already installed, though 11971 // it has been renamed to an older name. The package we 11972 // are trying to install should be installed as an update to 11973 // the existing one, but that has not been requested, so bail. 11974 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11975 + " without first uninstalling package running as " 11976 + mSettings.mRenamedPackages.get(pkgName)); 11977 return; 11978 } 11979 if (mPackages.containsKey(pkgName)) { 11980 // Don't allow installation over an existing package with the same name. 11981 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11982 + " without first uninstalling."); 11983 return; 11984 } 11985 } 11986 11987 try { 11988 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 11989 System.currentTimeMillis(), user); 11990 11991 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11992 // delete the partially installed application. the data directory will have to be 11993 // restored if it was already existing 11994 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11995 // remove package from internal structures. Note that we want deletePackageX to 11996 // delete the package data and cache directories that it created in 11997 // scanPackageLocked, unless those directories existed before we even tried to 11998 // install. 11999 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12000 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12001 res.removedInfo, true); 12002 } 12003 12004 } catch (PackageManagerException e) { 12005 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12006 } 12007 12008 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12009 } 12010 12011 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12012 // Can't rotate keys during boot or if sharedUser. 12013 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12014 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12015 return false; 12016 } 12017 // app is using upgradeKeySets; make sure all are valid 12018 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12019 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12020 for (int i = 0; i < upgradeKeySets.length; i++) { 12021 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12022 Slog.wtf(TAG, "Package " 12023 + (oldPs.name != null ? oldPs.name : "<null>") 12024 + " contains upgrade-key-set reference to unknown key-set: " 12025 + upgradeKeySets[i] 12026 + " reverting to signatures check."); 12027 return false; 12028 } 12029 } 12030 return true; 12031 } 12032 12033 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12034 // Upgrade keysets are being used. Determine if new package has a superset of the 12035 // required keys. 12036 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12037 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12038 for (int i = 0; i < upgradeKeySets.length; i++) { 12039 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12040 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12041 return true; 12042 } 12043 } 12044 return false; 12045 } 12046 12047 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12048 UserHandle user, String installerPackageName, String volumeUuid, 12049 PackageInstalledInfo res) { 12050 final PackageParser.Package oldPackage; 12051 final String pkgName = pkg.packageName; 12052 final int[] allUsers; 12053 final boolean[] perUserInstalled; 12054 12055 // First find the old package info and check signatures 12056 synchronized(mPackages) { 12057 oldPackage = mPackages.get(pkgName); 12058 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12059 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12060 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12061 if(!checkUpgradeKeySetLP(ps, pkg)) { 12062 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12063 "New package not signed by keys specified by upgrade-keysets: " 12064 + pkgName); 12065 return; 12066 } 12067 } else { 12068 // default to original signature matching 12069 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12070 != PackageManager.SIGNATURE_MATCH) { 12071 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12072 "New package has a different signature: " + pkgName); 12073 return; 12074 } 12075 } 12076 12077 // In case of rollback, remember per-user/profile install state 12078 allUsers = sUserManager.getUserIds(); 12079 perUserInstalled = new boolean[allUsers.length]; 12080 for (int i = 0; i < allUsers.length; i++) { 12081 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12082 } 12083 } 12084 12085 boolean sysPkg = (isSystemApp(oldPackage)); 12086 if (sysPkg) { 12087 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12088 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12089 } else { 12090 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12091 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12092 } 12093 } 12094 12095 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12096 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12097 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12098 String volumeUuid, PackageInstalledInfo res) { 12099 String pkgName = deletedPackage.packageName; 12100 boolean deletedPkg = true; 12101 boolean updatedSettings = false; 12102 12103 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12104 + deletedPackage); 12105 long origUpdateTime; 12106 if (pkg.mExtras != null) { 12107 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12108 } else { 12109 origUpdateTime = 0; 12110 } 12111 12112 // First delete the existing package while retaining the data directory 12113 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12114 res.removedInfo, true)) { 12115 // If the existing package wasn't successfully deleted 12116 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12117 deletedPkg = false; 12118 } else { 12119 // Successfully deleted the old package; proceed with replace. 12120 12121 // If deleted package lived in a container, give users a chance to 12122 // relinquish resources before killing. 12123 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12124 if (DEBUG_INSTALL) { 12125 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12126 } 12127 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12128 final ArrayList<String> pkgList = new ArrayList<String>(1); 12129 pkgList.add(deletedPackage.applicationInfo.packageName); 12130 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12131 } 12132 12133 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12134 try { 12135 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12136 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12137 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12138 perUserInstalled, res, user); 12139 updatedSettings = true; 12140 } catch (PackageManagerException e) { 12141 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12142 } 12143 } 12144 12145 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12146 // remove package from internal structures. Note that we want deletePackageX to 12147 // delete the package data and cache directories that it created in 12148 // scanPackageLocked, unless those directories existed before we even tried to 12149 // install. 12150 if(updatedSettings) { 12151 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12152 deletePackageLI( 12153 pkgName, null, true, allUsers, perUserInstalled, 12154 PackageManager.DELETE_KEEP_DATA, 12155 res.removedInfo, true); 12156 } 12157 // Since we failed to install the new package we need to restore the old 12158 // package that we deleted. 12159 if (deletedPkg) { 12160 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12161 File restoreFile = new File(deletedPackage.codePath); 12162 // Parse old package 12163 boolean oldExternal = isExternal(deletedPackage); 12164 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12165 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12166 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12167 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12168 try { 12169 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12170 null); 12171 } catch (PackageManagerException e) { 12172 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12173 + e.getMessage()); 12174 return; 12175 } 12176 // Restore of old package succeeded. Update permissions. 12177 // writer 12178 synchronized (mPackages) { 12179 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12180 UPDATE_PERMISSIONS_ALL); 12181 // can downgrade to reader 12182 mSettings.writeLPr(); 12183 } 12184 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12185 } 12186 } 12187 } 12188 12189 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12190 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12191 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12192 String volumeUuid, PackageInstalledInfo res) { 12193 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12194 + ", old=" + deletedPackage); 12195 boolean disabledSystem = false; 12196 boolean updatedSettings = false; 12197 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12198 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12199 != 0) { 12200 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12201 } 12202 String packageName = deletedPackage.packageName; 12203 if (packageName == null) { 12204 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12205 "Attempt to delete null packageName."); 12206 return; 12207 } 12208 PackageParser.Package oldPkg; 12209 PackageSetting oldPkgSetting; 12210 // reader 12211 synchronized (mPackages) { 12212 oldPkg = mPackages.get(packageName); 12213 oldPkgSetting = mSettings.mPackages.get(packageName); 12214 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12215 (oldPkgSetting == null)) { 12216 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12217 "Couldn't find package:" + packageName + " information"); 12218 return; 12219 } 12220 } 12221 12222 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12223 12224 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12225 res.removedInfo.removedPackage = packageName; 12226 // Remove existing system package 12227 removePackageLI(oldPkgSetting, true); 12228 // writer 12229 synchronized (mPackages) { 12230 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12231 if (!disabledSystem && deletedPackage != null) { 12232 // We didn't need to disable the .apk as a current system package, 12233 // which means we are replacing another update that is already 12234 // installed. We need to make sure to delete the older one's .apk. 12235 res.removedInfo.args = createInstallArgsForExisting(0, 12236 deletedPackage.applicationInfo.getCodePath(), 12237 deletedPackage.applicationInfo.getResourcePath(), 12238 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12239 } else { 12240 res.removedInfo.args = null; 12241 } 12242 } 12243 12244 // Successfully disabled the old package. Now proceed with re-installation 12245 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12246 12247 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12248 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12249 12250 PackageParser.Package newPackage = null; 12251 try { 12252 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12253 if (newPackage.mExtras != null) { 12254 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12255 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12256 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12257 12258 // is the update attempting to change shared user? that isn't going to work... 12259 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12260 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12261 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12262 + " to " + newPkgSetting.sharedUser); 12263 updatedSettings = true; 12264 } 12265 } 12266 12267 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12268 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12269 perUserInstalled, res, user); 12270 updatedSettings = true; 12271 } 12272 12273 } catch (PackageManagerException e) { 12274 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12275 } 12276 12277 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12278 // Re installation failed. Restore old information 12279 // Remove new pkg information 12280 if (newPackage != null) { 12281 removeInstalledPackageLI(newPackage, true); 12282 } 12283 // Add back the old system package 12284 try { 12285 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12286 } catch (PackageManagerException e) { 12287 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12288 } 12289 // Restore the old system information in Settings 12290 synchronized (mPackages) { 12291 if (disabledSystem) { 12292 mSettings.enableSystemPackageLPw(packageName); 12293 } 12294 if (updatedSettings) { 12295 mSettings.setInstallerPackageName(packageName, 12296 oldPkgSetting.installerPackageName); 12297 } 12298 mSettings.writeLPr(); 12299 } 12300 } 12301 } 12302 12303 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12304 // Collect all used permissions in the UID 12305 ArraySet<String> usedPermissions = new ArraySet<>(); 12306 final int packageCount = su.packages.size(); 12307 for (int i = 0; i < packageCount; i++) { 12308 PackageSetting ps = su.packages.valueAt(i); 12309 if (ps.pkg == null) { 12310 continue; 12311 } 12312 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12313 for (int j = 0; j < requestedPermCount; j++) { 12314 String permission = ps.pkg.requestedPermissions.get(j); 12315 BasePermission bp = mSettings.mPermissions.get(permission); 12316 if (bp != null) { 12317 usedPermissions.add(permission); 12318 } 12319 } 12320 } 12321 12322 PermissionsState permissionsState = su.getPermissionsState(); 12323 // Prune install permissions 12324 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12325 final int installPermCount = installPermStates.size(); 12326 for (int i = installPermCount - 1; i >= 0; i--) { 12327 PermissionState permissionState = installPermStates.get(i); 12328 if (!usedPermissions.contains(permissionState.getName())) { 12329 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12330 if (bp != null) { 12331 permissionsState.revokeInstallPermission(bp); 12332 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12333 PackageManager.MASK_PERMISSION_FLAGS, 0); 12334 } 12335 } 12336 } 12337 12338 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12339 12340 // Prune runtime permissions 12341 for (int userId : allUserIds) { 12342 List<PermissionState> runtimePermStates = permissionsState 12343 .getRuntimePermissionStates(userId); 12344 final int runtimePermCount = runtimePermStates.size(); 12345 for (int i = runtimePermCount - 1; i >= 0; i--) { 12346 PermissionState permissionState = runtimePermStates.get(i); 12347 if (!usedPermissions.contains(permissionState.getName())) { 12348 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12349 if (bp != null) { 12350 permissionsState.revokeRuntimePermission(bp, userId); 12351 permissionsState.updatePermissionFlags(bp, userId, 12352 PackageManager.MASK_PERMISSION_FLAGS, 0); 12353 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12354 runtimePermissionChangedUserIds, userId); 12355 } 12356 } 12357 } 12358 } 12359 12360 return runtimePermissionChangedUserIds; 12361 } 12362 12363 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12364 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12365 UserHandle user) { 12366 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12367 12368 String pkgName = newPackage.packageName; 12369 synchronized (mPackages) { 12370 //write settings. the installStatus will be incomplete at this stage. 12371 //note that the new package setting would have already been 12372 //added to mPackages. It hasn't been persisted yet. 12373 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12375 mSettings.writeLPr(); 12376 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12377 } 12378 12379 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12380 synchronized (mPackages) { 12381 updatePermissionsLPw(newPackage.packageName, newPackage, 12382 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12383 ? UPDATE_PERMISSIONS_ALL : 0)); 12384 // For system-bundled packages, we assume that installing an upgraded version 12385 // of the package implies that the user actually wants to run that new code, 12386 // so we enable the package. 12387 PackageSetting ps = mSettings.mPackages.get(pkgName); 12388 if (ps != null) { 12389 if (isSystemApp(newPackage)) { 12390 // NB: implicit assumption that system package upgrades apply to all users 12391 if (DEBUG_INSTALL) { 12392 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12393 } 12394 if (res.origUsers != null) { 12395 for (int userHandle : res.origUsers) { 12396 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12397 userHandle, installerPackageName); 12398 } 12399 } 12400 // Also convey the prior install/uninstall state 12401 if (allUsers != null && perUserInstalled != null) { 12402 for (int i = 0; i < allUsers.length; i++) { 12403 if (DEBUG_INSTALL) { 12404 Slog.d(TAG, " user " + allUsers[i] 12405 + " => " + perUserInstalled[i]); 12406 } 12407 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12408 } 12409 // these install state changes will be persisted in the 12410 // upcoming call to mSettings.writeLPr(). 12411 } 12412 } 12413 // It's implied that when a user requests installation, they want the app to be 12414 // installed and enabled. 12415 int userId = user.getIdentifier(); 12416 if (userId != UserHandle.USER_ALL) { 12417 ps.setInstalled(true, userId); 12418 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12419 } 12420 } 12421 res.name = pkgName; 12422 res.uid = newPackage.applicationInfo.uid; 12423 res.pkg = newPackage; 12424 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12425 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12426 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12427 //to update install status 12428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12429 mSettings.writeLPr(); 12430 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12431 } 12432 12433 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12434 } 12435 12436 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12437 try { 12438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12439 installPackageLI(args, res); 12440 } finally { 12441 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12442 } 12443 } 12444 12445 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12446 final int installFlags = args.installFlags; 12447 final String installerPackageName = args.installerPackageName; 12448 final String volumeUuid = args.volumeUuid; 12449 final File tmpPackageFile = new File(args.getCodePath()); 12450 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12451 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12452 || (args.volumeUuid != null)); 12453 final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0); 12454 boolean replace = false; 12455 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12456 if (args.move != null) { 12457 // moving a complete application; perfom an initial scan on the new install location 12458 scanFlags |= SCAN_INITIAL; 12459 } 12460 // Result object to be returned 12461 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12462 12463 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12464 12465 // Retrieve PackageSettings and parse package 12466 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12467 | PackageParser.PARSE_ENFORCE_CODE 12468 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12469 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12470 | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0); 12471 PackageParser pp = new PackageParser(); 12472 pp.setSeparateProcesses(mSeparateProcesses); 12473 pp.setDisplayMetrics(mMetrics); 12474 12475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12476 final PackageParser.Package pkg; 12477 try { 12478 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12479 } catch (PackageParserException e) { 12480 res.setError("Failed parse during installPackageLI", e); 12481 return; 12482 } finally { 12483 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12484 } 12485 12486 // Mark that we have an install time CPU ABI override. 12487 pkg.cpuAbiOverride = args.abiOverride; 12488 12489 String pkgName = res.name = pkg.packageName; 12490 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12491 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12492 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12493 return; 12494 } 12495 } 12496 12497 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12498 try { 12499 pp.collectCertificates(pkg, parseFlags); 12500 } catch (PackageParserException e) { 12501 res.setError("Failed collect during installPackageLI", e); 12502 return; 12503 } finally { 12504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12505 } 12506 12507 /* If the installer passed in a manifest digest, compare it now. */ 12508 if (args.manifestDigest != null) { 12509 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest"); 12510 try { 12511 pp.collectManifestDigest(pkg); 12512 } catch (PackageParserException e) { 12513 res.setError("Failed collect during installPackageLI", e); 12514 return; 12515 } finally { 12516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12517 } 12518 12519 if (DEBUG_INSTALL) { 12520 final String parsedManifest = pkg.manifestDigest == null ? "null" 12521 : pkg.manifestDigest.toString(); 12522 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12523 + parsedManifest); 12524 } 12525 12526 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12527 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12528 return; 12529 } 12530 } else if (DEBUG_INSTALL) { 12531 final String parsedManifest = pkg.manifestDigest == null 12532 ? "null" : pkg.manifestDigest.toString(); 12533 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12534 } 12535 12536 // Get rid of all references to package scan path via parser. 12537 pp = null; 12538 String oldCodePath = null; 12539 boolean systemApp = false; 12540 synchronized (mPackages) { 12541 // Check if installing already existing package 12542 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12543 String oldName = mSettings.mRenamedPackages.get(pkgName); 12544 if (pkg.mOriginalPackages != null 12545 && pkg.mOriginalPackages.contains(oldName) 12546 && mPackages.containsKey(oldName)) { 12547 // This package is derived from an original package, 12548 // and this device has been updating from that original 12549 // name. We must continue using the original name, so 12550 // rename the new package here. 12551 pkg.setPackageName(oldName); 12552 pkgName = pkg.packageName; 12553 replace = true; 12554 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12555 + oldName + " pkgName=" + pkgName); 12556 } else if (mPackages.containsKey(pkgName)) { 12557 // This package, under its official name, already exists 12558 // on the device; we should replace it. 12559 replace = true; 12560 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12561 } 12562 12563 // Prevent apps opting out from runtime permissions 12564 if (replace) { 12565 PackageParser.Package oldPackage = mPackages.get(pkgName); 12566 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12567 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12568 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12569 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12570 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12571 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12572 + " doesn't support runtime permissions but the old" 12573 + " target SDK " + oldTargetSdk + " does."); 12574 return; 12575 } 12576 } 12577 } 12578 12579 PackageSetting ps = mSettings.mPackages.get(pkgName); 12580 if (ps != null) { 12581 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12582 12583 // Quick sanity check that we're signed correctly if updating; 12584 // we'll check this again later when scanning, but we want to 12585 // bail early here before tripping over redefined permissions. 12586 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12587 if (!checkUpgradeKeySetLP(ps, pkg)) { 12588 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12589 + pkg.packageName + " upgrade keys do not match the " 12590 + "previously installed version"); 12591 return; 12592 } 12593 } else { 12594 try { 12595 verifySignaturesLP(ps, pkg); 12596 } catch (PackageManagerException e) { 12597 res.setError(e.error, e.getMessage()); 12598 return; 12599 } 12600 } 12601 12602 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12603 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12604 systemApp = (ps.pkg.applicationInfo.flags & 12605 ApplicationInfo.FLAG_SYSTEM) != 0; 12606 } 12607 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12608 } 12609 12610 // Check whether the newly-scanned package wants to define an already-defined perm 12611 int N = pkg.permissions.size(); 12612 for (int i = N-1; i >= 0; i--) { 12613 PackageParser.Permission perm = pkg.permissions.get(i); 12614 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12615 if (bp != null) { 12616 // If the defining package is signed with our cert, it's okay. This 12617 // also includes the "updating the same package" case, of course. 12618 // "updating same package" could also involve key-rotation. 12619 final boolean sigsOk; 12620 if (bp.sourcePackage.equals(pkg.packageName) 12621 && (bp.packageSetting instanceof PackageSetting) 12622 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12623 scanFlags))) { 12624 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12625 } else { 12626 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12627 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12628 } 12629 if (!sigsOk) { 12630 // If the owning package is the system itself, we log but allow 12631 // install to proceed; we fail the install on all other permission 12632 // redefinitions. 12633 if (!bp.sourcePackage.equals("android")) { 12634 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12635 + pkg.packageName + " attempting to redeclare permission " 12636 + perm.info.name + " already owned by " + bp.sourcePackage); 12637 res.origPermission = perm.info.name; 12638 res.origPackage = bp.sourcePackage; 12639 return; 12640 } else { 12641 Slog.w(TAG, "Package " + pkg.packageName 12642 + " attempting to redeclare system permission " 12643 + perm.info.name + "; ignoring new declaration"); 12644 pkg.permissions.remove(i); 12645 } 12646 } 12647 } 12648 } 12649 12650 } 12651 12652 if (systemApp && onExternal) { 12653 // Disable updates to system apps on sdcard 12654 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12655 "Cannot install updates to system apps on sdcard"); 12656 return; 12657 } 12658 12659 if (args.move != null) { 12660 // We did an in-place move, so dex is ready to roll 12661 scanFlags |= SCAN_NO_DEX; 12662 scanFlags |= SCAN_MOVE; 12663 12664 synchronized (mPackages) { 12665 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12666 if (ps == null) { 12667 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12668 "Missing settings for moved package " + pkgName); 12669 } 12670 12671 // We moved the entire application as-is, so bring over the 12672 // previously derived ABI information. 12673 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12674 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12675 } 12676 12677 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12678 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12679 scanFlags |= SCAN_NO_DEX; 12680 12681 try { 12682 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12683 true /* extract libs */); 12684 } catch (PackageManagerException pme) { 12685 Slog.e(TAG, "Error deriving application ABI", pme); 12686 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12687 return; 12688 } 12689 12690 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12691 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 12692 12693 int result = mPackageDexOptimizer 12694 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12695 false /* defer */, false /* inclDependencies */, 12696 true /*bootComplete*/, quickInstall /*useJit*/); 12697 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12698 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12699 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12700 return; 12701 } 12702 } 12703 12704 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12705 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12706 return; 12707 } 12708 12709 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12710 12711 if (replace) { 12712 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 12713 installerPackageName, volumeUuid, res); 12714 } else { 12715 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12716 args.user, installerPackageName, volumeUuid, res); 12717 } 12718 synchronized (mPackages) { 12719 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12720 if (ps != null) { 12721 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12722 } 12723 } 12724 } 12725 12726 private void startIntentFilterVerifications(int userId, boolean replacing, 12727 PackageParser.Package pkg) { 12728 if (mIntentFilterVerifierComponent == null) { 12729 Slog.w(TAG, "No IntentFilter verification will not be done as " 12730 + "there is no IntentFilterVerifier available!"); 12731 return; 12732 } 12733 12734 final int verifierUid = getPackageUid( 12735 mIntentFilterVerifierComponent.getPackageName(), 12736 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 12737 12738 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12739 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12740 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12741 mHandler.sendMessage(msg); 12742 } 12743 12744 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12745 PackageParser.Package pkg) { 12746 int size = pkg.activities.size(); 12747 if (size == 0) { 12748 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12749 "No activity, so no need to verify any IntentFilter!"); 12750 return; 12751 } 12752 12753 final boolean hasDomainURLs = hasDomainURLs(pkg); 12754 if (!hasDomainURLs) { 12755 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12756 "No domain URLs, so no need to verify any IntentFilter!"); 12757 return; 12758 } 12759 12760 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12761 + " if any IntentFilter from the " + size 12762 + " Activities needs verification ..."); 12763 12764 int count = 0; 12765 final String packageName = pkg.packageName; 12766 12767 synchronized (mPackages) { 12768 // If this is a new install and we see that we've already run verification for this 12769 // package, we have nothing to do: it means the state was restored from backup. 12770 if (!replacing) { 12771 IntentFilterVerificationInfo ivi = 12772 mSettings.getIntentFilterVerificationLPr(packageName); 12773 if (ivi != null) { 12774 if (DEBUG_DOMAIN_VERIFICATION) { 12775 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12776 + ivi.getStatusString()); 12777 } 12778 return; 12779 } 12780 } 12781 12782 // If any filters need to be verified, then all need to be. 12783 boolean needToVerify = false; 12784 for (PackageParser.Activity a : pkg.activities) { 12785 for (ActivityIntentInfo filter : a.intents) { 12786 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12787 if (DEBUG_DOMAIN_VERIFICATION) { 12788 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12789 } 12790 needToVerify = true; 12791 break; 12792 } 12793 } 12794 } 12795 12796 if (needToVerify) { 12797 final int verificationId = mIntentFilterVerificationToken++; 12798 for (PackageParser.Activity a : pkg.activities) { 12799 for (ActivityIntentInfo filter : a.intents) { 12800 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12801 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12802 "Verification needed for IntentFilter:" + filter.toString()); 12803 mIntentFilterVerifier.addOneIntentFilterVerification( 12804 verifierUid, userId, verificationId, filter, packageName); 12805 count++; 12806 } 12807 } 12808 } 12809 } 12810 } 12811 12812 if (count > 0) { 12813 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12814 + " IntentFilter verification" + (count > 1 ? "s" : "") 12815 + " for userId:" + userId); 12816 mIntentFilterVerifier.startVerifications(userId); 12817 } else { 12818 if (DEBUG_DOMAIN_VERIFICATION) { 12819 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12820 } 12821 } 12822 } 12823 12824 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12825 final ComponentName cn = filter.activity.getComponentName(); 12826 final String packageName = cn.getPackageName(); 12827 12828 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12829 packageName); 12830 if (ivi == null) { 12831 return true; 12832 } 12833 int status = ivi.getStatus(); 12834 switch (status) { 12835 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12836 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12837 return true; 12838 12839 default: 12840 // Nothing to do 12841 return false; 12842 } 12843 } 12844 12845 private static boolean isMultiArch(PackageSetting ps) { 12846 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12847 } 12848 12849 private static boolean isMultiArch(ApplicationInfo info) { 12850 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12851 } 12852 12853 private static boolean isExternal(PackageParser.Package pkg) { 12854 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12855 } 12856 12857 private static boolean isExternal(PackageSetting ps) { 12858 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12859 } 12860 12861 private static boolean isExternal(ApplicationInfo info) { 12862 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12863 } 12864 12865 private static boolean isSystemApp(PackageParser.Package pkg) { 12866 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12867 } 12868 12869 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12870 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12871 } 12872 12873 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12874 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12875 } 12876 12877 private static boolean isSystemApp(PackageSetting ps) { 12878 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12879 } 12880 12881 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12882 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12883 } 12884 12885 private int packageFlagsToInstallFlags(PackageSetting ps) { 12886 int installFlags = 0; 12887 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12888 // This existing package was an external ASEC install when we have 12889 // the external flag without a UUID 12890 installFlags |= PackageManager.INSTALL_EXTERNAL; 12891 } 12892 if (ps.isForwardLocked()) { 12893 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12894 } 12895 return installFlags; 12896 } 12897 12898 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 12899 if (isExternal(pkg)) { 12900 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12901 return StorageManager.UUID_PRIMARY_PHYSICAL; 12902 } else { 12903 return pkg.volumeUuid; 12904 } 12905 } else { 12906 return StorageManager.UUID_PRIVATE_INTERNAL; 12907 } 12908 } 12909 12910 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 12911 if (isExternal(pkg)) { 12912 if (TextUtils.isEmpty(pkg.volumeUuid)) { 12913 return mSettings.getExternalVersion(); 12914 } else { 12915 return mSettings.findOrCreateVersion(pkg.volumeUuid); 12916 } 12917 } else { 12918 return mSettings.getInternalVersion(); 12919 } 12920 } 12921 12922 private void deleteTempPackageFiles() { 12923 final FilenameFilter filter = new FilenameFilter() { 12924 public boolean accept(File dir, String name) { 12925 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12926 } 12927 }; 12928 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12929 file.delete(); 12930 } 12931 } 12932 12933 @Override 12934 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12935 int flags) { 12936 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12937 flags); 12938 } 12939 12940 @Override 12941 public void deletePackage(final String packageName, 12942 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12943 mContext.enforceCallingOrSelfPermission( 12944 android.Manifest.permission.DELETE_PACKAGES, null); 12945 Preconditions.checkNotNull(packageName); 12946 Preconditions.checkNotNull(observer); 12947 final int uid = Binder.getCallingUid(); 12948 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 12949 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 12950 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 12951 mContext.enforceCallingPermission( 12952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12953 "deletePackage for user " + userId); 12954 } 12955 12956 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12957 try { 12958 observer.onPackageDeleted(packageName, 12959 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12960 } catch (RemoteException re) { 12961 } 12962 return; 12963 } 12964 12965 for (int currentUserId : users) { 12966 if (getBlockUninstallForUser(packageName, currentUserId)) { 12967 try { 12968 observer.onPackageDeleted(packageName, 12969 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 12970 } catch (RemoteException re) { 12971 } 12972 return; 12973 } 12974 } 12975 12976 if (DEBUG_REMOVE) { 12977 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12978 } 12979 // Queue up an async operation since the package deletion may take a little while. 12980 mHandler.post(new Runnable() { 12981 public void run() { 12982 mHandler.removeCallbacks(this); 12983 final int returnCode = deletePackageX(packageName, userId, flags); 12984 try { 12985 observer.onPackageDeleted(packageName, returnCode, null); 12986 } catch (RemoteException e) { 12987 Log.i(TAG, "Observer no longer exists."); 12988 } //end catch 12989 } //end run 12990 }); 12991 } 12992 12993 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12994 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12995 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12996 try { 12997 if (dpm != null) { 12998 // Does the package contains the device owner? 12999 if (dpm.isDeviceOwnerPackage(packageName)) { 13000 return true; 13001 } 13002 // Does it contain a device admin for any user? 13003 int[] users; 13004 if (userId == UserHandle.USER_ALL) { 13005 users = sUserManager.getUserIds(); 13006 } else { 13007 users = new int[]{userId}; 13008 } 13009 for (int i = 0; i < users.length; ++i) { 13010 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13011 return true; 13012 } 13013 } 13014 } 13015 } catch (RemoteException e) { 13016 } 13017 return false; 13018 } 13019 13020 /** 13021 * This method is an internal method that could be get invoked either 13022 * to delete an installed package or to clean up a failed installation. 13023 * After deleting an installed package, a broadcast is sent to notify any 13024 * listeners that the package has been installed. For cleaning up a failed 13025 * installation, the broadcast is not necessary since the package's 13026 * installation wouldn't have sent the initial broadcast either 13027 * The key steps in deleting a package are 13028 * deleting the package information in internal structures like mPackages, 13029 * deleting the packages base directories through installd 13030 * updating mSettings to reflect current status 13031 * persisting settings for later use 13032 * sending a broadcast if necessary 13033 */ 13034 private int deletePackageX(String packageName, int userId, int flags) { 13035 final PackageRemovedInfo info = new PackageRemovedInfo(); 13036 final boolean res; 13037 13038 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13039 ? UserHandle.ALL : new UserHandle(userId); 13040 13041 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13042 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13043 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13044 } 13045 13046 boolean removedForAllUsers = false; 13047 boolean systemUpdate = false; 13048 13049 // for the uninstall-updates case and restricted profiles, remember the per- 13050 // userhandle installed state 13051 int[] allUsers; 13052 boolean[] perUserInstalled; 13053 synchronized (mPackages) { 13054 PackageSetting ps = mSettings.mPackages.get(packageName); 13055 allUsers = sUserManager.getUserIds(); 13056 perUserInstalled = new boolean[allUsers.length]; 13057 for (int i = 0; i < allUsers.length; i++) { 13058 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13059 } 13060 } 13061 13062 synchronized (mInstallLock) { 13063 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13064 res = deletePackageLI(packageName, removeForUser, 13065 true, allUsers, perUserInstalled, 13066 flags | REMOVE_CHATTY, info, true); 13067 systemUpdate = info.isRemovedPackageSystemUpdate; 13068 if (res && !systemUpdate && mPackages.get(packageName) == null) { 13069 removedForAllUsers = true; 13070 } 13071 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13072 + " removedForAllUsers=" + removedForAllUsers); 13073 } 13074 13075 if (res) { 13076 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13077 13078 // If the removed package was a system update, the old system package 13079 // was re-enabled; we need to broadcast this information 13080 if (systemUpdate) { 13081 Bundle extras = new Bundle(1); 13082 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13083 ? info.removedAppId : info.uid); 13084 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13085 13086 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13087 extras, null, null, null); 13088 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13089 extras, null, null, null); 13090 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13091 null, packageName, null, null); 13092 } 13093 } 13094 // Force a gc here. 13095 Runtime.getRuntime().gc(); 13096 // Delete the resources here after sending the broadcast to let 13097 // other processes clean up before deleting resources. 13098 if (info.args != null) { 13099 synchronized (mInstallLock) { 13100 info.args.doPostDeleteLI(true); 13101 } 13102 } 13103 13104 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13105 } 13106 13107 class PackageRemovedInfo { 13108 String removedPackage; 13109 int uid = -1; 13110 int removedAppId = -1; 13111 int[] removedUsers = null; 13112 boolean isRemovedPackageSystemUpdate = false; 13113 // Clean up resources deleted packages. 13114 InstallArgs args = null; 13115 13116 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13117 Bundle extras = new Bundle(1); 13118 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13119 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13120 if (replacing) { 13121 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13122 } 13123 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13124 if (removedPackage != null) { 13125 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13126 extras, null, null, removedUsers); 13127 if (fullRemove && !replacing) { 13128 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13129 extras, null, null, removedUsers); 13130 } 13131 } 13132 if (removedAppId >= 0) { 13133 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 13134 removedUsers); 13135 } 13136 } 13137 } 13138 13139 /* 13140 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13141 * flag is not set, the data directory is removed as well. 13142 * make sure this flag is set for partially installed apps. If not its meaningless to 13143 * delete a partially installed application. 13144 */ 13145 private void removePackageDataLI(PackageSetting ps, 13146 int[] allUserHandles, boolean[] perUserInstalled, 13147 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13148 String packageName = ps.name; 13149 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13150 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13151 // Retrieve object to delete permissions for shared user later on 13152 final PackageSetting deletedPs; 13153 // reader 13154 synchronized (mPackages) { 13155 deletedPs = mSettings.mPackages.get(packageName); 13156 if (outInfo != null) { 13157 outInfo.removedPackage = packageName; 13158 outInfo.removedUsers = deletedPs != null 13159 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13160 : null; 13161 } 13162 } 13163 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13164 removeDataDirsLI(ps.volumeUuid, packageName); 13165 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13166 } 13167 // writer 13168 synchronized (mPackages) { 13169 if (deletedPs != null) { 13170 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13171 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13172 clearDefaultBrowserIfNeeded(packageName); 13173 if (outInfo != null) { 13174 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13175 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13176 } 13177 updatePermissionsLPw(deletedPs.name, null, 0); 13178 if (deletedPs.sharedUser != null) { 13179 // Remove permissions associated with package. Since runtime 13180 // permissions are per user we have to kill the removed package 13181 // or packages running under the shared user of the removed 13182 // package if revoking the permissions requested only by the removed 13183 // package is successful and this causes a change in gids. 13184 for (int userId : UserManagerService.getInstance().getUserIds()) { 13185 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13186 userId); 13187 if (userIdToKill == UserHandle.USER_ALL 13188 || userIdToKill >= UserHandle.USER_SYSTEM) { 13189 // If gids changed for this user, kill all affected packages. 13190 mHandler.post(new Runnable() { 13191 @Override 13192 public void run() { 13193 // This has to happen with no lock held. 13194 killApplication(deletedPs.name, deletedPs.appId, 13195 KILL_APP_REASON_GIDS_CHANGED); 13196 } 13197 }); 13198 break; 13199 } 13200 } 13201 } 13202 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13203 } 13204 // make sure to preserve per-user disabled state if this removal was just 13205 // a downgrade of a system app to the factory package 13206 if (allUserHandles != null && perUserInstalled != null) { 13207 if (DEBUG_REMOVE) { 13208 Slog.d(TAG, "Propagating install state across downgrade"); 13209 } 13210 for (int i = 0; i < allUserHandles.length; i++) { 13211 if (DEBUG_REMOVE) { 13212 Slog.d(TAG, " user " + allUserHandles[i] 13213 + " => " + perUserInstalled[i]); 13214 } 13215 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13216 } 13217 } 13218 } 13219 // can downgrade to reader 13220 if (writeSettings) { 13221 // Save settings now 13222 mSettings.writeLPr(); 13223 } 13224 } 13225 if (outInfo != null) { 13226 // A user ID was deleted here. Go through all users and remove it 13227 // from KeyStore. 13228 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13229 } 13230 } 13231 13232 static boolean locationIsPrivileged(File path) { 13233 try { 13234 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13235 .getCanonicalPath(); 13236 return path.getCanonicalPath().startsWith(privilegedAppDir); 13237 } catch (IOException e) { 13238 Slog.e(TAG, "Unable to access code path " + path); 13239 } 13240 return false; 13241 } 13242 13243 /* 13244 * Tries to delete system package. 13245 */ 13246 private boolean deleteSystemPackageLI(PackageSetting newPs, 13247 int[] allUserHandles, boolean[] perUserInstalled, 13248 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13249 final boolean applyUserRestrictions 13250 = (allUserHandles != null) && (perUserInstalled != null); 13251 PackageSetting disabledPs = null; 13252 // Confirm if the system package has been updated 13253 // An updated system app can be deleted. This will also have to restore 13254 // the system pkg from system partition 13255 // reader 13256 synchronized (mPackages) { 13257 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13258 } 13259 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13260 + " disabledPs=" + disabledPs); 13261 if (disabledPs == null) { 13262 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13263 return false; 13264 } else if (DEBUG_REMOVE) { 13265 Slog.d(TAG, "Deleting system pkg from data partition"); 13266 } 13267 if (DEBUG_REMOVE) { 13268 if (applyUserRestrictions) { 13269 Slog.d(TAG, "Remembering install states:"); 13270 for (int i = 0; i < allUserHandles.length; i++) { 13271 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13272 } 13273 } 13274 } 13275 // Delete the updated package 13276 outInfo.isRemovedPackageSystemUpdate = true; 13277 if (disabledPs.versionCode < newPs.versionCode) { 13278 // Delete data for downgrades 13279 flags &= ~PackageManager.DELETE_KEEP_DATA; 13280 } else { 13281 // Preserve data by setting flag 13282 flags |= PackageManager.DELETE_KEEP_DATA; 13283 } 13284 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13285 allUserHandles, perUserInstalled, outInfo, writeSettings); 13286 if (!ret) { 13287 return false; 13288 } 13289 // writer 13290 synchronized (mPackages) { 13291 // Reinstate the old system package 13292 mSettings.enableSystemPackageLPw(newPs.name); 13293 // Remove any native libraries from the upgraded package. 13294 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13295 } 13296 // Install the system package 13297 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13298 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13299 if (locationIsPrivileged(disabledPs.codePath)) { 13300 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13301 } 13302 13303 final PackageParser.Package newPkg; 13304 try { 13305 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13306 } catch (PackageManagerException e) { 13307 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 13308 return false; 13309 } 13310 13311 // writer 13312 synchronized (mPackages) { 13313 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13314 13315 // Propagate the permissions state as we do not want to drop on the floor 13316 // runtime permissions. The update permissions method below will take 13317 // care of removing obsolete permissions and grant install permissions. 13318 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13319 updatePermissionsLPw(newPkg.packageName, newPkg, 13320 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13321 13322 if (applyUserRestrictions) { 13323 if (DEBUG_REMOVE) { 13324 Slog.d(TAG, "Propagating install state across reinstall"); 13325 } 13326 for (int i = 0; i < allUserHandles.length; i++) { 13327 if (DEBUG_REMOVE) { 13328 Slog.d(TAG, " user " + allUserHandles[i] 13329 + " => " + perUserInstalled[i]); 13330 } 13331 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13332 13333 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13334 } 13335 // Regardless of writeSettings we need to ensure that this restriction 13336 // state propagation is persisted 13337 mSettings.writeAllUsersPackageRestrictionsLPr(); 13338 } 13339 // can downgrade to reader here 13340 if (writeSettings) { 13341 mSettings.writeLPr(); 13342 } 13343 } 13344 return true; 13345 } 13346 13347 private boolean deleteInstalledPackageLI(PackageSetting ps, 13348 boolean deleteCodeAndResources, int flags, 13349 int[] allUserHandles, boolean[] perUserInstalled, 13350 PackageRemovedInfo outInfo, boolean writeSettings) { 13351 if (outInfo != null) { 13352 outInfo.uid = ps.appId; 13353 } 13354 13355 // Delete package data from internal structures and also remove data if flag is set 13356 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13357 13358 // Delete application code and resources 13359 if (deleteCodeAndResources && (outInfo != null)) { 13360 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13361 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13362 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13363 } 13364 return true; 13365 } 13366 13367 @Override 13368 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13369 int userId) { 13370 mContext.enforceCallingOrSelfPermission( 13371 android.Manifest.permission.DELETE_PACKAGES, null); 13372 synchronized (mPackages) { 13373 PackageSetting ps = mSettings.mPackages.get(packageName); 13374 if (ps == null) { 13375 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13376 return false; 13377 } 13378 if (!ps.getInstalled(userId)) { 13379 // Can't block uninstall for an app that is not installed or enabled. 13380 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13381 return false; 13382 } 13383 ps.setBlockUninstall(blockUninstall, userId); 13384 mSettings.writePackageRestrictionsLPr(userId); 13385 } 13386 return true; 13387 } 13388 13389 @Override 13390 public boolean getBlockUninstallForUser(String packageName, int userId) { 13391 synchronized (mPackages) { 13392 PackageSetting ps = mSettings.mPackages.get(packageName); 13393 if (ps == null) { 13394 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13395 return false; 13396 } 13397 return ps.getBlockUninstall(userId); 13398 } 13399 } 13400 13401 /* 13402 * This method handles package deletion in general 13403 */ 13404 private boolean deletePackageLI(String packageName, UserHandle user, 13405 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13406 int flags, PackageRemovedInfo outInfo, 13407 boolean writeSettings) { 13408 if (packageName == null) { 13409 Slog.w(TAG, "Attempt to delete null packageName."); 13410 return false; 13411 } 13412 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13413 PackageSetting ps; 13414 boolean dataOnly = false; 13415 int removeUser = -1; 13416 int appId = -1; 13417 synchronized (mPackages) { 13418 ps = mSettings.mPackages.get(packageName); 13419 if (ps == null) { 13420 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13421 return false; 13422 } 13423 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13424 && user.getIdentifier() != UserHandle.USER_ALL) { 13425 // The caller is asking that the package only be deleted for a single 13426 // user. To do this, we just mark its uninstalled state and delete 13427 // its data. If this is a system app, we only allow this to happen if 13428 // they have set the special DELETE_SYSTEM_APP which requests different 13429 // semantics than normal for uninstalling system apps. 13430 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13431 final int userId = user.getIdentifier(); 13432 ps.setUserState(userId, 13433 COMPONENT_ENABLED_STATE_DEFAULT, 13434 false, //installed 13435 true, //stopped 13436 true, //notLaunched 13437 false, //hidden 13438 null, null, null, 13439 false, // blockUninstall 13440 ps.readUserState(userId).domainVerificationStatus, 0); 13441 if (!isSystemApp(ps)) { 13442 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 13443 // Other user still have this package installed, so all 13444 // we need to do is clear this user's data and save that 13445 // it is uninstalled. 13446 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13447 removeUser = user.getIdentifier(); 13448 appId = ps.appId; 13449 scheduleWritePackageRestrictionsLocked(removeUser); 13450 } else { 13451 // We need to set it back to 'installed' so the uninstall 13452 // broadcasts will be sent correctly. 13453 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13454 ps.setInstalled(true, user.getIdentifier()); 13455 } 13456 } else { 13457 // This is a system app, so we assume that the 13458 // other users still have this package installed, so all 13459 // we need to do is clear this user's data and save that 13460 // it is uninstalled. 13461 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13462 removeUser = user.getIdentifier(); 13463 appId = ps.appId; 13464 scheduleWritePackageRestrictionsLocked(removeUser); 13465 } 13466 } 13467 } 13468 13469 if (removeUser >= 0) { 13470 // From above, we determined that we are deleting this only 13471 // for a single user. Continue the work here. 13472 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13473 if (outInfo != null) { 13474 outInfo.removedPackage = packageName; 13475 outInfo.removedAppId = appId; 13476 outInfo.removedUsers = new int[] {removeUser}; 13477 } 13478 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13479 removeKeystoreDataIfNeeded(removeUser, appId); 13480 schedulePackageCleaning(packageName, removeUser, false); 13481 synchronized (mPackages) { 13482 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13483 scheduleWritePackageRestrictionsLocked(removeUser); 13484 } 13485 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13486 } 13487 return true; 13488 } 13489 13490 if (dataOnly) { 13491 // Delete application data first 13492 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13493 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13494 return true; 13495 } 13496 13497 boolean ret = false; 13498 if (isSystemApp(ps)) { 13499 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13500 // When an updated system application is deleted we delete the existing resources as well and 13501 // fall back to existing code in system partition 13502 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13503 flags, outInfo, writeSettings); 13504 } else { 13505 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13506 // Kill application pre-emptively especially for apps on sd. 13507 killApplication(packageName, ps.appId, "uninstall pkg"); 13508 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13509 allUserHandles, perUserInstalled, 13510 outInfo, writeSettings); 13511 } 13512 13513 return ret; 13514 } 13515 13516 private final class ClearStorageConnection implements ServiceConnection { 13517 IMediaContainerService mContainerService; 13518 13519 @Override 13520 public void onServiceConnected(ComponentName name, IBinder service) { 13521 synchronized (this) { 13522 mContainerService = IMediaContainerService.Stub.asInterface(service); 13523 notifyAll(); 13524 } 13525 } 13526 13527 @Override 13528 public void onServiceDisconnected(ComponentName name) { 13529 } 13530 } 13531 13532 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13533 final boolean mounted; 13534 if (Environment.isExternalStorageEmulated()) { 13535 mounted = true; 13536 } else { 13537 final String status = Environment.getExternalStorageState(); 13538 13539 mounted = status.equals(Environment.MEDIA_MOUNTED) 13540 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13541 } 13542 13543 if (!mounted) { 13544 return; 13545 } 13546 13547 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13548 int[] users; 13549 if (userId == UserHandle.USER_ALL) { 13550 users = sUserManager.getUserIds(); 13551 } else { 13552 users = new int[] { userId }; 13553 } 13554 final ClearStorageConnection conn = new ClearStorageConnection(); 13555 if (mContext.bindServiceAsUser( 13556 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13557 try { 13558 for (int curUser : users) { 13559 long timeout = SystemClock.uptimeMillis() + 5000; 13560 synchronized (conn) { 13561 long now = SystemClock.uptimeMillis(); 13562 while (conn.mContainerService == null && now < timeout) { 13563 try { 13564 conn.wait(timeout - now); 13565 } catch (InterruptedException e) { 13566 } 13567 } 13568 } 13569 if (conn.mContainerService == null) { 13570 return; 13571 } 13572 13573 final UserEnvironment userEnv = new UserEnvironment(curUser); 13574 clearDirectory(conn.mContainerService, 13575 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13576 if (allData) { 13577 clearDirectory(conn.mContainerService, 13578 userEnv.buildExternalStorageAppDataDirs(packageName)); 13579 clearDirectory(conn.mContainerService, 13580 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13581 } 13582 } 13583 } finally { 13584 mContext.unbindService(conn); 13585 } 13586 } 13587 } 13588 13589 @Override 13590 public void clearApplicationUserData(final String packageName, 13591 final IPackageDataObserver observer, final int userId) { 13592 mContext.enforceCallingOrSelfPermission( 13593 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13594 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13595 // Queue up an async operation since the package deletion may take a little while. 13596 mHandler.post(new Runnable() { 13597 public void run() { 13598 mHandler.removeCallbacks(this); 13599 final boolean succeeded; 13600 synchronized (mInstallLock) { 13601 succeeded = clearApplicationUserDataLI(packageName, userId); 13602 } 13603 clearExternalStorageDataSync(packageName, userId, true); 13604 if (succeeded) { 13605 // invoke DeviceStorageMonitor's update method to clear any notifications 13606 DeviceStorageMonitorInternal 13607 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13608 if (dsm != null) { 13609 dsm.checkMemory(); 13610 } 13611 } 13612 if(observer != null) { 13613 try { 13614 observer.onRemoveCompleted(packageName, succeeded); 13615 } catch (RemoteException e) { 13616 Log.i(TAG, "Observer no longer exists."); 13617 } 13618 } //end if observer 13619 } //end run 13620 }); 13621 } 13622 13623 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13624 if (packageName == null) { 13625 Slog.w(TAG, "Attempt to delete null packageName."); 13626 return false; 13627 } 13628 13629 // Try finding details about the requested package 13630 PackageParser.Package pkg; 13631 synchronized (mPackages) { 13632 pkg = mPackages.get(packageName); 13633 if (pkg == null) { 13634 final PackageSetting ps = mSettings.mPackages.get(packageName); 13635 if (ps != null) { 13636 pkg = ps.pkg; 13637 } 13638 } 13639 13640 if (pkg == null) { 13641 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13642 return false; 13643 } 13644 13645 PackageSetting ps = (PackageSetting) pkg.mExtras; 13646 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13647 } 13648 13649 // Always delete data directories for package, even if we found no other 13650 // record of app. This helps users recover from UID mismatches without 13651 // resorting to a full data wipe. 13652 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13653 if (retCode < 0) { 13654 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13655 return false; 13656 } 13657 13658 final int appId = pkg.applicationInfo.uid; 13659 removeKeystoreDataIfNeeded(userId, appId); 13660 13661 // Create a native library symlink only if we have native libraries 13662 // and if the native libraries are 32 bit libraries. We do not provide 13663 // this symlink for 64 bit libraries. 13664 if (pkg.applicationInfo.primaryCpuAbi != null && 13665 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13666 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13667 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13668 nativeLibPath, userId) < 0) { 13669 Slog.w(TAG, "Failed linking native library dir"); 13670 return false; 13671 } 13672 } 13673 13674 return true; 13675 } 13676 13677 /** 13678 * Reverts user permission state changes (permissions and flags) in 13679 * all packages for a given user. 13680 * 13681 * @param userId The device user for which to do a reset. 13682 */ 13683 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 13684 final int packageCount = mPackages.size(); 13685 for (int i = 0; i < packageCount; i++) { 13686 PackageParser.Package pkg = mPackages.valueAt(i); 13687 PackageSetting ps = (PackageSetting) pkg.mExtras; 13688 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 13689 } 13690 } 13691 13692 /** 13693 * Reverts user permission state changes (permissions and flags). 13694 * 13695 * @param ps The package for which to reset. 13696 * @param userId The device user for which to do a reset. 13697 */ 13698 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 13699 final PackageSetting ps, final int userId) { 13700 if (ps.pkg == null) { 13701 return; 13702 } 13703 13704 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13705 | FLAG_PERMISSION_USER_FIXED 13706 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13707 13708 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13709 | FLAG_PERMISSION_POLICY_FIXED; 13710 13711 boolean writeInstallPermissions = false; 13712 boolean writeRuntimePermissions = false; 13713 13714 final int permissionCount = ps.pkg.requestedPermissions.size(); 13715 for (int i = 0; i < permissionCount; i++) { 13716 String permission = ps.pkg.requestedPermissions.get(i); 13717 13718 BasePermission bp = mSettings.mPermissions.get(permission); 13719 if (bp == null) { 13720 continue; 13721 } 13722 13723 // If shared user we just reset the state to which only this app contributed. 13724 if (ps.sharedUser != null) { 13725 boolean used = false; 13726 final int packageCount = ps.sharedUser.packages.size(); 13727 for (int j = 0; j < packageCount; j++) { 13728 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13729 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13730 && pkg.pkg.requestedPermissions.contains(permission)) { 13731 used = true; 13732 break; 13733 } 13734 } 13735 if (used) { 13736 continue; 13737 } 13738 } 13739 13740 PermissionsState permissionsState = ps.getPermissionsState(); 13741 13742 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13743 13744 // Always clear the user settable flags. 13745 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13746 bp.name) != null; 13747 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13748 if (hasInstallState) { 13749 writeInstallPermissions = true; 13750 } else { 13751 writeRuntimePermissions = true; 13752 } 13753 } 13754 13755 // Below is only runtime permission handling. 13756 if (!bp.isRuntime()) { 13757 continue; 13758 } 13759 13760 // Never clobber system or policy. 13761 if ((oldFlags & policyOrSystemFlags) != 0) { 13762 continue; 13763 } 13764 13765 // If this permission was granted by default, make sure it is. 13766 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13767 if (permissionsState.grantRuntimePermission(bp, userId) 13768 != PERMISSION_OPERATION_FAILURE) { 13769 writeRuntimePermissions = true; 13770 } 13771 } else { 13772 // Otherwise, reset the permission. 13773 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13774 switch (revokeResult) { 13775 case PERMISSION_OPERATION_SUCCESS: { 13776 writeRuntimePermissions = true; 13777 } break; 13778 13779 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13780 writeRuntimePermissions = true; 13781 final int appId = ps.appId; 13782 mHandler.post(new Runnable() { 13783 @Override 13784 public void run() { 13785 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 13786 } 13787 }); 13788 } break; 13789 } 13790 } 13791 } 13792 13793 // Synchronously write as we are taking permissions away. 13794 if (writeRuntimePermissions) { 13795 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13796 } 13797 13798 // Synchronously write as we are taking permissions away. 13799 if (writeInstallPermissions) { 13800 mSettings.writeLPr(); 13801 } 13802 } 13803 13804 /** 13805 * Remove entries from the keystore daemon. Will only remove it if the 13806 * {@code appId} is valid. 13807 */ 13808 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13809 if (appId < 0) { 13810 return; 13811 } 13812 13813 final KeyStore keyStore = KeyStore.getInstance(); 13814 if (keyStore != null) { 13815 if (userId == UserHandle.USER_ALL) { 13816 for (final int individual : sUserManager.getUserIds()) { 13817 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13818 } 13819 } else { 13820 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13821 } 13822 } else { 13823 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13824 } 13825 } 13826 13827 @Override 13828 public void deleteApplicationCacheFiles(final String packageName, 13829 final IPackageDataObserver observer) { 13830 mContext.enforceCallingOrSelfPermission( 13831 android.Manifest.permission.DELETE_CACHE_FILES, null); 13832 // Queue up an async operation since the package deletion may take a little while. 13833 final int userId = UserHandle.getCallingUserId(); 13834 mHandler.post(new Runnable() { 13835 public void run() { 13836 mHandler.removeCallbacks(this); 13837 final boolean succeded; 13838 synchronized (mInstallLock) { 13839 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13840 } 13841 clearExternalStorageDataSync(packageName, userId, false); 13842 if (observer != null) { 13843 try { 13844 observer.onRemoveCompleted(packageName, succeded); 13845 } catch (RemoteException e) { 13846 Log.i(TAG, "Observer no longer exists."); 13847 } 13848 } //end if observer 13849 } //end run 13850 }); 13851 } 13852 13853 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13854 if (packageName == null) { 13855 Slog.w(TAG, "Attempt to delete null packageName."); 13856 return false; 13857 } 13858 PackageParser.Package p; 13859 synchronized (mPackages) { 13860 p = mPackages.get(packageName); 13861 } 13862 if (p == null) { 13863 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13864 return false; 13865 } 13866 final ApplicationInfo applicationInfo = p.applicationInfo; 13867 if (applicationInfo == null) { 13868 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13869 return false; 13870 } 13871 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13872 if (retCode < 0) { 13873 Slog.w(TAG, "Couldn't remove cache files for package: " 13874 + packageName + " u" + userId); 13875 return false; 13876 } 13877 return true; 13878 } 13879 13880 @Override 13881 public void getPackageSizeInfo(final String packageName, int userHandle, 13882 final IPackageStatsObserver observer) { 13883 mContext.enforceCallingOrSelfPermission( 13884 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13885 if (packageName == null) { 13886 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13887 } 13888 13889 PackageStats stats = new PackageStats(packageName, userHandle); 13890 13891 /* 13892 * Queue up an async operation since the package measurement may take a 13893 * little while. 13894 */ 13895 Message msg = mHandler.obtainMessage(INIT_COPY); 13896 msg.obj = new MeasureParams(stats, observer); 13897 mHandler.sendMessage(msg); 13898 } 13899 13900 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13901 PackageStats pStats) { 13902 if (packageName == null) { 13903 Slog.w(TAG, "Attempt to get size of null packageName."); 13904 return false; 13905 } 13906 PackageParser.Package p; 13907 boolean dataOnly = false; 13908 String libDirRoot = null; 13909 String asecPath = null; 13910 PackageSetting ps = null; 13911 synchronized (mPackages) { 13912 p = mPackages.get(packageName); 13913 ps = mSettings.mPackages.get(packageName); 13914 if(p == null) { 13915 dataOnly = true; 13916 if((ps == null) || (ps.pkg == null)) { 13917 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13918 return false; 13919 } 13920 p = ps.pkg; 13921 } 13922 if (ps != null) { 13923 libDirRoot = ps.legacyNativeLibraryPathString; 13924 } 13925 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 13926 final long token = Binder.clearCallingIdentity(); 13927 try { 13928 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13929 if (secureContainerId != null) { 13930 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13931 } 13932 } finally { 13933 Binder.restoreCallingIdentity(token); 13934 } 13935 } 13936 } 13937 String publicSrcDir = null; 13938 if(!dataOnly) { 13939 final ApplicationInfo applicationInfo = p.applicationInfo; 13940 if (applicationInfo == null) { 13941 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13942 return false; 13943 } 13944 if (p.isForwardLocked()) { 13945 publicSrcDir = applicationInfo.getBaseResourcePath(); 13946 } 13947 } 13948 // TODO: extend to measure size of split APKs 13949 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13950 // not just the first level. 13951 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13952 // just the primary. 13953 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13954 13955 String apkPath; 13956 File packageDir = new File(p.codePath); 13957 13958 if (packageDir.isDirectory() && p.canHaveOatDir()) { 13959 apkPath = packageDir.getAbsolutePath(); 13960 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 13961 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 13962 libDirRoot = null; 13963 } 13964 } else { 13965 apkPath = p.baseCodePath; 13966 } 13967 13968 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 13969 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13970 if (res < 0) { 13971 return false; 13972 } 13973 13974 // Fix-up for forward-locked applications in ASEC containers. 13975 if (!isExternal(p)) { 13976 pStats.codeSize += pStats.externalCodeSize; 13977 pStats.externalCodeSize = 0L; 13978 } 13979 13980 return true; 13981 } 13982 13983 13984 @Override 13985 public void addPackageToPreferred(String packageName) { 13986 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13987 } 13988 13989 @Override 13990 public void removePackageFromPreferred(String packageName) { 13991 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13992 } 13993 13994 @Override 13995 public List<PackageInfo> getPreferredPackages(int flags) { 13996 return new ArrayList<PackageInfo>(); 13997 } 13998 13999 private int getUidTargetSdkVersionLockedLPr(int uid) { 14000 Object obj = mSettings.getUserIdLPr(uid); 14001 if (obj instanceof SharedUserSetting) { 14002 final SharedUserSetting sus = (SharedUserSetting) obj; 14003 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14004 final Iterator<PackageSetting> it = sus.packages.iterator(); 14005 while (it.hasNext()) { 14006 final PackageSetting ps = it.next(); 14007 if (ps.pkg != null) { 14008 int v = ps.pkg.applicationInfo.targetSdkVersion; 14009 if (v < vers) vers = v; 14010 } 14011 } 14012 return vers; 14013 } else if (obj instanceof PackageSetting) { 14014 final PackageSetting ps = (PackageSetting) obj; 14015 if (ps.pkg != null) { 14016 return ps.pkg.applicationInfo.targetSdkVersion; 14017 } 14018 } 14019 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14020 } 14021 14022 @Override 14023 public void addPreferredActivity(IntentFilter filter, int match, 14024 ComponentName[] set, ComponentName activity, int userId) { 14025 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14026 "Adding preferred"); 14027 } 14028 14029 private void addPreferredActivityInternal(IntentFilter filter, int match, 14030 ComponentName[] set, ComponentName activity, boolean always, int userId, 14031 String opname) { 14032 // writer 14033 int callingUid = Binder.getCallingUid(); 14034 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14035 if (filter.countActions() == 0) { 14036 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14037 return; 14038 } 14039 synchronized (mPackages) { 14040 if (mContext.checkCallingOrSelfPermission( 14041 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14042 != PackageManager.PERMISSION_GRANTED) { 14043 if (getUidTargetSdkVersionLockedLPr(callingUid) 14044 < Build.VERSION_CODES.FROYO) { 14045 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14046 + callingUid); 14047 return; 14048 } 14049 mContext.enforceCallingOrSelfPermission( 14050 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14051 } 14052 14053 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14054 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14055 + userId + ":"); 14056 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14057 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14058 scheduleWritePackageRestrictionsLocked(userId); 14059 } 14060 } 14061 14062 @Override 14063 public void replacePreferredActivity(IntentFilter filter, int match, 14064 ComponentName[] set, ComponentName activity, int userId) { 14065 if (filter.countActions() != 1) { 14066 throw new IllegalArgumentException( 14067 "replacePreferredActivity expects filter to have only 1 action."); 14068 } 14069 if (filter.countDataAuthorities() != 0 14070 || filter.countDataPaths() != 0 14071 || filter.countDataSchemes() > 1 14072 || filter.countDataTypes() != 0) { 14073 throw new IllegalArgumentException( 14074 "replacePreferredActivity expects filter to have no data authorities, " + 14075 "paths, or types; and at most one scheme."); 14076 } 14077 14078 final int callingUid = Binder.getCallingUid(); 14079 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14080 synchronized (mPackages) { 14081 if (mContext.checkCallingOrSelfPermission( 14082 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14083 != PackageManager.PERMISSION_GRANTED) { 14084 if (getUidTargetSdkVersionLockedLPr(callingUid) 14085 < Build.VERSION_CODES.FROYO) { 14086 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14087 + Binder.getCallingUid()); 14088 return; 14089 } 14090 mContext.enforceCallingOrSelfPermission( 14091 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14092 } 14093 14094 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14095 if (pir != null) { 14096 // Get all of the existing entries that exactly match this filter. 14097 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14098 if (existing != null && existing.size() == 1) { 14099 PreferredActivity cur = existing.get(0); 14100 if (DEBUG_PREFERRED) { 14101 Slog.i(TAG, "Checking replace of preferred:"); 14102 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14103 if (!cur.mPref.mAlways) { 14104 Slog.i(TAG, " -- CUR; not mAlways!"); 14105 } else { 14106 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14107 Slog.i(TAG, " -- CUR: mSet=" 14108 + Arrays.toString(cur.mPref.mSetComponents)); 14109 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14110 Slog.i(TAG, " -- NEW: mMatch=" 14111 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14112 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14113 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14114 } 14115 } 14116 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14117 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14118 && cur.mPref.sameSet(set)) { 14119 // Setting the preferred activity to what it happens to be already 14120 if (DEBUG_PREFERRED) { 14121 Slog.i(TAG, "Replacing with same preferred activity " 14122 + cur.mPref.mShortComponent + " for user " 14123 + userId + ":"); 14124 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14125 } 14126 return; 14127 } 14128 } 14129 14130 if (existing != null) { 14131 if (DEBUG_PREFERRED) { 14132 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14133 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14134 } 14135 for (int i = 0; i < existing.size(); i++) { 14136 PreferredActivity pa = existing.get(i); 14137 if (DEBUG_PREFERRED) { 14138 Slog.i(TAG, "Removing existing preferred activity " 14139 + pa.mPref.mComponent + ":"); 14140 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14141 } 14142 pir.removeFilter(pa); 14143 } 14144 } 14145 } 14146 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14147 "Replacing preferred"); 14148 } 14149 } 14150 14151 @Override 14152 public void clearPackagePreferredActivities(String packageName) { 14153 final int uid = Binder.getCallingUid(); 14154 // writer 14155 synchronized (mPackages) { 14156 PackageParser.Package pkg = mPackages.get(packageName); 14157 if (pkg == null || pkg.applicationInfo.uid != uid) { 14158 if (mContext.checkCallingOrSelfPermission( 14159 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14160 != PackageManager.PERMISSION_GRANTED) { 14161 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14162 < Build.VERSION_CODES.FROYO) { 14163 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14164 + Binder.getCallingUid()); 14165 return; 14166 } 14167 mContext.enforceCallingOrSelfPermission( 14168 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14169 } 14170 } 14171 14172 int user = UserHandle.getCallingUserId(); 14173 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14174 scheduleWritePackageRestrictionsLocked(user); 14175 } 14176 } 14177 } 14178 14179 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14180 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14181 ArrayList<PreferredActivity> removed = null; 14182 boolean changed = false; 14183 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14184 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14185 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14186 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14187 continue; 14188 } 14189 Iterator<PreferredActivity> it = pir.filterIterator(); 14190 while (it.hasNext()) { 14191 PreferredActivity pa = it.next(); 14192 // Mark entry for removal only if it matches the package name 14193 // and the entry is of type "always". 14194 if (packageName == null || 14195 (pa.mPref.mComponent.getPackageName().equals(packageName) 14196 && pa.mPref.mAlways)) { 14197 if (removed == null) { 14198 removed = new ArrayList<PreferredActivity>(); 14199 } 14200 removed.add(pa); 14201 } 14202 } 14203 if (removed != null) { 14204 for (int j=0; j<removed.size(); j++) { 14205 PreferredActivity pa = removed.get(j); 14206 pir.removeFilter(pa); 14207 } 14208 changed = true; 14209 } 14210 } 14211 return changed; 14212 } 14213 14214 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14215 private void clearIntentFilterVerificationsLPw(int userId) { 14216 final int packageCount = mPackages.size(); 14217 for (int i = 0; i < packageCount; i++) { 14218 PackageParser.Package pkg = mPackages.valueAt(i); 14219 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14220 } 14221 } 14222 14223 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14224 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14225 if (userId == UserHandle.USER_ALL) { 14226 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14227 sUserManager.getUserIds())) { 14228 for (int oneUserId : sUserManager.getUserIds()) { 14229 scheduleWritePackageRestrictionsLocked(oneUserId); 14230 } 14231 } 14232 } else { 14233 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14234 scheduleWritePackageRestrictionsLocked(userId); 14235 } 14236 } 14237 } 14238 14239 void clearDefaultBrowserIfNeeded(String packageName) { 14240 for (int oneUserId : sUserManager.getUserIds()) { 14241 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14242 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14243 if (packageName.equals(defaultBrowserPackageName)) { 14244 setDefaultBrowserPackageName(null, oneUserId); 14245 } 14246 } 14247 } 14248 14249 @Override 14250 public void resetApplicationPreferences(int userId) { 14251 mContext.enforceCallingOrSelfPermission( 14252 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14253 // writer 14254 synchronized (mPackages) { 14255 final long identity = Binder.clearCallingIdentity(); 14256 try { 14257 clearPackagePreferredActivitiesLPw(null, userId); 14258 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14259 // TODO: We have to reset the default SMS and Phone. This requires 14260 // significant refactoring to keep all default apps in the package 14261 // manager (cleaner but more work) or have the services provide 14262 // callbacks to the package manager to request a default app reset. 14263 applyFactoryDefaultBrowserLPw(userId); 14264 clearIntentFilterVerificationsLPw(userId); 14265 primeDomainVerificationsLPw(userId); 14266 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14267 scheduleWritePackageRestrictionsLocked(userId); 14268 } finally { 14269 Binder.restoreCallingIdentity(identity); 14270 } 14271 } 14272 } 14273 14274 @Override 14275 public int getPreferredActivities(List<IntentFilter> outFilters, 14276 List<ComponentName> outActivities, String packageName) { 14277 14278 int num = 0; 14279 final int userId = UserHandle.getCallingUserId(); 14280 // reader 14281 synchronized (mPackages) { 14282 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14283 if (pir != null) { 14284 final Iterator<PreferredActivity> it = pir.filterIterator(); 14285 while (it.hasNext()) { 14286 final PreferredActivity pa = it.next(); 14287 if (packageName == null 14288 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14289 && pa.mPref.mAlways)) { 14290 if (outFilters != null) { 14291 outFilters.add(new IntentFilter(pa)); 14292 } 14293 if (outActivities != null) { 14294 outActivities.add(pa.mPref.mComponent); 14295 } 14296 } 14297 } 14298 } 14299 } 14300 14301 return num; 14302 } 14303 14304 @Override 14305 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14306 int userId) { 14307 int callingUid = Binder.getCallingUid(); 14308 if (callingUid != Process.SYSTEM_UID) { 14309 throw new SecurityException( 14310 "addPersistentPreferredActivity can only be run by the system"); 14311 } 14312 if (filter.countActions() == 0) { 14313 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14314 return; 14315 } 14316 synchronized (mPackages) { 14317 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14318 " :"); 14319 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14320 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14321 new PersistentPreferredActivity(filter, activity)); 14322 scheduleWritePackageRestrictionsLocked(userId); 14323 } 14324 } 14325 14326 @Override 14327 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14328 int callingUid = Binder.getCallingUid(); 14329 if (callingUid != Process.SYSTEM_UID) { 14330 throw new SecurityException( 14331 "clearPackagePersistentPreferredActivities can only be run by the system"); 14332 } 14333 ArrayList<PersistentPreferredActivity> removed = null; 14334 boolean changed = false; 14335 synchronized (mPackages) { 14336 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14337 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14338 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14339 .valueAt(i); 14340 if (userId != thisUserId) { 14341 continue; 14342 } 14343 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14344 while (it.hasNext()) { 14345 PersistentPreferredActivity ppa = it.next(); 14346 // Mark entry for removal only if it matches the package name. 14347 if (ppa.mComponent.getPackageName().equals(packageName)) { 14348 if (removed == null) { 14349 removed = new ArrayList<PersistentPreferredActivity>(); 14350 } 14351 removed.add(ppa); 14352 } 14353 } 14354 if (removed != null) { 14355 for (int j=0; j<removed.size(); j++) { 14356 PersistentPreferredActivity ppa = removed.get(j); 14357 ppir.removeFilter(ppa); 14358 } 14359 changed = true; 14360 } 14361 } 14362 14363 if (changed) { 14364 scheduleWritePackageRestrictionsLocked(userId); 14365 } 14366 } 14367 } 14368 14369 /** 14370 * Common machinery for picking apart a restored XML blob and passing 14371 * it to a caller-supplied functor to be applied to the running system. 14372 */ 14373 private void restoreFromXml(XmlPullParser parser, int userId, 14374 String expectedStartTag, BlobXmlRestorer functor) 14375 throws IOException, XmlPullParserException { 14376 int type; 14377 while ((type = parser.next()) != XmlPullParser.START_TAG 14378 && type != XmlPullParser.END_DOCUMENT) { 14379 } 14380 if (type != XmlPullParser.START_TAG) { 14381 // oops didn't find a start tag?! 14382 if (DEBUG_BACKUP) { 14383 Slog.e(TAG, "Didn't find start tag during restore"); 14384 } 14385 return; 14386 } 14387 14388 // this is supposed to be TAG_PREFERRED_BACKUP 14389 if (!expectedStartTag.equals(parser.getName())) { 14390 if (DEBUG_BACKUP) { 14391 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14392 } 14393 return; 14394 } 14395 14396 // skip interfering stuff, then we're aligned with the backing implementation 14397 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14398 functor.apply(parser, userId); 14399 } 14400 14401 private interface BlobXmlRestorer { 14402 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14403 } 14404 14405 /** 14406 * Non-Binder method, support for the backup/restore mechanism: write the 14407 * full set of preferred activities in its canonical XML format. Returns the 14408 * XML output as a byte array, or null if there is none. 14409 */ 14410 @Override 14411 public byte[] getPreferredActivityBackup(int userId) { 14412 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14413 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14414 } 14415 14416 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14417 try { 14418 final XmlSerializer serializer = new FastXmlSerializer(); 14419 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14420 serializer.startDocument(null, true); 14421 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14422 14423 synchronized (mPackages) { 14424 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14425 } 14426 14427 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14428 serializer.endDocument(); 14429 serializer.flush(); 14430 } catch (Exception e) { 14431 if (DEBUG_BACKUP) { 14432 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14433 } 14434 return null; 14435 } 14436 14437 return dataStream.toByteArray(); 14438 } 14439 14440 @Override 14441 public void restorePreferredActivities(byte[] backup, int userId) { 14442 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14443 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14444 } 14445 14446 try { 14447 final XmlPullParser parser = Xml.newPullParser(); 14448 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14449 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14450 new BlobXmlRestorer() { 14451 @Override 14452 public void apply(XmlPullParser parser, int userId) 14453 throws XmlPullParserException, IOException { 14454 synchronized (mPackages) { 14455 mSettings.readPreferredActivitiesLPw(parser, userId); 14456 } 14457 } 14458 } ); 14459 } catch (Exception e) { 14460 if (DEBUG_BACKUP) { 14461 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14462 } 14463 } 14464 } 14465 14466 /** 14467 * Non-Binder method, support for the backup/restore mechanism: write the 14468 * default browser (etc) settings in its canonical XML format. Returns the default 14469 * browser XML representation as a byte array, or null if there is none. 14470 */ 14471 @Override 14472 public byte[] getDefaultAppsBackup(int userId) { 14473 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14474 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14475 } 14476 14477 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14478 try { 14479 final XmlSerializer serializer = new FastXmlSerializer(); 14480 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14481 serializer.startDocument(null, true); 14482 serializer.startTag(null, TAG_DEFAULT_APPS); 14483 14484 synchronized (mPackages) { 14485 mSettings.writeDefaultAppsLPr(serializer, userId); 14486 } 14487 14488 serializer.endTag(null, TAG_DEFAULT_APPS); 14489 serializer.endDocument(); 14490 serializer.flush(); 14491 } catch (Exception e) { 14492 if (DEBUG_BACKUP) { 14493 Slog.e(TAG, "Unable to write default apps for backup", e); 14494 } 14495 return null; 14496 } 14497 14498 return dataStream.toByteArray(); 14499 } 14500 14501 @Override 14502 public void restoreDefaultApps(byte[] backup, int userId) { 14503 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14504 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14505 } 14506 14507 try { 14508 final XmlPullParser parser = Xml.newPullParser(); 14509 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14510 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14511 new BlobXmlRestorer() { 14512 @Override 14513 public void apply(XmlPullParser parser, int userId) 14514 throws XmlPullParserException, IOException { 14515 synchronized (mPackages) { 14516 mSettings.readDefaultAppsLPw(parser, userId); 14517 } 14518 } 14519 } ); 14520 } catch (Exception e) { 14521 if (DEBUG_BACKUP) { 14522 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14523 } 14524 } 14525 } 14526 14527 @Override 14528 public byte[] getIntentFilterVerificationBackup(int userId) { 14529 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14530 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14531 } 14532 14533 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14534 try { 14535 final XmlSerializer serializer = new FastXmlSerializer(); 14536 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14537 serializer.startDocument(null, true); 14538 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14539 14540 synchronized (mPackages) { 14541 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14542 } 14543 14544 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14545 serializer.endDocument(); 14546 serializer.flush(); 14547 } catch (Exception e) { 14548 if (DEBUG_BACKUP) { 14549 Slog.e(TAG, "Unable to write default apps for backup", e); 14550 } 14551 return null; 14552 } 14553 14554 return dataStream.toByteArray(); 14555 } 14556 14557 @Override 14558 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14559 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14560 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14561 } 14562 14563 try { 14564 final XmlPullParser parser = Xml.newPullParser(); 14565 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14566 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14567 new BlobXmlRestorer() { 14568 @Override 14569 public void apply(XmlPullParser parser, int userId) 14570 throws XmlPullParserException, IOException { 14571 synchronized (mPackages) { 14572 mSettings.readAllDomainVerificationsLPr(parser, userId); 14573 mSettings.writeLPr(); 14574 } 14575 } 14576 } ); 14577 } catch (Exception e) { 14578 if (DEBUG_BACKUP) { 14579 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14580 } 14581 } 14582 } 14583 14584 @Override 14585 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14586 int sourceUserId, int targetUserId, int flags) { 14587 mContext.enforceCallingOrSelfPermission( 14588 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14589 int callingUid = Binder.getCallingUid(); 14590 enforceOwnerRights(ownerPackage, callingUid); 14591 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14592 if (intentFilter.countActions() == 0) { 14593 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14594 return; 14595 } 14596 synchronized (mPackages) { 14597 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14598 ownerPackage, targetUserId, flags); 14599 CrossProfileIntentResolver resolver = 14600 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14601 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14602 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14603 if (existing != null) { 14604 int size = existing.size(); 14605 for (int i = 0; i < size; i++) { 14606 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14607 return; 14608 } 14609 } 14610 } 14611 resolver.addFilter(newFilter); 14612 scheduleWritePackageRestrictionsLocked(sourceUserId); 14613 } 14614 } 14615 14616 @Override 14617 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14618 mContext.enforceCallingOrSelfPermission( 14619 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14620 int callingUid = Binder.getCallingUid(); 14621 enforceOwnerRights(ownerPackage, callingUid); 14622 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14623 synchronized (mPackages) { 14624 CrossProfileIntentResolver resolver = 14625 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14626 ArraySet<CrossProfileIntentFilter> set = 14627 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14628 for (CrossProfileIntentFilter filter : set) { 14629 if (filter.getOwnerPackage().equals(ownerPackage)) { 14630 resolver.removeFilter(filter); 14631 } 14632 } 14633 scheduleWritePackageRestrictionsLocked(sourceUserId); 14634 } 14635 } 14636 14637 // Enforcing that callingUid is owning pkg on userId 14638 private void enforceOwnerRights(String pkg, int callingUid) { 14639 // The system owns everything. 14640 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14641 return; 14642 } 14643 int callingUserId = UserHandle.getUserId(callingUid); 14644 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14645 if (pi == null) { 14646 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14647 + callingUserId); 14648 } 14649 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14650 throw new SecurityException("Calling uid " + callingUid 14651 + " does not own package " + pkg); 14652 } 14653 } 14654 14655 @Override 14656 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14657 Intent intent = new Intent(Intent.ACTION_MAIN); 14658 intent.addCategory(Intent.CATEGORY_HOME); 14659 14660 final int callingUserId = UserHandle.getCallingUserId(); 14661 List<ResolveInfo> list = queryIntentActivities(intent, null, 14662 PackageManager.GET_META_DATA, callingUserId); 14663 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14664 true, false, false, callingUserId); 14665 14666 allHomeCandidates.clear(); 14667 if (list != null) { 14668 for (ResolveInfo ri : list) { 14669 allHomeCandidates.add(ri); 14670 } 14671 } 14672 return (preferred == null || preferred.activityInfo == null) 14673 ? null 14674 : new ComponentName(preferred.activityInfo.packageName, 14675 preferred.activityInfo.name); 14676 } 14677 14678 @Override 14679 public void setApplicationEnabledSetting(String appPackageName, 14680 int newState, int flags, int userId, String callingPackage) { 14681 if (!sUserManager.exists(userId)) return; 14682 if (callingPackage == null) { 14683 callingPackage = Integer.toString(Binder.getCallingUid()); 14684 } 14685 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14686 } 14687 14688 @Override 14689 public void setComponentEnabledSetting(ComponentName componentName, 14690 int newState, int flags, int userId) { 14691 if (!sUserManager.exists(userId)) return; 14692 setEnabledSetting(componentName.getPackageName(), 14693 componentName.getClassName(), newState, flags, userId, null); 14694 } 14695 14696 private void setEnabledSetting(final String packageName, String className, int newState, 14697 final int flags, int userId, String callingPackage) { 14698 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14699 || newState == COMPONENT_ENABLED_STATE_ENABLED 14700 || newState == COMPONENT_ENABLED_STATE_DISABLED 14701 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14702 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14703 throw new IllegalArgumentException("Invalid new component state: " 14704 + newState); 14705 } 14706 PackageSetting pkgSetting; 14707 final int uid = Binder.getCallingUid(); 14708 final int permission = mContext.checkCallingOrSelfPermission( 14709 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14710 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14711 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14712 boolean sendNow = false; 14713 boolean isApp = (className == null); 14714 String componentName = isApp ? packageName : className; 14715 int packageUid = -1; 14716 ArrayList<String> components; 14717 14718 // writer 14719 synchronized (mPackages) { 14720 pkgSetting = mSettings.mPackages.get(packageName); 14721 if (pkgSetting == null) { 14722 if (className == null) { 14723 throw new IllegalArgumentException( 14724 "Unknown package: " + packageName); 14725 } 14726 throw new IllegalArgumentException( 14727 "Unknown component: " + packageName 14728 + "/" + className); 14729 } 14730 // Allow root and verify that userId is not being specified by a different user 14731 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14732 throw new SecurityException( 14733 "Permission Denial: attempt to change component state from pid=" 14734 + Binder.getCallingPid() 14735 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14736 } 14737 if (className == null) { 14738 // We're dealing with an application/package level state change 14739 if (pkgSetting.getEnabled(userId) == newState) { 14740 // Nothing to do 14741 return; 14742 } 14743 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14744 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14745 // Don't care about who enables an app. 14746 callingPackage = null; 14747 } 14748 pkgSetting.setEnabled(newState, userId, callingPackage); 14749 // pkgSetting.pkg.mSetEnabled = newState; 14750 } else { 14751 // We're dealing with a component level state change 14752 // First, verify that this is a valid class name. 14753 PackageParser.Package pkg = pkgSetting.pkg; 14754 if (pkg == null || !pkg.hasComponentClassName(className)) { 14755 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14756 throw new IllegalArgumentException("Component class " + className 14757 + " does not exist in " + packageName); 14758 } else { 14759 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14760 + className + " does not exist in " + packageName); 14761 } 14762 } 14763 switch (newState) { 14764 case COMPONENT_ENABLED_STATE_ENABLED: 14765 if (!pkgSetting.enableComponentLPw(className, userId)) { 14766 return; 14767 } 14768 break; 14769 case COMPONENT_ENABLED_STATE_DISABLED: 14770 if (!pkgSetting.disableComponentLPw(className, userId)) { 14771 return; 14772 } 14773 break; 14774 case COMPONENT_ENABLED_STATE_DEFAULT: 14775 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14776 return; 14777 } 14778 break; 14779 default: 14780 Slog.e(TAG, "Invalid new component state: " + newState); 14781 return; 14782 } 14783 } 14784 scheduleWritePackageRestrictionsLocked(userId); 14785 components = mPendingBroadcasts.get(userId, packageName); 14786 final boolean newPackage = components == null; 14787 if (newPackage) { 14788 components = new ArrayList<String>(); 14789 } 14790 if (!components.contains(componentName)) { 14791 components.add(componentName); 14792 } 14793 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14794 sendNow = true; 14795 // Purge entry from pending broadcast list if another one exists already 14796 // since we are sending one right away. 14797 mPendingBroadcasts.remove(userId, packageName); 14798 } else { 14799 if (newPackage) { 14800 mPendingBroadcasts.put(userId, packageName, components); 14801 } 14802 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14803 // Schedule a message 14804 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14805 } 14806 } 14807 } 14808 14809 long callingId = Binder.clearCallingIdentity(); 14810 try { 14811 if (sendNow) { 14812 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14813 sendPackageChangedBroadcast(packageName, 14814 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14815 } 14816 } finally { 14817 Binder.restoreCallingIdentity(callingId); 14818 } 14819 } 14820 14821 private void sendPackageChangedBroadcast(String packageName, 14822 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14823 if (DEBUG_INSTALL) 14824 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14825 + componentNames); 14826 Bundle extras = new Bundle(4); 14827 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14828 String nameList[] = new String[componentNames.size()]; 14829 componentNames.toArray(nameList); 14830 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14831 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14832 extras.putInt(Intent.EXTRA_UID, packageUid); 14833 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14834 new int[] {UserHandle.getUserId(packageUid)}); 14835 } 14836 14837 @Override 14838 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14839 if (!sUserManager.exists(userId)) return; 14840 final int uid = Binder.getCallingUid(); 14841 final int permission = mContext.checkCallingOrSelfPermission( 14842 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14843 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14844 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14845 // writer 14846 synchronized (mPackages) { 14847 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14848 allowedByPermission, uid, userId)) { 14849 scheduleWritePackageRestrictionsLocked(userId); 14850 } 14851 } 14852 } 14853 14854 @Override 14855 public String getInstallerPackageName(String packageName) { 14856 // reader 14857 synchronized (mPackages) { 14858 return mSettings.getInstallerPackageNameLPr(packageName); 14859 } 14860 } 14861 14862 @Override 14863 public int getApplicationEnabledSetting(String packageName, int userId) { 14864 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14865 int uid = Binder.getCallingUid(); 14866 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14867 // reader 14868 synchronized (mPackages) { 14869 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14870 } 14871 } 14872 14873 @Override 14874 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14875 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14876 int uid = Binder.getCallingUid(); 14877 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14878 // reader 14879 synchronized (mPackages) { 14880 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14881 } 14882 } 14883 14884 @Override 14885 public void enterSafeMode() { 14886 enforceSystemOrRoot("Only the system can request entering safe mode"); 14887 14888 if (!mSystemReady) { 14889 mSafeMode = true; 14890 } 14891 } 14892 14893 @Override 14894 public void systemReady() { 14895 mSystemReady = true; 14896 14897 // Read the compatibilty setting when the system is ready. 14898 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14899 mContext.getContentResolver(), 14900 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14901 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14902 if (DEBUG_SETTINGS) { 14903 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14904 } 14905 14906 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14907 14908 synchronized (mPackages) { 14909 // Verify that all of the preferred activity components actually 14910 // exist. It is possible for applications to be updated and at 14911 // that point remove a previously declared activity component that 14912 // had been set as a preferred activity. We try to clean this up 14913 // the next time we encounter that preferred activity, but it is 14914 // possible for the user flow to never be able to return to that 14915 // situation so here we do a sanity check to make sure we haven't 14916 // left any junk around. 14917 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14918 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14919 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14920 removed.clear(); 14921 for (PreferredActivity pa : pir.filterSet()) { 14922 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14923 removed.add(pa); 14924 } 14925 } 14926 if (removed.size() > 0) { 14927 for (int r=0; r<removed.size(); r++) { 14928 PreferredActivity pa = removed.get(r); 14929 Slog.w(TAG, "Removing dangling preferred activity: " 14930 + pa.mPref.mComponent); 14931 pir.removeFilter(pa); 14932 } 14933 mSettings.writePackageRestrictionsLPr( 14934 mSettings.mPreferredActivities.keyAt(i)); 14935 } 14936 } 14937 14938 for (int userId : UserManagerService.getInstance().getUserIds()) { 14939 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14940 grantPermissionsUserIds = ArrayUtils.appendInt( 14941 grantPermissionsUserIds, userId); 14942 } 14943 } 14944 } 14945 sUserManager.systemReady(); 14946 14947 // If we upgraded grant all default permissions before kicking off. 14948 for (int userId : grantPermissionsUserIds) { 14949 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14950 } 14951 14952 // Kick off any messages waiting for system ready 14953 if (mPostSystemReadyMessages != null) { 14954 for (Message msg : mPostSystemReadyMessages) { 14955 msg.sendToTarget(); 14956 } 14957 mPostSystemReadyMessages = null; 14958 } 14959 14960 // Watch for external volumes that come and go over time 14961 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14962 storage.registerListener(mStorageListener); 14963 14964 mInstallerService.systemReady(); 14965 mPackageDexOptimizer.systemReady(); 14966 14967 MountServiceInternal mountServiceInternal = LocalServices.getService( 14968 MountServiceInternal.class); 14969 mountServiceInternal.addExternalStoragePolicy( 14970 new MountServiceInternal.ExternalStorageMountPolicy() { 14971 @Override 14972 public int getMountMode(int uid, String packageName) { 14973 if (Process.isIsolated(uid)) { 14974 return Zygote.MOUNT_EXTERNAL_NONE; 14975 } 14976 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14977 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14978 } 14979 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14980 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14981 } 14982 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14983 return Zygote.MOUNT_EXTERNAL_READ; 14984 } 14985 return Zygote.MOUNT_EXTERNAL_WRITE; 14986 } 14987 14988 @Override 14989 public boolean hasExternalStorage(int uid, String packageName) { 14990 return true; 14991 } 14992 }); 14993 } 14994 14995 @Override 14996 public boolean isSafeMode() { 14997 return mSafeMode; 14998 } 14999 15000 @Override 15001 public boolean hasSystemUidErrors() { 15002 return mHasSystemUidErrors; 15003 } 15004 15005 static String arrayToString(int[] array) { 15006 StringBuffer buf = new StringBuffer(128); 15007 buf.append('['); 15008 if (array != null) { 15009 for (int i=0; i<array.length; i++) { 15010 if (i > 0) buf.append(", "); 15011 buf.append(array[i]); 15012 } 15013 } 15014 buf.append(']'); 15015 return buf.toString(); 15016 } 15017 15018 static class DumpState { 15019 public static final int DUMP_LIBS = 1 << 0; 15020 public static final int DUMP_FEATURES = 1 << 1; 15021 public static final int DUMP_RESOLVERS = 1 << 2; 15022 public static final int DUMP_PERMISSIONS = 1 << 3; 15023 public static final int DUMP_PACKAGES = 1 << 4; 15024 public static final int DUMP_SHARED_USERS = 1 << 5; 15025 public static final int DUMP_MESSAGES = 1 << 6; 15026 public static final int DUMP_PROVIDERS = 1 << 7; 15027 public static final int DUMP_VERIFIERS = 1 << 8; 15028 public static final int DUMP_PREFERRED = 1 << 9; 15029 public static final int DUMP_PREFERRED_XML = 1 << 10; 15030 public static final int DUMP_KEYSETS = 1 << 11; 15031 public static final int DUMP_VERSION = 1 << 12; 15032 public static final int DUMP_INSTALLS = 1 << 13; 15033 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 15034 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 15035 15036 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15037 15038 private int mTypes; 15039 15040 private int mOptions; 15041 15042 private boolean mTitlePrinted; 15043 15044 private SharedUserSetting mSharedUser; 15045 15046 public boolean isDumping(int type) { 15047 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15048 return true; 15049 } 15050 15051 return (mTypes & type) != 0; 15052 } 15053 15054 public void setDump(int type) { 15055 mTypes |= type; 15056 } 15057 15058 public boolean isOptionEnabled(int option) { 15059 return (mOptions & option) != 0; 15060 } 15061 15062 public void setOptionEnabled(int option) { 15063 mOptions |= option; 15064 } 15065 15066 public boolean onTitlePrinted() { 15067 final boolean printed = mTitlePrinted; 15068 mTitlePrinted = true; 15069 return printed; 15070 } 15071 15072 public boolean getTitlePrinted() { 15073 return mTitlePrinted; 15074 } 15075 15076 public void setTitlePrinted(boolean enabled) { 15077 mTitlePrinted = enabled; 15078 } 15079 15080 public SharedUserSetting getSharedUser() { 15081 return mSharedUser; 15082 } 15083 15084 public void setSharedUser(SharedUserSetting user) { 15085 mSharedUser = user; 15086 } 15087 } 15088 15089 @Override 15090 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15091 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15092 (new PackageManagerShellCommand(this)).exec( 15093 this, in, out, err, args, resultReceiver); 15094 } 15095 15096 @Override 15097 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15098 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15099 != PackageManager.PERMISSION_GRANTED) { 15100 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15101 + Binder.getCallingPid() 15102 + ", uid=" + Binder.getCallingUid() 15103 + " without permission " 15104 + android.Manifest.permission.DUMP); 15105 return; 15106 } 15107 15108 DumpState dumpState = new DumpState(); 15109 boolean fullPreferred = false; 15110 boolean checkin = false; 15111 15112 String packageName = null; 15113 ArraySet<String> permissionNames = null; 15114 15115 int opti = 0; 15116 while (opti < args.length) { 15117 String opt = args[opti]; 15118 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15119 break; 15120 } 15121 opti++; 15122 15123 if ("-a".equals(opt)) { 15124 // Right now we only know how to print all. 15125 } else if ("-h".equals(opt)) { 15126 pw.println("Package manager dump options:"); 15127 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15128 pw.println(" --checkin: dump for a checkin"); 15129 pw.println(" -f: print details of intent filters"); 15130 pw.println(" -h: print this help"); 15131 pw.println(" cmd may be one of:"); 15132 pw.println(" l[ibraries]: list known shared libraries"); 15133 pw.println(" f[ibraries]: list device features"); 15134 pw.println(" k[eysets]: print known keysets"); 15135 pw.println(" r[esolvers]: dump intent resolvers"); 15136 pw.println(" perm[issions]: dump permissions"); 15137 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15138 pw.println(" pref[erred]: print preferred package settings"); 15139 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15140 pw.println(" prov[iders]: dump content providers"); 15141 pw.println(" p[ackages]: dump installed packages"); 15142 pw.println(" s[hared-users]: dump shared user IDs"); 15143 pw.println(" m[essages]: print collected runtime messages"); 15144 pw.println(" v[erifiers]: print package verifier info"); 15145 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15146 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15147 pw.println(" version: print database version info"); 15148 pw.println(" write: write current settings now"); 15149 pw.println(" installs: details about install sessions"); 15150 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15151 pw.println(" <package.name>: info about given package"); 15152 return; 15153 } else if ("--checkin".equals(opt)) { 15154 checkin = true; 15155 } else if ("-f".equals(opt)) { 15156 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15157 } else { 15158 pw.println("Unknown argument: " + opt + "; use -h for help"); 15159 } 15160 } 15161 15162 // Is the caller requesting to dump a particular piece of data? 15163 if (opti < args.length) { 15164 String cmd = args[opti]; 15165 opti++; 15166 // Is this a package name? 15167 if ("android".equals(cmd) || cmd.contains(".")) { 15168 packageName = cmd; 15169 // When dumping a single package, we always dump all of its 15170 // filter information since the amount of data will be reasonable. 15171 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15172 } else if ("check-permission".equals(cmd)) { 15173 if (opti >= args.length) { 15174 pw.println("Error: check-permission missing permission argument"); 15175 return; 15176 } 15177 String perm = args[opti]; 15178 opti++; 15179 if (opti >= args.length) { 15180 pw.println("Error: check-permission missing package argument"); 15181 return; 15182 } 15183 String pkg = args[opti]; 15184 opti++; 15185 int user = UserHandle.getUserId(Binder.getCallingUid()); 15186 if (opti < args.length) { 15187 try { 15188 user = Integer.parseInt(args[opti]); 15189 } catch (NumberFormatException e) { 15190 pw.println("Error: check-permission user argument is not a number: " 15191 + args[opti]); 15192 return; 15193 } 15194 } 15195 pw.println(checkPermission(perm, pkg, user)); 15196 return; 15197 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15198 dumpState.setDump(DumpState.DUMP_LIBS); 15199 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15200 dumpState.setDump(DumpState.DUMP_FEATURES); 15201 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15202 dumpState.setDump(DumpState.DUMP_RESOLVERS); 15203 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15204 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15205 } else if ("permission".equals(cmd)) { 15206 if (opti >= args.length) { 15207 pw.println("Error: permission requires permission name"); 15208 return; 15209 } 15210 permissionNames = new ArraySet<>(); 15211 while (opti < args.length) { 15212 permissionNames.add(args[opti]); 15213 opti++; 15214 } 15215 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15216 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15217 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15218 dumpState.setDump(DumpState.DUMP_PREFERRED); 15219 } else if ("preferred-xml".equals(cmd)) { 15220 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15221 if (opti < args.length && "--full".equals(args[opti])) { 15222 fullPreferred = true; 15223 opti++; 15224 } 15225 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15226 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15227 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15228 dumpState.setDump(DumpState.DUMP_PACKAGES); 15229 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15230 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15231 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15232 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15233 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15234 dumpState.setDump(DumpState.DUMP_MESSAGES); 15235 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15236 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15237 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15238 || "intent-filter-verifiers".equals(cmd)) { 15239 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15240 } else if ("version".equals(cmd)) { 15241 dumpState.setDump(DumpState.DUMP_VERSION); 15242 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15243 dumpState.setDump(DumpState.DUMP_KEYSETS); 15244 } else if ("installs".equals(cmd)) { 15245 dumpState.setDump(DumpState.DUMP_INSTALLS); 15246 } else if ("write".equals(cmd)) { 15247 synchronized (mPackages) { 15248 mSettings.writeLPr(); 15249 pw.println("Settings written."); 15250 return; 15251 } 15252 } 15253 } 15254 15255 if (checkin) { 15256 pw.println("vers,1"); 15257 } 15258 15259 // reader 15260 synchronized (mPackages) { 15261 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15262 if (!checkin) { 15263 if (dumpState.onTitlePrinted()) 15264 pw.println(); 15265 pw.println("Database versions:"); 15266 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15267 } 15268 } 15269 15270 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15271 if (!checkin) { 15272 if (dumpState.onTitlePrinted()) 15273 pw.println(); 15274 pw.println("Verifiers:"); 15275 pw.print(" Required: "); 15276 pw.print(mRequiredVerifierPackage); 15277 pw.print(" (uid="); 15278 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15279 pw.println(")"); 15280 } else if (mRequiredVerifierPackage != null) { 15281 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15282 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15283 } 15284 } 15285 15286 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15287 packageName == null) { 15288 if (mIntentFilterVerifierComponent != null) { 15289 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15290 if (!checkin) { 15291 if (dumpState.onTitlePrinted()) 15292 pw.println(); 15293 pw.println("Intent Filter Verifier:"); 15294 pw.print(" Using: "); 15295 pw.print(verifierPackageName); 15296 pw.print(" (uid="); 15297 pw.print(getPackageUid(verifierPackageName, 0)); 15298 pw.println(")"); 15299 } else if (verifierPackageName != null) { 15300 pw.print("ifv,"); pw.print(verifierPackageName); 15301 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15302 } 15303 } else { 15304 pw.println(); 15305 pw.println("No Intent Filter Verifier available!"); 15306 } 15307 } 15308 15309 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15310 boolean printedHeader = false; 15311 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15312 while (it.hasNext()) { 15313 String name = it.next(); 15314 SharedLibraryEntry ent = mSharedLibraries.get(name); 15315 if (!checkin) { 15316 if (!printedHeader) { 15317 if (dumpState.onTitlePrinted()) 15318 pw.println(); 15319 pw.println("Libraries:"); 15320 printedHeader = true; 15321 } 15322 pw.print(" "); 15323 } else { 15324 pw.print("lib,"); 15325 } 15326 pw.print(name); 15327 if (!checkin) { 15328 pw.print(" -> "); 15329 } 15330 if (ent.path != null) { 15331 if (!checkin) { 15332 pw.print("(jar) "); 15333 pw.print(ent.path); 15334 } else { 15335 pw.print(",jar,"); 15336 pw.print(ent.path); 15337 } 15338 } else { 15339 if (!checkin) { 15340 pw.print("(apk) "); 15341 pw.print(ent.apk); 15342 } else { 15343 pw.print(",apk,"); 15344 pw.print(ent.apk); 15345 } 15346 } 15347 pw.println(); 15348 } 15349 } 15350 15351 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15352 if (dumpState.onTitlePrinted()) 15353 pw.println(); 15354 if (!checkin) { 15355 pw.println("Features:"); 15356 } 15357 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15358 while (it.hasNext()) { 15359 String name = it.next(); 15360 if (!checkin) { 15361 pw.print(" "); 15362 } else { 15363 pw.print("feat,"); 15364 } 15365 pw.println(name); 15366 } 15367 } 15368 15369 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 15370 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15371 : "Activity Resolver Table:", " ", packageName, 15372 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15373 dumpState.setTitlePrinted(true); 15374 } 15375 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15376 : "Receiver Resolver Table:", " ", packageName, 15377 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15378 dumpState.setTitlePrinted(true); 15379 } 15380 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15381 : "Service Resolver Table:", " ", packageName, 15382 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15383 dumpState.setTitlePrinted(true); 15384 } 15385 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15386 : "Provider Resolver Table:", " ", packageName, 15387 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15388 dumpState.setTitlePrinted(true); 15389 } 15390 } 15391 15392 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15393 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15394 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15395 int user = mSettings.mPreferredActivities.keyAt(i); 15396 if (pir.dump(pw, 15397 dumpState.getTitlePrinted() 15398 ? "\nPreferred Activities User " + user + ":" 15399 : "Preferred Activities User " + user + ":", " ", 15400 packageName, true, false)) { 15401 dumpState.setTitlePrinted(true); 15402 } 15403 } 15404 } 15405 15406 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15407 pw.flush(); 15408 FileOutputStream fout = new FileOutputStream(fd); 15409 BufferedOutputStream str = new BufferedOutputStream(fout); 15410 XmlSerializer serializer = new FastXmlSerializer(); 15411 try { 15412 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15413 serializer.startDocument(null, true); 15414 serializer.setFeature( 15415 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15416 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15417 serializer.endDocument(); 15418 serializer.flush(); 15419 } catch (IllegalArgumentException e) { 15420 pw.println("Failed writing: " + e); 15421 } catch (IllegalStateException e) { 15422 pw.println("Failed writing: " + e); 15423 } catch (IOException e) { 15424 pw.println("Failed writing: " + e); 15425 } 15426 } 15427 15428 if (!checkin 15429 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15430 && packageName == null) { 15431 pw.println(); 15432 int count = mSettings.mPackages.size(); 15433 if (count == 0) { 15434 pw.println("No applications!"); 15435 pw.println(); 15436 } else { 15437 final String prefix = " "; 15438 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15439 if (allPackageSettings.size() == 0) { 15440 pw.println("No domain preferred apps!"); 15441 pw.println(); 15442 } else { 15443 pw.println("App verification status:"); 15444 pw.println(); 15445 count = 0; 15446 for (PackageSetting ps : allPackageSettings) { 15447 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15448 if (ivi == null || ivi.getPackageName() == null) continue; 15449 pw.println(prefix + "Package: " + ivi.getPackageName()); 15450 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15451 pw.println(prefix + "Status: " + ivi.getStatusString()); 15452 pw.println(); 15453 count++; 15454 } 15455 if (count == 0) { 15456 pw.println(prefix + "No app verification established."); 15457 pw.println(); 15458 } 15459 for (int userId : sUserManager.getUserIds()) { 15460 pw.println("App linkages for user " + userId + ":"); 15461 pw.println(); 15462 count = 0; 15463 for (PackageSetting ps : allPackageSettings) { 15464 final long status = ps.getDomainVerificationStatusForUser(userId); 15465 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15466 continue; 15467 } 15468 pw.println(prefix + "Package: " + ps.name); 15469 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15470 String statusStr = IntentFilterVerificationInfo. 15471 getStatusStringFromValue(status); 15472 pw.println(prefix + "Status: " + statusStr); 15473 pw.println(); 15474 count++; 15475 } 15476 if (count == 0) { 15477 pw.println(prefix + "No configured app linkages."); 15478 pw.println(); 15479 } 15480 } 15481 } 15482 } 15483 } 15484 15485 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15486 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15487 if (packageName == null && permissionNames == null) { 15488 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15489 if (iperm == 0) { 15490 if (dumpState.onTitlePrinted()) 15491 pw.println(); 15492 pw.println("AppOp Permissions:"); 15493 } 15494 pw.print(" AppOp Permission "); 15495 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15496 pw.println(":"); 15497 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15498 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15499 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15500 } 15501 } 15502 } 15503 } 15504 15505 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15506 boolean printedSomething = false; 15507 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15508 if (packageName != null && !packageName.equals(p.info.packageName)) { 15509 continue; 15510 } 15511 if (!printedSomething) { 15512 if (dumpState.onTitlePrinted()) 15513 pw.println(); 15514 pw.println("Registered ContentProviders:"); 15515 printedSomething = true; 15516 } 15517 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15518 pw.print(" "); pw.println(p.toString()); 15519 } 15520 printedSomething = false; 15521 for (Map.Entry<String, PackageParser.Provider> entry : 15522 mProvidersByAuthority.entrySet()) { 15523 PackageParser.Provider p = entry.getValue(); 15524 if (packageName != null && !packageName.equals(p.info.packageName)) { 15525 continue; 15526 } 15527 if (!printedSomething) { 15528 if (dumpState.onTitlePrinted()) 15529 pw.println(); 15530 pw.println("ContentProvider Authorities:"); 15531 printedSomething = true; 15532 } 15533 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15534 pw.print(" "); pw.println(p.toString()); 15535 if (p.info != null && p.info.applicationInfo != null) { 15536 final String appInfo = p.info.applicationInfo.toString(); 15537 pw.print(" applicationInfo="); pw.println(appInfo); 15538 } 15539 } 15540 } 15541 15542 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15543 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15544 } 15545 15546 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15547 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15548 } 15549 15550 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15551 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15552 } 15553 15554 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15555 // XXX should handle packageName != null by dumping only install data that 15556 // the given package is involved with. 15557 if (dumpState.onTitlePrinted()) pw.println(); 15558 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15559 } 15560 15561 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15562 if (dumpState.onTitlePrinted()) pw.println(); 15563 mSettings.dumpReadMessagesLPr(pw, dumpState); 15564 15565 pw.println(); 15566 pw.println("Package warning messages:"); 15567 BufferedReader in = null; 15568 String line = null; 15569 try { 15570 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15571 while ((line = in.readLine()) != null) { 15572 if (line.contains("ignored: updated version")) continue; 15573 pw.println(line); 15574 } 15575 } catch (IOException ignored) { 15576 } finally { 15577 IoUtils.closeQuietly(in); 15578 } 15579 } 15580 15581 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15582 BufferedReader in = null; 15583 String line = null; 15584 try { 15585 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15586 while ((line = in.readLine()) != null) { 15587 if (line.contains("ignored: updated version")) continue; 15588 pw.print("msg,"); 15589 pw.println(line); 15590 } 15591 } catch (IOException ignored) { 15592 } finally { 15593 IoUtils.closeQuietly(in); 15594 } 15595 } 15596 } 15597 } 15598 15599 private String dumpDomainString(String packageName) { 15600 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15601 List<IntentFilter> filters = getAllIntentFilters(packageName); 15602 15603 ArraySet<String> result = new ArraySet<>(); 15604 if (iviList.size() > 0) { 15605 for (IntentFilterVerificationInfo ivi : iviList) { 15606 for (String host : ivi.getDomains()) { 15607 result.add(host); 15608 } 15609 } 15610 } 15611 if (filters != null && filters.size() > 0) { 15612 for (IntentFilter filter : filters) { 15613 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15614 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15615 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15616 result.addAll(filter.getHostsList()); 15617 } 15618 } 15619 } 15620 15621 StringBuilder sb = new StringBuilder(result.size() * 16); 15622 for (String domain : result) { 15623 if (sb.length() > 0) sb.append(" "); 15624 sb.append(domain); 15625 } 15626 return sb.toString(); 15627 } 15628 15629 // ------- apps on sdcard specific code ------- 15630 static final boolean DEBUG_SD_INSTALL = false; 15631 15632 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15633 15634 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15635 15636 private boolean mMediaMounted = false; 15637 15638 static String getEncryptKey() { 15639 try { 15640 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15641 SD_ENCRYPTION_KEYSTORE_NAME); 15642 if (sdEncKey == null) { 15643 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15644 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15645 if (sdEncKey == null) { 15646 Slog.e(TAG, "Failed to create encryption keys"); 15647 return null; 15648 } 15649 } 15650 return sdEncKey; 15651 } catch (NoSuchAlgorithmException nsae) { 15652 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15653 return null; 15654 } catch (IOException ioe) { 15655 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15656 return null; 15657 } 15658 } 15659 15660 /* 15661 * Update media status on PackageManager. 15662 */ 15663 @Override 15664 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15665 int callingUid = Binder.getCallingUid(); 15666 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15667 throw new SecurityException("Media status can only be updated by the system"); 15668 } 15669 // reader; this apparently protects mMediaMounted, but should probably 15670 // be a different lock in that case. 15671 synchronized (mPackages) { 15672 Log.i(TAG, "Updating external media status from " 15673 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15674 + (mediaStatus ? "mounted" : "unmounted")); 15675 if (DEBUG_SD_INSTALL) 15676 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15677 + ", mMediaMounted=" + mMediaMounted); 15678 if (mediaStatus == mMediaMounted) { 15679 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15680 : 0, -1); 15681 mHandler.sendMessage(msg); 15682 return; 15683 } 15684 mMediaMounted = mediaStatus; 15685 } 15686 // Queue up an async operation since the package installation may take a 15687 // little while. 15688 mHandler.post(new Runnable() { 15689 public void run() { 15690 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15691 } 15692 }); 15693 } 15694 15695 /** 15696 * Called by MountService when the initial ASECs to scan are available. 15697 * Should block until all the ASEC containers are finished being scanned. 15698 */ 15699 public void scanAvailableAsecs() { 15700 updateExternalMediaStatusInner(true, false, false); 15701 if (mShouldRestoreconData) { 15702 SELinuxMMAC.setRestoreconDone(); 15703 mShouldRestoreconData = false; 15704 } 15705 } 15706 15707 /* 15708 * Collect information of applications on external media, map them against 15709 * existing containers and update information based on current mount status. 15710 * Please note that we always have to report status if reportStatus has been 15711 * set to true especially when unloading packages. 15712 */ 15713 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15714 boolean externalStorage) { 15715 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15716 int[] uidArr = EmptyArray.INT; 15717 15718 final String[] list = PackageHelper.getSecureContainerList(); 15719 if (ArrayUtils.isEmpty(list)) { 15720 Log.i(TAG, "No secure containers found"); 15721 } else { 15722 // Process list of secure containers and categorize them 15723 // as active or stale based on their package internal state. 15724 15725 // reader 15726 synchronized (mPackages) { 15727 for (String cid : list) { 15728 // Leave stages untouched for now; installer service owns them 15729 if (PackageInstallerService.isStageName(cid)) continue; 15730 15731 if (DEBUG_SD_INSTALL) 15732 Log.i(TAG, "Processing container " + cid); 15733 String pkgName = getAsecPackageName(cid); 15734 if (pkgName == null) { 15735 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15736 continue; 15737 } 15738 if (DEBUG_SD_INSTALL) 15739 Log.i(TAG, "Looking for pkg : " + pkgName); 15740 15741 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15742 if (ps == null) { 15743 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15744 continue; 15745 } 15746 15747 /* 15748 * Skip packages that are not external if we're unmounting 15749 * external storage. 15750 */ 15751 if (externalStorage && !isMounted && !isExternal(ps)) { 15752 continue; 15753 } 15754 15755 final AsecInstallArgs args = new AsecInstallArgs(cid, 15756 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15757 // The package status is changed only if the code path 15758 // matches between settings and the container id. 15759 if (ps.codePathString != null 15760 && ps.codePathString.startsWith(args.getCodePath())) { 15761 if (DEBUG_SD_INSTALL) { 15762 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15763 + " at code path: " + ps.codePathString); 15764 } 15765 15766 // We do have a valid package installed on sdcard 15767 processCids.put(args, ps.codePathString); 15768 final int uid = ps.appId; 15769 if (uid != -1) { 15770 uidArr = ArrayUtils.appendInt(uidArr, uid); 15771 } 15772 } else { 15773 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15774 + ps.codePathString); 15775 } 15776 } 15777 } 15778 15779 Arrays.sort(uidArr); 15780 } 15781 15782 // Process packages with valid entries. 15783 if (isMounted) { 15784 if (DEBUG_SD_INSTALL) 15785 Log.i(TAG, "Loading packages"); 15786 loadMediaPackages(processCids, uidArr, externalStorage); 15787 startCleaningPackages(); 15788 mInstallerService.onSecureContainersAvailable(); 15789 } else { 15790 if (DEBUG_SD_INSTALL) 15791 Log.i(TAG, "Unloading packages"); 15792 unloadMediaPackages(processCids, uidArr, reportStatus); 15793 } 15794 } 15795 15796 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15797 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15798 final int size = infos.size(); 15799 final String[] packageNames = new String[size]; 15800 final int[] packageUids = new int[size]; 15801 for (int i = 0; i < size; i++) { 15802 final ApplicationInfo info = infos.get(i); 15803 packageNames[i] = info.packageName; 15804 packageUids[i] = info.uid; 15805 } 15806 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15807 finishedReceiver); 15808 } 15809 15810 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15811 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15812 sendResourcesChangedBroadcast(mediaStatus, replacing, 15813 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15814 } 15815 15816 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15817 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15818 int size = pkgList.length; 15819 if (size > 0) { 15820 // Send broadcasts here 15821 Bundle extras = new Bundle(); 15822 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15823 if (uidArr != null) { 15824 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15825 } 15826 if (replacing) { 15827 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15828 } 15829 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15830 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15831 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15832 } 15833 } 15834 15835 /* 15836 * Look at potentially valid container ids from processCids If package 15837 * information doesn't match the one on record or package scanning fails, 15838 * the cid is added to list of removeCids. We currently don't delete stale 15839 * containers. 15840 */ 15841 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 15842 boolean externalStorage) { 15843 ArrayList<String> pkgList = new ArrayList<String>(); 15844 Set<AsecInstallArgs> keys = processCids.keySet(); 15845 15846 for (AsecInstallArgs args : keys) { 15847 String codePath = processCids.get(args); 15848 if (DEBUG_SD_INSTALL) 15849 Log.i(TAG, "Loading container : " + args.cid); 15850 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15851 try { 15852 // Make sure there are no container errors first. 15853 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15854 Slog.e(TAG, "Failed to mount cid : " + args.cid 15855 + " when installing from sdcard"); 15856 continue; 15857 } 15858 // Check code path here. 15859 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15860 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15861 + " does not match one in settings " + codePath); 15862 continue; 15863 } 15864 // Parse package 15865 int parseFlags = mDefParseFlags; 15866 if (args.isExternalAsec()) { 15867 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15868 } 15869 if (args.isFwdLocked()) { 15870 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15871 } 15872 15873 synchronized (mInstallLock) { 15874 PackageParser.Package pkg = null; 15875 try { 15876 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 15877 } catch (PackageManagerException e) { 15878 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15879 } 15880 // Scan the package 15881 if (pkg != null) { 15882 /* 15883 * TODO why is the lock being held? doPostInstall is 15884 * called in other places without the lock. This needs 15885 * to be straightened out. 15886 */ 15887 // writer 15888 synchronized (mPackages) { 15889 retCode = PackageManager.INSTALL_SUCCEEDED; 15890 pkgList.add(pkg.packageName); 15891 // Post process args 15892 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15893 pkg.applicationInfo.uid); 15894 } 15895 } else { 15896 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15897 } 15898 } 15899 15900 } finally { 15901 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15902 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15903 } 15904 } 15905 } 15906 // writer 15907 synchronized (mPackages) { 15908 // If the platform SDK has changed since the last time we booted, 15909 // we need to re-grant app permission to catch any new ones that 15910 // appear. This is really a hack, and means that apps can in some 15911 // cases get permissions that the user didn't initially explicitly 15912 // allow... it would be nice to have some better way to handle 15913 // this situation. 15914 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 15915 : mSettings.getInternalVersion(); 15916 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 15917 : StorageManager.UUID_PRIVATE_INTERNAL; 15918 15919 int updateFlags = UPDATE_PERMISSIONS_ALL; 15920 if (ver.sdkVersion != mSdkVersion) { 15921 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 15922 + mSdkVersion + "; regranting permissions for external"); 15923 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 15924 } 15925 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 15926 15927 // Yay, everything is now upgraded 15928 ver.forceCurrent(); 15929 15930 // can downgrade to reader 15931 // Persist settings 15932 mSettings.writeLPr(); 15933 } 15934 // Send a broadcast to let everyone know we are done processing 15935 if (pkgList.size() > 0) { 15936 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15937 } 15938 } 15939 15940 /* 15941 * Utility method to unload a list of specified containers 15942 */ 15943 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15944 // Just unmount all valid containers. 15945 for (AsecInstallArgs arg : cidArgs) { 15946 synchronized (mInstallLock) { 15947 arg.doPostDeleteLI(false); 15948 } 15949 } 15950 } 15951 15952 /* 15953 * Unload packages mounted on external media. This involves deleting package 15954 * data from internal structures, sending broadcasts about diabled packages, 15955 * gc'ing to free up references, unmounting all secure containers 15956 * corresponding to packages on external media, and posting a 15957 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15958 * that we always have to post this message if status has been requested no 15959 * matter what. 15960 */ 15961 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15962 final boolean reportStatus) { 15963 if (DEBUG_SD_INSTALL) 15964 Log.i(TAG, "unloading media packages"); 15965 ArrayList<String> pkgList = new ArrayList<String>(); 15966 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15967 final Set<AsecInstallArgs> keys = processCids.keySet(); 15968 for (AsecInstallArgs args : keys) { 15969 String pkgName = args.getPackageName(); 15970 if (DEBUG_SD_INSTALL) 15971 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15972 // Delete package internally 15973 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15974 synchronized (mInstallLock) { 15975 boolean res = deletePackageLI(pkgName, null, false, null, null, 15976 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15977 if (res) { 15978 pkgList.add(pkgName); 15979 } else { 15980 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15981 failedList.add(args); 15982 } 15983 } 15984 } 15985 15986 // reader 15987 synchronized (mPackages) { 15988 // We didn't update the settings after removing each package; 15989 // write them now for all packages. 15990 mSettings.writeLPr(); 15991 } 15992 15993 // We have to absolutely send UPDATED_MEDIA_STATUS only 15994 // after confirming that all the receivers processed the ordered 15995 // broadcast when packages get disabled, force a gc to clean things up. 15996 // and unload all the containers. 15997 if (pkgList.size() > 0) { 15998 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15999 new IIntentReceiver.Stub() { 16000 public void performReceive(Intent intent, int resultCode, String data, 16001 Bundle extras, boolean ordered, boolean sticky, 16002 int sendingUser) throws RemoteException { 16003 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16004 reportStatus ? 1 : 0, 1, keys); 16005 mHandler.sendMessage(msg); 16006 } 16007 }); 16008 } else { 16009 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16010 keys); 16011 mHandler.sendMessage(msg); 16012 } 16013 } 16014 16015 private void loadPrivatePackages(final VolumeInfo vol) { 16016 mHandler.post(new Runnable() { 16017 @Override 16018 public void run() { 16019 loadPrivatePackagesInner(vol); 16020 } 16021 }); 16022 } 16023 16024 private void loadPrivatePackagesInner(VolumeInfo vol) { 16025 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16026 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16027 16028 final VersionInfo ver; 16029 final List<PackageSetting> packages; 16030 synchronized (mPackages) { 16031 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16032 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16033 } 16034 16035 for (PackageSetting ps : packages) { 16036 synchronized (mInstallLock) { 16037 final PackageParser.Package pkg; 16038 try { 16039 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16040 loaded.add(pkg.applicationInfo); 16041 } catch (PackageManagerException e) { 16042 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16043 } 16044 16045 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16046 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16047 } 16048 } 16049 } 16050 16051 synchronized (mPackages) { 16052 int updateFlags = UPDATE_PERMISSIONS_ALL; 16053 if (ver.sdkVersion != mSdkVersion) { 16054 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16055 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16056 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16057 } 16058 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16059 16060 // Yay, everything is now upgraded 16061 ver.forceCurrent(); 16062 16063 mSettings.writeLPr(); 16064 } 16065 16066 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16067 sendResourcesChangedBroadcast(true, false, loaded, null); 16068 } 16069 16070 private void unloadPrivatePackages(final VolumeInfo vol) { 16071 mHandler.post(new Runnable() { 16072 @Override 16073 public void run() { 16074 unloadPrivatePackagesInner(vol); 16075 } 16076 }); 16077 } 16078 16079 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16080 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16081 synchronized (mInstallLock) { 16082 synchronized (mPackages) { 16083 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16084 for (PackageSetting ps : packages) { 16085 if (ps.pkg == null) continue; 16086 16087 final ApplicationInfo info = ps.pkg.applicationInfo; 16088 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16089 if (deletePackageLI(ps.name, null, false, null, null, 16090 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16091 unloaded.add(info); 16092 } else { 16093 Slog.w(TAG, "Failed to unload " + ps.codePath); 16094 } 16095 } 16096 16097 mSettings.writeLPr(); 16098 } 16099 } 16100 16101 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16102 sendResourcesChangedBroadcast(false, false, unloaded, null); 16103 } 16104 16105 /** 16106 * Examine all users present on given mounted volume, and destroy data 16107 * belonging to users that are no longer valid, or whose user ID has been 16108 * recycled. 16109 */ 16110 private void reconcileUsers(String volumeUuid) { 16111 final File[] files = FileUtils 16112 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16113 for (File file : files) { 16114 if (!file.isDirectory()) continue; 16115 16116 final int userId; 16117 final UserInfo info; 16118 try { 16119 userId = Integer.parseInt(file.getName()); 16120 info = sUserManager.getUserInfo(userId); 16121 } catch (NumberFormatException e) { 16122 Slog.w(TAG, "Invalid user directory " + file); 16123 continue; 16124 } 16125 16126 boolean destroyUser = false; 16127 if (info == null) { 16128 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16129 + " because no matching user was found"); 16130 destroyUser = true; 16131 } else { 16132 try { 16133 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16134 } catch (IOException e) { 16135 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16136 + " because we failed to enforce serial number: " + e); 16137 destroyUser = true; 16138 } 16139 } 16140 16141 if (destroyUser) { 16142 synchronized (mInstallLock) { 16143 mInstaller.removeUserDataDirs(volumeUuid, userId); 16144 } 16145 } 16146 } 16147 16148 final UserManager um = mContext.getSystemService(UserManager.class); 16149 for (UserInfo user : um.getUsers()) { 16150 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16151 if (userDir.exists()) continue; 16152 16153 try { 16154 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 16155 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16156 } catch (IOException e) { 16157 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16158 } 16159 } 16160 } 16161 16162 /** 16163 * Examine all apps present on given mounted volume, and destroy apps that 16164 * aren't expected, either due to uninstallation or reinstallation on 16165 * another volume. 16166 */ 16167 private void reconcileApps(String volumeUuid) { 16168 final File[] files = FileUtils 16169 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16170 for (File file : files) { 16171 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16172 && !PackageInstallerService.isStageName(file.getName()); 16173 if (!isPackage) { 16174 // Ignore entries which are not packages 16175 continue; 16176 } 16177 16178 boolean destroyApp = false; 16179 String packageName = null; 16180 try { 16181 final PackageLite pkg = PackageParser.parsePackageLite(file, 16182 PackageParser.PARSE_MUST_BE_APK); 16183 packageName = pkg.packageName; 16184 16185 synchronized (mPackages) { 16186 final PackageSetting ps = mSettings.mPackages.get(packageName); 16187 if (ps == null) { 16188 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16189 + volumeUuid + " because we found no install record"); 16190 destroyApp = true; 16191 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16192 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16193 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16194 destroyApp = true; 16195 } 16196 } 16197 16198 } catch (PackageParserException e) { 16199 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16200 destroyApp = true; 16201 } 16202 16203 if (destroyApp) { 16204 synchronized (mInstallLock) { 16205 if (packageName != null) { 16206 removeDataDirsLI(volumeUuid, packageName); 16207 } 16208 if (file.isDirectory()) { 16209 mInstaller.rmPackageDir(file.getAbsolutePath()); 16210 } else { 16211 file.delete(); 16212 } 16213 } 16214 } 16215 } 16216 } 16217 16218 private void unfreezePackage(String packageName) { 16219 synchronized (mPackages) { 16220 final PackageSetting ps = mSettings.mPackages.get(packageName); 16221 if (ps != null) { 16222 ps.frozen = false; 16223 } 16224 } 16225 } 16226 16227 @Override 16228 public int movePackage(final String packageName, final String volumeUuid) { 16229 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16230 16231 final int moveId = mNextMoveId.getAndIncrement(); 16232 try { 16233 movePackageInternal(packageName, volumeUuid, moveId); 16234 } catch (PackageManagerException e) { 16235 Slog.w(TAG, "Failed to move " + packageName, e); 16236 mMoveCallbacks.notifyStatusChanged(moveId, 16237 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16238 } 16239 return moveId; 16240 } 16241 16242 private void movePackageInternal(final String packageName, final String volumeUuid, 16243 final int moveId) throws PackageManagerException { 16244 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16245 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16246 final PackageManager pm = mContext.getPackageManager(); 16247 16248 final boolean currentAsec; 16249 final String currentVolumeUuid; 16250 final File codeFile; 16251 final String installerPackageName; 16252 final String packageAbiOverride; 16253 final int appId; 16254 final String seinfo; 16255 final String label; 16256 16257 // reader 16258 synchronized (mPackages) { 16259 final PackageParser.Package pkg = mPackages.get(packageName); 16260 final PackageSetting ps = mSettings.mPackages.get(packageName); 16261 if (pkg == null || ps == null) { 16262 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16263 } 16264 16265 if (pkg.applicationInfo.isSystemApp()) { 16266 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16267 "Cannot move system application"); 16268 } 16269 16270 if (pkg.applicationInfo.isExternalAsec()) { 16271 currentAsec = true; 16272 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16273 } else if (pkg.applicationInfo.isForwardLocked()) { 16274 currentAsec = true; 16275 currentVolumeUuid = "forward_locked"; 16276 } else { 16277 currentAsec = false; 16278 currentVolumeUuid = ps.volumeUuid; 16279 16280 final File probe = new File(pkg.codePath); 16281 final File probeOat = new File(probe, "oat"); 16282 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16283 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16284 "Move only supported for modern cluster style installs"); 16285 } 16286 } 16287 16288 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16289 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16290 "Package already moved to " + volumeUuid); 16291 } 16292 16293 if (ps.frozen) { 16294 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16295 "Failed to move already frozen package"); 16296 } 16297 ps.frozen = true; 16298 16299 codeFile = new File(pkg.codePath); 16300 installerPackageName = ps.installerPackageName; 16301 packageAbiOverride = ps.cpuAbiOverrideString; 16302 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16303 seinfo = pkg.applicationInfo.seinfo; 16304 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16305 } 16306 16307 // Now that we're guarded by frozen state, kill app during move 16308 final long token = Binder.clearCallingIdentity(); 16309 try { 16310 killApplication(packageName, appId, "move pkg"); 16311 } finally { 16312 Binder.restoreCallingIdentity(token); 16313 } 16314 16315 final Bundle extras = new Bundle(); 16316 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16317 extras.putString(Intent.EXTRA_TITLE, label); 16318 mMoveCallbacks.notifyCreated(moveId, extras); 16319 16320 int installFlags; 16321 final boolean moveCompleteApp; 16322 final File measurePath; 16323 16324 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16325 installFlags = INSTALL_INTERNAL; 16326 moveCompleteApp = !currentAsec; 16327 measurePath = Environment.getDataAppDirectory(volumeUuid); 16328 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16329 installFlags = INSTALL_EXTERNAL; 16330 moveCompleteApp = false; 16331 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16332 } else { 16333 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16334 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16335 || !volume.isMountedWritable()) { 16336 unfreezePackage(packageName); 16337 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16338 "Move location not mounted private volume"); 16339 } 16340 16341 Preconditions.checkState(!currentAsec); 16342 16343 installFlags = INSTALL_INTERNAL; 16344 moveCompleteApp = true; 16345 measurePath = Environment.getDataAppDirectory(volumeUuid); 16346 } 16347 16348 final PackageStats stats = new PackageStats(null, -1); 16349 synchronized (mInstaller) { 16350 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16351 unfreezePackage(packageName); 16352 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16353 "Failed to measure package size"); 16354 } 16355 } 16356 16357 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16358 + stats.dataSize); 16359 16360 final long startFreeBytes = measurePath.getFreeSpace(); 16361 final long sizeBytes; 16362 if (moveCompleteApp) { 16363 sizeBytes = stats.codeSize + stats.dataSize; 16364 } else { 16365 sizeBytes = stats.codeSize; 16366 } 16367 16368 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16369 unfreezePackage(packageName); 16370 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16371 "Not enough free space to move"); 16372 } 16373 16374 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16375 16376 final CountDownLatch installedLatch = new CountDownLatch(1); 16377 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16378 @Override 16379 public void onUserActionRequired(Intent intent) throws RemoteException { 16380 throw new IllegalStateException(); 16381 } 16382 16383 @Override 16384 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16385 Bundle extras) throws RemoteException { 16386 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16387 + PackageManager.installStatusToString(returnCode, msg)); 16388 16389 installedLatch.countDown(); 16390 16391 // Regardless of success or failure of the move operation, 16392 // always unfreeze the package 16393 unfreezePackage(packageName); 16394 16395 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16396 switch (status) { 16397 case PackageInstaller.STATUS_SUCCESS: 16398 mMoveCallbacks.notifyStatusChanged(moveId, 16399 PackageManager.MOVE_SUCCEEDED); 16400 break; 16401 case PackageInstaller.STATUS_FAILURE_STORAGE: 16402 mMoveCallbacks.notifyStatusChanged(moveId, 16403 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16404 break; 16405 default: 16406 mMoveCallbacks.notifyStatusChanged(moveId, 16407 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16408 break; 16409 } 16410 } 16411 }; 16412 16413 final MoveInfo move; 16414 if (moveCompleteApp) { 16415 // Kick off a thread to report progress estimates 16416 new Thread() { 16417 @Override 16418 public void run() { 16419 while (true) { 16420 try { 16421 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16422 break; 16423 } 16424 } catch (InterruptedException ignored) { 16425 } 16426 16427 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16428 final int progress = 10 + (int) MathUtils.constrain( 16429 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16430 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16431 } 16432 } 16433 }.start(); 16434 16435 final String dataAppName = codeFile.getName(); 16436 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16437 dataAppName, appId, seinfo); 16438 } else { 16439 move = null; 16440 } 16441 16442 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16443 16444 final Message msg = mHandler.obtainMessage(INIT_COPY); 16445 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16446 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16447 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16448 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16449 msg.obj = params; 16450 16451 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16452 System.identityHashCode(msg.obj)); 16453 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16454 System.identityHashCode(msg.obj)); 16455 16456 mHandler.sendMessage(msg); 16457 } 16458 16459 @Override 16460 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16461 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16462 16463 final int realMoveId = mNextMoveId.getAndIncrement(); 16464 final Bundle extras = new Bundle(); 16465 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16466 mMoveCallbacks.notifyCreated(realMoveId, extras); 16467 16468 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16469 @Override 16470 public void onCreated(int moveId, Bundle extras) { 16471 // Ignored 16472 } 16473 16474 @Override 16475 public void onStatusChanged(int moveId, int status, long estMillis) { 16476 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16477 } 16478 }; 16479 16480 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16481 storage.setPrimaryStorageUuid(volumeUuid, callback); 16482 return realMoveId; 16483 } 16484 16485 @Override 16486 public int getMoveStatus(int moveId) { 16487 mContext.enforceCallingOrSelfPermission( 16488 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16489 return mMoveCallbacks.mLastStatus.get(moveId); 16490 } 16491 16492 @Override 16493 public void registerMoveCallback(IPackageMoveObserver callback) { 16494 mContext.enforceCallingOrSelfPermission( 16495 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16496 mMoveCallbacks.register(callback); 16497 } 16498 16499 @Override 16500 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16501 mContext.enforceCallingOrSelfPermission( 16502 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16503 mMoveCallbacks.unregister(callback); 16504 } 16505 16506 @Override 16507 public boolean setInstallLocation(int loc) { 16508 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16509 null); 16510 if (getInstallLocation() == loc) { 16511 return true; 16512 } 16513 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16514 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16515 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16516 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16517 return true; 16518 } 16519 return false; 16520 } 16521 16522 @Override 16523 public int getInstallLocation() { 16524 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16525 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16526 PackageHelper.APP_INSTALL_AUTO); 16527 } 16528 16529 /** Called by UserManagerService */ 16530 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 16531 mDirtyUsers.remove(userHandle); 16532 mSettings.removeUserLPw(userHandle); 16533 mPendingBroadcasts.remove(userHandle); 16534 if (mInstaller != null) { 16535 // Technically, we shouldn't be doing this with the package lock 16536 // held. However, this is very rare, and there is already so much 16537 // other disk I/O going on, that we'll let it slide for now. 16538 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16539 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16540 final String volumeUuid = vol.getFsUuid(); 16541 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16542 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16543 } 16544 } 16545 mUserNeedsBadging.delete(userHandle); 16546 removeUnusedPackagesLILPw(userManager, userHandle); 16547 } 16548 16549 /** 16550 * We're removing userHandle and would like to remove any downloaded packages 16551 * that are no longer in use by any other user. 16552 * @param userHandle the user being removed 16553 */ 16554 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16555 final boolean DEBUG_CLEAN_APKS = false; 16556 int [] users = userManager.getUserIdsLPr(); 16557 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16558 while (psit.hasNext()) { 16559 PackageSetting ps = psit.next(); 16560 if (ps.pkg == null) { 16561 continue; 16562 } 16563 final String packageName = ps.pkg.packageName; 16564 // Skip over if system app 16565 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16566 continue; 16567 } 16568 if (DEBUG_CLEAN_APKS) { 16569 Slog.i(TAG, "Checking package " + packageName); 16570 } 16571 boolean keep = false; 16572 for (int i = 0; i < users.length; i++) { 16573 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16574 keep = true; 16575 if (DEBUG_CLEAN_APKS) { 16576 Slog.i(TAG, " Keeping package " + packageName + " for user " 16577 + users[i]); 16578 } 16579 break; 16580 } 16581 } 16582 if (!keep) { 16583 if (DEBUG_CLEAN_APKS) { 16584 Slog.i(TAG, " Removing package " + packageName); 16585 } 16586 mHandler.post(new Runnable() { 16587 public void run() { 16588 deletePackageX(packageName, userHandle, 0); 16589 } //end run 16590 }); 16591 } 16592 } 16593 } 16594 16595 /** Called by UserManagerService */ 16596 void createNewUserLILPw(int userHandle) { 16597 if (mInstaller != null) { 16598 mInstaller.createUserConfig(userHandle); 16599 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16600 applyFactoryDefaultBrowserLPw(userHandle); 16601 primeDomainVerificationsLPw(userHandle); 16602 } 16603 } 16604 16605 void newUserCreated(final int userHandle) { 16606 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16607 } 16608 16609 @Override 16610 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16611 mContext.enforceCallingOrSelfPermission( 16612 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16613 "Only package verification agents can read the verifier device identity"); 16614 16615 synchronized (mPackages) { 16616 return mSettings.getVerifierDeviceIdentityLPw(); 16617 } 16618 } 16619 16620 @Override 16621 public void setPermissionEnforced(String permission, boolean enforced) { 16622 // TODO: Now that we no longer change GID for storage, this should to away. 16623 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 16624 "setPermissionEnforced"); 16625 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16626 synchronized (mPackages) { 16627 if (mSettings.mReadExternalStorageEnforced == null 16628 || mSettings.mReadExternalStorageEnforced != enforced) { 16629 mSettings.mReadExternalStorageEnforced = enforced; 16630 mSettings.writeLPr(); 16631 } 16632 } 16633 // kill any non-foreground processes so we restart them and 16634 // grant/revoke the GID. 16635 final IActivityManager am = ActivityManagerNative.getDefault(); 16636 if (am != null) { 16637 final long token = Binder.clearCallingIdentity(); 16638 try { 16639 am.killProcessesBelowForeground("setPermissionEnforcement"); 16640 } catch (RemoteException e) { 16641 } finally { 16642 Binder.restoreCallingIdentity(token); 16643 } 16644 } 16645 } else { 16646 throw new IllegalArgumentException("No selective enforcement for " + permission); 16647 } 16648 } 16649 16650 @Override 16651 @Deprecated 16652 public boolean isPermissionEnforced(String permission) { 16653 return true; 16654 } 16655 16656 @Override 16657 public boolean isStorageLow() { 16658 final long token = Binder.clearCallingIdentity(); 16659 try { 16660 final DeviceStorageMonitorInternal 16661 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16662 if (dsm != null) { 16663 return dsm.isMemoryLow(); 16664 } else { 16665 return false; 16666 } 16667 } finally { 16668 Binder.restoreCallingIdentity(token); 16669 } 16670 } 16671 16672 @Override 16673 public IPackageInstaller getPackageInstaller() { 16674 return mInstallerService; 16675 } 16676 16677 private boolean userNeedsBadging(int userId) { 16678 int index = mUserNeedsBadging.indexOfKey(userId); 16679 if (index < 0) { 16680 final UserInfo userInfo; 16681 final long token = Binder.clearCallingIdentity(); 16682 try { 16683 userInfo = sUserManager.getUserInfo(userId); 16684 } finally { 16685 Binder.restoreCallingIdentity(token); 16686 } 16687 final boolean b; 16688 if (userInfo != null && userInfo.isManagedProfile()) { 16689 b = true; 16690 } else { 16691 b = false; 16692 } 16693 mUserNeedsBadging.put(userId, b); 16694 return b; 16695 } 16696 return mUserNeedsBadging.valueAt(index); 16697 } 16698 16699 @Override 16700 public KeySet getKeySetByAlias(String packageName, String alias) { 16701 if (packageName == null || alias == null) { 16702 return null; 16703 } 16704 synchronized(mPackages) { 16705 final PackageParser.Package pkg = mPackages.get(packageName); 16706 if (pkg == null) { 16707 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16708 throw new IllegalArgumentException("Unknown package: " + packageName); 16709 } 16710 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16711 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16712 } 16713 } 16714 16715 @Override 16716 public KeySet getSigningKeySet(String packageName) { 16717 if (packageName == null) { 16718 return null; 16719 } 16720 synchronized(mPackages) { 16721 final PackageParser.Package pkg = mPackages.get(packageName); 16722 if (pkg == null) { 16723 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16724 throw new IllegalArgumentException("Unknown package: " + packageName); 16725 } 16726 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16727 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16728 throw new SecurityException("May not access signing KeySet of other apps."); 16729 } 16730 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16731 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16732 } 16733 } 16734 16735 @Override 16736 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16737 if (packageName == null || ks == null) { 16738 return false; 16739 } 16740 synchronized(mPackages) { 16741 final PackageParser.Package pkg = mPackages.get(packageName); 16742 if (pkg == null) { 16743 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16744 throw new IllegalArgumentException("Unknown package: " + packageName); 16745 } 16746 IBinder ksh = ks.getToken(); 16747 if (ksh instanceof KeySetHandle) { 16748 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16749 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16750 } 16751 return false; 16752 } 16753 } 16754 16755 @Override 16756 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16757 if (packageName == null || ks == null) { 16758 return false; 16759 } 16760 synchronized(mPackages) { 16761 final PackageParser.Package pkg = mPackages.get(packageName); 16762 if (pkg == null) { 16763 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16764 throw new IllegalArgumentException("Unknown package: " + packageName); 16765 } 16766 IBinder ksh = ks.getToken(); 16767 if (ksh instanceof KeySetHandle) { 16768 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16769 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16770 } 16771 return false; 16772 } 16773 } 16774 16775 public void getUsageStatsIfNoPackageUsageInfo() { 16776 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16777 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16778 if (usm == null) { 16779 throw new IllegalStateException("UsageStatsManager must be initialized"); 16780 } 16781 long now = System.currentTimeMillis(); 16782 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16783 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16784 String packageName = entry.getKey(); 16785 PackageParser.Package pkg = mPackages.get(packageName); 16786 if (pkg == null) { 16787 continue; 16788 } 16789 UsageStats usage = entry.getValue(); 16790 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16791 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16792 } 16793 } 16794 } 16795 16796 /** 16797 * Check and throw if the given before/after packages would be considered a 16798 * downgrade. 16799 */ 16800 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16801 throws PackageManagerException { 16802 if (after.versionCode < before.mVersionCode) { 16803 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16804 "Update version code " + after.versionCode + " is older than current " 16805 + before.mVersionCode); 16806 } else if (after.versionCode == before.mVersionCode) { 16807 if (after.baseRevisionCode < before.baseRevisionCode) { 16808 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16809 "Update base revision code " + after.baseRevisionCode 16810 + " is older than current " + before.baseRevisionCode); 16811 } 16812 16813 if (!ArrayUtils.isEmpty(after.splitNames)) { 16814 for (int i = 0; i < after.splitNames.length; i++) { 16815 final String splitName = after.splitNames[i]; 16816 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16817 if (j != -1) { 16818 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16819 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16820 "Update split " + splitName + " revision code " 16821 + after.splitRevisionCodes[i] + " is older than current " 16822 + before.splitRevisionCodes[j]); 16823 } 16824 } 16825 } 16826 } 16827 } 16828 } 16829 16830 private static class MoveCallbacks extends Handler { 16831 private static final int MSG_CREATED = 1; 16832 private static final int MSG_STATUS_CHANGED = 2; 16833 16834 private final RemoteCallbackList<IPackageMoveObserver> 16835 mCallbacks = new RemoteCallbackList<>(); 16836 16837 private final SparseIntArray mLastStatus = new SparseIntArray(); 16838 16839 public MoveCallbacks(Looper looper) { 16840 super(looper); 16841 } 16842 16843 public void register(IPackageMoveObserver callback) { 16844 mCallbacks.register(callback); 16845 } 16846 16847 public void unregister(IPackageMoveObserver callback) { 16848 mCallbacks.unregister(callback); 16849 } 16850 16851 @Override 16852 public void handleMessage(Message msg) { 16853 final SomeArgs args = (SomeArgs) msg.obj; 16854 final int n = mCallbacks.beginBroadcast(); 16855 for (int i = 0; i < n; i++) { 16856 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16857 try { 16858 invokeCallback(callback, msg.what, args); 16859 } catch (RemoteException ignored) { 16860 } 16861 } 16862 mCallbacks.finishBroadcast(); 16863 args.recycle(); 16864 } 16865 16866 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16867 throws RemoteException { 16868 switch (what) { 16869 case MSG_CREATED: { 16870 callback.onCreated(args.argi1, (Bundle) args.arg2); 16871 break; 16872 } 16873 case MSG_STATUS_CHANGED: { 16874 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16875 break; 16876 } 16877 } 16878 } 16879 16880 private void notifyCreated(int moveId, Bundle extras) { 16881 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16882 16883 final SomeArgs args = SomeArgs.obtain(); 16884 args.argi1 = moveId; 16885 args.arg2 = extras; 16886 obtainMessage(MSG_CREATED, args).sendToTarget(); 16887 } 16888 16889 private void notifyStatusChanged(int moveId, int status) { 16890 notifyStatusChanged(moveId, status, -1); 16891 } 16892 16893 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16894 Slog.v(TAG, "Move " + moveId + " status " + status); 16895 16896 final SomeArgs args = SomeArgs.obtain(); 16897 args.argi1 = moveId; 16898 args.argi2 = status; 16899 args.arg3 = estMillis; 16900 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16901 16902 synchronized (mLastStatus) { 16903 mLastStatus.put(moveId, status); 16904 } 16905 } 16906 } 16907 16908 private final class OnPermissionChangeListeners extends Handler { 16909 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16910 16911 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16912 new RemoteCallbackList<>(); 16913 16914 public OnPermissionChangeListeners(Looper looper) { 16915 super(looper); 16916 } 16917 16918 @Override 16919 public void handleMessage(Message msg) { 16920 switch (msg.what) { 16921 case MSG_ON_PERMISSIONS_CHANGED: { 16922 final int uid = msg.arg1; 16923 handleOnPermissionsChanged(uid); 16924 } break; 16925 } 16926 } 16927 16928 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16929 mPermissionListeners.register(listener); 16930 16931 } 16932 16933 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16934 mPermissionListeners.unregister(listener); 16935 } 16936 16937 public void onPermissionsChanged(int uid) { 16938 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16939 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16940 } 16941 } 16942 16943 private void handleOnPermissionsChanged(int uid) { 16944 final int count = mPermissionListeners.beginBroadcast(); 16945 try { 16946 for (int i = 0; i < count; i++) { 16947 IOnPermissionsChangeListener callback = mPermissionListeners 16948 .getBroadcastItem(i); 16949 try { 16950 callback.onPermissionsChanged(uid); 16951 } catch (RemoteException e) { 16952 Log.e(TAG, "Permission listener is dead", e); 16953 } 16954 } 16955 } finally { 16956 mPermissionListeners.finishBroadcast(); 16957 } 16958 } 16959 } 16960 16961 private class PackageManagerInternalImpl extends PackageManagerInternal { 16962 @Override 16963 public void setLocationPackagesProvider(PackagesProvider provider) { 16964 synchronized (mPackages) { 16965 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16966 } 16967 } 16968 16969 @Override 16970 public void setImePackagesProvider(PackagesProvider provider) { 16971 synchronized (mPackages) { 16972 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16973 } 16974 } 16975 16976 @Override 16977 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16978 synchronized (mPackages) { 16979 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16980 } 16981 } 16982 16983 @Override 16984 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16985 synchronized (mPackages) { 16986 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16987 } 16988 } 16989 16990 @Override 16991 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16992 synchronized (mPackages) { 16993 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16994 } 16995 } 16996 16997 @Override 16998 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 16999 synchronized (mPackages) { 17000 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17001 } 17002 } 17003 17004 @Override 17005 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17006 synchronized (mPackages) { 17007 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17008 } 17009 } 17010 17011 @Override 17012 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17013 synchronized (mPackages) { 17014 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17015 packageName, userId); 17016 } 17017 } 17018 17019 @Override 17020 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17021 synchronized (mPackages) { 17022 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17023 packageName, userId); 17024 } 17025 } 17026 @Override 17027 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17028 synchronized (mPackages) { 17029 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17030 packageName, userId); 17031 } 17032 } 17033 } 17034 17035 @Override 17036 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17037 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17038 synchronized (mPackages) { 17039 final long identity = Binder.clearCallingIdentity(); 17040 try { 17041 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17042 packageNames, userId); 17043 } finally { 17044 Binder.restoreCallingIdentity(identity); 17045 } 17046 } 17047 } 17048 17049 private static void enforceSystemOrPhoneCaller(String tag) { 17050 int callingUid = Binder.getCallingUid(); 17051 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17052 throw new SecurityException( 17053 "Cannot call " + tag + " from UID " + callingUid); 17054 } 17055 } 17056} 17057