PackageManagerService.java revision a57940dd76e4b0d18d6ab944a311276a634be98f
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.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 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.system.OsConstants.O_CREAT; 71import static android.system.OsConstants.O_RDWR; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 76import static com.android.internal.util.ArrayUtils.appendInt; 77import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 80import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 81import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 85 86import android.Manifest; 87import android.app.ActivityManager; 88import android.app.ActivityManagerNative; 89import android.app.AppGlobals; 90import android.app.IActivityManager; 91import android.app.admin.IDevicePolicyManager; 92import android.app.backup.IBackupManager; 93import android.app.usage.UsageStats; 94import android.app.usage.UsageStatsManager; 95import android.content.BroadcastReceiver; 96import android.content.ComponentName; 97import android.content.Context; 98import android.content.IIntentReceiver; 99import android.content.Intent; 100import android.content.IntentFilter; 101import android.content.IntentSender; 102import android.content.IntentSender.SendIntentException; 103import android.content.ServiceConnection; 104import android.content.pm.ActivityInfo; 105import android.content.pm.ApplicationInfo; 106import android.content.pm.FeatureInfo; 107import android.content.pm.IOnPermissionsChangeListener; 108import android.content.pm.IPackageDataObserver; 109import android.content.pm.IPackageDeleteObserver; 110import android.content.pm.IPackageDeleteObserver2; 111import android.content.pm.IPackageInstallObserver2; 112import android.content.pm.IPackageInstaller; 113import android.content.pm.IPackageManager; 114import android.content.pm.IPackageMoveObserver; 115import android.content.pm.IPackageStatsObserver; 116import android.content.pm.InstrumentationInfo; 117import android.content.pm.IntentFilterVerificationInfo; 118import android.content.pm.KeySet; 119import android.content.pm.ManifestDigest; 120import android.content.pm.PackageCleanItem; 121import android.content.pm.PackageInfo; 122import android.content.pm.PackageInfoLite; 123import android.content.pm.PackageInstaller; 124import android.content.pm.PackageManager; 125import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 126import android.content.pm.PackageManagerInternal; 127import android.content.pm.PackageParser; 128import android.content.pm.PackageParser.ActivityIntentInfo; 129import android.content.pm.PackageParser.PackageLite; 130import android.content.pm.PackageParser.PackageParserException; 131import android.content.pm.PackageStats; 132import android.content.pm.PackageUserState; 133import android.content.pm.ParceledListSlice; 134import android.content.pm.PermissionGroupInfo; 135import android.content.pm.PermissionInfo; 136import android.content.pm.ProviderInfo; 137import android.content.pm.ResolveInfo; 138import android.content.pm.ServiceInfo; 139import android.content.pm.Signature; 140import android.content.pm.UserInfo; 141import android.content.pm.VerificationParams; 142import android.content.pm.VerifierDeviceIdentity; 143import android.content.pm.VerifierInfo; 144import android.content.res.Resources; 145import android.hardware.display.DisplayManager; 146import android.net.Uri; 147import android.os.Debug; 148import android.os.Binder; 149import android.os.Build; 150import android.os.Bundle; 151import android.os.Environment; 152import android.os.Environment.UserEnvironment; 153import android.os.FileUtils; 154import android.os.Handler; 155import android.os.IBinder; 156import android.os.Looper; 157import android.os.Message; 158import android.os.Parcel; 159import android.os.ParcelFileDescriptor; 160import android.os.Process; 161import android.os.RemoteCallbackList; 162import android.os.RemoteException; 163import android.os.SELinux; 164import android.os.ServiceManager; 165import android.os.SystemClock; 166import android.os.SystemProperties; 167import android.os.UserHandle; 168import android.os.UserManager; 169import android.os.storage.IMountService; 170import android.os.storage.MountServiceInternal; 171import android.os.storage.StorageEventListener; 172import android.os.storage.StorageManager; 173import android.os.storage.VolumeInfo; 174import android.os.storage.VolumeRecord; 175import android.security.KeyStore; 176import android.security.SystemKeyStore; 177import android.system.ErrnoException; 178import android.system.Os; 179import android.system.StructStat; 180import android.text.TextUtils; 181import android.text.format.DateUtils; 182import android.util.ArrayMap; 183import android.util.ArraySet; 184import android.util.AtomicFile; 185import android.util.DisplayMetrics; 186import android.util.EventLog; 187import android.util.ExceptionUtils; 188import android.util.Log; 189import android.util.LogPrinter; 190import android.util.MathUtils; 191import android.util.PrintStreamPrinter; 192import android.util.Slog; 193import android.util.SparseArray; 194import android.util.SparseBooleanArray; 195import android.util.SparseIntArray; 196import android.util.Xml; 197import android.view.Display; 198 199import dalvik.system.DexFile; 200import dalvik.system.VMRuntime; 201 202import libcore.io.IoUtils; 203import libcore.util.EmptyArray; 204 205import com.android.internal.R; 206import com.android.internal.annotations.GuardedBy; 207import com.android.internal.app.IMediaContainerService; 208import com.android.internal.app.ResolverActivity; 209import com.android.internal.content.NativeLibraryHelper; 210import com.android.internal.content.PackageHelper; 211import com.android.internal.os.IParcelFileDescriptorFactory; 212import com.android.internal.os.SomeArgs; 213import com.android.internal.os.Zygote; 214import com.android.internal.util.ArrayUtils; 215import com.android.internal.util.FastPrintWriter; 216import com.android.internal.util.FastXmlSerializer; 217import com.android.internal.util.IndentingPrintWriter; 218import com.android.internal.util.Preconditions; 219import com.android.server.EventLogTags; 220import com.android.server.FgThread; 221import com.android.server.IntentResolver; 222import com.android.server.LocalServices; 223import com.android.server.ServiceThread; 224import com.android.server.SystemConfig; 225import com.android.server.Watchdog; 226import com.android.server.pm.PermissionsState.PermissionState; 227import com.android.server.pm.Settings.DatabaseVersion; 228import com.android.server.storage.DeviceStorageMonitorInternal; 229 230import org.xmlpull.v1.XmlPullParser; 231import org.xmlpull.v1.XmlPullParserException; 232import org.xmlpull.v1.XmlSerializer; 233 234import java.io.BufferedInputStream; 235import java.io.BufferedOutputStream; 236import java.io.BufferedReader; 237import java.io.ByteArrayInputStream; 238import java.io.ByteArrayOutputStream; 239import java.io.File; 240import java.io.FileDescriptor; 241import java.io.FileNotFoundException; 242import java.io.FileOutputStream; 243import java.io.FileReader; 244import java.io.FilenameFilter; 245import java.io.IOException; 246import java.io.InputStream; 247import java.io.PrintWriter; 248import java.nio.charset.StandardCharsets; 249import java.security.NoSuchAlgorithmException; 250import java.security.PublicKey; 251import java.security.cert.CertificateEncodingException; 252import java.security.cert.CertificateException; 253import java.text.SimpleDateFormat; 254import java.util.ArrayList; 255import java.util.Arrays; 256import java.util.Collection; 257import java.util.Collections; 258import java.util.Comparator; 259import java.util.Date; 260import java.util.Iterator; 261import java.util.List; 262import java.util.Map; 263import java.util.Objects; 264import java.util.Set; 265import java.util.concurrent.CountDownLatch; 266import java.util.concurrent.TimeUnit; 267import java.util.concurrent.atomic.AtomicBoolean; 268import java.util.concurrent.atomic.AtomicInteger; 269import java.util.concurrent.atomic.AtomicLong; 270 271/** 272 * Keep track of all those .apks everywhere. 273 * 274 * This is very central to the platform's security; please run the unit 275 * tests whenever making modifications here: 276 * 277runtest -c android.content.pm.PackageManagerTests frameworks-core 278 * 279 * {@hide} 280 */ 281public class PackageManagerService extends IPackageManager.Stub { 282 static final String TAG = "PackageManager"; 283 static final boolean DEBUG_SETTINGS = false; 284 static final boolean DEBUG_PREFERRED = false; 285 static final boolean DEBUG_UPGRADE = false; 286 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 287 private static final boolean DEBUG_BACKUP = false; 288 private static final boolean DEBUG_INSTALL = false; 289 private static final boolean DEBUG_REMOVE = false; 290 private static final boolean DEBUG_BROADCASTS = false; 291 private static final boolean DEBUG_SHOW_INFO = false; 292 private static final boolean DEBUG_PACKAGE_INFO = false; 293 private static final boolean DEBUG_INTENT_MATCHING = false; 294 private static final boolean DEBUG_PACKAGE_SCANNING = false; 295 private static final boolean DEBUG_VERIFY = false; 296 private static final boolean DEBUG_DEXOPT = false; 297 private static final boolean DEBUG_ABI_SELECTION = false; 298 299 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 300 301 private static final int RADIO_UID = Process.PHONE_UID; 302 private static final int LOG_UID = Process.LOG_UID; 303 private static final int NFC_UID = Process.NFC_UID; 304 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 305 private static final int SHELL_UID = Process.SHELL_UID; 306 307 // Cap the size of permission trees that 3rd party apps can define 308 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 309 310 // Suffix used during package installation when copying/moving 311 // package apks to install directory. 312 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 313 314 static final int SCAN_NO_DEX = 1<<1; 315 static final int SCAN_FORCE_DEX = 1<<2; 316 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 317 static final int SCAN_NEW_INSTALL = 1<<4; 318 static final int SCAN_NO_PATHS = 1<<5; 319 static final int SCAN_UPDATE_TIME = 1<<6; 320 static final int SCAN_DEFER_DEX = 1<<7; 321 static final int SCAN_BOOTING = 1<<8; 322 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 323 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 324 static final int SCAN_REQUIRE_KNOWN = 1<<12; 325 static final int SCAN_MOVE = 1<<13; 326 static final int SCAN_INITIAL = 1<<14; 327 328 static final int REMOVE_CHATTY = 1<<16; 329 330 private static final int[] EMPTY_INT_ARRAY = new int[0]; 331 332 /** 333 * Timeout (in milliseconds) after which the watchdog should declare that 334 * our handler thread is wedged. The usual default for such things is one 335 * minute but we sometimes do very lengthy I/O operations on this thread, 336 * such as installing multi-gigabyte applications, so ours needs to be longer. 337 */ 338 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 339 340 /** 341 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 342 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 343 * settings entry if available, otherwise we use the hardcoded default. If it's been 344 * more than this long since the last fstrim, we force one during the boot sequence. 345 * 346 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 347 * one gets run at the next available charging+idle time. This final mandatory 348 * no-fstrim check kicks in only of the other scheduling criteria is never met. 349 */ 350 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 351 352 /** 353 * Whether verification is enabled by default. 354 */ 355 private static final boolean DEFAULT_VERIFY_ENABLE = true; 356 357 /** 358 * The default maximum time to wait for the verification agent to return in 359 * milliseconds. 360 */ 361 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 362 363 /** 364 * The default response for package verification timeout. 365 * 366 * This can be either PackageManager.VERIFICATION_ALLOW or 367 * PackageManager.VERIFICATION_REJECT. 368 */ 369 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 370 371 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 372 373 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 374 DEFAULT_CONTAINER_PACKAGE, 375 "com.android.defcontainer.DefaultContainerService"); 376 377 private static final String KILL_APP_REASON_GIDS_CHANGED = 378 "permission grant or revoke changed gids"; 379 380 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 381 "permissions revoked"; 382 383 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 384 385 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 386 387 /** Permission grant: not grant the permission. */ 388 private static final int GRANT_DENIED = 1; 389 390 /** Permission grant: grant the permission as an install permission. */ 391 private static final int GRANT_INSTALL = 2; 392 393 /** Permission grant: grant the permission as an install permission for a legacy app. */ 394 private static final int GRANT_INSTALL_LEGACY = 3; 395 396 /** Permission grant: grant the permission as a runtime one. */ 397 private static final int GRANT_RUNTIME = 4; 398 399 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 400 private static final int GRANT_UPGRADE = 5; 401 402 /** Canonical intent used to identify what counts as a "web browser" app */ 403 private static final Intent sBrowserIntent; 404 static { 405 sBrowserIntent = new Intent(); 406 sBrowserIntent.setAction(Intent.ACTION_VIEW); 407 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 408 sBrowserIntent.setData(Uri.parse("http:")); 409 } 410 411 final ServiceThread mHandlerThread; 412 413 final PackageHandler mHandler; 414 415 /** 416 * Messages for {@link #mHandler} that need to wait for system ready before 417 * being dispatched. 418 */ 419 private ArrayList<Message> mPostSystemReadyMessages; 420 421 final int mSdkVersion = Build.VERSION.SDK_INT; 422 423 final Context mContext; 424 final boolean mFactoryTest; 425 final boolean mOnlyCore; 426 final boolean mLazyDexOpt; 427 final long mDexOptLRUThresholdInMills; 428 final DisplayMetrics mMetrics; 429 final int mDefParseFlags; 430 final String[] mSeparateProcesses; 431 final boolean mIsUpgrade; 432 433 // This is where all application persistent data goes. 434 final File mAppDataDir; 435 436 // This is where all application persistent data goes for secondary users. 437 final File mUserAppDataDir; 438 439 /** The location for ASEC container files on internal storage. */ 440 final String mAsecInternalPath; 441 442 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 443 // LOCK HELD. Can be called with mInstallLock held. 444 @GuardedBy("mInstallLock") 445 final Installer mInstaller; 446 447 /** Directory where installed third-party apps stored */ 448 final File mAppInstallDir; 449 450 /** 451 * Directory to which applications installed internally have their 452 * 32 bit native libraries copied. 453 */ 454 private File mAppLib32InstallDir; 455 456 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 457 // apps. 458 final File mDrmAppPrivateInstallDir; 459 460 // ---------------------------------------------------------------- 461 462 // Lock for state used when installing and doing other long running 463 // operations. Methods that must be called with this lock held have 464 // the suffix "LI". 465 final Object mInstallLock = new Object(); 466 467 // ---------------------------------------------------------------- 468 469 // Keys are String (package name), values are Package. This also serves 470 // as the lock for the global state. Methods that must be called with 471 // this lock held have the prefix "LP". 472 @GuardedBy("mPackages") 473 final ArrayMap<String, PackageParser.Package> mPackages = 474 new ArrayMap<String, PackageParser.Package>(); 475 476 // Tracks available target package names -> overlay package paths. 477 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 478 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 479 480 /** 481 * Tracks new system packages [receiving in an OTA] that we expect to 482 * find updated user-installed versions. Keys are package name, values 483 * are package location. 484 */ 485 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 486 487 final Settings mSettings; 488 boolean mRestoredSettings; 489 490 // System configuration read by SystemConfig. 491 final int[] mGlobalGids; 492 final SparseArray<ArraySet<String>> mSystemPermissions; 493 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 494 495 // If mac_permissions.xml was found for seinfo labeling. 496 boolean mFoundPolicyFile; 497 498 // If a recursive restorecon of /data/data/<pkg> is needed. 499 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 500 501 public static final class SharedLibraryEntry { 502 public final String path; 503 public final String apk; 504 505 SharedLibraryEntry(String _path, String _apk) { 506 path = _path; 507 apk = _apk; 508 } 509 } 510 511 // Currently known shared libraries. 512 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 513 new ArrayMap<String, SharedLibraryEntry>(); 514 515 // All available activities, for your resolving pleasure. 516 final ActivityIntentResolver mActivities = 517 new ActivityIntentResolver(); 518 519 // All available receivers, for your resolving pleasure. 520 final ActivityIntentResolver mReceivers = 521 new ActivityIntentResolver(); 522 523 // All available services, for your resolving pleasure. 524 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 525 526 // All available providers, for your resolving pleasure. 527 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 528 529 // Mapping from provider base names (first directory in content URI codePath) 530 // to the provider information. 531 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 532 new ArrayMap<String, PackageParser.Provider>(); 533 534 // Mapping from instrumentation class names to info about them. 535 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 536 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 537 538 // Mapping from permission names to info about them. 539 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 540 new ArrayMap<String, PackageParser.PermissionGroup>(); 541 542 // Packages whose data we have transfered into another package, thus 543 // should no longer exist. 544 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 545 546 // Broadcast actions that are only available to the system. 547 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 548 549 /** List of packages waiting for verification. */ 550 final SparseArray<PackageVerificationState> mPendingVerification 551 = new SparseArray<PackageVerificationState>(); 552 553 /** Set of packages associated with each app op permission. */ 554 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 555 556 final PackageInstallerService mInstallerService; 557 558 private final PackageDexOptimizer mPackageDexOptimizer; 559 560 private AtomicInteger mNextMoveId = new AtomicInteger(); 561 private final MoveCallbacks mMoveCallbacks; 562 563 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 564 565 // Cache of users who need badging. 566 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 567 568 /** Token for keys in mPendingVerification. */ 569 private int mPendingVerificationToken = 0; 570 571 volatile boolean mSystemReady; 572 volatile boolean mSafeMode; 573 volatile boolean mHasSystemUidErrors; 574 575 ApplicationInfo mAndroidApplication; 576 final ActivityInfo mResolveActivity = new ActivityInfo(); 577 final ResolveInfo mResolveInfo = new ResolveInfo(); 578 ComponentName mResolveComponentName; 579 PackageParser.Package mPlatformPackage; 580 ComponentName mCustomResolverComponentName; 581 582 boolean mResolverReplaced = false; 583 584 private final ComponentName mIntentFilterVerifierComponent; 585 private int mIntentFilterVerificationToken = 0; 586 587 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 588 = new SparseArray<IntentFilterVerificationState>(); 589 590 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 591 new DefaultPermissionGrantPolicy(this); 592 593 private static class IFVerificationParams { 594 PackageParser.Package pkg; 595 boolean replacing; 596 int userId; 597 int verifierUid; 598 599 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 600 int _userId, int _verifierUid) { 601 pkg = _pkg; 602 replacing = _replacing; 603 userId = _userId; 604 replacing = _replacing; 605 verifierUid = _verifierUid; 606 } 607 } 608 609 private interface IntentFilterVerifier<T extends IntentFilter> { 610 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 611 T filter, String packageName); 612 void startVerifications(int userId); 613 void receiveVerificationResponse(int verificationId); 614 } 615 616 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 617 private Context mContext; 618 private ComponentName mIntentFilterVerifierComponent; 619 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 620 621 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 622 mContext = context; 623 mIntentFilterVerifierComponent = verifierComponent; 624 } 625 626 private String getDefaultScheme() { 627 return IntentFilter.SCHEME_HTTPS; 628 } 629 630 @Override 631 public void startVerifications(int userId) { 632 // Launch verifications requests 633 int count = mCurrentIntentFilterVerifications.size(); 634 for (int n=0; n<count; n++) { 635 int verificationId = mCurrentIntentFilterVerifications.get(n); 636 final IntentFilterVerificationState ivs = 637 mIntentFilterVerificationStates.get(verificationId); 638 639 String packageName = ivs.getPackageName(); 640 641 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 642 final int filterCount = filters.size(); 643 ArraySet<String> domainsSet = new ArraySet<>(); 644 for (int m=0; m<filterCount; m++) { 645 PackageParser.ActivityIntentInfo filter = filters.get(m); 646 domainsSet.addAll(filter.getHostsList()); 647 } 648 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 649 synchronized (mPackages) { 650 if (mSettings.createIntentFilterVerificationIfNeededLPw( 651 packageName, domainsList) != null) { 652 scheduleWriteSettingsLocked(); 653 } 654 } 655 sendVerificationRequest(userId, verificationId, ivs); 656 } 657 mCurrentIntentFilterVerifications.clear(); 658 } 659 660 private void sendVerificationRequest(int userId, int verificationId, 661 IntentFilterVerificationState ivs) { 662 663 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 664 verificationIntent.putExtra( 665 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 666 verificationId); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 669 getDefaultScheme()); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 672 ivs.getHostsString()); 673 verificationIntent.putExtra( 674 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 675 ivs.getPackageName()); 676 verificationIntent.setComponent(mIntentFilterVerifierComponent); 677 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 678 679 UserHandle user = new UserHandle(userId); 680 mContext.sendBroadcastAsUser(verificationIntent, user); 681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 682 "Sending IntentFilter verification broadcast"); 683 } 684 685 public void receiveVerificationResponse(int verificationId) { 686 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 687 688 final boolean verified = ivs.isVerified(); 689 690 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 691 final int count = filters.size(); 692 if (DEBUG_DOMAIN_VERIFICATION) { 693 Slog.i(TAG, "Received verification response " + verificationId 694 + " for " + count + " filters, verified=" + verified); 695 } 696 for (int n=0; n<count; n++) { 697 PackageParser.ActivityIntentInfo filter = filters.get(n); 698 filter.setVerified(verified); 699 700 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 701 + " verified with result:" + verified + " and hosts:" 702 + ivs.getHostsString()); 703 } 704 705 mIntentFilterVerificationStates.remove(verificationId); 706 707 final String packageName = ivs.getPackageName(); 708 IntentFilterVerificationInfo ivi = null; 709 710 synchronized (mPackages) { 711 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 712 } 713 if (ivi == null) { 714 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 715 + verificationId + " packageName:" + packageName); 716 return; 717 } 718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 719 "Updating IntentFilterVerificationInfo for package " + packageName 720 +" verificationId:" + verificationId); 721 722 synchronized (mPackages) { 723 if (verified) { 724 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 725 } else { 726 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 727 } 728 scheduleWriteSettingsLocked(); 729 730 final int userId = ivs.getUserId(); 731 if (userId != UserHandle.USER_ALL) { 732 final int userStatus = 733 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 734 735 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 736 boolean needUpdate = false; 737 738 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 739 // already been set by the User thru the Disambiguation dialog 740 switch (userStatus) { 741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 742 if (verified) { 743 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 744 } else { 745 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 746 } 747 needUpdate = true; 748 break; 749 750 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 751 if (verified) { 752 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 753 needUpdate = true; 754 } 755 break; 756 757 default: 758 // Nothing to do 759 } 760 761 if (needUpdate) { 762 mSettings.updateIntentFilterVerificationStatusLPw( 763 packageName, updatedStatus, userId); 764 scheduleWritePackageRestrictionsLocked(userId); 765 } 766 } 767 } 768 } 769 770 @Override 771 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 772 ActivityIntentInfo filter, String packageName) { 773 if (!hasValidDomains(filter)) { 774 return false; 775 } 776 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 777 if (ivs == null) { 778 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 779 packageName); 780 } 781 if (DEBUG_DOMAIN_VERIFICATION) { 782 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 783 } 784 ivs.addFilter(filter); 785 return true; 786 } 787 788 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 789 int userId, int verificationId, String packageName) { 790 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 791 verifierUid, userId, packageName); 792 ivs.setPendingState(); 793 synchronized (mPackages) { 794 mIntentFilterVerificationStates.append(verificationId, ivs); 795 mCurrentIntentFilterVerifications.add(verificationId); 796 } 797 return ivs; 798 } 799 } 800 801 private static boolean hasValidDomains(ActivityIntentInfo filter) { 802 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 803 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 804 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 805 } 806 807 private IntentFilterVerifier mIntentFilterVerifier; 808 809 // Set of pending broadcasts for aggregating enable/disable of components. 810 static class PendingPackageBroadcasts { 811 // for each user id, a map of <package name -> components within that package> 812 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 813 814 public PendingPackageBroadcasts() { 815 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 816 } 817 818 public ArrayList<String> get(int userId, String packageName) { 819 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 820 return packages.get(packageName); 821 } 822 823 public void put(int userId, String packageName, ArrayList<String> components) { 824 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 825 packages.put(packageName, components); 826 } 827 828 public void remove(int userId, String packageName) { 829 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 830 if (packages != null) { 831 packages.remove(packageName); 832 } 833 } 834 835 public void remove(int userId) { 836 mUidMap.remove(userId); 837 } 838 839 public int userIdCount() { 840 return mUidMap.size(); 841 } 842 843 public int userIdAt(int n) { 844 return mUidMap.keyAt(n); 845 } 846 847 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 848 return mUidMap.get(userId); 849 } 850 851 public int size() { 852 // total number of pending broadcast entries across all userIds 853 int num = 0; 854 for (int i = 0; i< mUidMap.size(); i++) { 855 num += mUidMap.valueAt(i).size(); 856 } 857 return num; 858 } 859 860 public void clear() { 861 mUidMap.clear(); 862 } 863 864 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 865 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 866 if (map == null) { 867 map = new ArrayMap<String, ArrayList<String>>(); 868 mUidMap.put(userId, map); 869 } 870 return map; 871 } 872 } 873 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 874 875 // Service Connection to remote media container service to copy 876 // package uri's from external media onto secure containers 877 // or internal storage. 878 private IMediaContainerService mContainerService = null; 879 880 static final int SEND_PENDING_BROADCAST = 1; 881 static final int MCS_BOUND = 3; 882 static final int END_COPY = 4; 883 static final int INIT_COPY = 5; 884 static final int MCS_UNBIND = 6; 885 static final int START_CLEANING_PACKAGE = 7; 886 static final int FIND_INSTALL_LOC = 8; 887 static final int POST_INSTALL = 9; 888 static final int MCS_RECONNECT = 10; 889 static final int MCS_GIVE_UP = 11; 890 static final int UPDATED_MEDIA_STATUS = 12; 891 static final int WRITE_SETTINGS = 13; 892 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 893 static final int PACKAGE_VERIFIED = 15; 894 static final int CHECK_PENDING_VERIFICATION = 16; 895 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 896 static final int INTENT_FILTER_VERIFIED = 18; 897 898 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 899 900 // Delay time in millisecs 901 static final int BROADCAST_DELAY = 10 * 1000; 902 903 static UserManagerService sUserManager; 904 905 // Stores a list of users whose package restrictions file needs to be updated 906 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 907 908 final private DefaultContainerConnection mDefContainerConn = 909 new DefaultContainerConnection(); 910 class DefaultContainerConnection implements ServiceConnection { 911 public void onServiceConnected(ComponentName name, IBinder service) { 912 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 913 IMediaContainerService imcs = 914 IMediaContainerService.Stub.asInterface(service); 915 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 916 } 917 918 public void onServiceDisconnected(ComponentName name) { 919 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 920 } 921 } 922 923 // Recordkeeping of restore-after-install operations that are currently in flight 924 // between the Package Manager and the Backup Manager 925 class PostInstallData { 926 public InstallArgs args; 927 public PackageInstalledInfo res; 928 929 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 930 args = _a; 931 res = _r; 932 } 933 } 934 935 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 936 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 937 938 // XML tags for backup/restore of various bits of state 939 private static final String TAG_PREFERRED_BACKUP = "pa"; 940 private static final String TAG_DEFAULT_APPS = "da"; 941 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 942 943 final String mRequiredVerifierPackage; 944 final String mRequiredInstallerPackage; 945 946 private final PackageUsage mPackageUsage = new PackageUsage(); 947 948 private class PackageUsage { 949 private static final int WRITE_INTERVAL 950 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 951 952 private final Object mFileLock = new Object(); 953 private final AtomicLong mLastWritten = new AtomicLong(0); 954 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 955 956 private boolean mIsHistoricalPackageUsageAvailable = true; 957 958 boolean isHistoricalPackageUsageAvailable() { 959 return mIsHistoricalPackageUsageAvailable; 960 } 961 962 void write(boolean force) { 963 if (force) { 964 writeInternal(); 965 return; 966 } 967 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 968 && !DEBUG_DEXOPT) { 969 return; 970 } 971 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 972 new Thread("PackageUsage_DiskWriter") { 973 @Override 974 public void run() { 975 try { 976 writeInternal(); 977 } finally { 978 mBackgroundWriteRunning.set(false); 979 } 980 } 981 }.start(); 982 } 983 } 984 985 private void writeInternal() { 986 synchronized (mPackages) { 987 synchronized (mFileLock) { 988 AtomicFile file = getFile(); 989 FileOutputStream f = null; 990 try { 991 f = file.startWrite(); 992 BufferedOutputStream out = new BufferedOutputStream(f); 993 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 994 StringBuilder sb = new StringBuilder(); 995 for (PackageParser.Package pkg : mPackages.values()) { 996 if (pkg.mLastPackageUsageTimeInMills == 0) { 997 continue; 998 } 999 sb.setLength(0); 1000 sb.append(pkg.packageName); 1001 sb.append(' '); 1002 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1003 sb.append('\n'); 1004 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1005 } 1006 out.flush(); 1007 file.finishWrite(f); 1008 } catch (IOException e) { 1009 if (f != null) { 1010 file.failWrite(f); 1011 } 1012 Log.e(TAG, "Failed to write package usage times", e); 1013 } 1014 } 1015 } 1016 mLastWritten.set(SystemClock.elapsedRealtime()); 1017 } 1018 1019 void readLP() { 1020 synchronized (mFileLock) { 1021 AtomicFile file = getFile(); 1022 BufferedInputStream in = null; 1023 try { 1024 in = new BufferedInputStream(file.openRead()); 1025 StringBuffer sb = new StringBuffer(); 1026 while (true) { 1027 String packageName = readToken(in, sb, ' '); 1028 if (packageName == null) { 1029 break; 1030 } 1031 String timeInMillisString = readToken(in, sb, '\n'); 1032 if (timeInMillisString == null) { 1033 throw new IOException("Failed to find last usage time for package " 1034 + packageName); 1035 } 1036 PackageParser.Package pkg = mPackages.get(packageName); 1037 if (pkg == null) { 1038 continue; 1039 } 1040 long timeInMillis; 1041 try { 1042 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1043 } catch (NumberFormatException e) { 1044 throw new IOException("Failed to parse " + timeInMillisString 1045 + " as a long.", e); 1046 } 1047 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1048 } 1049 } catch (FileNotFoundException expected) { 1050 mIsHistoricalPackageUsageAvailable = false; 1051 } catch (IOException e) { 1052 Log.w(TAG, "Failed to read package usage times", e); 1053 } finally { 1054 IoUtils.closeQuietly(in); 1055 } 1056 } 1057 mLastWritten.set(SystemClock.elapsedRealtime()); 1058 } 1059 1060 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1061 throws IOException { 1062 sb.setLength(0); 1063 while (true) { 1064 int ch = in.read(); 1065 if (ch == -1) { 1066 if (sb.length() == 0) { 1067 return null; 1068 } 1069 throw new IOException("Unexpected EOF"); 1070 } 1071 if (ch == endOfToken) { 1072 return sb.toString(); 1073 } 1074 sb.append((char)ch); 1075 } 1076 } 1077 1078 private AtomicFile getFile() { 1079 File dataDir = Environment.getDataDirectory(); 1080 File systemDir = new File(dataDir, "system"); 1081 File fname = new File(systemDir, "package-usage.list"); 1082 return new AtomicFile(fname); 1083 } 1084 } 1085 1086 class PackageHandler extends Handler { 1087 private boolean mBound = false; 1088 final ArrayList<HandlerParams> mPendingInstalls = 1089 new ArrayList<HandlerParams>(); 1090 1091 private boolean connectToService() { 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1093 " DefaultContainerService"); 1094 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1095 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1096 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1097 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1099 mBound = true; 1100 return true; 1101 } 1102 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1103 return false; 1104 } 1105 1106 private void disconnectService() { 1107 mContainerService = null; 1108 mBound = false; 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 mContext.unbindService(mDefContainerConn); 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 } 1113 1114 PackageHandler(Looper looper) { 1115 super(looper); 1116 } 1117 1118 public void handleMessage(Message msg) { 1119 try { 1120 doHandleMessage(msg); 1121 } finally { 1122 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1123 } 1124 } 1125 1126 void doHandleMessage(Message msg) { 1127 switch (msg.what) { 1128 case INIT_COPY: { 1129 HandlerParams params = (HandlerParams) msg.obj; 1130 int idx = mPendingInstalls.size(); 1131 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1132 // If a bind was already initiated we dont really 1133 // need to do anything. The pending install 1134 // will be processed later on. 1135 if (!mBound) { 1136 // If this is the only one pending we might 1137 // have to bind to the service again. 1138 if (!connectToService()) { 1139 Slog.e(TAG, "Failed to bind to media container service"); 1140 params.serviceError(); 1141 return; 1142 } else { 1143 // Once we bind to the service, the first 1144 // pending request will be processed. 1145 mPendingInstalls.add(idx, params); 1146 } 1147 } else { 1148 mPendingInstalls.add(idx, params); 1149 // Already bound to the service. Just make 1150 // sure we trigger off processing the first request. 1151 if (idx == 0) { 1152 mHandler.sendEmptyMessage(MCS_BOUND); 1153 } 1154 } 1155 break; 1156 } 1157 case MCS_BOUND: { 1158 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1159 if (msg.obj != null) { 1160 mContainerService = (IMediaContainerService) msg.obj; 1161 } 1162 if (mContainerService == null) { 1163 if (!mBound) { 1164 // Something seriously wrong since we are not bound and we are not 1165 // waiting for connection. Bail out. 1166 Slog.e(TAG, "Cannot bind to media container service"); 1167 for (HandlerParams params : mPendingInstalls) { 1168 // Indicate service bind error 1169 params.serviceError(); 1170 } 1171 mPendingInstalls.clear(); 1172 } else { 1173 Slog.w(TAG, "Waiting to connect to media container service"); 1174 } 1175 } else if (mPendingInstalls.size() > 0) { 1176 HandlerParams params = mPendingInstalls.get(0); 1177 if (params != null) { 1178 if (params.startCopy()) { 1179 // We are done... look for more work or to 1180 // go idle. 1181 if (DEBUG_SD_INSTALL) Log.i(TAG, 1182 "Checking for more work or unbind..."); 1183 // Delete pending install 1184 if (mPendingInstalls.size() > 0) { 1185 mPendingInstalls.remove(0); 1186 } 1187 if (mPendingInstalls.size() == 0) { 1188 if (mBound) { 1189 if (DEBUG_SD_INSTALL) Log.i(TAG, 1190 "Posting delayed MCS_UNBIND"); 1191 removeMessages(MCS_UNBIND); 1192 Message ubmsg = obtainMessage(MCS_UNBIND); 1193 // Unbind after a little delay, to avoid 1194 // continual thrashing. 1195 sendMessageDelayed(ubmsg, 10000); 1196 } 1197 } else { 1198 // There are more pending requests in queue. 1199 // Just post MCS_BOUND message to trigger processing 1200 // of next pending install. 1201 if (DEBUG_SD_INSTALL) Log.i(TAG, 1202 "Posting MCS_BOUND for next work"); 1203 mHandler.sendEmptyMessage(MCS_BOUND); 1204 } 1205 } 1206 } 1207 } else { 1208 // Should never happen ideally. 1209 Slog.w(TAG, "Empty queue"); 1210 } 1211 break; 1212 } 1213 case MCS_RECONNECT: { 1214 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1215 if (mPendingInstalls.size() > 0) { 1216 if (mBound) { 1217 disconnectService(); 1218 } 1219 if (!connectToService()) { 1220 Slog.e(TAG, "Failed to bind to media container service"); 1221 for (HandlerParams params : mPendingInstalls) { 1222 // Indicate service bind error 1223 params.serviceError(); 1224 } 1225 mPendingInstalls.clear(); 1226 } 1227 } 1228 break; 1229 } 1230 case MCS_UNBIND: { 1231 // If there is no actual work left, then time to unbind. 1232 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1233 1234 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1235 if (mBound) { 1236 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1237 1238 disconnectService(); 1239 } 1240 } else if (mPendingInstalls.size() > 0) { 1241 // There are more pending requests in queue. 1242 // Just post MCS_BOUND message to trigger processing 1243 // of next pending install. 1244 mHandler.sendEmptyMessage(MCS_BOUND); 1245 } 1246 1247 break; 1248 } 1249 case MCS_GIVE_UP: { 1250 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1251 mPendingInstalls.remove(0); 1252 break; 1253 } 1254 case SEND_PENDING_BROADCAST: { 1255 String packages[]; 1256 ArrayList<String> components[]; 1257 int size = 0; 1258 int uids[]; 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1260 synchronized (mPackages) { 1261 if (mPendingBroadcasts == null) { 1262 return; 1263 } 1264 size = mPendingBroadcasts.size(); 1265 if (size <= 0) { 1266 // Nothing to be done. Just return 1267 return; 1268 } 1269 packages = new String[size]; 1270 components = new ArrayList[size]; 1271 uids = new int[size]; 1272 int i = 0; // filling out the above arrays 1273 1274 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1275 int packageUserId = mPendingBroadcasts.userIdAt(n); 1276 Iterator<Map.Entry<String, ArrayList<String>>> it 1277 = mPendingBroadcasts.packagesForUserId(packageUserId) 1278 .entrySet().iterator(); 1279 while (it.hasNext() && i < size) { 1280 Map.Entry<String, ArrayList<String>> ent = it.next(); 1281 packages[i] = ent.getKey(); 1282 components[i] = ent.getValue(); 1283 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1284 uids[i] = (ps != null) 1285 ? UserHandle.getUid(packageUserId, ps.appId) 1286 : -1; 1287 i++; 1288 } 1289 } 1290 size = i; 1291 mPendingBroadcasts.clear(); 1292 } 1293 // Send broadcasts 1294 for (int i = 0; i < size; i++) { 1295 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1296 } 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1298 break; 1299 } 1300 case START_CLEANING_PACKAGE: { 1301 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1302 final String packageName = (String)msg.obj; 1303 final int userId = msg.arg1; 1304 final boolean andCode = msg.arg2 != 0; 1305 synchronized (mPackages) { 1306 if (userId == UserHandle.USER_ALL) { 1307 int[] users = sUserManager.getUserIds(); 1308 for (int user : users) { 1309 mSettings.addPackageToCleanLPw( 1310 new PackageCleanItem(user, packageName, andCode)); 1311 } 1312 } else { 1313 mSettings.addPackageToCleanLPw( 1314 new PackageCleanItem(userId, packageName, andCode)); 1315 } 1316 } 1317 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1318 startCleaningPackages(); 1319 } break; 1320 case POST_INSTALL: { 1321 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1322 PostInstallData data = mRunningInstalls.get(msg.arg1); 1323 mRunningInstalls.delete(msg.arg1); 1324 boolean deleteOld = false; 1325 1326 if (data != null) { 1327 InstallArgs args = data.args; 1328 PackageInstalledInfo res = data.res; 1329 1330 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1331 final String packageName = res.pkg.applicationInfo.packageName; 1332 res.removedInfo.sendBroadcast(false, true, false); 1333 Bundle extras = new Bundle(1); 1334 extras.putInt(Intent.EXTRA_UID, res.uid); 1335 1336 // Now that we successfully installed the package, grant runtime 1337 // permissions if requested before broadcasting the install. 1338 if ((args.installFlags 1339 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1340 grantRequestedRuntimePermissions(res.pkg, 1341 args.user.getIdentifier()); 1342 } 1343 1344 // Determine the set of users who are adding this 1345 // package for the first time vs. those who are seeing 1346 // an update. 1347 int[] firstUsers; 1348 int[] updateUsers = new int[0]; 1349 if (res.origUsers == null || res.origUsers.length == 0) { 1350 firstUsers = res.newUsers; 1351 } else { 1352 firstUsers = new int[0]; 1353 for (int i=0; i<res.newUsers.length; i++) { 1354 int user = res.newUsers[i]; 1355 boolean isNew = true; 1356 for (int j=0; j<res.origUsers.length; j++) { 1357 if (res.origUsers[j] == user) { 1358 isNew = false; 1359 break; 1360 } 1361 } 1362 if (isNew) { 1363 int[] newFirst = new int[firstUsers.length+1]; 1364 System.arraycopy(firstUsers, 0, newFirst, 0, 1365 firstUsers.length); 1366 newFirst[firstUsers.length] = user; 1367 firstUsers = newFirst; 1368 } else { 1369 int[] newUpdate = new int[updateUsers.length+1]; 1370 System.arraycopy(updateUsers, 0, newUpdate, 0, 1371 updateUsers.length); 1372 newUpdate[updateUsers.length] = user; 1373 updateUsers = newUpdate; 1374 } 1375 } 1376 } 1377 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1378 packageName, extras, null, null, firstUsers); 1379 final boolean update = res.removedInfo.removedPackage != null; 1380 if (update) { 1381 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1382 } 1383 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1384 packageName, extras, null, null, updateUsers); 1385 if (update) { 1386 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1387 packageName, extras, null, null, updateUsers); 1388 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1389 null, null, packageName, null, updateUsers); 1390 1391 // treat asec-hosted packages like removable media on upgrade 1392 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1393 if (DEBUG_INSTALL) { 1394 Slog.i(TAG, "upgrading pkg " + res.pkg 1395 + " is ASEC-hosted -> AVAILABLE"); 1396 } 1397 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1398 ArrayList<String> pkgList = new ArrayList<String>(1); 1399 pkgList.add(packageName); 1400 sendResourcesChangedBroadcast(true, true, 1401 pkgList,uidArray, null); 1402 } 1403 } 1404 if (res.removedInfo.args != null) { 1405 // Remove the replaced package's older resources safely now 1406 deleteOld = true; 1407 } 1408 1409 // If this app is a browser and it's newly-installed for some 1410 // users, clear any default-browser state in those users 1411 if (firstUsers.length > 0) { 1412 // the app's nature doesn't depend on the user, so we can just 1413 // check its browser nature in any user and generalize. 1414 if (packageIsBrowser(packageName, firstUsers[0])) { 1415 synchronized (mPackages) { 1416 for (int userId : firstUsers) { 1417 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1418 } 1419 } 1420 } 1421 } 1422 // Log current value of "unknown sources" setting 1423 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1424 getUnknownSourcesSettings()); 1425 } 1426 // Force a gc to clear up things 1427 Runtime.getRuntime().gc(); 1428 // We delete after a gc for applications on sdcard. 1429 if (deleteOld) { 1430 synchronized (mInstallLock) { 1431 res.removedInfo.args.doPostDeleteLI(true); 1432 } 1433 } 1434 if (args.observer != null) { 1435 try { 1436 Bundle extras = extrasForInstallResult(res); 1437 args.observer.onPackageInstalled(res.name, res.returnCode, 1438 res.returnMsg, extras); 1439 } catch (RemoteException e) { 1440 Slog.i(TAG, "Observer no longer exists."); 1441 } 1442 } 1443 } else { 1444 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1445 } 1446 } break; 1447 case UPDATED_MEDIA_STATUS: { 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1449 boolean reportStatus = msg.arg1 == 1; 1450 boolean doGc = msg.arg2 == 1; 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1452 if (doGc) { 1453 // Force a gc to clear up stale containers. 1454 Runtime.getRuntime().gc(); 1455 } 1456 if (msg.obj != null) { 1457 @SuppressWarnings("unchecked") 1458 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1460 // Unload containers 1461 unloadAllContainers(args); 1462 } 1463 if (reportStatus) { 1464 try { 1465 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1466 PackageHelper.getMountService().finishMediaUpdate(); 1467 } catch (RemoteException e) { 1468 Log.e(TAG, "MountService not running?"); 1469 } 1470 } 1471 } break; 1472 case WRITE_SETTINGS: { 1473 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1474 synchronized (mPackages) { 1475 removeMessages(WRITE_SETTINGS); 1476 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1477 mSettings.writeLPr(); 1478 mDirtyUsers.clear(); 1479 } 1480 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1481 } break; 1482 case WRITE_PACKAGE_RESTRICTIONS: { 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1484 synchronized (mPackages) { 1485 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1486 for (int userId : mDirtyUsers) { 1487 mSettings.writePackageRestrictionsLPr(userId); 1488 } 1489 mDirtyUsers.clear(); 1490 } 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1492 } break; 1493 case CHECK_PENDING_VERIFICATION: { 1494 final int verificationId = msg.arg1; 1495 final PackageVerificationState state = mPendingVerification.get(verificationId); 1496 1497 if ((state != null) && !state.timeoutExtended()) { 1498 final InstallArgs args = state.getInstallArgs(); 1499 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1500 1501 Slog.i(TAG, "Verification timed out for " + originUri); 1502 mPendingVerification.remove(verificationId); 1503 1504 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1505 1506 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1507 Slog.i(TAG, "Continuing with installation of " + originUri); 1508 state.setVerifierResponse(Binder.getCallingUid(), 1509 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1510 broadcastPackageVerified(verificationId, originUri, 1511 PackageManager.VERIFICATION_ALLOW, 1512 state.getInstallArgs().getUser()); 1513 try { 1514 ret = args.copyApk(mContainerService, true); 1515 } catch (RemoteException e) { 1516 Slog.e(TAG, "Could not contact the ContainerService"); 1517 } 1518 } else { 1519 broadcastPackageVerified(verificationId, originUri, 1520 PackageManager.VERIFICATION_REJECT, 1521 state.getInstallArgs().getUser()); 1522 } 1523 1524 processPendingInstall(args, ret); 1525 mHandler.sendEmptyMessage(MCS_UNBIND); 1526 } 1527 break; 1528 } 1529 case PACKAGE_VERIFIED: { 1530 final int verificationId = msg.arg1; 1531 1532 final PackageVerificationState state = mPendingVerification.get(verificationId); 1533 if (state == null) { 1534 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1535 break; 1536 } 1537 1538 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1539 1540 state.setVerifierResponse(response.callerUid, response.code); 1541 1542 if (state.isVerificationComplete()) { 1543 mPendingVerification.remove(verificationId); 1544 1545 final InstallArgs args = state.getInstallArgs(); 1546 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1547 1548 int ret; 1549 if (state.isInstallAllowed()) { 1550 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1551 broadcastPackageVerified(verificationId, originUri, 1552 response.code, state.getInstallArgs().getUser()); 1553 try { 1554 ret = args.copyApk(mContainerService, true); 1555 } catch (RemoteException e) { 1556 Slog.e(TAG, "Could not contact the ContainerService"); 1557 } 1558 } else { 1559 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1560 } 1561 1562 processPendingInstall(args, ret); 1563 1564 mHandler.sendEmptyMessage(MCS_UNBIND); 1565 } 1566 1567 break; 1568 } 1569 case START_INTENT_FILTER_VERIFICATIONS: { 1570 IFVerificationParams params = (IFVerificationParams) msg.obj; 1571 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1572 params.replacing, params.pkg); 1573 break; 1574 } 1575 case INTENT_FILTER_VERIFIED: { 1576 final int verificationId = msg.arg1; 1577 1578 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1579 verificationId); 1580 if (state == null) { 1581 Slog.w(TAG, "Invalid IntentFilter verification token " 1582 + verificationId + " received"); 1583 break; 1584 } 1585 1586 final int userId = state.getUserId(); 1587 1588 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1589 "Processing IntentFilter verification with token:" 1590 + verificationId + " and userId:" + userId); 1591 1592 final IntentFilterVerificationResponse response = 1593 (IntentFilterVerificationResponse) msg.obj; 1594 1595 state.setVerifierResponse(response.callerUid, response.code); 1596 1597 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1598 "IntentFilter verification with token:" + verificationId 1599 + " and userId:" + userId 1600 + " is settings verifier response with response code:" 1601 + response.code); 1602 1603 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1604 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1605 + response.getFailedDomainsString()); 1606 } 1607 1608 if (state.isVerificationComplete()) { 1609 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1610 } else { 1611 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1612 "IntentFilter verification with token:" + verificationId 1613 + " was not said to be complete"); 1614 } 1615 1616 break; 1617 } 1618 } 1619 } 1620 } 1621 1622 private StorageEventListener mStorageListener = new StorageEventListener() { 1623 @Override 1624 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1625 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1626 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1627 final String volumeUuid = vol.getFsUuid(); 1628 1629 // Clean up any users or apps that were removed or recreated 1630 // while this volume was missing 1631 reconcileUsers(volumeUuid); 1632 reconcileApps(volumeUuid); 1633 1634 // Clean up any install sessions that expired or were 1635 // cancelled while this volume was missing 1636 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1637 1638 loadPrivatePackages(vol); 1639 1640 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1641 unloadPrivatePackages(vol); 1642 } 1643 } 1644 1645 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1646 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1647 updateExternalMediaStatus(true, false); 1648 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1649 updateExternalMediaStatus(false, false); 1650 } 1651 } 1652 } 1653 1654 @Override 1655 public void onVolumeForgotten(String fsUuid) { 1656 // Remove any apps installed on the forgotten volume 1657 synchronized (mPackages) { 1658 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1659 for (PackageSetting ps : packages) { 1660 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1661 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1662 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1663 } 1664 1665 mSettings.writeLPr(); 1666 } 1667 } 1668 }; 1669 1670 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1671 if (userId >= UserHandle.USER_OWNER) { 1672 grantRequestedRuntimePermissionsForUser(pkg, userId); 1673 } else if (userId == UserHandle.USER_ALL) { 1674 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1675 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1676 } 1677 } 1678 1679 // We could have touched GID membership, so flush out packages.list 1680 synchronized (mPackages) { 1681 mSettings.writePackageListLPr(); 1682 } 1683 } 1684 1685 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1686 SettingBase sb = (SettingBase) pkg.mExtras; 1687 if (sb == null) { 1688 return; 1689 } 1690 1691 PermissionsState permissionsState = sb.getPermissionsState(); 1692 1693 for (String permission : pkg.requestedPermissions) { 1694 BasePermission bp = mSettings.mPermissions.get(permission); 1695 if (bp != null && bp.isRuntime()) { 1696 permissionsState.grantRuntimePermission(bp, userId); 1697 } 1698 } 1699 } 1700 1701 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1702 Bundle extras = null; 1703 switch (res.returnCode) { 1704 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1705 extras = new Bundle(); 1706 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1707 res.origPermission); 1708 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1709 res.origPackage); 1710 break; 1711 } 1712 case PackageManager.INSTALL_SUCCEEDED: { 1713 extras = new Bundle(); 1714 extras.putBoolean(Intent.EXTRA_REPLACING, 1715 res.removedInfo != null && res.removedInfo.removedPackage != null); 1716 break; 1717 } 1718 } 1719 return extras; 1720 } 1721 1722 void scheduleWriteSettingsLocked() { 1723 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1724 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1725 } 1726 } 1727 1728 void scheduleWritePackageRestrictionsLocked(int userId) { 1729 if (!sUserManager.exists(userId)) return; 1730 mDirtyUsers.add(userId); 1731 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1732 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1733 } 1734 } 1735 1736 public static PackageManagerService main(Context context, Installer installer, 1737 boolean factoryTest, boolean onlyCore) { 1738 PackageManagerService m = new PackageManagerService(context, installer, 1739 factoryTest, onlyCore); 1740 ServiceManager.addService("package", m); 1741 return m; 1742 } 1743 1744 static String[] splitString(String str, char sep) { 1745 int count = 1; 1746 int i = 0; 1747 while ((i=str.indexOf(sep, i)) >= 0) { 1748 count++; 1749 i++; 1750 } 1751 1752 String[] res = new String[count]; 1753 i=0; 1754 count = 0; 1755 int lastI=0; 1756 while ((i=str.indexOf(sep, i)) >= 0) { 1757 res[count] = str.substring(lastI, i); 1758 count++; 1759 i++; 1760 lastI = i; 1761 } 1762 res[count] = str.substring(lastI, str.length()); 1763 return res; 1764 } 1765 1766 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1767 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1768 Context.DISPLAY_SERVICE); 1769 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1770 } 1771 1772 public PackageManagerService(Context context, Installer installer, 1773 boolean factoryTest, boolean onlyCore) { 1774 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1775 SystemClock.uptimeMillis()); 1776 1777 if (mSdkVersion <= 0) { 1778 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1779 } 1780 1781 mContext = context; 1782 mFactoryTest = factoryTest; 1783 mOnlyCore = onlyCore; 1784 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1785 mMetrics = new DisplayMetrics(); 1786 mSettings = new Settings(mPackages); 1787 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1788 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1789 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1790 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1791 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1792 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1793 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1794 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1795 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1796 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1797 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1798 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1799 1800 // TODO: add a property to control this? 1801 long dexOptLRUThresholdInMinutes; 1802 if (mLazyDexOpt) { 1803 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1804 } else { 1805 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1806 } 1807 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1808 1809 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1810 if (separateProcesses != null && separateProcesses.length() > 0) { 1811 if ("*".equals(separateProcesses)) { 1812 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1813 mSeparateProcesses = null; 1814 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1815 } else { 1816 mDefParseFlags = 0; 1817 mSeparateProcesses = separateProcesses.split(","); 1818 Slog.w(TAG, "Running with debug.separate_processes: " 1819 + separateProcesses); 1820 } 1821 } else { 1822 mDefParseFlags = 0; 1823 mSeparateProcesses = null; 1824 } 1825 1826 mInstaller = installer; 1827 mPackageDexOptimizer = new PackageDexOptimizer(this); 1828 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1829 1830 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1831 FgThread.get().getLooper()); 1832 1833 getDefaultDisplayMetrics(context, mMetrics); 1834 1835 SystemConfig systemConfig = SystemConfig.getInstance(); 1836 mGlobalGids = systemConfig.getGlobalGids(); 1837 mSystemPermissions = systemConfig.getSystemPermissions(); 1838 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1839 1840 synchronized (mInstallLock) { 1841 // writer 1842 synchronized (mPackages) { 1843 mHandlerThread = new ServiceThread(TAG, 1844 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1845 mHandlerThread.start(); 1846 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1847 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1848 1849 File dataDir = Environment.getDataDirectory(); 1850 mAppDataDir = new File(dataDir, "data"); 1851 mAppInstallDir = new File(dataDir, "app"); 1852 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1853 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1854 mUserAppDataDir = new File(dataDir, "user"); 1855 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1856 1857 sUserManager = new UserManagerService(context, this, 1858 mInstallLock, mPackages); 1859 1860 // Propagate permission configuration in to package manager. 1861 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1862 = systemConfig.getPermissions(); 1863 for (int i=0; i<permConfig.size(); i++) { 1864 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1865 BasePermission bp = mSettings.mPermissions.get(perm.name); 1866 if (bp == null) { 1867 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1868 mSettings.mPermissions.put(perm.name, bp); 1869 } 1870 if (perm.gids != null) { 1871 bp.setGids(perm.gids, perm.perUser); 1872 } 1873 } 1874 1875 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1876 for (int i=0; i<libConfig.size(); i++) { 1877 mSharedLibraries.put(libConfig.keyAt(i), 1878 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1879 } 1880 1881 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1882 1883 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1884 mSdkVersion, mOnlyCore); 1885 1886 String customResolverActivity = Resources.getSystem().getString( 1887 R.string.config_customResolverActivity); 1888 if (TextUtils.isEmpty(customResolverActivity)) { 1889 customResolverActivity = null; 1890 } else { 1891 mCustomResolverComponentName = ComponentName.unflattenFromString( 1892 customResolverActivity); 1893 } 1894 1895 long startTime = SystemClock.uptimeMillis(); 1896 1897 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1898 startTime); 1899 1900 // Set flag to monitor and not change apk file paths when 1901 // scanning install directories. 1902 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1903 1904 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1905 1906 /** 1907 * Add everything in the in the boot class path to the 1908 * list of process files because dexopt will have been run 1909 * if necessary during zygote startup. 1910 */ 1911 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1912 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1913 1914 if (bootClassPath != null) { 1915 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1916 for (String element : bootClassPathElements) { 1917 alreadyDexOpted.add(element); 1918 } 1919 } else { 1920 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1921 } 1922 1923 if (systemServerClassPath != null) { 1924 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1925 for (String element : systemServerClassPathElements) { 1926 alreadyDexOpted.add(element); 1927 } 1928 } else { 1929 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1930 } 1931 1932 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1933 final String[] dexCodeInstructionSets = 1934 getDexCodeInstructionSets( 1935 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1936 1937 /** 1938 * Ensure all external libraries have had dexopt run on them. 1939 */ 1940 if (mSharedLibraries.size() > 0) { 1941 // NOTE: For now, we're compiling these system "shared libraries" 1942 // (and framework jars) into all available architectures. It's possible 1943 // to compile them only when we come across an app that uses them (there's 1944 // already logic for that in scanPackageLI) but that adds some complexity. 1945 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1946 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1947 final String lib = libEntry.path; 1948 if (lib == null) { 1949 continue; 1950 } 1951 1952 try { 1953 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1954 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1955 alreadyDexOpted.add(lib); 1956 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1957 } 1958 } catch (FileNotFoundException e) { 1959 Slog.w(TAG, "Library not found: " + lib); 1960 } catch (IOException e) { 1961 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1962 + e.getMessage()); 1963 } 1964 } 1965 } 1966 } 1967 1968 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1969 1970 // Gross hack for now: we know this file doesn't contain any 1971 // code, so don't dexopt it to avoid the resulting log spew. 1972 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1973 1974 // Gross hack for now: we know this file is only part of 1975 // the boot class path for art, so don't dexopt it to 1976 // avoid the resulting log spew. 1977 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1978 1979 /** 1980 * There are a number of commands implemented in Java, which 1981 * we currently need to do the dexopt on so that they can be 1982 * run from a non-root shell. 1983 */ 1984 String[] frameworkFiles = frameworkDir.list(); 1985 if (frameworkFiles != null) { 1986 // TODO: We could compile these only for the most preferred ABI. We should 1987 // first double check that the dex files for these commands are not referenced 1988 // by other system apps. 1989 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1990 for (int i=0; i<frameworkFiles.length; i++) { 1991 File libPath = new File(frameworkDir, frameworkFiles[i]); 1992 String path = libPath.getPath(); 1993 // Skip the file if we already did it. 1994 if (alreadyDexOpted.contains(path)) { 1995 continue; 1996 } 1997 // Skip the file if it is not a type we want to dexopt. 1998 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1999 continue; 2000 } 2001 try { 2002 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 2003 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2004 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 2005 } 2006 } catch (FileNotFoundException e) { 2007 Slog.w(TAG, "Jar not found: " + path); 2008 } catch (IOException e) { 2009 Slog.w(TAG, "Exception reading jar: " + path, e); 2010 } 2011 } 2012 } 2013 } 2014 2015 // Collect vendor overlay packages. 2016 // (Do this before scanning any apps.) 2017 // For security and version matching reason, only consider 2018 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2019 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2020 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2021 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2022 2023 // Find base frameworks (resource packages without code). 2024 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2025 | PackageParser.PARSE_IS_SYSTEM_DIR 2026 | PackageParser.PARSE_IS_PRIVILEGED, 2027 scanFlags | SCAN_NO_DEX, 0); 2028 2029 // Collected privileged system packages. 2030 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2031 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2032 | PackageParser.PARSE_IS_SYSTEM_DIR 2033 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2034 2035 // Collect ordinary system packages. 2036 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2037 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2038 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2039 2040 // Collect all vendor packages. 2041 File vendorAppDir = new File("/vendor/app"); 2042 try { 2043 vendorAppDir = vendorAppDir.getCanonicalFile(); 2044 } catch (IOException e) { 2045 // failed to look up canonical path, continue with original one 2046 } 2047 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2048 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2049 2050 // Collect all OEM packages. 2051 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2052 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2053 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2054 2055 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2056 mInstaller.moveFiles(); 2057 2058 // Prune any system packages that no longer exist. 2059 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2060 if (!mOnlyCore) { 2061 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2062 while (psit.hasNext()) { 2063 PackageSetting ps = psit.next(); 2064 2065 /* 2066 * If this is not a system app, it can't be a 2067 * disable system app. 2068 */ 2069 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2070 continue; 2071 } 2072 2073 /* 2074 * If the package is scanned, it's not erased. 2075 */ 2076 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2077 if (scannedPkg != null) { 2078 /* 2079 * If the system app is both scanned and in the 2080 * disabled packages list, then it must have been 2081 * added via OTA. Remove it from the currently 2082 * scanned package so the previously user-installed 2083 * application can be scanned. 2084 */ 2085 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2086 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2087 + ps.name + "; removing system app. Last known codePath=" 2088 + ps.codePathString + ", installStatus=" + ps.installStatus 2089 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2090 + scannedPkg.mVersionCode); 2091 removePackageLI(ps, true); 2092 mExpectingBetter.put(ps.name, ps.codePath); 2093 } 2094 2095 continue; 2096 } 2097 2098 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2099 psit.remove(); 2100 logCriticalInfo(Log.WARN, "System package " + ps.name 2101 + " no longer exists; wiping its data"); 2102 removeDataDirsLI(null, ps.name); 2103 } else { 2104 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2105 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2106 possiblyDeletedUpdatedSystemApps.add(ps.name); 2107 } 2108 } 2109 } 2110 } 2111 2112 //look for any incomplete package installations 2113 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2114 //clean up list 2115 for(int i = 0; i < deletePkgsList.size(); i++) { 2116 //clean up here 2117 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2118 } 2119 //delete tmp files 2120 deleteTempPackageFiles(); 2121 2122 // Remove any shared userIDs that have no associated packages 2123 mSettings.pruneSharedUsersLPw(); 2124 2125 if (!mOnlyCore) { 2126 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2127 SystemClock.uptimeMillis()); 2128 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2129 2130 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2131 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2132 2133 /** 2134 * Remove disable package settings for any updated system 2135 * apps that were removed via an OTA. If they're not a 2136 * previously-updated app, remove them completely. 2137 * Otherwise, just revoke their system-level permissions. 2138 */ 2139 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2140 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2141 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2142 2143 String msg; 2144 if (deletedPkg == null) { 2145 msg = "Updated system package " + deletedAppName 2146 + " no longer exists; wiping its data"; 2147 removeDataDirsLI(null, deletedAppName); 2148 } else { 2149 msg = "Updated system app + " + deletedAppName 2150 + " no longer present; removing system privileges for " 2151 + deletedAppName; 2152 2153 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2154 2155 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2156 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2157 } 2158 logCriticalInfo(Log.WARN, msg); 2159 } 2160 2161 /** 2162 * Make sure all system apps that we expected to appear on 2163 * the userdata partition actually showed up. If they never 2164 * appeared, crawl back and revive the system version. 2165 */ 2166 for (int i = 0; i < mExpectingBetter.size(); i++) { 2167 final String packageName = mExpectingBetter.keyAt(i); 2168 if (!mPackages.containsKey(packageName)) { 2169 final File scanFile = mExpectingBetter.valueAt(i); 2170 2171 logCriticalInfo(Log.WARN, "Expected better " + packageName 2172 + " but never showed up; reverting to system"); 2173 2174 final int reparseFlags; 2175 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2176 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2177 | PackageParser.PARSE_IS_SYSTEM_DIR 2178 | PackageParser.PARSE_IS_PRIVILEGED; 2179 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2180 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2181 | PackageParser.PARSE_IS_SYSTEM_DIR; 2182 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2183 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2184 | PackageParser.PARSE_IS_SYSTEM_DIR; 2185 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2186 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2187 | PackageParser.PARSE_IS_SYSTEM_DIR; 2188 } else { 2189 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2190 continue; 2191 } 2192 2193 mSettings.enableSystemPackageLPw(packageName); 2194 2195 try { 2196 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2197 } catch (PackageManagerException e) { 2198 Slog.e(TAG, "Failed to parse original system package: " 2199 + e.getMessage()); 2200 } 2201 } 2202 } 2203 } 2204 mExpectingBetter.clear(); 2205 2206 // Now that we know all of the shared libraries, update all clients to have 2207 // the correct library paths. 2208 updateAllSharedLibrariesLPw(); 2209 2210 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2211 // NOTE: We ignore potential failures here during a system scan (like 2212 // the rest of the commands above) because there's precious little we 2213 // can do about it. A settings error is reported, though. 2214 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2215 false /* force dexopt */, false /* defer dexopt */); 2216 } 2217 2218 // Now that we know all the packages we are keeping, 2219 // read and update their last usage times. 2220 mPackageUsage.readLP(); 2221 2222 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2223 SystemClock.uptimeMillis()); 2224 Slog.i(TAG, "Time to scan packages: " 2225 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2226 + " seconds"); 2227 2228 // If the platform SDK has changed since the last time we booted, 2229 // we need to re-grant app permission to catch any new ones that 2230 // appear. This is really a hack, and means that apps can in some 2231 // cases get permissions that the user didn't initially explicitly 2232 // allow... it would be nice to have some better way to handle 2233 // this situation. 2234 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2235 != mSdkVersion; 2236 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2237 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2238 + "; regranting permissions for internal storage"); 2239 mSettings.mInternalSdkPlatform = mSdkVersion; 2240 2241 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2242 | (regrantPermissions 2243 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2244 : 0)); 2245 2246 // If this is the first boot, and it is a normal boot, then 2247 // we need to initialize the default preferred apps. 2248 if (!mRestoredSettings && !onlyCore) { 2249 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2250 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2251 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2252 } 2253 2254 // If this is first boot after an OTA, and a normal boot, then 2255 // we need to clear code cache directories. 2256 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2257 if (mIsUpgrade && !onlyCore) { 2258 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2259 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2260 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2261 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2262 } 2263 mSettings.mFingerprint = Build.FINGERPRINT; 2264 } 2265 2266 checkDefaultBrowser(); 2267 2268 // All the changes are done during package scanning. 2269 mSettings.updateInternalDatabaseVersion(); 2270 2271 // can downgrade to reader 2272 mSettings.writeLPr(); 2273 2274 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2275 SystemClock.uptimeMillis()); 2276 2277 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2278 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2279 2280 mInstallerService = new PackageInstallerService(context, this); 2281 2282 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2283 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2284 mIntentFilterVerifierComponent); 2285 2286 } // synchronized (mPackages) 2287 } // synchronized (mInstallLock) 2288 2289 // Now after opening every single application zip, make sure they 2290 // are all flushed. Not really needed, but keeps things nice and 2291 // tidy. 2292 Runtime.getRuntime().gc(); 2293 2294 // Expose private service for system components to use. 2295 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2296 } 2297 2298 @Override 2299 public boolean isFirstBoot() { 2300 return !mRestoredSettings; 2301 } 2302 2303 @Override 2304 public boolean isOnlyCoreApps() { 2305 return mOnlyCore; 2306 } 2307 2308 @Override 2309 public boolean isUpgrade() { 2310 return mIsUpgrade; 2311 } 2312 2313 private String getRequiredVerifierLPr() { 2314 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2315 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2316 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2317 2318 String requiredVerifier = null; 2319 2320 final int N = receivers.size(); 2321 for (int i = 0; i < N; i++) { 2322 final ResolveInfo info = receivers.get(i); 2323 2324 if (info.activityInfo == null) { 2325 continue; 2326 } 2327 2328 final String packageName = info.activityInfo.packageName; 2329 2330 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2331 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2332 continue; 2333 } 2334 2335 if (requiredVerifier != null) { 2336 throw new RuntimeException("There can be only one required verifier"); 2337 } 2338 2339 requiredVerifier = packageName; 2340 } 2341 2342 return requiredVerifier; 2343 } 2344 2345 private String getRequiredInstallerLPr() { 2346 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2347 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2348 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2349 2350 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2351 PACKAGE_MIME_TYPE, 0, 0); 2352 2353 String requiredInstaller = null; 2354 2355 final int N = installers.size(); 2356 for (int i = 0; i < N; i++) { 2357 final ResolveInfo info = installers.get(i); 2358 final String packageName = info.activityInfo.packageName; 2359 2360 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2361 continue; 2362 } 2363 2364 if (requiredInstaller != null) { 2365 throw new RuntimeException("There must be one required installer"); 2366 } 2367 2368 requiredInstaller = packageName; 2369 } 2370 2371 if (requiredInstaller == null) { 2372 throw new RuntimeException("There must be one required installer"); 2373 } 2374 2375 return requiredInstaller; 2376 } 2377 2378 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2379 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2380 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2381 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2382 2383 ComponentName verifierComponentName = null; 2384 2385 int priority = -1000; 2386 final int N = receivers.size(); 2387 for (int i = 0; i < N; i++) { 2388 final ResolveInfo info = receivers.get(i); 2389 2390 if (info.activityInfo == null) { 2391 continue; 2392 } 2393 2394 final String packageName = info.activityInfo.packageName; 2395 2396 final PackageSetting ps = mSettings.mPackages.get(packageName); 2397 if (ps == null) { 2398 continue; 2399 } 2400 2401 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2402 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2403 continue; 2404 } 2405 2406 // Select the IntentFilterVerifier with the highest priority 2407 if (priority < info.priority) { 2408 priority = info.priority; 2409 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2410 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2411 + verifierComponentName + " with priority: " + info.priority); 2412 } 2413 } 2414 2415 return verifierComponentName; 2416 } 2417 2418 private void primeDomainVerificationsLPw(int userId) { 2419 if (DEBUG_DOMAIN_VERIFICATION) { 2420 Slog.d(TAG, "Priming domain verifications in user " + userId); 2421 } 2422 2423 SystemConfig systemConfig = SystemConfig.getInstance(); 2424 ArraySet<String> packages = systemConfig.getLinkedApps(); 2425 ArraySet<String> domains = new ArraySet<String>(); 2426 2427 for (String packageName : packages) { 2428 PackageParser.Package pkg = mPackages.get(packageName); 2429 if (pkg != null) { 2430 if (!pkg.isSystemApp()) { 2431 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2432 continue; 2433 } 2434 2435 domains.clear(); 2436 for (PackageParser.Activity a : pkg.activities) { 2437 for (ActivityIntentInfo filter : a.intents) { 2438 if (hasValidDomains(filter)) { 2439 domains.addAll(filter.getHostsList()); 2440 } 2441 } 2442 } 2443 2444 if (domains.size() > 0) { 2445 if (DEBUG_DOMAIN_VERIFICATION) { 2446 Slog.v(TAG, " + " + packageName); 2447 } 2448 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2449 // state w.r.t. the formal app-linkage "no verification attempted" state; 2450 // and then 'always' in the per-user state actually used for intent resolution. 2451 final IntentFilterVerificationInfo ivi; 2452 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2453 new ArrayList<String>(domains)); 2454 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2455 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2456 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2457 } else { 2458 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2459 + "' does not handle web links"); 2460 } 2461 } else { 2462 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2463 } 2464 } 2465 2466 scheduleWritePackageRestrictionsLocked(userId); 2467 scheduleWriteSettingsLocked(); 2468 } 2469 2470 private void applyFactoryDefaultBrowserLPw(int userId) { 2471 // The default browser app's package name is stored in a string resource, 2472 // with a product-specific overlay used for vendor customization. 2473 String browserPkg = mContext.getResources().getString( 2474 com.android.internal.R.string.default_browser); 2475 if (!TextUtils.isEmpty(browserPkg)) { 2476 // non-empty string => required to be a known package 2477 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2478 if (ps == null) { 2479 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2480 browserPkg = null; 2481 } else { 2482 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2483 } 2484 } 2485 2486 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2487 // default. If there's more than one, just leave everything alone. 2488 if (browserPkg == null) { 2489 calculateDefaultBrowserLPw(userId); 2490 } 2491 } 2492 2493 private void calculateDefaultBrowserLPw(int userId) { 2494 List<String> allBrowsers = resolveAllBrowserApps(userId); 2495 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2496 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2497 } 2498 2499 private List<String> resolveAllBrowserApps(int userId) { 2500 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2501 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2502 PackageManager.MATCH_ALL, userId); 2503 2504 final int count = list.size(); 2505 List<String> result = new ArrayList<String>(count); 2506 for (int i=0; i<count; i++) { 2507 ResolveInfo info = list.get(i); 2508 if (info.activityInfo == null 2509 || !info.handleAllWebDataURI 2510 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2511 || result.contains(info.activityInfo.packageName)) { 2512 continue; 2513 } 2514 result.add(info.activityInfo.packageName); 2515 } 2516 2517 return result; 2518 } 2519 2520 private boolean packageIsBrowser(String packageName, int userId) { 2521 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2522 PackageManager.MATCH_ALL, userId); 2523 final int N = list.size(); 2524 for (int i = 0; i < N; i++) { 2525 ResolveInfo info = list.get(i); 2526 if (packageName.equals(info.activityInfo.packageName)) { 2527 return true; 2528 } 2529 } 2530 return false; 2531 } 2532 2533 private void checkDefaultBrowser() { 2534 final int myUserId = UserHandle.myUserId(); 2535 final String packageName = getDefaultBrowserPackageName(myUserId); 2536 if (packageName != null) { 2537 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2538 if (info == null) { 2539 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2540 synchronized (mPackages) { 2541 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2542 } 2543 } 2544 } 2545 } 2546 2547 @Override 2548 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2549 throws RemoteException { 2550 try { 2551 return super.onTransact(code, data, reply, flags); 2552 } catch (RuntimeException e) { 2553 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2554 Slog.wtf(TAG, "Package Manager Crash", e); 2555 } 2556 throw e; 2557 } 2558 } 2559 2560 void cleanupInstallFailedPackage(PackageSetting ps) { 2561 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2562 2563 removeDataDirsLI(ps.volumeUuid, ps.name); 2564 if (ps.codePath != null) { 2565 if (ps.codePath.isDirectory()) { 2566 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2567 } else { 2568 ps.codePath.delete(); 2569 } 2570 } 2571 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2572 if (ps.resourcePath.isDirectory()) { 2573 FileUtils.deleteContents(ps.resourcePath); 2574 } 2575 ps.resourcePath.delete(); 2576 } 2577 mSettings.removePackageLPw(ps.name); 2578 } 2579 2580 static int[] appendInts(int[] cur, int[] add) { 2581 if (add == null) return cur; 2582 if (cur == null) return add; 2583 final int N = add.length; 2584 for (int i=0; i<N; i++) { 2585 cur = appendInt(cur, add[i]); 2586 } 2587 return cur; 2588 } 2589 2590 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2591 if (!sUserManager.exists(userId)) return null; 2592 final PackageSetting ps = (PackageSetting) p.mExtras; 2593 if (ps == null) { 2594 return null; 2595 } 2596 2597 final PermissionsState permissionsState = ps.getPermissionsState(); 2598 2599 final int[] gids = permissionsState.computeGids(userId); 2600 final Set<String> permissions = permissionsState.getPermissions(userId); 2601 final PackageUserState state = ps.readUserState(userId); 2602 2603 return PackageParser.generatePackageInfo(p, gids, flags, 2604 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2605 } 2606 2607 @Override 2608 public boolean isPackageFrozen(String packageName) { 2609 synchronized (mPackages) { 2610 final PackageSetting ps = mSettings.mPackages.get(packageName); 2611 if (ps != null) { 2612 return ps.frozen; 2613 } 2614 } 2615 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2616 return true; 2617 } 2618 2619 @Override 2620 public boolean isPackageAvailable(String packageName, int userId) { 2621 if (!sUserManager.exists(userId)) return false; 2622 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2623 synchronized (mPackages) { 2624 PackageParser.Package p = mPackages.get(packageName); 2625 if (p != null) { 2626 final PackageSetting ps = (PackageSetting) p.mExtras; 2627 if (ps != null) { 2628 final PackageUserState state = ps.readUserState(userId); 2629 if (state != null) { 2630 return PackageParser.isAvailable(state); 2631 } 2632 } 2633 } 2634 } 2635 return false; 2636 } 2637 2638 @Override 2639 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2640 if (!sUserManager.exists(userId)) return null; 2641 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2642 // reader 2643 synchronized (mPackages) { 2644 PackageParser.Package p = mPackages.get(packageName); 2645 if (DEBUG_PACKAGE_INFO) 2646 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2647 if (p != null) { 2648 return generatePackageInfo(p, flags, userId); 2649 } 2650 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2651 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2652 } 2653 } 2654 return null; 2655 } 2656 2657 @Override 2658 public String[] currentToCanonicalPackageNames(String[] names) { 2659 String[] out = new String[names.length]; 2660 // reader 2661 synchronized (mPackages) { 2662 for (int i=names.length-1; i>=0; i--) { 2663 PackageSetting ps = mSettings.mPackages.get(names[i]); 2664 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2665 } 2666 } 2667 return out; 2668 } 2669 2670 @Override 2671 public String[] canonicalToCurrentPackageNames(String[] names) { 2672 String[] out = new String[names.length]; 2673 // reader 2674 synchronized (mPackages) { 2675 for (int i=names.length-1; i>=0; i--) { 2676 String cur = mSettings.mRenamedPackages.get(names[i]); 2677 out[i] = cur != null ? cur : names[i]; 2678 } 2679 } 2680 return out; 2681 } 2682 2683 @Override 2684 public int getPackageUid(String packageName, int userId) { 2685 if (!sUserManager.exists(userId)) return -1; 2686 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2687 2688 // reader 2689 synchronized (mPackages) { 2690 PackageParser.Package p = mPackages.get(packageName); 2691 if(p != null) { 2692 return UserHandle.getUid(userId, p.applicationInfo.uid); 2693 } 2694 PackageSetting ps = mSettings.mPackages.get(packageName); 2695 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2696 return -1; 2697 } 2698 p = ps.pkg; 2699 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2700 } 2701 } 2702 2703 @Override 2704 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2705 if (!sUserManager.exists(userId)) { 2706 return null; 2707 } 2708 2709 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2710 "getPackageGids"); 2711 2712 // reader 2713 synchronized (mPackages) { 2714 PackageParser.Package p = mPackages.get(packageName); 2715 if (DEBUG_PACKAGE_INFO) { 2716 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2717 } 2718 if (p != null) { 2719 PackageSetting ps = (PackageSetting) p.mExtras; 2720 return ps.getPermissionsState().computeGids(userId); 2721 } 2722 } 2723 2724 return null; 2725 } 2726 2727 static PermissionInfo generatePermissionInfo( 2728 BasePermission bp, int flags) { 2729 if (bp.perm != null) { 2730 return PackageParser.generatePermissionInfo(bp.perm, flags); 2731 } 2732 PermissionInfo pi = new PermissionInfo(); 2733 pi.name = bp.name; 2734 pi.packageName = bp.sourcePackage; 2735 pi.nonLocalizedLabel = bp.name; 2736 pi.protectionLevel = bp.protectionLevel; 2737 return pi; 2738 } 2739 2740 @Override 2741 public PermissionInfo getPermissionInfo(String name, int flags) { 2742 // reader 2743 synchronized (mPackages) { 2744 final BasePermission p = mSettings.mPermissions.get(name); 2745 if (p != null) { 2746 return generatePermissionInfo(p, flags); 2747 } 2748 return null; 2749 } 2750 } 2751 2752 @Override 2753 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2754 // reader 2755 synchronized (mPackages) { 2756 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2757 for (BasePermission p : mSettings.mPermissions.values()) { 2758 if (group == null) { 2759 if (p.perm == null || p.perm.info.group == null) { 2760 out.add(generatePermissionInfo(p, flags)); 2761 } 2762 } else { 2763 if (p.perm != null && group.equals(p.perm.info.group)) { 2764 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2765 } 2766 } 2767 } 2768 2769 if (out.size() > 0) { 2770 return out; 2771 } 2772 return mPermissionGroups.containsKey(group) ? out : null; 2773 } 2774 } 2775 2776 @Override 2777 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2778 // reader 2779 synchronized (mPackages) { 2780 return PackageParser.generatePermissionGroupInfo( 2781 mPermissionGroups.get(name), flags); 2782 } 2783 } 2784 2785 @Override 2786 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2787 // reader 2788 synchronized (mPackages) { 2789 final int N = mPermissionGroups.size(); 2790 ArrayList<PermissionGroupInfo> out 2791 = new ArrayList<PermissionGroupInfo>(N); 2792 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2793 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2794 } 2795 return out; 2796 } 2797 } 2798 2799 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2800 int userId) { 2801 if (!sUserManager.exists(userId)) return null; 2802 PackageSetting ps = mSettings.mPackages.get(packageName); 2803 if (ps != null) { 2804 if (ps.pkg == null) { 2805 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2806 flags, userId); 2807 if (pInfo != null) { 2808 return pInfo.applicationInfo; 2809 } 2810 return null; 2811 } 2812 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2813 ps.readUserState(userId), userId); 2814 } 2815 return null; 2816 } 2817 2818 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2819 int userId) { 2820 if (!sUserManager.exists(userId)) return null; 2821 PackageSetting ps = mSettings.mPackages.get(packageName); 2822 if (ps != null) { 2823 PackageParser.Package pkg = ps.pkg; 2824 if (pkg == null) { 2825 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2826 return null; 2827 } 2828 // Only data remains, so we aren't worried about code paths 2829 pkg = new PackageParser.Package(packageName); 2830 pkg.applicationInfo.packageName = packageName; 2831 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2832 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2833 pkg.applicationInfo.dataDir = Environment 2834 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2835 .getAbsolutePath(); 2836 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2837 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2838 } 2839 return generatePackageInfo(pkg, flags, userId); 2840 } 2841 return null; 2842 } 2843 2844 @Override 2845 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2846 if (!sUserManager.exists(userId)) return null; 2847 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2848 // writer 2849 synchronized (mPackages) { 2850 PackageParser.Package p = mPackages.get(packageName); 2851 if (DEBUG_PACKAGE_INFO) Log.v( 2852 TAG, "getApplicationInfo " + packageName 2853 + ": " + p); 2854 if (p != null) { 2855 PackageSetting ps = mSettings.mPackages.get(packageName); 2856 if (ps == null) return null; 2857 // Note: isEnabledLP() does not apply here - always return info 2858 return PackageParser.generateApplicationInfo( 2859 p, flags, ps.readUserState(userId), userId); 2860 } 2861 if ("android".equals(packageName)||"system".equals(packageName)) { 2862 return mAndroidApplication; 2863 } 2864 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2865 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2866 } 2867 } 2868 return null; 2869 } 2870 2871 @Override 2872 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2873 final IPackageDataObserver observer) { 2874 mContext.enforceCallingOrSelfPermission( 2875 android.Manifest.permission.CLEAR_APP_CACHE, null); 2876 // Queue up an async operation since clearing cache may take a little while. 2877 mHandler.post(new Runnable() { 2878 public void run() { 2879 mHandler.removeCallbacks(this); 2880 int retCode = -1; 2881 synchronized (mInstallLock) { 2882 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2883 if (retCode < 0) { 2884 Slog.w(TAG, "Couldn't clear application caches"); 2885 } 2886 } 2887 if (observer != null) { 2888 try { 2889 observer.onRemoveCompleted(null, (retCode >= 0)); 2890 } catch (RemoteException e) { 2891 Slog.w(TAG, "RemoveException when invoking call back"); 2892 } 2893 } 2894 } 2895 }); 2896 } 2897 2898 @Override 2899 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2900 final IntentSender pi) { 2901 mContext.enforceCallingOrSelfPermission( 2902 android.Manifest.permission.CLEAR_APP_CACHE, null); 2903 // Queue up an async operation since clearing cache may take a little while. 2904 mHandler.post(new Runnable() { 2905 public void run() { 2906 mHandler.removeCallbacks(this); 2907 int retCode = -1; 2908 synchronized (mInstallLock) { 2909 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2910 if (retCode < 0) { 2911 Slog.w(TAG, "Couldn't clear application caches"); 2912 } 2913 } 2914 if(pi != null) { 2915 try { 2916 // Callback via pending intent 2917 int code = (retCode >= 0) ? 1 : 0; 2918 pi.sendIntent(null, code, null, 2919 null, null); 2920 } catch (SendIntentException e1) { 2921 Slog.i(TAG, "Failed to send pending intent"); 2922 } 2923 } 2924 } 2925 }); 2926 } 2927 2928 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2929 synchronized (mInstallLock) { 2930 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2931 throw new IOException("Failed to free enough space"); 2932 } 2933 } 2934 } 2935 2936 @Override 2937 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2938 if (!sUserManager.exists(userId)) return null; 2939 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2940 synchronized (mPackages) { 2941 PackageParser.Activity a = mActivities.mActivities.get(component); 2942 2943 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2944 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2945 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2946 if (ps == null) return null; 2947 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2948 userId); 2949 } 2950 if (mResolveComponentName.equals(component)) { 2951 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2952 new PackageUserState(), userId); 2953 } 2954 } 2955 return null; 2956 } 2957 2958 @Override 2959 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2960 String resolvedType) { 2961 synchronized (mPackages) { 2962 PackageParser.Activity a = mActivities.mActivities.get(component); 2963 if (a == null) { 2964 return false; 2965 } 2966 for (int i=0; i<a.intents.size(); i++) { 2967 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2968 intent.getData(), intent.getCategories(), TAG) >= 0) { 2969 return true; 2970 } 2971 } 2972 return false; 2973 } 2974 } 2975 2976 @Override 2977 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2978 if (!sUserManager.exists(userId)) return null; 2979 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2980 synchronized (mPackages) { 2981 PackageParser.Activity a = mReceivers.mActivities.get(component); 2982 if (DEBUG_PACKAGE_INFO) Log.v( 2983 TAG, "getReceiverInfo " + component + ": " + a); 2984 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2985 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2986 if (ps == null) return null; 2987 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2988 userId); 2989 } 2990 } 2991 return null; 2992 } 2993 2994 @Override 2995 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2996 if (!sUserManager.exists(userId)) return null; 2997 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2998 synchronized (mPackages) { 2999 PackageParser.Service s = mServices.mServices.get(component); 3000 if (DEBUG_PACKAGE_INFO) Log.v( 3001 TAG, "getServiceInfo " + component + ": " + s); 3002 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3003 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3004 if (ps == null) return null; 3005 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3006 userId); 3007 } 3008 } 3009 return null; 3010 } 3011 3012 @Override 3013 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3014 if (!sUserManager.exists(userId)) return null; 3015 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3016 synchronized (mPackages) { 3017 PackageParser.Provider p = mProviders.mProviders.get(component); 3018 if (DEBUG_PACKAGE_INFO) Log.v( 3019 TAG, "getProviderInfo " + component + ": " + p); 3020 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3021 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3022 if (ps == null) return null; 3023 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3024 userId); 3025 } 3026 } 3027 return null; 3028 } 3029 3030 @Override 3031 public String[] getSystemSharedLibraryNames() { 3032 Set<String> libSet; 3033 synchronized (mPackages) { 3034 libSet = mSharedLibraries.keySet(); 3035 int size = libSet.size(); 3036 if (size > 0) { 3037 String[] libs = new String[size]; 3038 libSet.toArray(libs); 3039 return libs; 3040 } 3041 } 3042 return null; 3043 } 3044 3045 /** 3046 * @hide 3047 */ 3048 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3049 synchronized (mPackages) { 3050 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3051 if (lib != null && lib.apk != null) { 3052 return mPackages.get(lib.apk); 3053 } 3054 } 3055 return null; 3056 } 3057 3058 @Override 3059 public FeatureInfo[] getSystemAvailableFeatures() { 3060 Collection<FeatureInfo> featSet; 3061 synchronized (mPackages) { 3062 featSet = mAvailableFeatures.values(); 3063 int size = featSet.size(); 3064 if (size > 0) { 3065 FeatureInfo[] features = new FeatureInfo[size+1]; 3066 featSet.toArray(features); 3067 FeatureInfo fi = new FeatureInfo(); 3068 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3069 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3070 features[size] = fi; 3071 return features; 3072 } 3073 } 3074 return null; 3075 } 3076 3077 @Override 3078 public boolean hasSystemFeature(String name) { 3079 synchronized (mPackages) { 3080 return mAvailableFeatures.containsKey(name); 3081 } 3082 } 3083 3084 private void checkValidCaller(int uid, int userId) { 3085 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3086 return; 3087 3088 throw new SecurityException("Caller uid=" + uid 3089 + " is not privileged to communicate with user=" + userId); 3090 } 3091 3092 @Override 3093 public int checkPermission(String permName, String pkgName, int userId) { 3094 if (!sUserManager.exists(userId)) { 3095 return PackageManager.PERMISSION_DENIED; 3096 } 3097 3098 synchronized (mPackages) { 3099 final PackageParser.Package p = mPackages.get(pkgName); 3100 if (p != null && p.mExtras != null) { 3101 final PackageSetting ps = (PackageSetting) p.mExtras; 3102 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3103 return PackageManager.PERMISSION_GRANTED; 3104 } 3105 } 3106 } 3107 3108 return PackageManager.PERMISSION_DENIED; 3109 } 3110 3111 @Override 3112 public int checkUidPermission(String permName, int uid) { 3113 final int userId = UserHandle.getUserId(uid); 3114 3115 if (!sUserManager.exists(userId)) { 3116 return PackageManager.PERMISSION_DENIED; 3117 } 3118 3119 synchronized (mPackages) { 3120 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3121 if (obj != null) { 3122 final SettingBase ps = (SettingBase) obj; 3123 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3124 return PackageManager.PERMISSION_GRANTED; 3125 } 3126 } else { 3127 ArraySet<String> perms = mSystemPermissions.get(uid); 3128 if (perms != null && perms.contains(permName)) { 3129 return PackageManager.PERMISSION_GRANTED; 3130 } 3131 } 3132 } 3133 3134 return PackageManager.PERMISSION_DENIED; 3135 } 3136 3137 @Override 3138 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3139 if (UserHandle.getCallingUserId() != userId) { 3140 mContext.enforceCallingPermission( 3141 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3142 "isPermissionRevokedByPolicy for user " + userId); 3143 } 3144 3145 if (checkPermission(permission, packageName, userId) 3146 == PackageManager.PERMISSION_GRANTED) { 3147 return false; 3148 } 3149 3150 final long identity = Binder.clearCallingIdentity(); 3151 try { 3152 final int flags = getPermissionFlags(permission, packageName, userId); 3153 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3154 } finally { 3155 Binder.restoreCallingIdentity(identity); 3156 } 3157 } 3158 3159 /** 3160 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3161 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3162 * @param checkShell TODO(yamasani): 3163 * @param message the message to log on security exception 3164 */ 3165 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3166 boolean checkShell, String message) { 3167 if (userId < 0) { 3168 throw new IllegalArgumentException("Invalid userId " + userId); 3169 } 3170 if (checkShell) { 3171 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3172 } 3173 if (userId == UserHandle.getUserId(callingUid)) return; 3174 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3175 if (requireFullPermission) { 3176 mContext.enforceCallingOrSelfPermission( 3177 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3178 } else { 3179 try { 3180 mContext.enforceCallingOrSelfPermission( 3181 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3182 } catch (SecurityException se) { 3183 mContext.enforceCallingOrSelfPermission( 3184 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3185 } 3186 } 3187 } 3188 } 3189 3190 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3191 if (callingUid == Process.SHELL_UID) { 3192 if (userHandle >= 0 3193 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3194 throw new SecurityException("Shell does not have permission to access user " 3195 + userHandle); 3196 } else if (userHandle < 0) { 3197 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3198 + Debug.getCallers(3)); 3199 } 3200 } 3201 } 3202 3203 private BasePermission findPermissionTreeLP(String permName) { 3204 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3205 if (permName.startsWith(bp.name) && 3206 permName.length() > bp.name.length() && 3207 permName.charAt(bp.name.length()) == '.') { 3208 return bp; 3209 } 3210 } 3211 return null; 3212 } 3213 3214 private BasePermission checkPermissionTreeLP(String permName) { 3215 if (permName != null) { 3216 BasePermission bp = findPermissionTreeLP(permName); 3217 if (bp != null) { 3218 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3219 return bp; 3220 } 3221 throw new SecurityException("Calling uid " 3222 + Binder.getCallingUid() 3223 + " is not allowed to add to permission tree " 3224 + bp.name + " owned by uid " + bp.uid); 3225 } 3226 } 3227 throw new SecurityException("No permission tree found for " + permName); 3228 } 3229 3230 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3231 if (s1 == null) { 3232 return s2 == null; 3233 } 3234 if (s2 == null) { 3235 return false; 3236 } 3237 if (s1.getClass() != s2.getClass()) { 3238 return false; 3239 } 3240 return s1.equals(s2); 3241 } 3242 3243 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3244 if (pi1.icon != pi2.icon) return false; 3245 if (pi1.logo != pi2.logo) return false; 3246 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3247 if (!compareStrings(pi1.name, pi2.name)) return false; 3248 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3249 // We'll take care of setting this one. 3250 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3251 // These are not currently stored in settings. 3252 //if (!compareStrings(pi1.group, pi2.group)) return false; 3253 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3254 //if (pi1.labelRes != pi2.labelRes) return false; 3255 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3256 return true; 3257 } 3258 3259 int permissionInfoFootprint(PermissionInfo info) { 3260 int size = info.name.length(); 3261 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3262 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3263 return size; 3264 } 3265 3266 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3267 int size = 0; 3268 for (BasePermission perm : mSettings.mPermissions.values()) { 3269 if (perm.uid == tree.uid) { 3270 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3271 } 3272 } 3273 return size; 3274 } 3275 3276 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3277 // We calculate the max size of permissions defined by this uid and throw 3278 // if that plus the size of 'info' would exceed our stated maximum. 3279 if (tree.uid != Process.SYSTEM_UID) { 3280 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3281 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3282 throw new SecurityException("Permission tree size cap exceeded"); 3283 } 3284 } 3285 } 3286 3287 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3288 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3289 throw new SecurityException("Label must be specified in permission"); 3290 } 3291 BasePermission tree = checkPermissionTreeLP(info.name); 3292 BasePermission bp = mSettings.mPermissions.get(info.name); 3293 boolean added = bp == null; 3294 boolean changed = true; 3295 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3296 if (added) { 3297 enforcePermissionCapLocked(info, tree); 3298 bp = new BasePermission(info.name, tree.sourcePackage, 3299 BasePermission.TYPE_DYNAMIC); 3300 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3301 throw new SecurityException( 3302 "Not allowed to modify non-dynamic permission " 3303 + info.name); 3304 } else { 3305 if (bp.protectionLevel == fixedLevel 3306 && bp.perm.owner.equals(tree.perm.owner) 3307 && bp.uid == tree.uid 3308 && comparePermissionInfos(bp.perm.info, info)) { 3309 changed = false; 3310 } 3311 } 3312 bp.protectionLevel = fixedLevel; 3313 info = new PermissionInfo(info); 3314 info.protectionLevel = fixedLevel; 3315 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3316 bp.perm.info.packageName = tree.perm.info.packageName; 3317 bp.uid = tree.uid; 3318 if (added) { 3319 mSettings.mPermissions.put(info.name, bp); 3320 } 3321 if (changed) { 3322 if (!async) { 3323 mSettings.writeLPr(); 3324 } else { 3325 scheduleWriteSettingsLocked(); 3326 } 3327 } 3328 return added; 3329 } 3330 3331 @Override 3332 public boolean addPermission(PermissionInfo info) { 3333 synchronized (mPackages) { 3334 return addPermissionLocked(info, false); 3335 } 3336 } 3337 3338 @Override 3339 public boolean addPermissionAsync(PermissionInfo info) { 3340 synchronized (mPackages) { 3341 return addPermissionLocked(info, true); 3342 } 3343 } 3344 3345 @Override 3346 public void removePermission(String name) { 3347 synchronized (mPackages) { 3348 checkPermissionTreeLP(name); 3349 BasePermission bp = mSettings.mPermissions.get(name); 3350 if (bp != null) { 3351 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3352 throw new SecurityException( 3353 "Not allowed to modify non-dynamic permission " 3354 + name); 3355 } 3356 mSettings.mPermissions.remove(name); 3357 mSettings.writeLPr(); 3358 } 3359 } 3360 } 3361 3362 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3363 BasePermission bp) { 3364 int index = pkg.requestedPermissions.indexOf(bp.name); 3365 if (index == -1) { 3366 throw new SecurityException("Package " + pkg.packageName 3367 + " has not requested permission " + bp.name); 3368 } 3369 if (!bp.isRuntime()) { 3370 throw new SecurityException("Permission " + bp.name 3371 + " is not a changeable permission type"); 3372 } 3373 } 3374 3375 @Override 3376 public void grantRuntimePermission(String packageName, String name, final int userId) { 3377 if (!sUserManager.exists(userId)) { 3378 Log.e(TAG, "No such user:" + userId); 3379 return; 3380 } 3381 3382 mContext.enforceCallingOrSelfPermission( 3383 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3384 "grantRuntimePermission"); 3385 3386 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3387 "grantRuntimePermission"); 3388 3389 final int uid; 3390 final SettingBase sb; 3391 3392 synchronized (mPackages) { 3393 final PackageParser.Package pkg = mPackages.get(packageName); 3394 if (pkg == null) { 3395 throw new IllegalArgumentException("Unknown package: " + packageName); 3396 } 3397 3398 final BasePermission bp = mSettings.mPermissions.get(name); 3399 if (bp == null) { 3400 throw new IllegalArgumentException("Unknown permission: " + name); 3401 } 3402 3403 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3404 3405 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3406 sb = (SettingBase) pkg.mExtras; 3407 if (sb == null) { 3408 throw new IllegalArgumentException("Unknown package: " + packageName); 3409 } 3410 3411 final PermissionsState permissionsState = sb.getPermissionsState(); 3412 3413 final int flags = permissionsState.getPermissionFlags(name, userId); 3414 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3415 throw new SecurityException("Cannot grant system fixed permission: " 3416 + name + " for package: " + packageName); 3417 } 3418 3419 final int result = permissionsState.grantRuntimePermission(bp, userId); 3420 switch (result) { 3421 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3422 return; 3423 } 3424 3425 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3426 mHandler.post(new Runnable() { 3427 @Override 3428 public void run() { 3429 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3430 } 3431 }); 3432 } break; 3433 } 3434 3435 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3436 3437 // Not critical if that is lost - app has to request again. 3438 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3439 } 3440 3441 // Only need to do this if user is initialized. Otherwise it's a new user 3442 // and there are no processes running as the user yet and there's no need 3443 // to make an expensive call to remount processes for the changed permissions. 3444 if (READ_EXTERNAL_STORAGE.equals(name) 3445 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3446 final long token = Binder.clearCallingIdentity(); 3447 try { 3448 if (sUserManager.isInitialized(userId)) { 3449 MountServiceInternal mountServiceInternal = LocalServices.getService( 3450 MountServiceInternal.class); 3451 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3452 } 3453 } finally { 3454 Binder.restoreCallingIdentity(token); 3455 } 3456 } 3457 } 3458 3459 @Override 3460 public void revokeRuntimePermission(String packageName, String name, int userId) { 3461 if (!sUserManager.exists(userId)) { 3462 Log.e(TAG, "No such user:" + userId); 3463 return; 3464 } 3465 3466 mContext.enforceCallingOrSelfPermission( 3467 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3468 "revokeRuntimePermission"); 3469 3470 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3471 "revokeRuntimePermission"); 3472 3473 final SettingBase sb; 3474 3475 synchronized (mPackages) { 3476 final PackageParser.Package pkg = mPackages.get(packageName); 3477 if (pkg == null) { 3478 throw new IllegalArgumentException("Unknown package: " + packageName); 3479 } 3480 3481 final BasePermission bp = mSettings.mPermissions.get(name); 3482 if (bp == null) { 3483 throw new IllegalArgumentException("Unknown permission: " + name); 3484 } 3485 3486 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3487 3488 sb = (SettingBase) pkg.mExtras; 3489 if (sb == null) { 3490 throw new IllegalArgumentException("Unknown package: " + packageName); 3491 } 3492 3493 final PermissionsState permissionsState = sb.getPermissionsState(); 3494 3495 final int flags = permissionsState.getPermissionFlags(name, userId); 3496 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3497 throw new SecurityException("Cannot revoke system fixed permission: " 3498 + name + " for package: " + packageName); 3499 } 3500 3501 if (permissionsState.revokeRuntimePermission(bp, userId) == 3502 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3503 return; 3504 } 3505 3506 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3507 3508 // Critical, after this call app should never have the permission. 3509 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3510 } 3511 3512 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3513 } 3514 3515 @Override 3516 public void resetRuntimePermissions() { 3517 mContext.enforceCallingOrSelfPermission( 3518 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3519 "revokeRuntimePermission"); 3520 3521 int callingUid = Binder.getCallingUid(); 3522 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3523 mContext.enforceCallingOrSelfPermission( 3524 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3525 "resetRuntimePermissions"); 3526 } 3527 3528 final int[] userIds; 3529 3530 synchronized (mPackages) { 3531 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3532 final int userCount = UserManagerService.getInstance().getUserIds().length; 3533 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3534 } 3535 3536 for (int userId : userIds) { 3537 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3538 } 3539 } 3540 3541 @Override 3542 public int getPermissionFlags(String name, String packageName, int userId) { 3543 if (!sUserManager.exists(userId)) { 3544 return 0; 3545 } 3546 3547 mContext.enforceCallingOrSelfPermission( 3548 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3549 "getPermissionFlags"); 3550 3551 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3552 "getPermissionFlags"); 3553 3554 synchronized (mPackages) { 3555 final PackageParser.Package pkg = mPackages.get(packageName); 3556 if (pkg == null) { 3557 throw new IllegalArgumentException("Unknown package: " + packageName); 3558 } 3559 3560 final BasePermission bp = mSettings.mPermissions.get(name); 3561 if (bp == null) { 3562 throw new IllegalArgumentException("Unknown permission: " + name); 3563 } 3564 3565 SettingBase sb = (SettingBase) pkg.mExtras; 3566 if (sb == null) { 3567 throw new IllegalArgumentException("Unknown package: " + packageName); 3568 } 3569 3570 PermissionsState permissionsState = sb.getPermissionsState(); 3571 return permissionsState.getPermissionFlags(name, userId); 3572 } 3573 } 3574 3575 @Override 3576 public void updatePermissionFlags(String name, String packageName, int flagMask, 3577 int flagValues, int userId) { 3578 if (!sUserManager.exists(userId)) { 3579 return; 3580 } 3581 3582 mContext.enforceCallingOrSelfPermission( 3583 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3584 "updatePermissionFlags"); 3585 3586 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3587 "updatePermissionFlags"); 3588 3589 // Only the system can change system fixed flags. 3590 if (getCallingUid() != Process.SYSTEM_UID) { 3591 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3592 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3593 } 3594 3595 synchronized (mPackages) { 3596 final PackageParser.Package pkg = mPackages.get(packageName); 3597 if (pkg == null) { 3598 throw new IllegalArgumentException("Unknown package: " + packageName); 3599 } 3600 3601 final BasePermission bp = mSettings.mPermissions.get(name); 3602 if (bp == null) { 3603 throw new IllegalArgumentException("Unknown permission: " + name); 3604 } 3605 3606 SettingBase sb = (SettingBase) pkg.mExtras; 3607 if (sb == null) { 3608 throw new IllegalArgumentException("Unknown package: " + packageName); 3609 } 3610 3611 PermissionsState permissionsState = sb.getPermissionsState(); 3612 3613 // Only the package manager can change flags for system component permissions. 3614 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3615 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3616 return; 3617 } 3618 3619 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3620 3621 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3622 // Install and runtime permissions are stored in different places, 3623 // so figure out what permission changed and persist the change. 3624 if (permissionsState.getInstallPermissionState(name) != null) { 3625 scheduleWriteSettingsLocked(); 3626 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3627 || hadState) { 3628 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3629 } 3630 } 3631 } 3632 } 3633 3634 /** 3635 * Update the permission flags for all packages and runtime permissions of a user in order 3636 * to allow device or profile owner to remove POLICY_FIXED. 3637 */ 3638 @Override 3639 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3640 if (!sUserManager.exists(userId)) { 3641 return; 3642 } 3643 3644 mContext.enforceCallingOrSelfPermission( 3645 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3646 "updatePermissionFlagsForAllApps"); 3647 3648 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3649 "updatePermissionFlagsForAllApps"); 3650 3651 // Only the system can change system fixed flags. 3652 if (getCallingUid() != Process.SYSTEM_UID) { 3653 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3654 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3655 } 3656 3657 synchronized (mPackages) { 3658 boolean changed = false; 3659 final int packageCount = mPackages.size(); 3660 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3661 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3662 SettingBase sb = (SettingBase) pkg.mExtras; 3663 if (sb == null) { 3664 continue; 3665 } 3666 PermissionsState permissionsState = sb.getPermissionsState(); 3667 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3668 userId, flagMask, flagValues); 3669 } 3670 if (changed) { 3671 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3672 } 3673 } 3674 } 3675 3676 @Override 3677 public boolean shouldShowRequestPermissionRationale(String permissionName, 3678 String packageName, int userId) { 3679 if (UserHandle.getCallingUserId() != userId) { 3680 mContext.enforceCallingPermission( 3681 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3682 "canShowRequestPermissionRationale for user " + userId); 3683 } 3684 3685 final int uid = getPackageUid(packageName, userId); 3686 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3687 return false; 3688 } 3689 3690 if (checkPermission(permissionName, packageName, userId) 3691 == PackageManager.PERMISSION_GRANTED) { 3692 return false; 3693 } 3694 3695 final int flags; 3696 3697 final long identity = Binder.clearCallingIdentity(); 3698 try { 3699 flags = getPermissionFlags(permissionName, 3700 packageName, userId); 3701 } finally { 3702 Binder.restoreCallingIdentity(identity); 3703 } 3704 3705 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3706 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3707 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3708 3709 if ((flags & fixedFlags) != 0) { 3710 return false; 3711 } 3712 3713 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3714 } 3715 3716 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3717 BasePermission bp = mSettings.mPermissions.get(permission); 3718 if (bp == null) { 3719 throw new SecurityException("Missing " + permission + " permission"); 3720 } 3721 3722 SettingBase sb = (SettingBase) pkg.mExtras; 3723 PermissionsState permissionsState = sb.getPermissionsState(); 3724 3725 if (permissionsState.grantInstallPermission(bp) != 3726 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3727 scheduleWriteSettingsLocked(); 3728 } 3729 } 3730 3731 @Override 3732 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3733 mContext.enforceCallingOrSelfPermission( 3734 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3735 "addOnPermissionsChangeListener"); 3736 3737 synchronized (mPackages) { 3738 mOnPermissionChangeListeners.addListenerLocked(listener); 3739 } 3740 } 3741 3742 @Override 3743 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3744 synchronized (mPackages) { 3745 mOnPermissionChangeListeners.removeListenerLocked(listener); 3746 } 3747 } 3748 3749 @Override 3750 public boolean isProtectedBroadcast(String actionName) { 3751 synchronized (mPackages) { 3752 return mProtectedBroadcasts.contains(actionName); 3753 } 3754 } 3755 3756 @Override 3757 public int checkSignatures(String pkg1, String pkg2) { 3758 synchronized (mPackages) { 3759 final PackageParser.Package p1 = mPackages.get(pkg1); 3760 final PackageParser.Package p2 = mPackages.get(pkg2); 3761 if (p1 == null || p1.mExtras == null 3762 || p2 == null || p2.mExtras == null) { 3763 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3764 } 3765 return compareSignatures(p1.mSignatures, p2.mSignatures); 3766 } 3767 } 3768 3769 @Override 3770 public int checkUidSignatures(int uid1, int uid2) { 3771 // Map to base uids. 3772 uid1 = UserHandle.getAppId(uid1); 3773 uid2 = UserHandle.getAppId(uid2); 3774 // reader 3775 synchronized (mPackages) { 3776 Signature[] s1; 3777 Signature[] s2; 3778 Object obj = mSettings.getUserIdLPr(uid1); 3779 if (obj != null) { 3780 if (obj instanceof SharedUserSetting) { 3781 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3782 } else if (obj instanceof PackageSetting) { 3783 s1 = ((PackageSetting)obj).signatures.mSignatures; 3784 } else { 3785 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3786 } 3787 } else { 3788 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3789 } 3790 obj = mSettings.getUserIdLPr(uid2); 3791 if (obj != null) { 3792 if (obj instanceof SharedUserSetting) { 3793 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3794 } else if (obj instanceof PackageSetting) { 3795 s2 = ((PackageSetting)obj).signatures.mSignatures; 3796 } else { 3797 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3798 } 3799 } else { 3800 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3801 } 3802 return compareSignatures(s1, s2); 3803 } 3804 } 3805 3806 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3807 final long identity = Binder.clearCallingIdentity(); 3808 try { 3809 if (sb instanceof SharedUserSetting) { 3810 SharedUserSetting sus = (SharedUserSetting) sb; 3811 final int packageCount = sus.packages.size(); 3812 for (int i = 0; i < packageCount; i++) { 3813 PackageSetting susPs = sus.packages.valueAt(i); 3814 if (userId == UserHandle.USER_ALL) { 3815 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3816 } else { 3817 final int uid = UserHandle.getUid(userId, susPs.appId); 3818 killUid(uid, reason); 3819 } 3820 } 3821 } else if (sb instanceof PackageSetting) { 3822 PackageSetting ps = (PackageSetting) sb; 3823 if (userId == UserHandle.USER_ALL) { 3824 killApplication(ps.pkg.packageName, ps.appId, reason); 3825 } else { 3826 final int uid = UserHandle.getUid(userId, ps.appId); 3827 killUid(uid, reason); 3828 } 3829 } 3830 } finally { 3831 Binder.restoreCallingIdentity(identity); 3832 } 3833 } 3834 3835 private static void killUid(int uid, String reason) { 3836 IActivityManager am = ActivityManagerNative.getDefault(); 3837 if (am != null) { 3838 try { 3839 am.killUid(uid, reason); 3840 } catch (RemoteException e) { 3841 /* ignore - same process */ 3842 } 3843 } 3844 } 3845 3846 /** 3847 * Compares two sets of signatures. Returns: 3848 * <br /> 3849 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3850 * <br /> 3851 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3852 * <br /> 3853 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3854 * <br /> 3855 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3856 * <br /> 3857 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3858 */ 3859 static int compareSignatures(Signature[] s1, Signature[] s2) { 3860 if (s1 == null) { 3861 return s2 == null 3862 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3863 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3864 } 3865 3866 if (s2 == null) { 3867 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3868 } 3869 3870 if (s1.length != s2.length) { 3871 return PackageManager.SIGNATURE_NO_MATCH; 3872 } 3873 3874 // Since both signature sets are of size 1, we can compare without HashSets. 3875 if (s1.length == 1) { 3876 return s1[0].equals(s2[0]) ? 3877 PackageManager.SIGNATURE_MATCH : 3878 PackageManager.SIGNATURE_NO_MATCH; 3879 } 3880 3881 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3882 for (Signature sig : s1) { 3883 set1.add(sig); 3884 } 3885 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3886 for (Signature sig : s2) { 3887 set2.add(sig); 3888 } 3889 // Make sure s2 contains all signatures in s1. 3890 if (set1.equals(set2)) { 3891 return PackageManager.SIGNATURE_MATCH; 3892 } 3893 return PackageManager.SIGNATURE_NO_MATCH; 3894 } 3895 3896 /** 3897 * If the database version for this type of package (internal storage or 3898 * external storage) is less than the version where package signatures 3899 * were updated, return true. 3900 */ 3901 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3902 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3903 DatabaseVersion.SIGNATURE_END_ENTITY)) 3904 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3905 DatabaseVersion.SIGNATURE_END_ENTITY)); 3906 } 3907 3908 /** 3909 * Used for backward compatibility to make sure any packages with 3910 * certificate chains get upgraded to the new style. {@code existingSigs} 3911 * will be in the old format (since they were stored on disk from before the 3912 * system upgrade) and {@code scannedSigs} will be in the newer format. 3913 */ 3914 private int compareSignaturesCompat(PackageSignatures existingSigs, 3915 PackageParser.Package scannedPkg) { 3916 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3917 return PackageManager.SIGNATURE_NO_MATCH; 3918 } 3919 3920 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3921 for (Signature sig : existingSigs.mSignatures) { 3922 existingSet.add(sig); 3923 } 3924 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3925 for (Signature sig : scannedPkg.mSignatures) { 3926 try { 3927 Signature[] chainSignatures = sig.getChainSignatures(); 3928 for (Signature chainSig : chainSignatures) { 3929 scannedCompatSet.add(chainSig); 3930 } 3931 } catch (CertificateEncodingException e) { 3932 scannedCompatSet.add(sig); 3933 } 3934 } 3935 /* 3936 * Make sure the expanded scanned set contains all signatures in the 3937 * existing one. 3938 */ 3939 if (scannedCompatSet.equals(existingSet)) { 3940 // Migrate the old signatures to the new scheme. 3941 existingSigs.assignSignatures(scannedPkg.mSignatures); 3942 // The new KeySets will be re-added later in the scanning process. 3943 synchronized (mPackages) { 3944 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3945 } 3946 return PackageManager.SIGNATURE_MATCH; 3947 } 3948 return PackageManager.SIGNATURE_NO_MATCH; 3949 } 3950 3951 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3952 if (isExternal(scannedPkg)) { 3953 return mSettings.isExternalDatabaseVersionOlderThan( 3954 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3955 } else { 3956 return mSettings.isInternalDatabaseVersionOlderThan( 3957 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3958 } 3959 } 3960 3961 private int compareSignaturesRecover(PackageSignatures existingSigs, 3962 PackageParser.Package scannedPkg) { 3963 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3964 return PackageManager.SIGNATURE_NO_MATCH; 3965 } 3966 3967 String msg = null; 3968 try { 3969 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3970 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3971 + scannedPkg.packageName); 3972 return PackageManager.SIGNATURE_MATCH; 3973 } 3974 } catch (CertificateException e) { 3975 msg = e.getMessage(); 3976 } 3977 3978 logCriticalInfo(Log.INFO, 3979 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3980 return PackageManager.SIGNATURE_NO_MATCH; 3981 } 3982 3983 @Override 3984 public String[] getPackagesForUid(int uid) { 3985 uid = UserHandle.getAppId(uid); 3986 // reader 3987 synchronized (mPackages) { 3988 Object obj = mSettings.getUserIdLPr(uid); 3989 if (obj instanceof SharedUserSetting) { 3990 final SharedUserSetting sus = (SharedUserSetting) obj; 3991 final int N = sus.packages.size(); 3992 final String[] res = new String[N]; 3993 final Iterator<PackageSetting> it = sus.packages.iterator(); 3994 int i = 0; 3995 while (it.hasNext()) { 3996 res[i++] = it.next().name; 3997 } 3998 return res; 3999 } else if (obj instanceof PackageSetting) { 4000 final PackageSetting ps = (PackageSetting) obj; 4001 return new String[] { ps.name }; 4002 } 4003 } 4004 return null; 4005 } 4006 4007 @Override 4008 public String getNameForUid(int uid) { 4009 // reader 4010 synchronized (mPackages) { 4011 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4012 if (obj instanceof SharedUserSetting) { 4013 final SharedUserSetting sus = (SharedUserSetting) obj; 4014 return sus.name + ":" + sus.userId; 4015 } else if (obj instanceof PackageSetting) { 4016 final PackageSetting ps = (PackageSetting) obj; 4017 return ps.name; 4018 } 4019 } 4020 return null; 4021 } 4022 4023 @Override 4024 public int getUidForSharedUser(String sharedUserName) { 4025 if(sharedUserName == null) { 4026 return -1; 4027 } 4028 // reader 4029 synchronized (mPackages) { 4030 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4031 if (suid == null) { 4032 return -1; 4033 } 4034 return suid.userId; 4035 } 4036 } 4037 4038 @Override 4039 public int getFlagsForUid(int uid) { 4040 synchronized (mPackages) { 4041 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4042 if (obj instanceof SharedUserSetting) { 4043 final SharedUserSetting sus = (SharedUserSetting) obj; 4044 return sus.pkgFlags; 4045 } else if (obj instanceof PackageSetting) { 4046 final PackageSetting ps = (PackageSetting) obj; 4047 return ps.pkgFlags; 4048 } 4049 } 4050 return 0; 4051 } 4052 4053 @Override 4054 public int getPrivateFlagsForUid(int uid) { 4055 synchronized (mPackages) { 4056 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4057 if (obj instanceof SharedUserSetting) { 4058 final SharedUserSetting sus = (SharedUserSetting) obj; 4059 return sus.pkgPrivateFlags; 4060 } else if (obj instanceof PackageSetting) { 4061 final PackageSetting ps = (PackageSetting) obj; 4062 return ps.pkgPrivateFlags; 4063 } 4064 } 4065 return 0; 4066 } 4067 4068 @Override 4069 public boolean isUidPrivileged(int uid) { 4070 uid = UserHandle.getAppId(uid); 4071 // reader 4072 synchronized (mPackages) { 4073 Object obj = mSettings.getUserIdLPr(uid); 4074 if (obj instanceof SharedUserSetting) { 4075 final SharedUserSetting sus = (SharedUserSetting) obj; 4076 final Iterator<PackageSetting> it = sus.packages.iterator(); 4077 while (it.hasNext()) { 4078 if (it.next().isPrivileged()) { 4079 return true; 4080 } 4081 } 4082 } else if (obj instanceof PackageSetting) { 4083 final PackageSetting ps = (PackageSetting) obj; 4084 return ps.isPrivileged(); 4085 } 4086 } 4087 return false; 4088 } 4089 4090 @Override 4091 public String[] getAppOpPermissionPackages(String permissionName) { 4092 synchronized (mPackages) { 4093 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4094 if (pkgs == null) { 4095 return null; 4096 } 4097 return pkgs.toArray(new String[pkgs.size()]); 4098 } 4099 } 4100 4101 @Override 4102 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4103 int flags, int userId) { 4104 if (!sUserManager.exists(userId)) return null; 4105 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4106 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4107 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4108 } 4109 4110 @Override 4111 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4112 IntentFilter filter, int match, ComponentName activity) { 4113 final int userId = UserHandle.getCallingUserId(); 4114 if (DEBUG_PREFERRED) { 4115 Log.v(TAG, "setLastChosenActivity intent=" + intent 4116 + " resolvedType=" + resolvedType 4117 + " flags=" + flags 4118 + " filter=" + filter 4119 + " match=" + match 4120 + " activity=" + activity); 4121 filter.dump(new PrintStreamPrinter(System.out), " "); 4122 } 4123 intent.setComponent(null); 4124 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4125 // Find any earlier preferred or last chosen entries and nuke them 4126 findPreferredActivity(intent, resolvedType, 4127 flags, query, 0, false, true, false, userId); 4128 // Add the new activity as the last chosen for this filter 4129 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4130 "Setting last chosen"); 4131 } 4132 4133 @Override 4134 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4135 final int userId = UserHandle.getCallingUserId(); 4136 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4137 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4138 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4139 false, false, false, userId); 4140 } 4141 4142 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4143 int flags, List<ResolveInfo> query, int userId) { 4144 if (query != null) { 4145 final int N = query.size(); 4146 if (N == 1) { 4147 return query.get(0); 4148 } else if (N > 1) { 4149 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4150 // If there is more than one activity with the same priority, 4151 // then let the user decide between them. 4152 ResolveInfo r0 = query.get(0); 4153 ResolveInfo r1 = query.get(1); 4154 if (DEBUG_INTENT_MATCHING || debug) { 4155 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4156 + r1.activityInfo.name + "=" + r1.priority); 4157 } 4158 // If the first activity has a higher priority, or a different 4159 // default, then it is always desireable to pick it. 4160 if (r0.priority != r1.priority 4161 || r0.preferredOrder != r1.preferredOrder 4162 || r0.isDefault != r1.isDefault) { 4163 return query.get(0); 4164 } 4165 // If we have saved a preference for a preferred activity for 4166 // this Intent, use that. 4167 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4168 flags, query, r0.priority, true, false, debug, userId); 4169 if (ri != null) { 4170 return ri; 4171 } 4172 if (userId != 0) { 4173 ri = new ResolveInfo(mResolveInfo); 4174 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4175 ri.activityInfo.applicationInfo = new ApplicationInfo( 4176 ri.activityInfo.applicationInfo); 4177 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4178 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4179 return ri; 4180 } 4181 return mResolveInfo; 4182 } 4183 } 4184 return null; 4185 } 4186 4187 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4188 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4189 final int N = query.size(); 4190 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4191 .get(userId); 4192 // Get the list of persistent preferred activities that handle the intent 4193 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4194 List<PersistentPreferredActivity> pprefs = ppir != null 4195 ? ppir.queryIntent(intent, resolvedType, 4196 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4197 : null; 4198 if (pprefs != null && pprefs.size() > 0) { 4199 final int M = pprefs.size(); 4200 for (int i=0; i<M; i++) { 4201 final PersistentPreferredActivity ppa = pprefs.get(i); 4202 if (DEBUG_PREFERRED || debug) { 4203 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4204 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4205 + "\n component=" + ppa.mComponent); 4206 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4207 } 4208 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4209 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4210 if (DEBUG_PREFERRED || debug) { 4211 Slog.v(TAG, "Found persistent preferred activity:"); 4212 if (ai != null) { 4213 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4214 } else { 4215 Slog.v(TAG, " null"); 4216 } 4217 } 4218 if (ai == null) { 4219 // This previously registered persistent preferred activity 4220 // component is no longer known. Ignore it and do NOT remove it. 4221 continue; 4222 } 4223 for (int j=0; j<N; j++) { 4224 final ResolveInfo ri = query.get(j); 4225 if (!ri.activityInfo.applicationInfo.packageName 4226 .equals(ai.applicationInfo.packageName)) { 4227 continue; 4228 } 4229 if (!ri.activityInfo.name.equals(ai.name)) { 4230 continue; 4231 } 4232 // Found a persistent preference that can handle the intent. 4233 if (DEBUG_PREFERRED || debug) { 4234 Slog.v(TAG, "Returning persistent preferred activity: " + 4235 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4236 } 4237 return ri; 4238 } 4239 } 4240 } 4241 return null; 4242 } 4243 4244 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4245 List<ResolveInfo> query, int priority, boolean always, 4246 boolean removeMatches, boolean debug, int userId) { 4247 if (!sUserManager.exists(userId)) return null; 4248 // writer 4249 synchronized (mPackages) { 4250 if (intent.getSelector() != null) { 4251 intent = intent.getSelector(); 4252 } 4253 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4254 4255 // Try to find a matching persistent preferred activity. 4256 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4257 debug, userId); 4258 4259 // If a persistent preferred activity matched, use it. 4260 if (pri != null) { 4261 return pri; 4262 } 4263 4264 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4265 // Get the list of preferred activities that handle the intent 4266 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4267 List<PreferredActivity> prefs = pir != null 4268 ? pir.queryIntent(intent, resolvedType, 4269 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4270 : null; 4271 if (prefs != null && prefs.size() > 0) { 4272 boolean changed = false; 4273 try { 4274 // First figure out how good the original match set is. 4275 // We will only allow preferred activities that came 4276 // from the same match quality. 4277 int match = 0; 4278 4279 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4280 4281 final int N = query.size(); 4282 for (int j=0; j<N; j++) { 4283 final ResolveInfo ri = query.get(j); 4284 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4285 + ": 0x" + Integer.toHexString(match)); 4286 if (ri.match > match) { 4287 match = ri.match; 4288 } 4289 } 4290 4291 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4292 + Integer.toHexString(match)); 4293 4294 match &= IntentFilter.MATCH_CATEGORY_MASK; 4295 final int M = prefs.size(); 4296 for (int i=0; i<M; i++) { 4297 final PreferredActivity pa = prefs.get(i); 4298 if (DEBUG_PREFERRED || debug) { 4299 Slog.v(TAG, "Checking PreferredActivity ds=" 4300 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4301 + "\n component=" + pa.mPref.mComponent); 4302 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4303 } 4304 if (pa.mPref.mMatch != match) { 4305 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4306 + Integer.toHexString(pa.mPref.mMatch)); 4307 continue; 4308 } 4309 // If it's not an "always" type preferred activity and that's what we're 4310 // looking for, skip it. 4311 if (always && !pa.mPref.mAlways) { 4312 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4313 continue; 4314 } 4315 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4316 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4317 if (DEBUG_PREFERRED || debug) { 4318 Slog.v(TAG, "Found preferred activity:"); 4319 if (ai != null) { 4320 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4321 } else { 4322 Slog.v(TAG, " null"); 4323 } 4324 } 4325 if (ai == null) { 4326 // This previously registered preferred activity 4327 // component is no longer known. Most likely an update 4328 // to the app was installed and in the new version this 4329 // component no longer exists. Clean it up by removing 4330 // it from the preferred activities list, and skip it. 4331 Slog.w(TAG, "Removing dangling preferred activity: " 4332 + pa.mPref.mComponent); 4333 pir.removeFilter(pa); 4334 changed = true; 4335 continue; 4336 } 4337 for (int j=0; j<N; j++) { 4338 final ResolveInfo ri = query.get(j); 4339 if (!ri.activityInfo.applicationInfo.packageName 4340 .equals(ai.applicationInfo.packageName)) { 4341 continue; 4342 } 4343 if (!ri.activityInfo.name.equals(ai.name)) { 4344 continue; 4345 } 4346 4347 if (removeMatches) { 4348 pir.removeFilter(pa); 4349 changed = true; 4350 if (DEBUG_PREFERRED) { 4351 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4352 } 4353 break; 4354 } 4355 4356 // Okay we found a previously set preferred or last chosen app. 4357 // If the result set is different from when this 4358 // was created, we need to clear it and re-ask the 4359 // user their preference, if we're looking for an "always" type entry. 4360 if (always && !pa.mPref.sameSet(query)) { 4361 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4362 + intent + " type " + resolvedType); 4363 if (DEBUG_PREFERRED) { 4364 Slog.v(TAG, "Removing preferred activity since set changed " 4365 + pa.mPref.mComponent); 4366 } 4367 pir.removeFilter(pa); 4368 // Re-add the filter as a "last chosen" entry (!always) 4369 PreferredActivity lastChosen = new PreferredActivity( 4370 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4371 pir.addFilter(lastChosen); 4372 changed = true; 4373 return null; 4374 } 4375 4376 // Yay! Either the set matched or we're looking for the last chosen 4377 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4378 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4379 return ri; 4380 } 4381 } 4382 } finally { 4383 if (changed) { 4384 if (DEBUG_PREFERRED) { 4385 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4386 } 4387 scheduleWritePackageRestrictionsLocked(userId); 4388 } 4389 } 4390 } 4391 } 4392 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4393 return null; 4394 } 4395 4396 /* 4397 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4398 */ 4399 @Override 4400 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4401 int targetUserId) { 4402 mContext.enforceCallingOrSelfPermission( 4403 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4404 List<CrossProfileIntentFilter> matches = 4405 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4406 if (matches != null) { 4407 int size = matches.size(); 4408 for (int i = 0; i < size; i++) { 4409 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4410 } 4411 } 4412 if (hasWebURI(intent)) { 4413 // cross-profile app linking works only towards the parent. 4414 final UserInfo parent = getProfileParent(sourceUserId); 4415 synchronized(mPackages) { 4416 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4417 intent, resolvedType, 0, sourceUserId, parent.id); 4418 return xpDomainInfo != null; 4419 } 4420 } 4421 return false; 4422 } 4423 4424 private UserInfo getProfileParent(int userId) { 4425 final long identity = Binder.clearCallingIdentity(); 4426 try { 4427 return sUserManager.getProfileParent(userId); 4428 } finally { 4429 Binder.restoreCallingIdentity(identity); 4430 } 4431 } 4432 4433 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4434 String resolvedType, int userId) { 4435 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4436 if (resolver != null) { 4437 return resolver.queryIntent(intent, resolvedType, false, userId); 4438 } 4439 return null; 4440 } 4441 4442 @Override 4443 public List<ResolveInfo> queryIntentActivities(Intent intent, 4444 String resolvedType, int flags, int userId) { 4445 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4446 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4447 ComponentName comp = intent.getComponent(); 4448 if (comp == null) { 4449 if (intent.getSelector() != null) { 4450 intent = intent.getSelector(); 4451 comp = intent.getComponent(); 4452 } 4453 } 4454 4455 if (comp != null) { 4456 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4457 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4458 if (ai != null) { 4459 final ResolveInfo ri = new ResolveInfo(); 4460 ri.activityInfo = ai; 4461 list.add(ri); 4462 } 4463 return list; 4464 } 4465 4466 // reader 4467 synchronized (mPackages) { 4468 final String pkgName = intent.getPackage(); 4469 if (pkgName == null) { 4470 List<CrossProfileIntentFilter> matchingFilters = 4471 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4472 // Check for results that need to skip the current profile. 4473 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4474 resolvedType, flags, userId); 4475 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4476 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4477 result.add(xpResolveInfo); 4478 return filterIfNotPrimaryUser(result, userId); 4479 } 4480 4481 // Check for results in the current profile. 4482 List<ResolveInfo> result = mActivities.queryIntent( 4483 intent, resolvedType, flags, userId); 4484 4485 // Check for cross profile results. 4486 xpResolveInfo = queryCrossProfileIntents( 4487 matchingFilters, intent, resolvedType, flags, userId); 4488 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4489 result.add(xpResolveInfo); 4490 Collections.sort(result, mResolvePrioritySorter); 4491 } 4492 result = filterIfNotPrimaryUser(result, userId); 4493 if (hasWebURI(intent)) { 4494 CrossProfileDomainInfo xpDomainInfo = null; 4495 final UserInfo parent = getProfileParent(userId); 4496 if (parent != null) { 4497 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4498 flags, userId, parent.id); 4499 } 4500 if (xpDomainInfo != null) { 4501 if (xpResolveInfo != null) { 4502 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4503 // in the result. 4504 result.remove(xpResolveInfo); 4505 } 4506 if (result.size() == 0) { 4507 result.add(xpDomainInfo.resolveInfo); 4508 return result; 4509 } 4510 } else if (result.size() <= 1) { 4511 return result; 4512 } 4513 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4514 xpDomainInfo, userId); 4515 Collections.sort(result, mResolvePrioritySorter); 4516 } 4517 return result; 4518 } 4519 final PackageParser.Package pkg = mPackages.get(pkgName); 4520 if (pkg != null) { 4521 return filterIfNotPrimaryUser( 4522 mActivities.queryIntentForPackage( 4523 intent, resolvedType, flags, pkg.activities, userId), 4524 userId); 4525 } 4526 return new ArrayList<ResolveInfo>(); 4527 } 4528 } 4529 4530 private static class CrossProfileDomainInfo { 4531 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4532 ResolveInfo resolveInfo; 4533 /* Best domain verification status of the activities found in the other profile */ 4534 int bestDomainVerificationStatus; 4535 } 4536 4537 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4538 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4539 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4540 sourceUserId)) { 4541 return null; 4542 } 4543 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4544 resolvedType, flags, parentUserId); 4545 4546 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4547 return null; 4548 } 4549 CrossProfileDomainInfo result = null; 4550 int size = resultTargetUser.size(); 4551 for (int i = 0; i < size; i++) { 4552 ResolveInfo riTargetUser = resultTargetUser.get(i); 4553 // Intent filter verification is only for filters that specify a host. So don't return 4554 // those that handle all web uris. 4555 if (riTargetUser.handleAllWebDataURI) { 4556 continue; 4557 } 4558 String packageName = riTargetUser.activityInfo.packageName; 4559 PackageSetting ps = mSettings.mPackages.get(packageName); 4560 if (ps == null) { 4561 continue; 4562 } 4563 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4564 int status = (int)(verificationState >> 32); 4565 if (result == null) { 4566 result = new CrossProfileDomainInfo(); 4567 result.resolveInfo = 4568 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4569 result.bestDomainVerificationStatus = status; 4570 } else { 4571 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4572 result.bestDomainVerificationStatus); 4573 } 4574 } 4575 // Don't consider matches with status NEVER across profiles. 4576 if (result != null && result.bestDomainVerificationStatus 4577 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4578 return null; 4579 } 4580 return result; 4581 } 4582 4583 /** 4584 * Verification statuses are ordered from the worse to the best, except for 4585 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4586 */ 4587 private int bestDomainVerificationStatus(int status1, int status2) { 4588 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4589 return status2; 4590 } 4591 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4592 return status1; 4593 } 4594 return (int) MathUtils.max(status1, status2); 4595 } 4596 4597 private boolean isUserEnabled(int userId) { 4598 long callingId = Binder.clearCallingIdentity(); 4599 try { 4600 UserInfo userInfo = sUserManager.getUserInfo(userId); 4601 return userInfo != null && userInfo.isEnabled(); 4602 } finally { 4603 Binder.restoreCallingIdentity(callingId); 4604 } 4605 } 4606 4607 /** 4608 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4609 * 4610 * @return filtered list 4611 */ 4612 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4613 if (userId == UserHandle.USER_OWNER) { 4614 return resolveInfos; 4615 } 4616 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4617 ResolveInfo info = resolveInfos.get(i); 4618 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4619 resolveInfos.remove(i); 4620 } 4621 } 4622 return resolveInfos; 4623 } 4624 4625 private static boolean hasWebURI(Intent intent) { 4626 if (intent.getData() == null) { 4627 return false; 4628 } 4629 final String scheme = intent.getScheme(); 4630 if (TextUtils.isEmpty(scheme)) { 4631 return false; 4632 } 4633 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4634 } 4635 4636 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 4637 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4638 int userId) { 4639 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 4640 4641 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4642 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4643 candidates.size()); 4644 } 4645 4646 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4647 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4648 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4649 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4650 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4651 4652 synchronized (mPackages) { 4653 final int count = candidates.size(); 4654 // First, try to use linked apps. Partition the candidates into four lists: 4655 // one for the final results, one for the "do not use ever", one for "undefined status" 4656 // and finally one for "browser app type". 4657 for (int n=0; n<count; n++) { 4658 ResolveInfo info = candidates.get(n); 4659 String packageName = info.activityInfo.packageName; 4660 PackageSetting ps = mSettings.mPackages.get(packageName); 4661 if (ps != null) { 4662 // Add to the special match all list (Browser use case) 4663 if (info.handleAllWebDataURI) { 4664 matchAllList.add(info); 4665 continue; 4666 } 4667 // Try to get the status from User settings first 4668 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4669 int status = (int)(packedStatus >> 32); 4670 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4671 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4672 if (DEBUG_DOMAIN_VERIFICATION) { 4673 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4674 + " : linkgen=" + linkGeneration); 4675 } 4676 // Use link-enabled generation as preferredOrder, i.e. 4677 // prefer newly-enabled over earlier-enabled. 4678 info.preferredOrder = linkGeneration; 4679 alwaysList.add(info); 4680 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4681 if (DEBUG_DOMAIN_VERIFICATION) { 4682 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4683 } 4684 neverList.add(info); 4685 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4686 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4687 if (DEBUG_DOMAIN_VERIFICATION) { 4688 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4689 } 4690 undefinedList.add(info); 4691 } 4692 } 4693 } 4694 // First try to add the "always" resolution(s) for the current user, if any 4695 if (alwaysList.size() > 0) { 4696 result.addAll(alwaysList); 4697 // if there is an "always" for the parent user, add it. 4698 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4699 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4700 result.add(xpDomainInfo.resolveInfo); 4701 } else { 4702 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4703 result.addAll(undefinedList); 4704 if (xpDomainInfo != null && ( 4705 xpDomainInfo.bestDomainVerificationStatus 4706 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4707 || xpDomainInfo.bestDomainVerificationStatus 4708 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4709 result.add(xpDomainInfo.resolveInfo); 4710 } 4711 // Also add Browsers (all of them or only the default one) 4712 if ((matchFlags & MATCH_ALL) != 0) { 4713 result.addAll(matchAllList); 4714 } else { 4715 // Browser/generic handling case. If there's a default browser, go straight 4716 // to that (but only if there is no other higher-priority match). 4717 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 4718 int maxMatchPrio = 0; 4719 ResolveInfo defaultBrowserMatch = null; 4720 final int numCandidates = matchAllList.size(); 4721 for (int n = 0; n < numCandidates; n++) { 4722 ResolveInfo info = matchAllList.get(n); 4723 // track the highest overall match priority... 4724 if (info.priority > maxMatchPrio) { 4725 maxMatchPrio = info.priority; 4726 } 4727 // ...and the highest-priority default browser match 4728 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4729 if (defaultBrowserMatch == null 4730 || (defaultBrowserMatch.priority < info.priority)) { 4731 if (debug) { 4732 Slog.v(TAG, "Considering default browser match " + info); 4733 } 4734 defaultBrowserMatch = info; 4735 } 4736 } 4737 } 4738 if (defaultBrowserMatch != null 4739 && defaultBrowserMatch.priority >= maxMatchPrio 4740 && !TextUtils.isEmpty(defaultBrowserPackageName)) 4741 { 4742 if (debug) { 4743 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 4744 } 4745 result.add(defaultBrowserMatch); 4746 } else { 4747 result.addAll(matchAllList); 4748 } 4749 } 4750 4751 // If there is nothing selected, add all candidates and remove the ones that the user 4752 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4753 if (result.size() == 0) { 4754 result.addAll(candidates); 4755 result.removeAll(neverList); 4756 } 4757 } 4758 } 4759 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4760 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4761 result.size()); 4762 for (ResolveInfo info : result) { 4763 Slog.v(TAG, " + " + info.activityInfo); 4764 } 4765 } 4766 return result; 4767 } 4768 4769 // Returns a packed value as a long: 4770 // 4771 // high 'int'-sized word: link status: undefined/ask/never/always. 4772 // low 'int'-sized word: relative priority among 'always' results. 4773 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4774 long result = ps.getDomainVerificationStatusForUser(userId); 4775 // if none available, get the master status 4776 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4777 if (ps.getIntentFilterVerificationInfo() != null) { 4778 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4779 } 4780 } 4781 return result; 4782 } 4783 4784 private ResolveInfo querySkipCurrentProfileIntents( 4785 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4786 int flags, int sourceUserId) { 4787 if (matchingFilters != null) { 4788 int size = matchingFilters.size(); 4789 for (int i = 0; i < size; i ++) { 4790 CrossProfileIntentFilter filter = matchingFilters.get(i); 4791 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4792 // Checking if there are activities in the target user that can handle the 4793 // intent. 4794 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4795 flags, sourceUserId); 4796 if (resolveInfo != null) { 4797 return resolveInfo; 4798 } 4799 } 4800 } 4801 } 4802 return null; 4803 } 4804 4805 // Return matching ResolveInfo if any for skip current profile intent filters. 4806 private ResolveInfo queryCrossProfileIntents( 4807 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4808 int flags, int sourceUserId) { 4809 if (matchingFilters != null) { 4810 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4811 // match the same intent. For performance reasons, it is better not to 4812 // run queryIntent twice for the same userId 4813 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4814 int size = matchingFilters.size(); 4815 for (int i = 0; i < size; i++) { 4816 CrossProfileIntentFilter filter = matchingFilters.get(i); 4817 int targetUserId = filter.getTargetUserId(); 4818 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4819 && !alreadyTriedUserIds.get(targetUserId)) { 4820 // Checking if there are activities in the target user that can handle the 4821 // intent. 4822 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4823 flags, sourceUserId); 4824 if (resolveInfo != null) return resolveInfo; 4825 alreadyTriedUserIds.put(targetUserId, true); 4826 } 4827 } 4828 } 4829 return null; 4830 } 4831 4832 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4833 String resolvedType, int flags, int sourceUserId) { 4834 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4835 resolvedType, flags, filter.getTargetUserId()); 4836 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4837 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4838 } 4839 return null; 4840 } 4841 4842 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4843 int sourceUserId, int targetUserId) { 4844 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4845 String className; 4846 if (targetUserId == UserHandle.USER_OWNER) { 4847 className = FORWARD_INTENT_TO_USER_OWNER; 4848 } else { 4849 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4850 } 4851 ComponentName forwardingActivityComponentName = new ComponentName( 4852 mAndroidApplication.packageName, className); 4853 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4854 sourceUserId); 4855 if (targetUserId == UserHandle.USER_OWNER) { 4856 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4857 forwardingResolveInfo.noResourceId = true; 4858 } 4859 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4860 forwardingResolveInfo.priority = 0; 4861 forwardingResolveInfo.preferredOrder = 0; 4862 forwardingResolveInfo.match = 0; 4863 forwardingResolveInfo.isDefault = true; 4864 forwardingResolveInfo.filter = filter; 4865 forwardingResolveInfo.targetUserId = targetUserId; 4866 return forwardingResolveInfo; 4867 } 4868 4869 @Override 4870 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4871 Intent[] specifics, String[] specificTypes, Intent intent, 4872 String resolvedType, int flags, int userId) { 4873 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4874 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4875 false, "query intent activity options"); 4876 final String resultsAction = intent.getAction(); 4877 4878 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4879 | PackageManager.GET_RESOLVED_FILTER, userId); 4880 4881 if (DEBUG_INTENT_MATCHING) { 4882 Log.v(TAG, "Query " + intent + ": " + results); 4883 } 4884 4885 int specificsPos = 0; 4886 int N; 4887 4888 // todo: note that the algorithm used here is O(N^2). This 4889 // isn't a problem in our current environment, but if we start running 4890 // into situations where we have more than 5 or 10 matches then this 4891 // should probably be changed to something smarter... 4892 4893 // First we go through and resolve each of the specific items 4894 // that were supplied, taking care of removing any corresponding 4895 // duplicate items in the generic resolve list. 4896 if (specifics != null) { 4897 for (int i=0; i<specifics.length; i++) { 4898 final Intent sintent = specifics[i]; 4899 if (sintent == null) { 4900 continue; 4901 } 4902 4903 if (DEBUG_INTENT_MATCHING) { 4904 Log.v(TAG, "Specific #" + i + ": " + sintent); 4905 } 4906 4907 String action = sintent.getAction(); 4908 if (resultsAction != null && resultsAction.equals(action)) { 4909 // If this action was explicitly requested, then don't 4910 // remove things that have it. 4911 action = null; 4912 } 4913 4914 ResolveInfo ri = null; 4915 ActivityInfo ai = null; 4916 4917 ComponentName comp = sintent.getComponent(); 4918 if (comp == null) { 4919 ri = resolveIntent( 4920 sintent, 4921 specificTypes != null ? specificTypes[i] : null, 4922 flags, userId); 4923 if (ri == null) { 4924 continue; 4925 } 4926 if (ri == mResolveInfo) { 4927 // ACK! Must do something better with this. 4928 } 4929 ai = ri.activityInfo; 4930 comp = new ComponentName(ai.applicationInfo.packageName, 4931 ai.name); 4932 } else { 4933 ai = getActivityInfo(comp, flags, userId); 4934 if (ai == null) { 4935 continue; 4936 } 4937 } 4938 4939 // Look for any generic query activities that are duplicates 4940 // of this specific one, and remove them from the results. 4941 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4942 N = results.size(); 4943 int j; 4944 for (j=specificsPos; j<N; j++) { 4945 ResolveInfo sri = results.get(j); 4946 if ((sri.activityInfo.name.equals(comp.getClassName()) 4947 && sri.activityInfo.applicationInfo.packageName.equals( 4948 comp.getPackageName())) 4949 || (action != null && sri.filter.matchAction(action))) { 4950 results.remove(j); 4951 if (DEBUG_INTENT_MATCHING) Log.v( 4952 TAG, "Removing duplicate item from " + j 4953 + " due to specific " + specificsPos); 4954 if (ri == null) { 4955 ri = sri; 4956 } 4957 j--; 4958 N--; 4959 } 4960 } 4961 4962 // Add this specific item to its proper place. 4963 if (ri == null) { 4964 ri = new ResolveInfo(); 4965 ri.activityInfo = ai; 4966 } 4967 results.add(specificsPos, ri); 4968 ri.specificIndex = i; 4969 specificsPos++; 4970 } 4971 } 4972 4973 // Now we go through the remaining generic results and remove any 4974 // duplicate actions that are found here. 4975 N = results.size(); 4976 for (int i=specificsPos; i<N-1; i++) { 4977 final ResolveInfo rii = results.get(i); 4978 if (rii.filter == null) { 4979 continue; 4980 } 4981 4982 // Iterate over all of the actions of this result's intent 4983 // filter... typically this should be just one. 4984 final Iterator<String> it = rii.filter.actionsIterator(); 4985 if (it == null) { 4986 continue; 4987 } 4988 while (it.hasNext()) { 4989 final String action = it.next(); 4990 if (resultsAction != null && resultsAction.equals(action)) { 4991 // If this action was explicitly requested, then don't 4992 // remove things that have it. 4993 continue; 4994 } 4995 for (int j=i+1; j<N; j++) { 4996 final ResolveInfo rij = results.get(j); 4997 if (rij.filter != null && rij.filter.hasAction(action)) { 4998 results.remove(j); 4999 if (DEBUG_INTENT_MATCHING) Log.v( 5000 TAG, "Removing duplicate item from " + j 5001 + " due to action " + action + " at " + i); 5002 j--; 5003 N--; 5004 } 5005 } 5006 } 5007 5008 // If the caller didn't request filter information, drop it now 5009 // so we don't have to marshall/unmarshall it. 5010 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5011 rii.filter = null; 5012 } 5013 } 5014 5015 // Filter out the caller activity if so requested. 5016 if (caller != null) { 5017 N = results.size(); 5018 for (int i=0; i<N; i++) { 5019 ActivityInfo ainfo = results.get(i).activityInfo; 5020 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5021 && caller.getClassName().equals(ainfo.name)) { 5022 results.remove(i); 5023 break; 5024 } 5025 } 5026 } 5027 5028 // If the caller didn't request filter information, 5029 // drop them now so we don't have to 5030 // marshall/unmarshall it. 5031 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5032 N = results.size(); 5033 for (int i=0; i<N; i++) { 5034 results.get(i).filter = null; 5035 } 5036 } 5037 5038 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5039 return results; 5040 } 5041 5042 @Override 5043 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5044 int userId) { 5045 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5046 ComponentName comp = intent.getComponent(); 5047 if (comp == null) { 5048 if (intent.getSelector() != null) { 5049 intent = intent.getSelector(); 5050 comp = intent.getComponent(); 5051 } 5052 } 5053 if (comp != null) { 5054 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5055 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5056 if (ai != null) { 5057 ResolveInfo ri = new ResolveInfo(); 5058 ri.activityInfo = ai; 5059 list.add(ri); 5060 } 5061 return list; 5062 } 5063 5064 // reader 5065 synchronized (mPackages) { 5066 String pkgName = intent.getPackage(); 5067 if (pkgName == null) { 5068 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5069 } 5070 final PackageParser.Package pkg = mPackages.get(pkgName); 5071 if (pkg != null) { 5072 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5073 userId); 5074 } 5075 return null; 5076 } 5077 } 5078 5079 @Override 5080 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5081 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5082 if (!sUserManager.exists(userId)) return null; 5083 if (query != null) { 5084 if (query.size() >= 1) { 5085 // If there is more than one service with the same priority, 5086 // just arbitrarily pick the first one. 5087 return query.get(0); 5088 } 5089 } 5090 return null; 5091 } 5092 5093 @Override 5094 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5095 int userId) { 5096 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5097 ComponentName comp = intent.getComponent(); 5098 if (comp == null) { 5099 if (intent.getSelector() != null) { 5100 intent = intent.getSelector(); 5101 comp = intent.getComponent(); 5102 } 5103 } 5104 if (comp != null) { 5105 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5106 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5107 if (si != null) { 5108 final ResolveInfo ri = new ResolveInfo(); 5109 ri.serviceInfo = si; 5110 list.add(ri); 5111 } 5112 return list; 5113 } 5114 5115 // reader 5116 synchronized (mPackages) { 5117 String pkgName = intent.getPackage(); 5118 if (pkgName == null) { 5119 return mServices.queryIntent(intent, resolvedType, flags, userId); 5120 } 5121 final PackageParser.Package pkg = mPackages.get(pkgName); 5122 if (pkg != null) { 5123 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5124 userId); 5125 } 5126 return null; 5127 } 5128 } 5129 5130 @Override 5131 public List<ResolveInfo> queryIntentContentProviders( 5132 Intent intent, String resolvedType, int flags, int userId) { 5133 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5134 ComponentName comp = intent.getComponent(); 5135 if (comp == null) { 5136 if (intent.getSelector() != null) { 5137 intent = intent.getSelector(); 5138 comp = intent.getComponent(); 5139 } 5140 } 5141 if (comp != null) { 5142 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5143 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5144 if (pi != null) { 5145 final ResolveInfo ri = new ResolveInfo(); 5146 ri.providerInfo = pi; 5147 list.add(ri); 5148 } 5149 return list; 5150 } 5151 5152 // reader 5153 synchronized (mPackages) { 5154 String pkgName = intent.getPackage(); 5155 if (pkgName == null) { 5156 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5157 } 5158 final PackageParser.Package pkg = mPackages.get(pkgName); 5159 if (pkg != null) { 5160 return mProviders.queryIntentForPackage( 5161 intent, resolvedType, flags, pkg.providers, userId); 5162 } 5163 return null; 5164 } 5165 } 5166 5167 @Override 5168 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5169 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5170 5171 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5172 5173 // writer 5174 synchronized (mPackages) { 5175 ArrayList<PackageInfo> list; 5176 if (listUninstalled) { 5177 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5178 for (PackageSetting ps : mSettings.mPackages.values()) { 5179 PackageInfo pi; 5180 if (ps.pkg != null) { 5181 pi = generatePackageInfo(ps.pkg, flags, userId); 5182 } else { 5183 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5184 } 5185 if (pi != null) { 5186 list.add(pi); 5187 } 5188 } 5189 } else { 5190 list = new ArrayList<PackageInfo>(mPackages.size()); 5191 for (PackageParser.Package p : mPackages.values()) { 5192 PackageInfo pi = generatePackageInfo(p, flags, userId); 5193 if (pi != null) { 5194 list.add(pi); 5195 } 5196 } 5197 } 5198 5199 return new ParceledListSlice<PackageInfo>(list); 5200 } 5201 } 5202 5203 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5204 String[] permissions, boolean[] tmp, int flags, int userId) { 5205 int numMatch = 0; 5206 final PermissionsState permissionsState = ps.getPermissionsState(); 5207 for (int i=0; i<permissions.length; i++) { 5208 final String permission = permissions[i]; 5209 if (permissionsState.hasPermission(permission, userId)) { 5210 tmp[i] = true; 5211 numMatch++; 5212 } else { 5213 tmp[i] = false; 5214 } 5215 } 5216 if (numMatch == 0) { 5217 return; 5218 } 5219 PackageInfo pi; 5220 if (ps.pkg != null) { 5221 pi = generatePackageInfo(ps.pkg, flags, userId); 5222 } else { 5223 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5224 } 5225 // The above might return null in cases of uninstalled apps or install-state 5226 // skew across users/profiles. 5227 if (pi != null) { 5228 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5229 if (numMatch == permissions.length) { 5230 pi.requestedPermissions = permissions; 5231 } else { 5232 pi.requestedPermissions = new String[numMatch]; 5233 numMatch = 0; 5234 for (int i=0; i<permissions.length; i++) { 5235 if (tmp[i]) { 5236 pi.requestedPermissions[numMatch] = permissions[i]; 5237 numMatch++; 5238 } 5239 } 5240 } 5241 } 5242 list.add(pi); 5243 } 5244 } 5245 5246 @Override 5247 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5248 String[] permissions, int flags, int userId) { 5249 if (!sUserManager.exists(userId)) return null; 5250 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5251 5252 // writer 5253 synchronized (mPackages) { 5254 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5255 boolean[] tmpBools = new boolean[permissions.length]; 5256 if (listUninstalled) { 5257 for (PackageSetting ps : mSettings.mPackages.values()) { 5258 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5259 } 5260 } else { 5261 for (PackageParser.Package pkg : mPackages.values()) { 5262 PackageSetting ps = (PackageSetting)pkg.mExtras; 5263 if (ps != null) { 5264 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5265 userId); 5266 } 5267 } 5268 } 5269 5270 return new ParceledListSlice<PackageInfo>(list); 5271 } 5272 } 5273 5274 @Override 5275 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5276 if (!sUserManager.exists(userId)) return null; 5277 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5278 5279 // writer 5280 synchronized (mPackages) { 5281 ArrayList<ApplicationInfo> list; 5282 if (listUninstalled) { 5283 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5284 for (PackageSetting ps : mSettings.mPackages.values()) { 5285 ApplicationInfo ai; 5286 if (ps.pkg != null) { 5287 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5288 ps.readUserState(userId), userId); 5289 } else { 5290 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5291 } 5292 if (ai != null) { 5293 list.add(ai); 5294 } 5295 } 5296 } else { 5297 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5298 for (PackageParser.Package p : mPackages.values()) { 5299 if (p.mExtras != null) { 5300 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5301 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5302 if (ai != null) { 5303 list.add(ai); 5304 } 5305 } 5306 } 5307 } 5308 5309 return new ParceledListSlice<ApplicationInfo>(list); 5310 } 5311 } 5312 5313 public List<ApplicationInfo> getPersistentApplications(int flags) { 5314 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5315 5316 // reader 5317 synchronized (mPackages) { 5318 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5319 final int userId = UserHandle.getCallingUserId(); 5320 while (i.hasNext()) { 5321 final PackageParser.Package p = i.next(); 5322 if (p.applicationInfo != null 5323 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5324 && (!mSafeMode || isSystemApp(p))) { 5325 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5326 if (ps != null) { 5327 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5328 ps.readUserState(userId), userId); 5329 if (ai != null) { 5330 finalList.add(ai); 5331 } 5332 } 5333 } 5334 } 5335 } 5336 5337 return finalList; 5338 } 5339 5340 @Override 5341 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5342 if (!sUserManager.exists(userId)) return null; 5343 // reader 5344 synchronized (mPackages) { 5345 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5346 PackageSetting ps = provider != null 5347 ? mSettings.mPackages.get(provider.owner.packageName) 5348 : null; 5349 return ps != null 5350 && mSettings.isEnabledLPr(provider.info, flags, userId) 5351 && (!mSafeMode || (provider.info.applicationInfo.flags 5352 &ApplicationInfo.FLAG_SYSTEM) != 0) 5353 ? PackageParser.generateProviderInfo(provider, flags, 5354 ps.readUserState(userId), userId) 5355 : null; 5356 } 5357 } 5358 5359 /** 5360 * @deprecated 5361 */ 5362 @Deprecated 5363 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5364 // reader 5365 synchronized (mPackages) { 5366 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5367 .entrySet().iterator(); 5368 final int userId = UserHandle.getCallingUserId(); 5369 while (i.hasNext()) { 5370 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5371 PackageParser.Provider p = entry.getValue(); 5372 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5373 5374 if (ps != null && p.syncable 5375 && (!mSafeMode || (p.info.applicationInfo.flags 5376 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5377 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5378 ps.readUserState(userId), userId); 5379 if (info != null) { 5380 outNames.add(entry.getKey()); 5381 outInfo.add(info); 5382 } 5383 } 5384 } 5385 } 5386 } 5387 5388 @Override 5389 public List<ProviderInfo> queryContentProviders(String processName, 5390 int uid, int flags) { 5391 ArrayList<ProviderInfo> finalList = null; 5392 // reader 5393 synchronized (mPackages) { 5394 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5395 final int userId = processName != null ? 5396 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5397 while (i.hasNext()) { 5398 final PackageParser.Provider p = i.next(); 5399 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5400 if (ps != null && p.info.authority != null 5401 && (processName == null 5402 || (p.info.processName.equals(processName) 5403 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5404 && mSettings.isEnabledLPr(p.info, flags, userId) 5405 && (!mSafeMode 5406 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5407 if (finalList == null) { 5408 finalList = new ArrayList<ProviderInfo>(3); 5409 } 5410 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5411 ps.readUserState(userId), userId); 5412 if (info != null) { 5413 finalList.add(info); 5414 } 5415 } 5416 } 5417 } 5418 5419 if (finalList != null) { 5420 Collections.sort(finalList, mProviderInitOrderSorter); 5421 } 5422 5423 return finalList; 5424 } 5425 5426 @Override 5427 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5428 int flags) { 5429 // reader 5430 synchronized (mPackages) { 5431 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5432 return PackageParser.generateInstrumentationInfo(i, flags); 5433 } 5434 } 5435 5436 @Override 5437 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5438 int flags) { 5439 ArrayList<InstrumentationInfo> finalList = 5440 new ArrayList<InstrumentationInfo>(); 5441 5442 // reader 5443 synchronized (mPackages) { 5444 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5445 while (i.hasNext()) { 5446 final PackageParser.Instrumentation p = i.next(); 5447 if (targetPackage == null 5448 || targetPackage.equals(p.info.targetPackage)) { 5449 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5450 flags); 5451 if (ii != null) { 5452 finalList.add(ii); 5453 } 5454 } 5455 } 5456 } 5457 5458 return finalList; 5459 } 5460 5461 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5462 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5463 if (overlays == null) { 5464 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5465 return; 5466 } 5467 for (PackageParser.Package opkg : overlays.values()) { 5468 // Not much to do if idmap fails: we already logged the error 5469 // and we certainly don't want to abort installation of pkg simply 5470 // because an overlay didn't fit properly. For these reasons, 5471 // ignore the return value of createIdmapForPackagePairLI. 5472 createIdmapForPackagePairLI(pkg, opkg); 5473 } 5474 } 5475 5476 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5477 PackageParser.Package opkg) { 5478 if (!opkg.mTrustedOverlay) { 5479 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5480 opkg.baseCodePath + ": overlay not trusted"); 5481 return false; 5482 } 5483 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5484 if (overlaySet == null) { 5485 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5486 opkg.baseCodePath + " but target package has no known overlays"); 5487 return false; 5488 } 5489 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5490 // TODO: generate idmap for split APKs 5491 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5492 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5493 + opkg.baseCodePath); 5494 return false; 5495 } 5496 PackageParser.Package[] overlayArray = 5497 overlaySet.values().toArray(new PackageParser.Package[0]); 5498 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5499 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5500 return p1.mOverlayPriority - p2.mOverlayPriority; 5501 } 5502 }; 5503 Arrays.sort(overlayArray, cmp); 5504 5505 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5506 int i = 0; 5507 for (PackageParser.Package p : overlayArray) { 5508 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5509 } 5510 return true; 5511 } 5512 5513 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5514 final File[] files = dir.listFiles(); 5515 if (ArrayUtils.isEmpty(files)) { 5516 Log.d(TAG, "No files in app dir " + dir); 5517 return; 5518 } 5519 5520 if (DEBUG_PACKAGE_SCANNING) { 5521 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5522 + " flags=0x" + Integer.toHexString(parseFlags)); 5523 } 5524 5525 for (File file : files) { 5526 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5527 && !PackageInstallerService.isStageName(file.getName()); 5528 if (!isPackage) { 5529 // Ignore entries which are not packages 5530 continue; 5531 } 5532 try { 5533 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5534 scanFlags, currentTime, null); 5535 } catch (PackageManagerException e) { 5536 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5537 5538 // Delete invalid userdata apps 5539 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5540 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5541 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5542 if (file.isDirectory()) { 5543 mInstaller.rmPackageDir(file.getAbsolutePath()); 5544 } else { 5545 file.delete(); 5546 } 5547 } 5548 } 5549 } 5550 } 5551 5552 private static File getSettingsProblemFile() { 5553 File dataDir = Environment.getDataDirectory(); 5554 File systemDir = new File(dataDir, "system"); 5555 File fname = new File(systemDir, "uiderrors.txt"); 5556 return fname; 5557 } 5558 5559 static void reportSettingsProblem(int priority, String msg) { 5560 logCriticalInfo(priority, msg); 5561 } 5562 5563 static void logCriticalInfo(int priority, String msg) { 5564 Slog.println(priority, TAG, msg); 5565 EventLogTags.writePmCriticalInfo(msg); 5566 try { 5567 File fname = getSettingsProblemFile(); 5568 FileOutputStream out = new FileOutputStream(fname, true); 5569 PrintWriter pw = new FastPrintWriter(out); 5570 SimpleDateFormat formatter = new SimpleDateFormat(); 5571 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5572 pw.println(dateString + ": " + msg); 5573 pw.close(); 5574 FileUtils.setPermissions( 5575 fname.toString(), 5576 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5577 -1, -1); 5578 } catch (java.io.IOException e) { 5579 } 5580 } 5581 5582 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5583 PackageParser.Package pkg, File srcFile, int parseFlags) 5584 throws PackageManagerException { 5585 if (ps != null 5586 && ps.codePath.equals(srcFile) 5587 && ps.timeStamp == srcFile.lastModified() 5588 && !isCompatSignatureUpdateNeeded(pkg) 5589 && !isRecoverSignatureUpdateNeeded(pkg)) { 5590 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5591 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5592 ArraySet<PublicKey> signingKs; 5593 synchronized (mPackages) { 5594 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5595 } 5596 if (ps.signatures.mSignatures != null 5597 && ps.signatures.mSignatures.length != 0 5598 && signingKs != null) { 5599 // Optimization: reuse the existing cached certificates 5600 // if the package appears to be unchanged. 5601 pkg.mSignatures = ps.signatures.mSignatures; 5602 pkg.mSigningKeys = signingKs; 5603 return; 5604 } 5605 5606 Slog.w(TAG, "PackageSetting for " + ps.name 5607 + " is missing signatures. Collecting certs again to recover them."); 5608 } else { 5609 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5610 } 5611 5612 try { 5613 pp.collectCertificates(pkg, parseFlags); 5614 pp.collectManifestDigest(pkg); 5615 } catch (PackageParserException e) { 5616 throw PackageManagerException.from(e); 5617 } 5618 } 5619 5620 /* 5621 * Scan a package and return the newly parsed package. 5622 * Returns null in case of errors and the error code is stored in mLastScanError 5623 */ 5624 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5625 long currentTime, UserHandle user) throws PackageManagerException { 5626 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5627 parseFlags |= mDefParseFlags; 5628 PackageParser pp = new PackageParser(); 5629 pp.setSeparateProcesses(mSeparateProcesses); 5630 pp.setOnlyCoreApps(mOnlyCore); 5631 pp.setDisplayMetrics(mMetrics); 5632 5633 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5634 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5635 } 5636 5637 final PackageParser.Package pkg; 5638 try { 5639 pkg = pp.parsePackage(scanFile, parseFlags); 5640 } catch (PackageParserException e) { 5641 throw PackageManagerException.from(e); 5642 } 5643 5644 PackageSetting ps = null; 5645 PackageSetting updatedPkg; 5646 // reader 5647 synchronized (mPackages) { 5648 // Look to see if we already know about this package. 5649 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5650 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5651 // This package has been renamed to its original name. Let's 5652 // use that. 5653 ps = mSettings.peekPackageLPr(oldName); 5654 } 5655 // If there was no original package, see one for the real package name. 5656 if (ps == null) { 5657 ps = mSettings.peekPackageLPr(pkg.packageName); 5658 } 5659 // Check to see if this package could be hiding/updating a system 5660 // package. Must look for it either under the original or real 5661 // package name depending on our state. 5662 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5663 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5664 } 5665 boolean updatedPkgBetter = false; 5666 // First check if this is a system package that may involve an update 5667 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5668 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5669 // it needs to drop FLAG_PRIVILEGED. 5670 if (locationIsPrivileged(scanFile)) { 5671 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5672 } else { 5673 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5674 } 5675 5676 if (ps != null && !ps.codePath.equals(scanFile)) { 5677 // The path has changed from what was last scanned... check the 5678 // version of the new path against what we have stored to determine 5679 // what to do. 5680 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5681 if (pkg.mVersionCode <= ps.versionCode) { 5682 // The system package has been updated and the code path does not match 5683 // Ignore entry. Skip it. 5684 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5685 + " ignored: updated version " + ps.versionCode 5686 + " better than this " + pkg.mVersionCode); 5687 if (!updatedPkg.codePath.equals(scanFile)) { 5688 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5689 + ps.name + " changing from " + updatedPkg.codePathString 5690 + " to " + scanFile); 5691 updatedPkg.codePath = scanFile; 5692 updatedPkg.codePathString = scanFile.toString(); 5693 updatedPkg.resourcePath = scanFile; 5694 updatedPkg.resourcePathString = scanFile.toString(); 5695 } 5696 updatedPkg.pkg = pkg; 5697 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5698 "Package " + ps.name + " at " + scanFile 5699 + " ignored: updated version " + ps.versionCode 5700 + " better than this " + pkg.mVersionCode); 5701 } else { 5702 // The current app on the system partition is better than 5703 // what we have updated to on the data partition; switch 5704 // back to the system partition version. 5705 // At this point, its safely assumed that package installation for 5706 // apps in system partition will go through. If not there won't be a working 5707 // version of the app 5708 // writer 5709 synchronized (mPackages) { 5710 // Just remove the loaded entries from package lists. 5711 mPackages.remove(ps.name); 5712 } 5713 5714 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5715 + " reverting from " + ps.codePathString 5716 + ": new version " + pkg.mVersionCode 5717 + " better than installed " + ps.versionCode); 5718 5719 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5720 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5721 synchronized (mInstallLock) { 5722 args.cleanUpResourcesLI(); 5723 } 5724 synchronized (mPackages) { 5725 mSettings.enableSystemPackageLPw(ps.name); 5726 } 5727 updatedPkgBetter = true; 5728 } 5729 } 5730 } 5731 5732 if (updatedPkg != null) { 5733 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5734 // initially 5735 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5736 5737 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5738 // flag set initially 5739 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5740 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5741 } 5742 } 5743 5744 // Verify certificates against what was last scanned 5745 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5746 5747 /* 5748 * A new system app appeared, but we already had a non-system one of the 5749 * same name installed earlier. 5750 */ 5751 boolean shouldHideSystemApp = false; 5752 if (updatedPkg == null && ps != null 5753 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5754 /* 5755 * Check to make sure the signatures match first. If they don't, 5756 * wipe the installed application and its data. 5757 */ 5758 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5759 != PackageManager.SIGNATURE_MATCH) { 5760 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5761 + " signatures don't match existing userdata copy; removing"); 5762 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5763 ps = null; 5764 } else { 5765 /* 5766 * If the newly-added system app is an older version than the 5767 * already installed version, hide it. It will be scanned later 5768 * and re-added like an update. 5769 */ 5770 if (pkg.mVersionCode <= ps.versionCode) { 5771 shouldHideSystemApp = true; 5772 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5773 + " but new version " + pkg.mVersionCode + " better than installed " 5774 + ps.versionCode + "; hiding system"); 5775 } else { 5776 /* 5777 * The newly found system app is a newer version that the 5778 * one previously installed. Simply remove the 5779 * already-installed application and replace it with our own 5780 * while keeping the application data. 5781 */ 5782 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5783 + " reverting from " + ps.codePathString + ": new version " 5784 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5785 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5786 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5787 synchronized (mInstallLock) { 5788 args.cleanUpResourcesLI(); 5789 } 5790 } 5791 } 5792 } 5793 5794 // The apk is forward locked (not public) if its code and resources 5795 // are kept in different files. (except for app in either system or 5796 // vendor path). 5797 // TODO grab this value from PackageSettings 5798 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5799 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5800 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5801 } 5802 } 5803 5804 // TODO: extend to support forward-locked splits 5805 String resourcePath = null; 5806 String baseResourcePath = null; 5807 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5808 if (ps != null && ps.resourcePathString != null) { 5809 resourcePath = ps.resourcePathString; 5810 baseResourcePath = ps.resourcePathString; 5811 } else { 5812 // Should not happen at all. Just log an error. 5813 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5814 } 5815 } else { 5816 resourcePath = pkg.codePath; 5817 baseResourcePath = pkg.baseCodePath; 5818 } 5819 5820 // Set application objects path explicitly. 5821 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5822 pkg.applicationInfo.setCodePath(pkg.codePath); 5823 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5824 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5825 pkg.applicationInfo.setResourcePath(resourcePath); 5826 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5827 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5828 5829 // Note that we invoke the following method only if we are about to unpack an application 5830 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5831 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5832 5833 /* 5834 * If the system app should be overridden by a previously installed 5835 * data, hide the system app now and let the /data/app scan pick it up 5836 * again. 5837 */ 5838 if (shouldHideSystemApp) { 5839 synchronized (mPackages) { 5840 /* 5841 * We have to grant systems permissions before we hide, because 5842 * grantPermissions will assume the package update is trying to 5843 * expand its permissions. 5844 */ 5845 grantPermissionsLPw(pkg, true, pkg.packageName); 5846 mSettings.disableSystemPackageLPw(pkg.packageName); 5847 } 5848 } 5849 5850 return scannedPkg; 5851 } 5852 5853 private static String fixProcessName(String defProcessName, 5854 String processName, int uid) { 5855 if (processName == null) { 5856 return defProcessName; 5857 } 5858 return processName; 5859 } 5860 5861 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5862 throws PackageManagerException { 5863 if (pkgSetting.signatures.mSignatures != null) { 5864 // Already existing package. Make sure signatures match 5865 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5866 == PackageManager.SIGNATURE_MATCH; 5867 if (!match) { 5868 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5869 == PackageManager.SIGNATURE_MATCH; 5870 } 5871 if (!match) { 5872 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5873 == PackageManager.SIGNATURE_MATCH; 5874 } 5875 if (!match) { 5876 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5877 + pkg.packageName + " signatures do not match the " 5878 + "previously installed version; ignoring!"); 5879 } 5880 } 5881 5882 // Check for shared user signatures 5883 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5884 // Already existing package. Make sure signatures match 5885 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5886 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5887 if (!match) { 5888 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5889 == PackageManager.SIGNATURE_MATCH; 5890 } 5891 if (!match) { 5892 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5893 == PackageManager.SIGNATURE_MATCH; 5894 } 5895 if (!match) { 5896 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5897 "Package " + pkg.packageName 5898 + " has no signatures that match those in shared user " 5899 + pkgSetting.sharedUser.name + "; ignoring!"); 5900 } 5901 } 5902 } 5903 5904 /** 5905 * Enforces that only the system UID or root's UID can call a method exposed 5906 * via Binder. 5907 * 5908 * @param message used as message if SecurityException is thrown 5909 * @throws SecurityException if the caller is not system or root 5910 */ 5911 private static final void enforceSystemOrRoot(String message) { 5912 final int uid = Binder.getCallingUid(); 5913 if (uid != Process.SYSTEM_UID && uid != 0) { 5914 throw new SecurityException(message); 5915 } 5916 } 5917 5918 @Override 5919 public void performBootDexOpt() { 5920 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5921 5922 // Before everything else, see whether we need to fstrim. 5923 try { 5924 IMountService ms = PackageHelper.getMountService(); 5925 if (ms != null) { 5926 final boolean isUpgrade = isUpgrade(); 5927 boolean doTrim = isUpgrade; 5928 if (doTrim) { 5929 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5930 } else { 5931 final long interval = android.provider.Settings.Global.getLong( 5932 mContext.getContentResolver(), 5933 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5934 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5935 if (interval > 0) { 5936 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5937 if (timeSinceLast > interval) { 5938 doTrim = true; 5939 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5940 + "; running immediately"); 5941 } 5942 } 5943 } 5944 if (doTrim) { 5945 if (!isFirstBoot()) { 5946 try { 5947 ActivityManagerNative.getDefault().showBootMessage( 5948 mContext.getResources().getString( 5949 R.string.android_upgrading_fstrim), true); 5950 } catch (RemoteException e) { 5951 } 5952 } 5953 ms.runMaintenance(); 5954 } 5955 } else { 5956 Slog.e(TAG, "Mount service unavailable!"); 5957 } 5958 } catch (RemoteException e) { 5959 // Can't happen; MountService is local 5960 } 5961 5962 final ArraySet<PackageParser.Package> pkgs; 5963 synchronized (mPackages) { 5964 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5965 } 5966 5967 if (pkgs != null) { 5968 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5969 // in case the device runs out of space. 5970 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5971 // Give priority to core apps. 5972 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5973 PackageParser.Package pkg = it.next(); 5974 if (pkg.coreApp) { 5975 if (DEBUG_DEXOPT) { 5976 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5977 } 5978 sortedPkgs.add(pkg); 5979 it.remove(); 5980 } 5981 } 5982 // Give priority to system apps that listen for pre boot complete. 5983 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5984 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5985 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5986 PackageParser.Package pkg = it.next(); 5987 if (pkgNames.contains(pkg.packageName)) { 5988 if (DEBUG_DEXOPT) { 5989 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5990 } 5991 sortedPkgs.add(pkg); 5992 it.remove(); 5993 } 5994 } 5995 // Give priority to system apps. 5996 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5997 PackageParser.Package pkg = it.next(); 5998 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5999 if (DEBUG_DEXOPT) { 6000 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 6001 } 6002 sortedPkgs.add(pkg); 6003 it.remove(); 6004 } 6005 } 6006 // Give priority to updated system apps. 6007 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6008 PackageParser.Package pkg = it.next(); 6009 if (pkg.isUpdatedSystemApp()) { 6010 if (DEBUG_DEXOPT) { 6011 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6012 } 6013 sortedPkgs.add(pkg); 6014 it.remove(); 6015 } 6016 } 6017 // Give priority to apps that listen for boot complete. 6018 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6019 pkgNames = getPackageNamesForIntent(intent); 6020 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6021 PackageParser.Package pkg = it.next(); 6022 if (pkgNames.contains(pkg.packageName)) { 6023 if (DEBUG_DEXOPT) { 6024 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6025 } 6026 sortedPkgs.add(pkg); 6027 it.remove(); 6028 } 6029 } 6030 // Filter out packages that aren't recently used. 6031 filterRecentlyUsedApps(pkgs); 6032 // Add all remaining apps. 6033 for (PackageParser.Package pkg : pkgs) { 6034 if (DEBUG_DEXOPT) { 6035 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6036 } 6037 sortedPkgs.add(pkg); 6038 } 6039 6040 // If we want to be lazy, filter everything that wasn't recently used. 6041 if (mLazyDexOpt) { 6042 filterRecentlyUsedApps(sortedPkgs); 6043 } 6044 6045 int i = 0; 6046 int total = sortedPkgs.size(); 6047 File dataDir = Environment.getDataDirectory(); 6048 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6049 if (lowThreshold == 0) { 6050 throw new IllegalStateException("Invalid low memory threshold"); 6051 } 6052 for (PackageParser.Package pkg : sortedPkgs) { 6053 long usableSpace = dataDir.getUsableSpace(); 6054 if (usableSpace < lowThreshold) { 6055 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6056 break; 6057 } 6058 performBootDexOpt(pkg, ++i, total); 6059 } 6060 } 6061 } 6062 6063 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6064 // Filter out packages that aren't recently used. 6065 // 6066 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6067 // should do a full dexopt. 6068 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6069 int total = pkgs.size(); 6070 int skipped = 0; 6071 long now = System.currentTimeMillis(); 6072 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6073 PackageParser.Package pkg = i.next(); 6074 long then = pkg.mLastPackageUsageTimeInMills; 6075 if (then + mDexOptLRUThresholdInMills < now) { 6076 if (DEBUG_DEXOPT) { 6077 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6078 ((then == 0) ? "never" : new Date(then))); 6079 } 6080 i.remove(); 6081 skipped++; 6082 } 6083 } 6084 if (DEBUG_DEXOPT) { 6085 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6086 } 6087 } 6088 } 6089 6090 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6091 List<ResolveInfo> ris = null; 6092 try { 6093 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6094 intent, null, 0, UserHandle.USER_OWNER); 6095 } catch (RemoteException e) { 6096 } 6097 ArraySet<String> pkgNames = new ArraySet<String>(); 6098 if (ris != null) { 6099 for (ResolveInfo ri : ris) { 6100 pkgNames.add(ri.activityInfo.packageName); 6101 } 6102 } 6103 return pkgNames; 6104 } 6105 6106 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6107 if (DEBUG_DEXOPT) { 6108 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6109 } 6110 if (!isFirstBoot()) { 6111 try { 6112 ActivityManagerNative.getDefault().showBootMessage( 6113 mContext.getResources().getString(R.string.android_upgrading_apk, 6114 curr, total), true); 6115 } catch (RemoteException e) { 6116 } 6117 } 6118 PackageParser.Package p = pkg; 6119 synchronized (mInstallLock) { 6120 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6121 false /* force dex */, false /* defer */, true /* include dependencies */); 6122 } 6123 } 6124 6125 @Override 6126 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6127 return performDexOpt(packageName, instructionSet, false); 6128 } 6129 6130 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6131 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6132 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6133 if (!dexopt && !updateUsage) { 6134 // We aren't going to dexopt or update usage, so bail early. 6135 return false; 6136 } 6137 PackageParser.Package p; 6138 final String targetInstructionSet; 6139 synchronized (mPackages) { 6140 p = mPackages.get(packageName); 6141 if (p == null) { 6142 return false; 6143 } 6144 if (updateUsage) { 6145 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6146 } 6147 mPackageUsage.write(false); 6148 if (!dexopt) { 6149 // We aren't going to dexopt, so bail early. 6150 return false; 6151 } 6152 6153 targetInstructionSet = instructionSet != null ? instructionSet : 6154 getPrimaryInstructionSet(p.applicationInfo); 6155 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6156 return false; 6157 } 6158 } 6159 6160 synchronized (mInstallLock) { 6161 final String[] instructionSets = new String[] { targetInstructionSet }; 6162 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6163 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6164 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6165 } 6166 } 6167 6168 public ArraySet<String> getPackagesThatNeedDexOpt() { 6169 ArraySet<String> pkgs = null; 6170 synchronized (mPackages) { 6171 for (PackageParser.Package p : mPackages.values()) { 6172 if (DEBUG_DEXOPT) { 6173 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6174 } 6175 if (!p.mDexOptPerformed.isEmpty()) { 6176 continue; 6177 } 6178 if (pkgs == null) { 6179 pkgs = new ArraySet<String>(); 6180 } 6181 pkgs.add(p.packageName); 6182 } 6183 } 6184 return pkgs; 6185 } 6186 6187 public void shutdown() { 6188 mPackageUsage.write(true); 6189 } 6190 6191 @Override 6192 public void forceDexOpt(String packageName) { 6193 enforceSystemOrRoot("forceDexOpt"); 6194 6195 PackageParser.Package pkg; 6196 synchronized (mPackages) { 6197 pkg = mPackages.get(packageName); 6198 if (pkg == null) { 6199 throw new IllegalArgumentException("Missing package: " + packageName); 6200 } 6201 } 6202 6203 synchronized (mInstallLock) { 6204 final String[] instructionSets = new String[] { 6205 getPrimaryInstructionSet(pkg.applicationInfo) }; 6206 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6207 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6208 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6209 throw new IllegalStateException("Failed to dexopt: " + res); 6210 } 6211 } 6212 } 6213 6214 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6215 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6216 Slog.w(TAG, "Unable to update from " + oldPkg.name 6217 + " to " + newPkg.packageName 6218 + ": old package not in system partition"); 6219 return false; 6220 } else if (mPackages.get(oldPkg.name) != null) { 6221 Slog.w(TAG, "Unable to update from " + oldPkg.name 6222 + " to " + newPkg.packageName 6223 + ": old package still exists"); 6224 return false; 6225 } 6226 return true; 6227 } 6228 6229 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6230 int[] users = sUserManager.getUserIds(); 6231 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6232 if (res < 0) { 6233 return res; 6234 } 6235 for (int user : users) { 6236 if (user != 0) { 6237 res = mInstaller.createUserData(volumeUuid, packageName, 6238 UserHandle.getUid(user, uid), user, seinfo); 6239 if (res < 0) { 6240 return res; 6241 } 6242 } 6243 } 6244 return res; 6245 } 6246 6247 private int removeDataDirsLI(String volumeUuid, String packageName) { 6248 int[] users = sUserManager.getUserIds(); 6249 int res = 0; 6250 for (int user : users) { 6251 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6252 if (resInner < 0) { 6253 res = resInner; 6254 } 6255 } 6256 6257 return res; 6258 } 6259 6260 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6261 int[] users = sUserManager.getUserIds(); 6262 int res = 0; 6263 for (int user : users) { 6264 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6265 if (resInner < 0) { 6266 res = resInner; 6267 } 6268 } 6269 return res; 6270 } 6271 6272 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6273 PackageParser.Package changingLib) { 6274 if (file.path != null) { 6275 usesLibraryFiles.add(file.path); 6276 return; 6277 } 6278 PackageParser.Package p = mPackages.get(file.apk); 6279 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6280 // If we are doing this while in the middle of updating a library apk, 6281 // then we need to make sure to use that new apk for determining the 6282 // dependencies here. (We haven't yet finished committing the new apk 6283 // to the package manager state.) 6284 if (p == null || p.packageName.equals(changingLib.packageName)) { 6285 p = changingLib; 6286 } 6287 } 6288 if (p != null) { 6289 usesLibraryFiles.addAll(p.getAllCodePaths()); 6290 } 6291 } 6292 6293 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6294 PackageParser.Package changingLib) throws PackageManagerException { 6295 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6296 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6297 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6298 for (int i=0; i<N; i++) { 6299 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6300 if (file == null) { 6301 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6302 "Package " + pkg.packageName + " requires unavailable shared library " 6303 + pkg.usesLibraries.get(i) + "; failing!"); 6304 } 6305 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6306 } 6307 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6308 for (int i=0; i<N; i++) { 6309 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6310 if (file == null) { 6311 Slog.w(TAG, "Package " + pkg.packageName 6312 + " desires unavailable shared library " 6313 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6314 } else { 6315 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6316 } 6317 } 6318 N = usesLibraryFiles.size(); 6319 if (N > 0) { 6320 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6321 } else { 6322 pkg.usesLibraryFiles = null; 6323 } 6324 } 6325 } 6326 6327 private static boolean hasString(List<String> list, List<String> which) { 6328 if (list == null) { 6329 return false; 6330 } 6331 for (int i=list.size()-1; i>=0; i--) { 6332 for (int j=which.size()-1; j>=0; j--) { 6333 if (which.get(j).equals(list.get(i))) { 6334 return true; 6335 } 6336 } 6337 } 6338 return false; 6339 } 6340 6341 private void updateAllSharedLibrariesLPw() { 6342 for (PackageParser.Package pkg : mPackages.values()) { 6343 try { 6344 updateSharedLibrariesLPw(pkg, null); 6345 } catch (PackageManagerException e) { 6346 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6347 } 6348 } 6349 } 6350 6351 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6352 PackageParser.Package changingPkg) { 6353 ArrayList<PackageParser.Package> res = null; 6354 for (PackageParser.Package pkg : mPackages.values()) { 6355 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6356 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6357 if (res == null) { 6358 res = new ArrayList<PackageParser.Package>(); 6359 } 6360 res.add(pkg); 6361 try { 6362 updateSharedLibrariesLPw(pkg, changingPkg); 6363 } catch (PackageManagerException e) { 6364 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6365 } 6366 } 6367 } 6368 return res; 6369 } 6370 6371 /** 6372 * Derive the value of the {@code cpuAbiOverride} based on the provided 6373 * value and an optional stored value from the package settings. 6374 */ 6375 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6376 String cpuAbiOverride = null; 6377 6378 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6379 cpuAbiOverride = null; 6380 } else if (abiOverride != null) { 6381 cpuAbiOverride = abiOverride; 6382 } else if (settings != null) { 6383 cpuAbiOverride = settings.cpuAbiOverrideString; 6384 } 6385 6386 return cpuAbiOverride; 6387 } 6388 6389 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6390 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6391 boolean success = false; 6392 try { 6393 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6394 currentTime, user); 6395 success = true; 6396 return res; 6397 } finally { 6398 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6399 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6400 } 6401 } 6402 } 6403 6404 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6405 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6406 final File scanFile = new File(pkg.codePath); 6407 if (pkg.applicationInfo.getCodePath() == null || 6408 pkg.applicationInfo.getResourcePath() == null) { 6409 // Bail out. The resource and code paths haven't been set. 6410 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6411 "Code and resource paths haven't been set correctly"); 6412 } 6413 6414 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6415 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6416 } else { 6417 // Only allow system apps to be flagged as core apps. 6418 pkg.coreApp = false; 6419 } 6420 6421 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6422 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6423 } 6424 6425 if (mCustomResolverComponentName != null && 6426 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6427 setUpCustomResolverActivity(pkg); 6428 } 6429 6430 if (pkg.packageName.equals("android")) { 6431 synchronized (mPackages) { 6432 if (mAndroidApplication != null) { 6433 Slog.w(TAG, "*************************************************"); 6434 Slog.w(TAG, "Core android package being redefined. Skipping."); 6435 Slog.w(TAG, " file=" + scanFile); 6436 Slog.w(TAG, "*************************************************"); 6437 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6438 "Core android package being redefined. Skipping."); 6439 } 6440 6441 // Set up information for our fall-back user intent resolution activity. 6442 mPlatformPackage = pkg; 6443 pkg.mVersionCode = mSdkVersion; 6444 mAndroidApplication = pkg.applicationInfo; 6445 6446 if (!mResolverReplaced) { 6447 mResolveActivity.applicationInfo = mAndroidApplication; 6448 mResolveActivity.name = ResolverActivity.class.getName(); 6449 mResolveActivity.packageName = mAndroidApplication.packageName; 6450 mResolveActivity.processName = "system:ui"; 6451 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6452 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6453 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6454 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6455 mResolveActivity.exported = true; 6456 mResolveActivity.enabled = true; 6457 mResolveInfo.activityInfo = mResolveActivity; 6458 mResolveInfo.priority = 0; 6459 mResolveInfo.preferredOrder = 0; 6460 mResolveInfo.match = 0; 6461 mResolveComponentName = new ComponentName( 6462 mAndroidApplication.packageName, mResolveActivity.name); 6463 } 6464 } 6465 } 6466 6467 if (DEBUG_PACKAGE_SCANNING) { 6468 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6469 Log.d(TAG, "Scanning package " + pkg.packageName); 6470 } 6471 6472 if (mPackages.containsKey(pkg.packageName) 6473 || mSharedLibraries.containsKey(pkg.packageName)) { 6474 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6475 "Application package " + pkg.packageName 6476 + " already installed. Skipping duplicate."); 6477 } 6478 6479 // If we're only installing presumed-existing packages, require that the 6480 // scanned APK is both already known and at the path previously established 6481 // for it. Previously unknown packages we pick up normally, but if we have an 6482 // a priori expectation about this package's install presence, enforce it. 6483 // With a singular exception for new system packages. When an OTA contains 6484 // a new system package, we allow the codepath to change from a system location 6485 // to the user-installed location. If we don't allow this change, any newer, 6486 // user-installed version of the application will be ignored. 6487 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6488 if (mExpectingBetter.containsKey(pkg.packageName)) { 6489 logCriticalInfo(Log.WARN, 6490 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6491 } else { 6492 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6493 if (known != null) { 6494 if (DEBUG_PACKAGE_SCANNING) { 6495 Log.d(TAG, "Examining " + pkg.codePath 6496 + " and requiring known paths " + known.codePathString 6497 + " & " + known.resourcePathString); 6498 } 6499 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6500 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6501 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6502 "Application package " + pkg.packageName 6503 + " found at " + pkg.applicationInfo.getCodePath() 6504 + " but expected at " + known.codePathString + "; ignoring."); 6505 } 6506 } 6507 } 6508 } 6509 6510 // Initialize package source and resource directories 6511 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6512 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6513 6514 SharedUserSetting suid = null; 6515 PackageSetting pkgSetting = null; 6516 6517 if (!isSystemApp(pkg)) { 6518 // Only system apps can use these features. 6519 pkg.mOriginalPackages = null; 6520 pkg.mRealPackage = null; 6521 pkg.mAdoptPermissions = null; 6522 } 6523 6524 // writer 6525 synchronized (mPackages) { 6526 if (pkg.mSharedUserId != null) { 6527 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6528 if (suid == null) { 6529 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6530 "Creating application package " + pkg.packageName 6531 + " for shared user failed"); 6532 } 6533 if (DEBUG_PACKAGE_SCANNING) { 6534 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6535 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6536 + "): packages=" + suid.packages); 6537 } 6538 } 6539 6540 // Check if we are renaming from an original package name. 6541 PackageSetting origPackage = null; 6542 String realName = null; 6543 if (pkg.mOriginalPackages != null) { 6544 // This package may need to be renamed to a previously 6545 // installed name. Let's check on that... 6546 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6547 if (pkg.mOriginalPackages.contains(renamed)) { 6548 // This package had originally been installed as the 6549 // original name, and we have already taken care of 6550 // transitioning to the new one. Just update the new 6551 // one to continue using the old name. 6552 realName = pkg.mRealPackage; 6553 if (!pkg.packageName.equals(renamed)) { 6554 // Callers into this function may have already taken 6555 // care of renaming the package; only do it here if 6556 // it is not already done. 6557 pkg.setPackageName(renamed); 6558 } 6559 6560 } else { 6561 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6562 if ((origPackage = mSettings.peekPackageLPr( 6563 pkg.mOriginalPackages.get(i))) != null) { 6564 // We do have the package already installed under its 6565 // original name... should we use it? 6566 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6567 // New package is not compatible with original. 6568 origPackage = null; 6569 continue; 6570 } else if (origPackage.sharedUser != null) { 6571 // Make sure uid is compatible between packages. 6572 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6573 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6574 + " to " + pkg.packageName + ": old uid " 6575 + origPackage.sharedUser.name 6576 + " differs from " + pkg.mSharedUserId); 6577 origPackage = null; 6578 continue; 6579 } 6580 } else { 6581 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6582 + pkg.packageName + " to old name " + origPackage.name); 6583 } 6584 break; 6585 } 6586 } 6587 } 6588 } 6589 6590 if (mTransferedPackages.contains(pkg.packageName)) { 6591 Slog.w(TAG, "Package " + pkg.packageName 6592 + " was transferred to another, but its .apk remains"); 6593 } 6594 6595 // Just create the setting, don't add it yet. For already existing packages 6596 // the PkgSetting exists already and doesn't have to be created. 6597 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6598 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6599 pkg.applicationInfo.primaryCpuAbi, 6600 pkg.applicationInfo.secondaryCpuAbi, 6601 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6602 user, false); 6603 if (pkgSetting == null) { 6604 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6605 "Creating application package " + pkg.packageName + " failed"); 6606 } 6607 6608 if (pkgSetting.origPackage != null) { 6609 // If we are first transitioning from an original package, 6610 // fix up the new package's name now. We need to do this after 6611 // looking up the package under its new name, so getPackageLP 6612 // can take care of fiddling things correctly. 6613 pkg.setPackageName(origPackage.name); 6614 6615 // File a report about this. 6616 String msg = "New package " + pkgSetting.realName 6617 + " renamed to replace old package " + pkgSetting.name; 6618 reportSettingsProblem(Log.WARN, msg); 6619 6620 // Make a note of it. 6621 mTransferedPackages.add(origPackage.name); 6622 6623 // No longer need to retain this. 6624 pkgSetting.origPackage = null; 6625 } 6626 6627 if (realName != null) { 6628 // Make a note of it. 6629 mTransferedPackages.add(pkg.packageName); 6630 } 6631 6632 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6633 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6634 } 6635 6636 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6637 // Check all shared libraries and map to their actual file path. 6638 // We only do this here for apps not on a system dir, because those 6639 // are the only ones that can fail an install due to this. We 6640 // will take care of the system apps by updating all of their 6641 // library paths after the scan is done. 6642 updateSharedLibrariesLPw(pkg, null); 6643 } 6644 6645 if (mFoundPolicyFile) { 6646 SELinuxMMAC.assignSeinfoValue(pkg); 6647 } 6648 6649 pkg.applicationInfo.uid = pkgSetting.appId; 6650 pkg.mExtras = pkgSetting; 6651 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6652 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6653 // We just determined the app is signed correctly, so bring 6654 // over the latest parsed certs. 6655 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6656 } else { 6657 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6658 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6659 "Package " + pkg.packageName + " upgrade keys do not match the " 6660 + "previously installed version"); 6661 } else { 6662 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6663 String msg = "System package " + pkg.packageName 6664 + " signature changed; retaining data."; 6665 reportSettingsProblem(Log.WARN, msg); 6666 } 6667 } 6668 } else { 6669 try { 6670 verifySignaturesLP(pkgSetting, pkg); 6671 // We just determined the app is signed correctly, so bring 6672 // over the latest parsed certs. 6673 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6674 } catch (PackageManagerException e) { 6675 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6676 throw e; 6677 } 6678 // The signature has changed, but this package is in the system 6679 // image... let's recover! 6680 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6681 // However... if this package is part of a shared user, but it 6682 // doesn't match the signature of the shared user, let's fail. 6683 // What this means is that you can't change the signatures 6684 // associated with an overall shared user, which doesn't seem all 6685 // that unreasonable. 6686 if (pkgSetting.sharedUser != null) { 6687 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6688 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6689 throw new PackageManagerException( 6690 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6691 "Signature mismatch for shared user : " 6692 + pkgSetting.sharedUser); 6693 } 6694 } 6695 // File a report about this. 6696 String msg = "System package " + pkg.packageName 6697 + " signature changed; retaining data."; 6698 reportSettingsProblem(Log.WARN, msg); 6699 } 6700 } 6701 // Verify that this new package doesn't have any content providers 6702 // that conflict with existing packages. Only do this if the 6703 // package isn't already installed, since we don't want to break 6704 // things that are installed. 6705 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6706 final int N = pkg.providers.size(); 6707 int i; 6708 for (i=0; i<N; i++) { 6709 PackageParser.Provider p = pkg.providers.get(i); 6710 if (p.info.authority != null) { 6711 String names[] = p.info.authority.split(";"); 6712 for (int j = 0; j < names.length; j++) { 6713 if (mProvidersByAuthority.containsKey(names[j])) { 6714 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6715 final String otherPackageName = 6716 ((other != null && other.getComponentName() != null) ? 6717 other.getComponentName().getPackageName() : "?"); 6718 throw new PackageManagerException( 6719 INSTALL_FAILED_CONFLICTING_PROVIDER, 6720 "Can't install because provider name " + names[j] 6721 + " (in package " + pkg.applicationInfo.packageName 6722 + ") is already used by " + otherPackageName); 6723 } 6724 } 6725 } 6726 } 6727 } 6728 6729 if (pkg.mAdoptPermissions != null) { 6730 // This package wants to adopt ownership of permissions from 6731 // another package. 6732 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6733 final String origName = pkg.mAdoptPermissions.get(i); 6734 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6735 if (orig != null) { 6736 if (verifyPackageUpdateLPr(orig, pkg)) { 6737 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6738 + pkg.packageName); 6739 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6740 } 6741 } 6742 } 6743 } 6744 } 6745 6746 final String pkgName = pkg.packageName; 6747 6748 final long scanFileTime = scanFile.lastModified(); 6749 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6750 pkg.applicationInfo.processName = fixProcessName( 6751 pkg.applicationInfo.packageName, 6752 pkg.applicationInfo.processName, 6753 pkg.applicationInfo.uid); 6754 6755 File dataPath; 6756 if (mPlatformPackage == pkg) { 6757 // The system package is special. 6758 dataPath = new File(Environment.getDataDirectory(), "system"); 6759 6760 pkg.applicationInfo.dataDir = dataPath.getPath(); 6761 6762 } else { 6763 // This is a normal package, need to make its data directory. 6764 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6765 UserHandle.USER_OWNER, pkg.packageName); 6766 6767 boolean uidError = false; 6768 if (dataPath.exists()) { 6769 int currentUid = 0; 6770 try { 6771 StructStat stat = Os.stat(dataPath.getPath()); 6772 currentUid = stat.st_uid; 6773 } catch (ErrnoException e) { 6774 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6775 } 6776 6777 // If we have mismatched owners for the data path, we have a problem. 6778 if (currentUid != pkg.applicationInfo.uid) { 6779 boolean recovered = false; 6780 if (currentUid == 0) { 6781 // The directory somehow became owned by root. Wow. 6782 // This is probably because the system was stopped while 6783 // installd was in the middle of messing with its libs 6784 // directory. Ask installd to fix that. 6785 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6786 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6787 if (ret >= 0) { 6788 recovered = true; 6789 String msg = "Package " + pkg.packageName 6790 + " unexpectedly changed to uid 0; recovered to " + 6791 + pkg.applicationInfo.uid; 6792 reportSettingsProblem(Log.WARN, msg); 6793 } 6794 } 6795 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6796 || (scanFlags&SCAN_BOOTING) != 0)) { 6797 // If this is a system app, we can at least delete its 6798 // current data so the application will still work. 6799 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6800 if (ret >= 0) { 6801 // TODO: Kill the processes first 6802 // Old data gone! 6803 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6804 ? "System package " : "Third party package "; 6805 String msg = prefix + pkg.packageName 6806 + " has changed from uid: " 6807 + currentUid + " to " 6808 + pkg.applicationInfo.uid + "; old data erased"; 6809 reportSettingsProblem(Log.WARN, msg); 6810 recovered = true; 6811 6812 // And now re-install the app. 6813 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6814 pkg.applicationInfo.seinfo); 6815 if (ret == -1) { 6816 // Ack should not happen! 6817 msg = prefix + pkg.packageName 6818 + " could not have data directory re-created after delete."; 6819 reportSettingsProblem(Log.WARN, msg); 6820 throw new PackageManagerException( 6821 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6822 } 6823 } 6824 if (!recovered) { 6825 mHasSystemUidErrors = true; 6826 } 6827 } else if (!recovered) { 6828 // If we allow this install to proceed, we will be broken. 6829 // Abort, abort! 6830 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6831 "scanPackageLI"); 6832 } 6833 if (!recovered) { 6834 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6835 + pkg.applicationInfo.uid + "/fs_" 6836 + currentUid; 6837 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6838 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6839 String msg = "Package " + pkg.packageName 6840 + " has mismatched uid: " 6841 + currentUid + " on disk, " 6842 + pkg.applicationInfo.uid + " in settings"; 6843 // writer 6844 synchronized (mPackages) { 6845 mSettings.mReadMessages.append(msg); 6846 mSettings.mReadMessages.append('\n'); 6847 uidError = true; 6848 if (!pkgSetting.uidError) { 6849 reportSettingsProblem(Log.ERROR, msg); 6850 } 6851 } 6852 } 6853 } 6854 pkg.applicationInfo.dataDir = dataPath.getPath(); 6855 if (mShouldRestoreconData) { 6856 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6857 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6858 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6859 } 6860 } else { 6861 if (DEBUG_PACKAGE_SCANNING) { 6862 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6863 Log.v(TAG, "Want this data dir: " + dataPath); 6864 } 6865 //invoke installer to do the actual installation 6866 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6867 pkg.applicationInfo.seinfo); 6868 if (ret < 0) { 6869 // Error from installer 6870 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6871 "Unable to create data dirs [errorCode=" + ret + "]"); 6872 } 6873 6874 if (dataPath.exists()) { 6875 pkg.applicationInfo.dataDir = dataPath.getPath(); 6876 } else { 6877 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6878 pkg.applicationInfo.dataDir = null; 6879 } 6880 } 6881 6882 pkgSetting.uidError = uidError; 6883 } 6884 6885 final String path = scanFile.getPath(); 6886 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6887 6888 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6889 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6890 6891 // Some system apps still use directory structure for native libraries 6892 // in which case we might end up not detecting abi solely based on apk 6893 // structure. Try to detect abi based on directory structure. 6894 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6895 pkg.applicationInfo.primaryCpuAbi == null) { 6896 setBundledAppAbisAndRoots(pkg, pkgSetting); 6897 setNativeLibraryPaths(pkg); 6898 } 6899 6900 } else { 6901 if ((scanFlags & SCAN_MOVE) != 0) { 6902 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6903 // but we already have this packages package info in the PackageSetting. We just 6904 // use that and derive the native library path based on the new codepath. 6905 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6906 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6907 } 6908 6909 // Set native library paths again. For moves, the path will be updated based on the 6910 // ABIs we've determined above. For non-moves, the path will be updated based on the 6911 // ABIs we determined during compilation, but the path will depend on the final 6912 // package path (after the rename away from the stage path). 6913 setNativeLibraryPaths(pkg); 6914 } 6915 6916 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6917 final int[] userIds = sUserManager.getUserIds(); 6918 synchronized (mInstallLock) { 6919 // Make sure all user data directories are ready to roll; we're okay 6920 // if they already exist 6921 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6922 for (int userId : userIds) { 6923 if (userId != 0) { 6924 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6925 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6926 pkg.applicationInfo.seinfo); 6927 } 6928 } 6929 } 6930 6931 // Create a native library symlink only if we have native libraries 6932 // and if the native libraries are 32 bit libraries. We do not provide 6933 // this symlink for 64 bit libraries. 6934 if (pkg.applicationInfo.primaryCpuAbi != null && 6935 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6936 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6937 for (int userId : userIds) { 6938 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6939 nativeLibPath, userId) < 0) { 6940 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6941 "Failed linking native library dir (user=" + userId + ")"); 6942 } 6943 } 6944 } 6945 } 6946 6947 // This is a special case for the "system" package, where the ABI is 6948 // dictated by the zygote configuration (and init.rc). We should keep track 6949 // of this ABI so that we can deal with "normal" applications that run under 6950 // the same UID correctly. 6951 if (mPlatformPackage == pkg) { 6952 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6953 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6954 } 6955 6956 // If there's a mismatch between the abi-override in the package setting 6957 // and the abiOverride specified for the install. Warn about this because we 6958 // would've already compiled the app without taking the package setting into 6959 // account. 6960 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6961 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6962 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6963 " for package: " + pkg.packageName); 6964 } 6965 } 6966 6967 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6968 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6969 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6970 6971 // Copy the derived override back to the parsed package, so that we can 6972 // update the package settings accordingly. 6973 pkg.cpuAbiOverride = cpuAbiOverride; 6974 6975 if (DEBUG_ABI_SELECTION) { 6976 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6977 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6978 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6979 } 6980 6981 // Push the derived path down into PackageSettings so we know what to 6982 // clean up at uninstall time. 6983 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6984 6985 if (DEBUG_ABI_SELECTION) { 6986 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6987 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6988 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6989 } 6990 6991 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6992 // We don't do this here during boot because we can do it all 6993 // at once after scanning all existing packages. 6994 // 6995 // We also do this *before* we perform dexopt on this package, so that 6996 // we can avoid redundant dexopts, and also to make sure we've got the 6997 // code and package path correct. 6998 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6999 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 7000 } 7001 7002 if ((scanFlags & SCAN_NO_DEX) == 0) { 7003 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7004 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7005 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7006 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7007 } 7008 } 7009 if (mFactoryTest && pkg.requestedPermissions.contains( 7010 android.Manifest.permission.FACTORY_TEST)) { 7011 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7012 } 7013 7014 ArrayList<PackageParser.Package> clientLibPkgs = null; 7015 7016 // writer 7017 synchronized (mPackages) { 7018 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7019 // Only system apps can add new shared libraries. 7020 if (pkg.libraryNames != null) { 7021 for (int i=0; i<pkg.libraryNames.size(); i++) { 7022 String name = pkg.libraryNames.get(i); 7023 boolean allowed = false; 7024 if (pkg.isUpdatedSystemApp()) { 7025 // New library entries can only be added through the 7026 // system image. This is important to get rid of a lot 7027 // of nasty edge cases: for example if we allowed a non- 7028 // system update of the app to add a library, then uninstalling 7029 // the update would make the library go away, and assumptions 7030 // we made such as through app install filtering would now 7031 // have allowed apps on the device which aren't compatible 7032 // with it. Better to just have the restriction here, be 7033 // conservative, and create many fewer cases that can negatively 7034 // impact the user experience. 7035 final PackageSetting sysPs = mSettings 7036 .getDisabledSystemPkgLPr(pkg.packageName); 7037 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7038 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7039 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7040 allowed = true; 7041 allowed = true; 7042 break; 7043 } 7044 } 7045 } 7046 } else { 7047 allowed = true; 7048 } 7049 if (allowed) { 7050 if (!mSharedLibraries.containsKey(name)) { 7051 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7052 } else if (!name.equals(pkg.packageName)) { 7053 Slog.w(TAG, "Package " + pkg.packageName + " library " 7054 + name + " already exists; skipping"); 7055 } 7056 } else { 7057 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7058 + name + " that is not declared on system image; skipping"); 7059 } 7060 } 7061 if ((scanFlags&SCAN_BOOTING) == 0) { 7062 // If we are not booting, we need to update any applications 7063 // that are clients of our shared library. If we are booting, 7064 // this will all be done once the scan is complete. 7065 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7066 } 7067 } 7068 } 7069 } 7070 7071 // We also need to dexopt any apps that are dependent on this library. Note that 7072 // if these fail, we should abort the install since installing the library will 7073 // result in some apps being broken. 7074 if (clientLibPkgs != null) { 7075 if ((scanFlags & SCAN_NO_DEX) == 0) { 7076 for (int i = 0; i < clientLibPkgs.size(); i++) { 7077 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7078 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7079 null /* instruction sets */, forceDex, 7080 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7081 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7082 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7083 "scanPackageLI failed to dexopt clientLibPkgs"); 7084 } 7085 } 7086 } 7087 } 7088 7089 // Also need to kill any apps that are dependent on the library. 7090 if (clientLibPkgs != null) { 7091 for (int i=0; i<clientLibPkgs.size(); i++) { 7092 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7093 killApplication(clientPkg.applicationInfo.packageName, 7094 clientPkg.applicationInfo.uid, "update lib"); 7095 } 7096 } 7097 7098 // Make sure we're not adding any bogus keyset info 7099 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7100 ksms.assertScannedPackageValid(pkg); 7101 7102 // writer 7103 synchronized (mPackages) { 7104 // We don't expect installation to fail beyond this point 7105 7106 // Add the new setting to mSettings 7107 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7108 // Add the new setting to mPackages 7109 mPackages.put(pkg.applicationInfo.packageName, pkg); 7110 // Make sure we don't accidentally delete its data. 7111 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7112 while (iter.hasNext()) { 7113 PackageCleanItem item = iter.next(); 7114 if (pkgName.equals(item.packageName)) { 7115 iter.remove(); 7116 } 7117 } 7118 7119 // Take care of first install / last update times. 7120 if (currentTime != 0) { 7121 if (pkgSetting.firstInstallTime == 0) { 7122 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7123 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7124 pkgSetting.lastUpdateTime = currentTime; 7125 } 7126 } else if (pkgSetting.firstInstallTime == 0) { 7127 // We need *something*. Take time time stamp of the file. 7128 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7129 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7130 if (scanFileTime != pkgSetting.timeStamp) { 7131 // A package on the system image has changed; consider this 7132 // to be an update. 7133 pkgSetting.lastUpdateTime = scanFileTime; 7134 } 7135 } 7136 7137 // Add the package's KeySets to the global KeySetManagerService 7138 ksms.addScannedPackageLPw(pkg); 7139 7140 int N = pkg.providers.size(); 7141 StringBuilder r = null; 7142 int i; 7143 for (i=0; i<N; i++) { 7144 PackageParser.Provider p = pkg.providers.get(i); 7145 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7146 p.info.processName, pkg.applicationInfo.uid); 7147 mProviders.addProvider(p); 7148 p.syncable = p.info.isSyncable; 7149 if (p.info.authority != null) { 7150 String names[] = p.info.authority.split(";"); 7151 p.info.authority = null; 7152 for (int j = 0; j < names.length; j++) { 7153 if (j == 1 && p.syncable) { 7154 // We only want the first authority for a provider to possibly be 7155 // syncable, so if we already added this provider using a different 7156 // authority clear the syncable flag. We copy the provider before 7157 // changing it because the mProviders object contains a reference 7158 // to a provider that we don't want to change. 7159 // Only do this for the second authority since the resulting provider 7160 // object can be the same for all future authorities for this provider. 7161 p = new PackageParser.Provider(p); 7162 p.syncable = false; 7163 } 7164 if (!mProvidersByAuthority.containsKey(names[j])) { 7165 mProvidersByAuthority.put(names[j], p); 7166 if (p.info.authority == null) { 7167 p.info.authority = names[j]; 7168 } else { 7169 p.info.authority = p.info.authority + ";" + names[j]; 7170 } 7171 if (DEBUG_PACKAGE_SCANNING) { 7172 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7173 Log.d(TAG, "Registered content provider: " + names[j] 7174 + ", className = " + p.info.name + ", isSyncable = " 7175 + p.info.isSyncable); 7176 } 7177 } else { 7178 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7179 Slog.w(TAG, "Skipping provider name " + names[j] + 7180 " (in package " + pkg.applicationInfo.packageName + 7181 "): name already used by " 7182 + ((other != null && other.getComponentName() != null) 7183 ? other.getComponentName().getPackageName() : "?")); 7184 } 7185 } 7186 } 7187 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7188 if (r == null) { 7189 r = new StringBuilder(256); 7190 } else { 7191 r.append(' '); 7192 } 7193 r.append(p.info.name); 7194 } 7195 } 7196 if (r != null) { 7197 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7198 } 7199 7200 N = pkg.services.size(); 7201 r = null; 7202 for (i=0; i<N; i++) { 7203 PackageParser.Service s = pkg.services.get(i); 7204 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7205 s.info.processName, pkg.applicationInfo.uid); 7206 mServices.addService(s); 7207 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7208 if (r == null) { 7209 r = new StringBuilder(256); 7210 } else { 7211 r.append(' '); 7212 } 7213 r.append(s.info.name); 7214 } 7215 } 7216 if (r != null) { 7217 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7218 } 7219 7220 N = pkg.receivers.size(); 7221 r = null; 7222 for (i=0; i<N; i++) { 7223 PackageParser.Activity a = pkg.receivers.get(i); 7224 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7225 a.info.processName, pkg.applicationInfo.uid); 7226 mReceivers.addActivity(a, "receiver"); 7227 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7228 if (r == null) { 7229 r = new StringBuilder(256); 7230 } else { 7231 r.append(' '); 7232 } 7233 r.append(a.info.name); 7234 } 7235 } 7236 if (r != null) { 7237 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7238 } 7239 7240 N = pkg.activities.size(); 7241 r = null; 7242 for (i=0; i<N; i++) { 7243 PackageParser.Activity a = pkg.activities.get(i); 7244 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7245 a.info.processName, pkg.applicationInfo.uid); 7246 mActivities.addActivity(a, "activity"); 7247 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7248 if (r == null) { 7249 r = new StringBuilder(256); 7250 } else { 7251 r.append(' '); 7252 } 7253 r.append(a.info.name); 7254 } 7255 } 7256 if (r != null) { 7257 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7258 } 7259 7260 N = pkg.permissionGroups.size(); 7261 r = null; 7262 for (i=0; i<N; i++) { 7263 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7264 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7265 if (cur == null) { 7266 mPermissionGroups.put(pg.info.name, pg); 7267 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7268 if (r == null) { 7269 r = new StringBuilder(256); 7270 } else { 7271 r.append(' '); 7272 } 7273 r.append(pg.info.name); 7274 } 7275 } else { 7276 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7277 + pg.info.packageName + " ignored: original from " 7278 + cur.info.packageName); 7279 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7280 if (r == null) { 7281 r = new StringBuilder(256); 7282 } else { 7283 r.append(' '); 7284 } 7285 r.append("DUP:"); 7286 r.append(pg.info.name); 7287 } 7288 } 7289 } 7290 if (r != null) { 7291 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7292 } 7293 7294 N = pkg.permissions.size(); 7295 r = null; 7296 for (i=0; i<N; i++) { 7297 PackageParser.Permission p = pkg.permissions.get(i); 7298 7299 // Now that permission groups have a special meaning, we ignore permission 7300 // groups for legacy apps to prevent unexpected behavior. In particular, 7301 // permissions for one app being granted to someone just becuase they happen 7302 // to be in a group defined by another app (before this had no implications). 7303 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7304 p.group = mPermissionGroups.get(p.info.group); 7305 // Warn for a permission in an unknown group. 7306 if (p.info.group != null && p.group == null) { 7307 Slog.w(TAG, "Permission " + p.info.name + " from package " 7308 + p.info.packageName + " in an unknown group " + p.info.group); 7309 } 7310 } 7311 7312 ArrayMap<String, BasePermission> permissionMap = 7313 p.tree ? mSettings.mPermissionTrees 7314 : mSettings.mPermissions; 7315 BasePermission bp = permissionMap.get(p.info.name); 7316 7317 // Allow system apps to redefine non-system permissions 7318 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7319 final boolean currentOwnerIsSystem = (bp.perm != null 7320 && isSystemApp(bp.perm.owner)); 7321 if (isSystemApp(p.owner)) { 7322 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7323 // It's a built-in permission and no owner, take ownership now 7324 bp.packageSetting = pkgSetting; 7325 bp.perm = p; 7326 bp.uid = pkg.applicationInfo.uid; 7327 bp.sourcePackage = p.info.packageName; 7328 } else if (!currentOwnerIsSystem) { 7329 String msg = "New decl " + p.owner + " of permission " 7330 + p.info.name + " is system; overriding " + bp.sourcePackage; 7331 reportSettingsProblem(Log.WARN, msg); 7332 bp = null; 7333 } 7334 } 7335 } 7336 7337 if (bp == null) { 7338 bp = new BasePermission(p.info.name, p.info.packageName, 7339 BasePermission.TYPE_NORMAL); 7340 permissionMap.put(p.info.name, bp); 7341 } 7342 7343 if (bp.perm == null) { 7344 if (bp.sourcePackage == null 7345 || bp.sourcePackage.equals(p.info.packageName)) { 7346 BasePermission tree = findPermissionTreeLP(p.info.name); 7347 if (tree == null 7348 || tree.sourcePackage.equals(p.info.packageName)) { 7349 bp.packageSetting = pkgSetting; 7350 bp.perm = p; 7351 bp.uid = pkg.applicationInfo.uid; 7352 bp.sourcePackage = p.info.packageName; 7353 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7354 if (r == null) { 7355 r = new StringBuilder(256); 7356 } else { 7357 r.append(' '); 7358 } 7359 r.append(p.info.name); 7360 } 7361 } else { 7362 Slog.w(TAG, "Permission " + p.info.name + " from package " 7363 + p.info.packageName + " ignored: base tree " 7364 + tree.name + " is from package " 7365 + tree.sourcePackage); 7366 } 7367 } else { 7368 Slog.w(TAG, "Permission " + p.info.name + " from package " 7369 + p.info.packageName + " ignored: original from " 7370 + bp.sourcePackage); 7371 } 7372 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7373 if (r == null) { 7374 r = new StringBuilder(256); 7375 } else { 7376 r.append(' '); 7377 } 7378 r.append("DUP:"); 7379 r.append(p.info.name); 7380 } 7381 if (bp.perm == p) { 7382 bp.protectionLevel = p.info.protectionLevel; 7383 } 7384 } 7385 7386 if (r != null) { 7387 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7388 } 7389 7390 N = pkg.instrumentation.size(); 7391 r = null; 7392 for (i=0; i<N; i++) { 7393 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7394 a.info.packageName = pkg.applicationInfo.packageName; 7395 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7396 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7397 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7398 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7399 a.info.dataDir = pkg.applicationInfo.dataDir; 7400 7401 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7402 // need other information about the application, like the ABI and what not ? 7403 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7404 mInstrumentation.put(a.getComponentName(), a); 7405 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7406 if (r == null) { 7407 r = new StringBuilder(256); 7408 } else { 7409 r.append(' '); 7410 } 7411 r.append(a.info.name); 7412 } 7413 } 7414 if (r != null) { 7415 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7416 } 7417 7418 if (pkg.protectedBroadcasts != null) { 7419 N = pkg.protectedBroadcasts.size(); 7420 for (i=0; i<N; i++) { 7421 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7422 } 7423 } 7424 7425 pkgSetting.setTimeStamp(scanFileTime); 7426 7427 // Create idmap files for pairs of (packages, overlay packages). 7428 // Note: "android", ie framework-res.apk, is handled by native layers. 7429 if (pkg.mOverlayTarget != null) { 7430 // This is an overlay package. 7431 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7432 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7433 mOverlays.put(pkg.mOverlayTarget, 7434 new ArrayMap<String, PackageParser.Package>()); 7435 } 7436 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7437 map.put(pkg.packageName, pkg); 7438 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7439 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7440 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7441 "scanPackageLI failed to createIdmap"); 7442 } 7443 } 7444 } else if (mOverlays.containsKey(pkg.packageName) && 7445 !pkg.packageName.equals("android")) { 7446 // This is a regular package, with one or more known overlay packages. 7447 createIdmapsForPackageLI(pkg); 7448 } 7449 } 7450 7451 return pkg; 7452 } 7453 7454 /** 7455 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7456 * is derived purely on the basis of the contents of {@code scanFile} and 7457 * {@code cpuAbiOverride}. 7458 * 7459 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7460 */ 7461 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7462 String cpuAbiOverride, boolean extractLibs) 7463 throws PackageManagerException { 7464 // TODO: We can probably be smarter about this stuff. For installed apps, 7465 // we can calculate this information at install time once and for all. For 7466 // system apps, we can probably assume that this information doesn't change 7467 // after the first boot scan. As things stand, we do lots of unnecessary work. 7468 7469 // Give ourselves some initial paths; we'll come back for another 7470 // pass once we've determined ABI below. 7471 setNativeLibraryPaths(pkg); 7472 7473 // We would never need to extract libs for forward-locked and external packages, 7474 // since the container service will do it for us. We shouldn't attempt to 7475 // extract libs from system app when it was not updated. 7476 if (pkg.isForwardLocked() || isExternal(pkg) || 7477 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7478 extractLibs = false; 7479 } 7480 7481 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7482 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7483 7484 NativeLibraryHelper.Handle handle = null; 7485 try { 7486 handle = NativeLibraryHelper.Handle.create(pkg); 7487 // TODO(multiArch): This can be null for apps that didn't go through the 7488 // usual installation process. We can calculate it again, like we 7489 // do during install time. 7490 // 7491 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7492 // unnecessary. 7493 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7494 7495 // Null out the abis so that they can be recalculated. 7496 pkg.applicationInfo.primaryCpuAbi = null; 7497 pkg.applicationInfo.secondaryCpuAbi = null; 7498 if (isMultiArch(pkg.applicationInfo)) { 7499 // Warn if we've set an abiOverride for multi-lib packages.. 7500 // By definition, we need to copy both 32 and 64 bit libraries for 7501 // such packages. 7502 if (pkg.cpuAbiOverride != null 7503 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7504 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7505 } 7506 7507 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7508 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7509 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7510 if (extractLibs) { 7511 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7512 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7513 useIsaSpecificSubdirs); 7514 } else { 7515 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7516 } 7517 } 7518 7519 maybeThrowExceptionForMultiArchCopy( 7520 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7521 7522 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7523 if (extractLibs) { 7524 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7525 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7526 useIsaSpecificSubdirs); 7527 } else { 7528 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7529 } 7530 } 7531 7532 maybeThrowExceptionForMultiArchCopy( 7533 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7534 7535 if (abi64 >= 0) { 7536 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7537 } 7538 7539 if (abi32 >= 0) { 7540 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7541 if (abi64 >= 0) { 7542 pkg.applicationInfo.secondaryCpuAbi = abi; 7543 } else { 7544 pkg.applicationInfo.primaryCpuAbi = abi; 7545 } 7546 } 7547 } else { 7548 String[] abiList = (cpuAbiOverride != null) ? 7549 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7550 7551 // Enable gross and lame hacks for apps that are built with old 7552 // SDK tools. We must scan their APKs for renderscript bitcode and 7553 // not launch them if it's present. Don't bother checking on devices 7554 // that don't have 64 bit support. 7555 boolean needsRenderScriptOverride = false; 7556 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7557 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7558 abiList = Build.SUPPORTED_32_BIT_ABIS; 7559 needsRenderScriptOverride = true; 7560 } 7561 7562 final int copyRet; 7563 if (extractLibs) { 7564 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7565 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7566 } else { 7567 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7568 } 7569 7570 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7571 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7572 "Error unpackaging native libs for app, errorCode=" + copyRet); 7573 } 7574 7575 if (copyRet >= 0) { 7576 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7577 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7578 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7579 } else if (needsRenderScriptOverride) { 7580 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7581 } 7582 } 7583 } catch (IOException ioe) { 7584 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7585 } finally { 7586 IoUtils.closeQuietly(handle); 7587 } 7588 7589 // Now that we've calculated the ABIs and determined if it's an internal app, 7590 // we will go ahead and populate the nativeLibraryPath. 7591 setNativeLibraryPaths(pkg); 7592 } 7593 7594 /** 7595 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7596 * i.e, so that all packages can be run inside a single process if required. 7597 * 7598 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7599 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7600 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7601 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7602 * updating a package that belongs to a shared user. 7603 * 7604 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7605 * adds unnecessary complexity. 7606 */ 7607 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7608 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7609 String requiredInstructionSet = null; 7610 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7611 requiredInstructionSet = VMRuntime.getInstructionSet( 7612 scannedPackage.applicationInfo.primaryCpuAbi); 7613 } 7614 7615 PackageSetting requirer = null; 7616 for (PackageSetting ps : packagesForUser) { 7617 // If packagesForUser contains scannedPackage, we skip it. This will happen 7618 // when scannedPackage is an update of an existing package. Without this check, 7619 // we will never be able to change the ABI of any package belonging to a shared 7620 // user, even if it's compatible with other packages. 7621 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7622 if (ps.primaryCpuAbiString == null) { 7623 continue; 7624 } 7625 7626 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7627 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7628 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7629 // this but there's not much we can do. 7630 String errorMessage = "Instruction set mismatch, " 7631 + ((requirer == null) ? "[caller]" : requirer) 7632 + " requires " + requiredInstructionSet + " whereas " + ps 7633 + " requires " + instructionSet; 7634 Slog.w(TAG, errorMessage); 7635 } 7636 7637 if (requiredInstructionSet == null) { 7638 requiredInstructionSet = instructionSet; 7639 requirer = ps; 7640 } 7641 } 7642 } 7643 7644 if (requiredInstructionSet != null) { 7645 String adjustedAbi; 7646 if (requirer != null) { 7647 // requirer != null implies that either scannedPackage was null or that scannedPackage 7648 // did not require an ABI, in which case we have to adjust scannedPackage to match 7649 // the ABI of the set (which is the same as requirer's ABI) 7650 adjustedAbi = requirer.primaryCpuAbiString; 7651 if (scannedPackage != null) { 7652 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7653 } 7654 } else { 7655 // requirer == null implies that we're updating all ABIs in the set to 7656 // match scannedPackage. 7657 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7658 } 7659 7660 for (PackageSetting ps : packagesForUser) { 7661 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7662 if (ps.primaryCpuAbiString != null) { 7663 continue; 7664 } 7665 7666 ps.primaryCpuAbiString = adjustedAbi; 7667 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7668 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7669 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7670 7671 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7672 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7673 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7674 ps.primaryCpuAbiString = null; 7675 ps.pkg.applicationInfo.primaryCpuAbi = null; 7676 return; 7677 } else { 7678 mInstaller.rmdex(ps.codePathString, 7679 getDexCodeInstructionSet(getPreferredInstructionSet())); 7680 } 7681 } 7682 } 7683 } 7684 } 7685 } 7686 7687 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7688 synchronized (mPackages) { 7689 mResolverReplaced = true; 7690 // Set up information for custom user intent resolution activity. 7691 mResolveActivity.applicationInfo = pkg.applicationInfo; 7692 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7693 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7694 mResolveActivity.processName = pkg.applicationInfo.packageName; 7695 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7696 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7697 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7698 mResolveActivity.theme = 0; 7699 mResolveActivity.exported = true; 7700 mResolveActivity.enabled = true; 7701 mResolveInfo.activityInfo = mResolveActivity; 7702 mResolveInfo.priority = 0; 7703 mResolveInfo.preferredOrder = 0; 7704 mResolveInfo.match = 0; 7705 mResolveComponentName = mCustomResolverComponentName; 7706 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7707 mResolveComponentName); 7708 } 7709 } 7710 7711 private static String calculateBundledApkRoot(final String codePathString) { 7712 final File codePath = new File(codePathString); 7713 final File codeRoot; 7714 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7715 codeRoot = Environment.getRootDirectory(); 7716 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7717 codeRoot = Environment.getOemDirectory(); 7718 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7719 codeRoot = Environment.getVendorDirectory(); 7720 } else { 7721 // Unrecognized code path; take its top real segment as the apk root: 7722 // e.g. /something/app/blah.apk => /something 7723 try { 7724 File f = codePath.getCanonicalFile(); 7725 File parent = f.getParentFile(); // non-null because codePath is a file 7726 File tmp; 7727 while ((tmp = parent.getParentFile()) != null) { 7728 f = parent; 7729 parent = tmp; 7730 } 7731 codeRoot = f; 7732 Slog.w(TAG, "Unrecognized code path " 7733 + codePath + " - using " + codeRoot); 7734 } catch (IOException e) { 7735 // Can't canonicalize the code path -- shenanigans? 7736 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7737 return Environment.getRootDirectory().getPath(); 7738 } 7739 } 7740 return codeRoot.getPath(); 7741 } 7742 7743 /** 7744 * Derive and set the location of native libraries for the given package, 7745 * which varies depending on where and how the package was installed. 7746 */ 7747 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7748 final ApplicationInfo info = pkg.applicationInfo; 7749 final String codePath = pkg.codePath; 7750 final File codeFile = new File(codePath); 7751 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7752 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7753 7754 info.nativeLibraryRootDir = null; 7755 info.nativeLibraryRootRequiresIsa = false; 7756 info.nativeLibraryDir = null; 7757 info.secondaryNativeLibraryDir = null; 7758 7759 if (isApkFile(codeFile)) { 7760 // Monolithic install 7761 if (bundledApp) { 7762 // If "/system/lib64/apkname" exists, assume that is the per-package 7763 // native library directory to use; otherwise use "/system/lib/apkname". 7764 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7765 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7766 getPrimaryInstructionSet(info)); 7767 7768 // This is a bundled system app so choose the path based on the ABI. 7769 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7770 // is just the default path. 7771 final String apkName = deriveCodePathName(codePath); 7772 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7773 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7774 apkName).getAbsolutePath(); 7775 7776 if (info.secondaryCpuAbi != null) { 7777 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7778 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7779 secondaryLibDir, apkName).getAbsolutePath(); 7780 } 7781 } else if (asecApp) { 7782 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7783 .getAbsolutePath(); 7784 } else { 7785 final String apkName = deriveCodePathName(codePath); 7786 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7787 .getAbsolutePath(); 7788 } 7789 7790 info.nativeLibraryRootRequiresIsa = false; 7791 info.nativeLibraryDir = info.nativeLibraryRootDir; 7792 } else { 7793 // Cluster install 7794 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7795 info.nativeLibraryRootRequiresIsa = true; 7796 7797 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7798 getPrimaryInstructionSet(info)).getAbsolutePath(); 7799 7800 if (info.secondaryCpuAbi != null) { 7801 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7802 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7803 } 7804 } 7805 } 7806 7807 /** 7808 * Calculate the abis and roots for a bundled app. These can uniquely 7809 * be determined from the contents of the system partition, i.e whether 7810 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7811 * of this information, and instead assume that the system was built 7812 * sensibly. 7813 */ 7814 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7815 PackageSetting pkgSetting) { 7816 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7817 7818 // If "/system/lib64/apkname" exists, assume that is the per-package 7819 // native library directory to use; otherwise use "/system/lib/apkname". 7820 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7821 setBundledAppAbi(pkg, apkRoot, apkName); 7822 // pkgSetting might be null during rescan following uninstall of updates 7823 // to a bundled app, so accommodate that possibility. The settings in 7824 // that case will be established later from the parsed package. 7825 // 7826 // If the settings aren't null, sync them up with what we've just derived. 7827 // note that apkRoot isn't stored in the package settings. 7828 if (pkgSetting != null) { 7829 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7830 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7831 } 7832 } 7833 7834 /** 7835 * Deduces the ABI of a bundled app and sets the relevant fields on the 7836 * parsed pkg object. 7837 * 7838 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7839 * under which system libraries are installed. 7840 * @param apkName the name of the installed package. 7841 */ 7842 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7843 final File codeFile = new File(pkg.codePath); 7844 7845 final boolean has64BitLibs; 7846 final boolean has32BitLibs; 7847 if (isApkFile(codeFile)) { 7848 // Monolithic install 7849 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7850 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7851 } else { 7852 // Cluster install 7853 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7854 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7855 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7856 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7857 has64BitLibs = (new File(rootDir, isa)).exists(); 7858 } else { 7859 has64BitLibs = false; 7860 } 7861 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7862 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7863 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7864 has32BitLibs = (new File(rootDir, isa)).exists(); 7865 } else { 7866 has32BitLibs = false; 7867 } 7868 } 7869 7870 if (has64BitLibs && !has32BitLibs) { 7871 // The package has 64 bit libs, but not 32 bit libs. Its primary 7872 // ABI should be 64 bit. We can safely assume here that the bundled 7873 // native libraries correspond to the most preferred ABI in the list. 7874 7875 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7876 pkg.applicationInfo.secondaryCpuAbi = null; 7877 } else if (has32BitLibs && !has64BitLibs) { 7878 // The package has 32 bit libs but not 64 bit libs. Its primary 7879 // ABI should be 32 bit. 7880 7881 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7882 pkg.applicationInfo.secondaryCpuAbi = null; 7883 } else if (has32BitLibs && has64BitLibs) { 7884 // The application has both 64 and 32 bit bundled libraries. We check 7885 // here that the app declares multiArch support, and warn if it doesn't. 7886 // 7887 // We will be lenient here and record both ABIs. The primary will be the 7888 // ABI that's higher on the list, i.e, a device that's configured to prefer 7889 // 64 bit apps will see a 64 bit primary ABI, 7890 7891 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7892 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7893 } 7894 7895 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7896 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7897 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7898 } else { 7899 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7900 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7901 } 7902 } else { 7903 pkg.applicationInfo.primaryCpuAbi = null; 7904 pkg.applicationInfo.secondaryCpuAbi = null; 7905 } 7906 } 7907 7908 private void killApplication(String pkgName, int appId, String reason) { 7909 // Request the ActivityManager to kill the process(only for existing packages) 7910 // so that we do not end up in a confused state while the user is still using the older 7911 // version of the application while the new one gets installed. 7912 IActivityManager am = ActivityManagerNative.getDefault(); 7913 if (am != null) { 7914 try { 7915 am.killApplicationWithAppId(pkgName, appId, reason); 7916 } catch (RemoteException e) { 7917 } 7918 } 7919 } 7920 7921 void removePackageLI(PackageSetting ps, boolean chatty) { 7922 if (DEBUG_INSTALL) { 7923 if (chatty) 7924 Log.d(TAG, "Removing package " + ps.name); 7925 } 7926 7927 // writer 7928 synchronized (mPackages) { 7929 mPackages.remove(ps.name); 7930 final PackageParser.Package pkg = ps.pkg; 7931 if (pkg != null) { 7932 cleanPackageDataStructuresLILPw(pkg, chatty); 7933 } 7934 } 7935 } 7936 7937 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7938 if (DEBUG_INSTALL) { 7939 if (chatty) 7940 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7941 } 7942 7943 // writer 7944 synchronized (mPackages) { 7945 mPackages.remove(pkg.applicationInfo.packageName); 7946 cleanPackageDataStructuresLILPw(pkg, chatty); 7947 } 7948 } 7949 7950 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7951 int N = pkg.providers.size(); 7952 StringBuilder r = null; 7953 int i; 7954 for (i=0; i<N; i++) { 7955 PackageParser.Provider p = pkg.providers.get(i); 7956 mProviders.removeProvider(p); 7957 if (p.info.authority == null) { 7958 7959 /* There was another ContentProvider with this authority when 7960 * this app was installed so this authority is null, 7961 * Ignore it as we don't have to unregister the provider. 7962 */ 7963 continue; 7964 } 7965 String names[] = p.info.authority.split(";"); 7966 for (int j = 0; j < names.length; j++) { 7967 if (mProvidersByAuthority.get(names[j]) == p) { 7968 mProvidersByAuthority.remove(names[j]); 7969 if (DEBUG_REMOVE) { 7970 if (chatty) 7971 Log.d(TAG, "Unregistered content provider: " + names[j] 7972 + ", className = " + p.info.name + ", isSyncable = " 7973 + p.info.isSyncable); 7974 } 7975 } 7976 } 7977 if (DEBUG_REMOVE && chatty) { 7978 if (r == null) { 7979 r = new StringBuilder(256); 7980 } else { 7981 r.append(' '); 7982 } 7983 r.append(p.info.name); 7984 } 7985 } 7986 if (r != null) { 7987 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7988 } 7989 7990 N = pkg.services.size(); 7991 r = null; 7992 for (i=0; i<N; i++) { 7993 PackageParser.Service s = pkg.services.get(i); 7994 mServices.removeService(s); 7995 if (chatty) { 7996 if (r == null) { 7997 r = new StringBuilder(256); 7998 } else { 7999 r.append(' '); 8000 } 8001 r.append(s.info.name); 8002 } 8003 } 8004 if (r != null) { 8005 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8006 } 8007 8008 N = pkg.receivers.size(); 8009 r = null; 8010 for (i=0; i<N; i++) { 8011 PackageParser.Activity a = pkg.receivers.get(i); 8012 mReceivers.removeActivity(a, "receiver"); 8013 if (DEBUG_REMOVE && chatty) { 8014 if (r == null) { 8015 r = new StringBuilder(256); 8016 } else { 8017 r.append(' '); 8018 } 8019 r.append(a.info.name); 8020 } 8021 } 8022 if (r != null) { 8023 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8024 } 8025 8026 N = pkg.activities.size(); 8027 r = null; 8028 for (i=0; i<N; i++) { 8029 PackageParser.Activity a = pkg.activities.get(i); 8030 mActivities.removeActivity(a, "activity"); 8031 if (DEBUG_REMOVE && chatty) { 8032 if (r == null) { 8033 r = new StringBuilder(256); 8034 } else { 8035 r.append(' '); 8036 } 8037 r.append(a.info.name); 8038 } 8039 } 8040 if (r != null) { 8041 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8042 } 8043 8044 N = pkg.permissions.size(); 8045 r = null; 8046 for (i=0; i<N; i++) { 8047 PackageParser.Permission p = pkg.permissions.get(i); 8048 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8049 if (bp == null) { 8050 bp = mSettings.mPermissionTrees.get(p.info.name); 8051 } 8052 if (bp != null && bp.perm == p) { 8053 bp.perm = null; 8054 if (DEBUG_REMOVE && chatty) { 8055 if (r == null) { 8056 r = new StringBuilder(256); 8057 } else { 8058 r.append(' '); 8059 } 8060 r.append(p.info.name); 8061 } 8062 } 8063 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8064 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8065 if (appOpPerms != null) { 8066 appOpPerms.remove(pkg.packageName); 8067 } 8068 } 8069 } 8070 if (r != null) { 8071 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8072 } 8073 8074 N = pkg.requestedPermissions.size(); 8075 r = null; 8076 for (i=0; i<N; i++) { 8077 String perm = pkg.requestedPermissions.get(i); 8078 BasePermission bp = mSettings.mPermissions.get(perm); 8079 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8080 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8081 if (appOpPerms != null) { 8082 appOpPerms.remove(pkg.packageName); 8083 if (appOpPerms.isEmpty()) { 8084 mAppOpPermissionPackages.remove(perm); 8085 } 8086 } 8087 } 8088 } 8089 if (r != null) { 8090 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8091 } 8092 8093 N = pkg.instrumentation.size(); 8094 r = null; 8095 for (i=0; i<N; i++) { 8096 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8097 mInstrumentation.remove(a.getComponentName()); 8098 if (DEBUG_REMOVE && chatty) { 8099 if (r == null) { 8100 r = new StringBuilder(256); 8101 } else { 8102 r.append(' '); 8103 } 8104 r.append(a.info.name); 8105 } 8106 } 8107 if (r != null) { 8108 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8109 } 8110 8111 r = null; 8112 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8113 // Only system apps can hold shared libraries. 8114 if (pkg.libraryNames != null) { 8115 for (i=0; i<pkg.libraryNames.size(); i++) { 8116 String name = pkg.libraryNames.get(i); 8117 SharedLibraryEntry cur = mSharedLibraries.get(name); 8118 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8119 mSharedLibraries.remove(name); 8120 if (DEBUG_REMOVE && chatty) { 8121 if (r == null) { 8122 r = new StringBuilder(256); 8123 } else { 8124 r.append(' '); 8125 } 8126 r.append(name); 8127 } 8128 } 8129 } 8130 } 8131 } 8132 if (r != null) { 8133 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8134 } 8135 } 8136 8137 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8138 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8139 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8140 return true; 8141 } 8142 } 8143 return false; 8144 } 8145 8146 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8147 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8148 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8149 8150 private void updatePermissionsLPw(String changingPkg, 8151 PackageParser.Package pkgInfo, int flags) { 8152 // Make sure there are no dangling permission trees. 8153 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8154 while (it.hasNext()) { 8155 final BasePermission bp = it.next(); 8156 if (bp.packageSetting == null) { 8157 // We may not yet have parsed the package, so just see if 8158 // we still know about its settings. 8159 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8160 } 8161 if (bp.packageSetting == null) { 8162 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8163 + " from package " + bp.sourcePackage); 8164 it.remove(); 8165 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8166 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8167 Slog.i(TAG, "Removing old permission tree: " + bp.name 8168 + " from package " + bp.sourcePackage); 8169 flags |= UPDATE_PERMISSIONS_ALL; 8170 it.remove(); 8171 } 8172 } 8173 } 8174 8175 // Make sure all dynamic permissions have been assigned to a package, 8176 // and make sure there are no dangling permissions. 8177 it = mSettings.mPermissions.values().iterator(); 8178 while (it.hasNext()) { 8179 final BasePermission bp = it.next(); 8180 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8181 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8182 + bp.name + " pkg=" + bp.sourcePackage 8183 + " info=" + bp.pendingInfo); 8184 if (bp.packageSetting == null && bp.pendingInfo != null) { 8185 final BasePermission tree = findPermissionTreeLP(bp.name); 8186 if (tree != null && tree.perm != null) { 8187 bp.packageSetting = tree.packageSetting; 8188 bp.perm = new PackageParser.Permission(tree.perm.owner, 8189 new PermissionInfo(bp.pendingInfo)); 8190 bp.perm.info.packageName = tree.perm.info.packageName; 8191 bp.perm.info.name = bp.name; 8192 bp.uid = tree.uid; 8193 } 8194 } 8195 } 8196 if (bp.packageSetting == null) { 8197 // We may not yet have parsed the package, so just see if 8198 // we still know about its settings. 8199 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8200 } 8201 if (bp.packageSetting == null) { 8202 Slog.w(TAG, "Removing dangling permission: " + bp.name 8203 + " from package " + bp.sourcePackage); 8204 it.remove(); 8205 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8206 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8207 Slog.i(TAG, "Removing old permission: " + bp.name 8208 + " from package " + bp.sourcePackage); 8209 flags |= UPDATE_PERMISSIONS_ALL; 8210 it.remove(); 8211 } 8212 } 8213 } 8214 8215 // Now update the permissions for all packages, in particular 8216 // replace the granted permissions of the system packages. 8217 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8218 for (PackageParser.Package pkg : mPackages.values()) { 8219 if (pkg != pkgInfo) { 8220 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8221 changingPkg); 8222 } 8223 } 8224 } 8225 8226 if (pkgInfo != null) { 8227 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8228 } 8229 } 8230 8231 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8232 String packageOfInterest) { 8233 // IMPORTANT: There are two types of permissions: install and runtime. 8234 // Install time permissions are granted when the app is installed to 8235 // all device users and users added in the future. Runtime permissions 8236 // are granted at runtime explicitly to specific users. Normal and signature 8237 // protected permissions are install time permissions. Dangerous permissions 8238 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8239 // otherwise they are runtime permissions. This function does not manage 8240 // runtime permissions except for the case an app targeting Lollipop MR1 8241 // being upgraded to target a newer SDK, in which case dangerous permissions 8242 // are transformed from install time to runtime ones. 8243 8244 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8245 if (ps == null) { 8246 return; 8247 } 8248 8249 PermissionsState permissionsState = ps.getPermissionsState(); 8250 PermissionsState origPermissions = permissionsState; 8251 8252 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8253 8254 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8255 8256 boolean changedInstallPermission = false; 8257 8258 if (replace) { 8259 ps.installPermissionsFixed = false; 8260 if (!ps.isSharedUser()) { 8261 origPermissions = new PermissionsState(permissionsState); 8262 permissionsState.reset(); 8263 } 8264 } 8265 8266 permissionsState.setGlobalGids(mGlobalGids); 8267 8268 final int N = pkg.requestedPermissions.size(); 8269 for (int i=0; i<N; i++) { 8270 final String name = pkg.requestedPermissions.get(i); 8271 final BasePermission bp = mSettings.mPermissions.get(name); 8272 8273 if (DEBUG_INSTALL) { 8274 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8275 } 8276 8277 if (bp == null || bp.packageSetting == null) { 8278 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8279 Slog.w(TAG, "Unknown permission " + name 8280 + " in package " + pkg.packageName); 8281 } 8282 continue; 8283 } 8284 8285 final String perm = bp.name; 8286 boolean allowedSig = false; 8287 int grant = GRANT_DENIED; 8288 8289 // Keep track of app op permissions. 8290 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8291 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8292 if (pkgs == null) { 8293 pkgs = new ArraySet<>(); 8294 mAppOpPermissionPackages.put(bp.name, pkgs); 8295 } 8296 pkgs.add(pkg.packageName); 8297 } 8298 8299 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8300 switch (level) { 8301 case PermissionInfo.PROTECTION_NORMAL: { 8302 // For all apps normal permissions are install time ones. 8303 grant = GRANT_INSTALL; 8304 } break; 8305 8306 case PermissionInfo.PROTECTION_DANGEROUS: { 8307 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8308 // For legacy apps dangerous permissions are install time ones. 8309 grant = GRANT_INSTALL_LEGACY; 8310 } else if (origPermissions.hasInstallPermission(bp.name)) { 8311 // For legacy apps that became modern, install becomes runtime. 8312 grant = GRANT_UPGRADE; 8313 } else { 8314 // For modern apps keep runtime permissions unchanged. 8315 grant = GRANT_RUNTIME; 8316 } 8317 } break; 8318 8319 case PermissionInfo.PROTECTION_SIGNATURE: { 8320 // For all apps signature permissions are install time ones. 8321 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8322 if (allowedSig) { 8323 grant = GRANT_INSTALL; 8324 } 8325 } break; 8326 } 8327 8328 if (DEBUG_INSTALL) { 8329 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8330 } 8331 8332 if (grant != GRANT_DENIED) { 8333 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8334 // If this is an existing, non-system package, then 8335 // we can't add any new permissions to it. 8336 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8337 // Except... if this is a permission that was added 8338 // to the platform (note: need to only do this when 8339 // updating the platform). 8340 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8341 grant = GRANT_DENIED; 8342 } 8343 } 8344 } 8345 8346 switch (grant) { 8347 case GRANT_INSTALL: { 8348 // Revoke this as runtime permission to handle the case of 8349 // a runtime permission being downgraded to an install one. 8350 for (int userId : UserManagerService.getInstance().getUserIds()) { 8351 if (origPermissions.getRuntimePermissionState( 8352 bp.name, userId) != null) { 8353 // Revoke the runtime permission and clear the flags. 8354 origPermissions.revokeRuntimePermission(bp, userId); 8355 origPermissions.updatePermissionFlags(bp, userId, 8356 PackageManager.MASK_PERMISSION_FLAGS, 0); 8357 // If we revoked a permission permission, we have to write. 8358 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8359 changedRuntimePermissionUserIds, userId); 8360 } 8361 } 8362 // Grant an install permission. 8363 if (permissionsState.grantInstallPermission(bp) != 8364 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8365 changedInstallPermission = true; 8366 } 8367 } break; 8368 8369 case GRANT_INSTALL_LEGACY: { 8370 // Grant an install permission. 8371 if (permissionsState.grantInstallPermission(bp) != 8372 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8373 changedInstallPermission = true; 8374 } 8375 } break; 8376 8377 case GRANT_RUNTIME: { 8378 // Grant previously granted runtime permissions. 8379 for (int userId : UserManagerService.getInstance().getUserIds()) { 8380 PermissionState permissionState = origPermissions 8381 .getRuntimePermissionState(bp.name, userId); 8382 final int flags = permissionState != null 8383 ? permissionState.getFlags() : 0; 8384 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8385 if (permissionsState.grantRuntimePermission(bp, userId) == 8386 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8387 // If we cannot put the permission as it was, we have to write. 8388 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8389 changedRuntimePermissionUserIds, userId); 8390 } 8391 } 8392 // Propagate the permission flags. 8393 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8394 } 8395 } break; 8396 8397 case GRANT_UPGRADE: { 8398 // Grant runtime permissions for a previously held install permission. 8399 PermissionState permissionState = origPermissions 8400 .getInstallPermissionState(bp.name); 8401 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8402 8403 if (origPermissions.revokeInstallPermission(bp) 8404 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8405 // We will be transferring the permission flags, so clear them. 8406 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8407 PackageManager.MASK_PERMISSION_FLAGS, 0); 8408 changedInstallPermission = true; 8409 } 8410 8411 // If the permission is not to be promoted to runtime we ignore it and 8412 // also its other flags as they are not applicable to install permissions. 8413 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8414 for (int userId : currentUserIds) { 8415 if (permissionsState.grantRuntimePermission(bp, userId) != 8416 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8417 // Transfer the permission flags. 8418 permissionsState.updatePermissionFlags(bp, userId, 8419 flags, flags); 8420 // If we granted the permission, we have to write. 8421 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8422 changedRuntimePermissionUserIds, userId); 8423 } 8424 } 8425 } 8426 } break; 8427 8428 default: { 8429 if (packageOfInterest == null 8430 || packageOfInterest.equals(pkg.packageName)) { 8431 Slog.w(TAG, "Not granting permission " + perm 8432 + " to package " + pkg.packageName 8433 + " because it was previously installed without"); 8434 } 8435 } break; 8436 } 8437 } else { 8438 if (permissionsState.revokeInstallPermission(bp) != 8439 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8440 // Also drop the permission flags. 8441 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8442 PackageManager.MASK_PERMISSION_FLAGS, 0); 8443 changedInstallPermission = true; 8444 Slog.i(TAG, "Un-granting permission " + perm 8445 + " from package " + pkg.packageName 8446 + " (protectionLevel=" + bp.protectionLevel 8447 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8448 + ")"); 8449 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8450 // Don't print warning for app op permissions, since it is fine for them 8451 // not to be granted, there is a UI for the user to decide. 8452 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8453 Slog.w(TAG, "Not granting permission " + perm 8454 + " to package " + pkg.packageName 8455 + " (protectionLevel=" + bp.protectionLevel 8456 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8457 + ")"); 8458 } 8459 } 8460 } 8461 } 8462 8463 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8464 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8465 // This is the first that we have heard about this package, so the 8466 // permissions we have now selected are fixed until explicitly 8467 // changed. 8468 ps.installPermissionsFixed = true; 8469 } 8470 8471 // Persist the runtime permissions state for users with changes. 8472 for (int userId : changedRuntimePermissionUserIds) { 8473 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8474 } 8475 } 8476 8477 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8478 boolean allowed = false; 8479 final int NP = PackageParser.NEW_PERMISSIONS.length; 8480 for (int ip=0; ip<NP; ip++) { 8481 final PackageParser.NewPermissionInfo npi 8482 = PackageParser.NEW_PERMISSIONS[ip]; 8483 if (npi.name.equals(perm) 8484 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8485 allowed = true; 8486 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8487 + pkg.packageName); 8488 break; 8489 } 8490 } 8491 return allowed; 8492 } 8493 8494 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8495 BasePermission bp, PermissionsState origPermissions) { 8496 boolean allowed; 8497 allowed = (compareSignatures( 8498 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8499 == PackageManager.SIGNATURE_MATCH) 8500 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8501 == PackageManager.SIGNATURE_MATCH); 8502 if (!allowed && (bp.protectionLevel 8503 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8504 if (isSystemApp(pkg)) { 8505 // For updated system applications, a system permission 8506 // is granted only if it had been defined by the original application. 8507 if (pkg.isUpdatedSystemApp()) { 8508 final PackageSetting sysPs = mSettings 8509 .getDisabledSystemPkgLPr(pkg.packageName); 8510 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8511 // If the original was granted this permission, we take 8512 // that grant decision as read and propagate it to the 8513 // update. 8514 if (sysPs.isPrivileged()) { 8515 allowed = true; 8516 } 8517 } else { 8518 // The system apk may have been updated with an older 8519 // version of the one on the data partition, but which 8520 // granted a new system permission that it didn't have 8521 // before. In this case we do want to allow the app to 8522 // now get the new permission if the ancestral apk is 8523 // privileged to get it. 8524 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8525 for (int j=0; 8526 j<sysPs.pkg.requestedPermissions.size(); j++) { 8527 if (perm.equals( 8528 sysPs.pkg.requestedPermissions.get(j))) { 8529 allowed = true; 8530 break; 8531 } 8532 } 8533 } 8534 } 8535 } else { 8536 allowed = isPrivilegedApp(pkg); 8537 } 8538 } 8539 } 8540 if (!allowed) { 8541 if (!allowed && (bp.protectionLevel 8542 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8543 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8544 // If this was a previously normal/dangerous permission that got moved 8545 // to a system permission as part of the runtime permission redesign, then 8546 // we still want to blindly grant it to old apps. 8547 allowed = true; 8548 } 8549 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8550 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8551 // If this permission is to be granted to the system installer and 8552 // this app is an installer, then it gets the permission. 8553 allowed = true; 8554 } 8555 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8556 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8557 // If this permission is to be granted to the system verifier and 8558 // this app is a verifier, then it gets the permission. 8559 allowed = true; 8560 } 8561 if (!allowed && (bp.protectionLevel 8562 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8563 && isSystemApp(pkg)) { 8564 // Any pre-installed system app is allowed to get this permission. 8565 allowed = true; 8566 } 8567 if (!allowed && (bp.protectionLevel 8568 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8569 // For development permissions, a development permission 8570 // is granted only if it was already granted. 8571 allowed = origPermissions.hasInstallPermission(perm); 8572 } 8573 } 8574 return allowed; 8575 } 8576 8577 final class ActivityIntentResolver 8578 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8579 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8580 boolean defaultOnly, int userId) { 8581 if (!sUserManager.exists(userId)) return null; 8582 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8583 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8584 } 8585 8586 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8587 int userId) { 8588 if (!sUserManager.exists(userId)) return null; 8589 mFlags = flags; 8590 return super.queryIntent(intent, resolvedType, 8591 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8592 } 8593 8594 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8595 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8596 if (!sUserManager.exists(userId)) return null; 8597 if (packageActivities == null) { 8598 return null; 8599 } 8600 mFlags = flags; 8601 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8602 final int N = packageActivities.size(); 8603 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8604 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8605 8606 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8607 for (int i = 0; i < N; ++i) { 8608 intentFilters = packageActivities.get(i).intents; 8609 if (intentFilters != null && intentFilters.size() > 0) { 8610 PackageParser.ActivityIntentInfo[] array = 8611 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8612 intentFilters.toArray(array); 8613 listCut.add(array); 8614 } 8615 } 8616 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8617 } 8618 8619 public final void addActivity(PackageParser.Activity a, String type) { 8620 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8621 mActivities.put(a.getComponentName(), a); 8622 if (DEBUG_SHOW_INFO) 8623 Log.v( 8624 TAG, " " + type + " " + 8625 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8626 if (DEBUG_SHOW_INFO) 8627 Log.v(TAG, " Class=" + a.info.name); 8628 final int NI = a.intents.size(); 8629 for (int j=0; j<NI; j++) { 8630 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8631 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8632 intent.setPriority(0); 8633 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8634 + a.className + " with priority > 0, forcing to 0"); 8635 } 8636 if (DEBUG_SHOW_INFO) { 8637 Log.v(TAG, " IntentFilter:"); 8638 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8639 } 8640 if (!intent.debugCheck()) { 8641 Log.w(TAG, "==> For Activity " + a.info.name); 8642 } 8643 addFilter(intent); 8644 } 8645 } 8646 8647 public final void removeActivity(PackageParser.Activity a, String type) { 8648 mActivities.remove(a.getComponentName()); 8649 if (DEBUG_SHOW_INFO) { 8650 Log.v(TAG, " " + type + " " 8651 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8652 : a.info.name) + ":"); 8653 Log.v(TAG, " Class=" + a.info.name); 8654 } 8655 final int NI = a.intents.size(); 8656 for (int j=0; j<NI; j++) { 8657 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8658 if (DEBUG_SHOW_INFO) { 8659 Log.v(TAG, " IntentFilter:"); 8660 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8661 } 8662 removeFilter(intent); 8663 } 8664 } 8665 8666 @Override 8667 protected boolean allowFilterResult( 8668 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8669 ActivityInfo filterAi = filter.activity.info; 8670 for (int i=dest.size()-1; i>=0; i--) { 8671 ActivityInfo destAi = dest.get(i).activityInfo; 8672 if (destAi.name == filterAi.name 8673 && destAi.packageName == filterAi.packageName) { 8674 return false; 8675 } 8676 } 8677 return true; 8678 } 8679 8680 @Override 8681 protected ActivityIntentInfo[] newArray(int size) { 8682 return new ActivityIntentInfo[size]; 8683 } 8684 8685 @Override 8686 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8687 if (!sUserManager.exists(userId)) return true; 8688 PackageParser.Package p = filter.activity.owner; 8689 if (p != null) { 8690 PackageSetting ps = (PackageSetting)p.mExtras; 8691 if (ps != null) { 8692 // System apps are never considered stopped for purposes of 8693 // filtering, because there may be no way for the user to 8694 // actually re-launch them. 8695 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8696 && ps.getStopped(userId); 8697 } 8698 } 8699 return false; 8700 } 8701 8702 @Override 8703 protected boolean isPackageForFilter(String packageName, 8704 PackageParser.ActivityIntentInfo info) { 8705 return packageName.equals(info.activity.owner.packageName); 8706 } 8707 8708 @Override 8709 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8710 int match, int userId) { 8711 if (!sUserManager.exists(userId)) return null; 8712 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8713 return null; 8714 } 8715 final PackageParser.Activity activity = info.activity; 8716 if (mSafeMode && (activity.info.applicationInfo.flags 8717 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8718 return null; 8719 } 8720 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8721 if (ps == null) { 8722 return null; 8723 } 8724 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8725 ps.readUserState(userId), userId); 8726 if (ai == null) { 8727 return null; 8728 } 8729 final ResolveInfo res = new ResolveInfo(); 8730 res.activityInfo = ai; 8731 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8732 res.filter = info; 8733 } 8734 if (info != null) { 8735 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8736 } 8737 res.priority = info.getPriority(); 8738 res.preferredOrder = activity.owner.mPreferredOrder; 8739 //System.out.println("Result: " + res.activityInfo.className + 8740 // " = " + res.priority); 8741 res.match = match; 8742 res.isDefault = info.hasDefault; 8743 res.labelRes = info.labelRes; 8744 res.nonLocalizedLabel = info.nonLocalizedLabel; 8745 if (userNeedsBadging(userId)) { 8746 res.noResourceId = true; 8747 } else { 8748 res.icon = info.icon; 8749 } 8750 res.iconResourceId = info.icon; 8751 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8752 return res; 8753 } 8754 8755 @Override 8756 protected void sortResults(List<ResolveInfo> results) { 8757 Collections.sort(results, mResolvePrioritySorter); 8758 } 8759 8760 @Override 8761 protected void dumpFilter(PrintWriter out, String prefix, 8762 PackageParser.ActivityIntentInfo filter) { 8763 out.print(prefix); out.print( 8764 Integer.toHexString(System.identityHashCode(filter.activity))); 8765 out.print(' '); 8766 filter.activity.printComponentShortName(out); 8767 out.print(" filter "); 8768 out.println(Integer.toHexString(System.identityHashCode(filter))); 8769 } 8770 8771 @Override 8772 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8773 return filter.activity; 8774 } 8775 8776 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8777 PackageParser.Activity activity = (PackageParser.Activity)label; 8778 out.print(prefix); out.print( 8779 Integer.toHexString(System.identityHashCode(activity))); 8780 out.print(' '); 8781 activity.printComponentShortName(out); 8782 if (count > 1) { 8783 out.print(" ("); out.print(count); out.print(" filters)"); 8784 } 8785 out.println(); 8786 } 8787 8788// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8789// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8790// final List<ResolveInfo> retList = Lists.newArrayList(); 8791// while (i.hasNext()) { 8792// final ResolveInfo resolveInfo = i.next(); 8793// if (isEnabledLP(resolveInfo.activityInfo)) { 8794// retList.add(resolveInfo); 8795// } 8796// } 8797// return retList; 8798// } 8799 8800 // Keys are String (activity class name), values are Activity. 8801 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8802 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8803 private int mFlags; 8804 } 8805 8806 private final class ServiceIntentResolver 8807 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8808 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8809 boolean defaultOnly, int userId) { 8810 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8811 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8812 } 8813 8814 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8815 int userId) { 8816 if (!sUserManager.exists(userId)) return null; 8817 mFlags = flags; 8818 return super.queryIntent(intent, resolvedType, 8819 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8820 } 8821 8822 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8823 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8824 if (!sUserManager.exists(userId)) return null; 8825 if (packageServices == null) { 8826 return null; 8827 } 8828 mFlags = flags; 8829 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8830 final int N = packageServices.size(); 8831 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8832 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8833 8834 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8835 for (int i = 0; i < N; ++i) { 8836 intentFilters = packageServices.get(i).intents; 8837 if (intentFilters != null && intentFilters.size() > 0) { 8838 PackageParser.ServiceIntentInfo[] array = 8839 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8840 intentFilters.toArray(array); 8841 listCut.add(array); 8842 } 8843 } 8844 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8845 } 8846 8847 public final void addService(PackageParser.Service s) { 8848 mServices.put(s.getComponentName(), s); 8849 if (DEBUG_SHOW_INFO) { 8850 Log.v(TAG, " " 8851 + (s.info.nonLocalizedLabel != null 8852 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8853 Log.v(TAG, " Class=" + s.info.name); 8854 } 8855 final int NI = s.intents.size(); 8856 int j; 8857 for (j=0; j<NI; j++) { 8858 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8859 if (DEBUG_SHOW_INFO) { 8860 Log.v(TAG, " IntentFilter:"); 8861 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8862 } 8863 if (!intent.debugCheck()) { 8864 Log.w(TAG, "==> For Service " + s.info.name); 8865 } 8866 addFilter(intent); 8867 } 8868 } 8869 8870 public final void removeService(PackageParser.Service s) { 8871 mServices.remove(s.getComponentName()); 8872 if (DEBUG_SHOW_INFO) { 8873 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8874 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8875 Log.v(TAG, " Class=" + s.info.name); 8876 } 8877 final int NI = s.intents.size(); 8878 int j; 8879 for (j=0; j<NI; j++) { 8880 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8881 if (DEBUG_SHOW_INFO) { 8882 Log.v(TAG, " IntentFilter:"); 8883 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8884 } 8885 removeFilter(intent); 8886 } 8887 } 8888 8889 @Override 8890 protected boolean allowFilterResult( 8891 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8892 ServiceInfo filterSi = filter.service.info; 8893 for (int i=dest.size()-1; i>=0; i--) { 8894 ServiceInfo destAi = dest.get(i).serviceInfo; 8895 if (destAi.name == filterSi.name 8896 && destAi.packageName == filterSi.packageName) { 8897 return false; 8898 } 8899 } 8900 return true; 8901 } 8902 8903 @Override 8904 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8905 return new PackageParser.ServiceIntentInfo[size]; 8906 } 8907 8908 @Override 8909 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8910 if (!sUserManager.exists(userId)) return true; 8911 PackageParser.Package p = filter.service.owner; 8912 if (p != null) { 8913 PackageSetting ps = (PackageSetting)p.mExtras; 8914 if (ps != null) { 8915 // System apps are never considered stopped for purposes of 8916 // filtering, because there may be no way for the user to 8917 // actually re-launch them. 8918 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8919 && ps.getStopped(userId); 8920 } 8921 } 8922 return false; 8923 } 8924 8925 @Override 8926 protected boolean isPackageForFilter(String packageName, 8927 PackageParser.ServiceIntentInfo info) { 8928 return packageName.equals(info.service.owner.packageName); 8929 } 8930 8931 @Override 8932 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8933 int match, int userId) { 8934 if (!sUserManager.exists(userId)) return null; 8935 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8936 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8937 return null; 8938 } 8939 final PackageParser.Service service = info.service; 8940 if (mSafeMode && (service.info.applicationInfo.flags 8941 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8942 return null; 8943 } 8944 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8945 if (ps == null) { 8946 return null; 8947 } 8948 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8949 ps.readUserState(userId), userId); 8950 if (si == null) { 8951 return null; 8952 } 8953 final ResolveInfo res = new ResolveInfo(); 8954 res.serviceInfo = si; 8955 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8956 res.filter = filter; 8957 } 8958 res.priority = info.getPriority(); 8959 res.preferredOrder = service.owner.mPreferredOrder; 8960 res.match = match; 8961 res.isDefault = info.hasDefault; 8962 res.labelRes = info.labelRes; 8963 res.nonLocalizedLabel = info.nonLocalizedLabel; 8964 res.icon = info.icon; 8965 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8966 return res; 8967 } 8968 8969 @Override 8970 protected void sortResults(List<ResolveInfo> results) { 8971 Collections.sort(results, mResolvePrioritySorter); 8972 } 8973 8974 @Override 8975 protected void dumpFilter(PrintWriter out, String prefix, 8976 PackageParser.ServiceIntentInfo filter) { 8977 out.print(prefix); out.print( 8978 Integer.toHexString(System.identityHashCode(filter.service))); 8979 out.print(' '); 8980 filter.service.printComponentShortName(out); 8981 out.print(" filter "); 8982 out.println(Integer.toHexString(System.identityHashCode(filter))); 8983 } 8984 8985 @Override 8986 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8987 return filter.service; 8988 } 8989 8990 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8991 PackageParser.Service service = (PackageParser.Service)label; 8992 out.print(prefix); out.print( 8993 Integer.toHexString(System.identityHashCode(service))); 8994 out.print(' '); 8995 service.printComponentShortName(out); 8996 if (count > 1) { 8997 out.print(" ("); out.print(count); out.print(" filters)"); 8998 } 8999 out.println(); 9000 } 9001 9002// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9003// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9004// final List<ResolveInfo> retList = Lists.newArrayList(); 9005// while (i.hasNext()) { 9006// final ResolveInfo resolveInfo = (ResolveInfo) i; 9007// if (isEnabledLP(resolveInfo.serviceInfo)) { 9008// retList.add(resolveInfo); 9009// } 9010// } 9011// return retList; 9012// } 9013 9014 // Keys are String (activity class name), values are Activity. 9015 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9016 = new ArrayMap<ComponentName, PackageParser.Service>(); 9017 private int mFlags; 9018 }; 9019 9020 private final class ProviderIntentResolver 9021 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9022 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9023 boolean defaultOnly, int userId) { 9024 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9025 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9026 } 9027 9028 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9029 int userId) { 9030 if (!sUserManager.exists(userId)) 9031 return null; 9032 mFlags = flags; 9033 return super.queryIntent(intent, resolvedType, 9034 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9035 } 9036 9037 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9038 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9039 if (!sUserManager.exists(userId)) 9040 return null; 9041 if (packageProviders == null) { 9042 return null; 9043 } 9044 mFlags = flags; 9045 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9046 final int N = packageProviders.size(); 9047 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9048 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9049 9050 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9051 for (int i = 0; i < N; ++i) { 9052 intentFilters = packageProviders.get(i).intents; 9053 if (intentFilters != null && intentFilters.size() > 0) { 9054 PackageParser.ProviderIntentInfo[] array = 9055 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9056 intentFilters.toArray(array); 9057 listCut.add(array); 9058 } 9059 } 9060 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9061 } 9062 9063 public final void addProvider(PackageParser.Provider p) { 9064 if (mProviders.containsKey(p.getComponentName())) { 9065 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9066 return; 9067 } 9068 9069 mProviders.put(p.getComponentName(), p); 9070 if (DEBUG_SHOW_INFO) { 9071 Log.v(TAG, " " 9072 + (p.info.nonLocalizedLabel != null 9073 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9074 Log.v(TAG, " Class=" + p.info.name); 9075 } 9076 final int NI = p.intents.size(); 9077 int j; 9078 for (j = 0; j < NI; j++) { 9079 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9080 if (DEBUG_SHOW_INFO) { 9081 Log.v(TAG, " IntentFilter:"); 9082 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9083 } 9084 if (!intent.debugCheck()) { 9085 Log.w(TAG, "==> For Provider " + p.info.name); 9086 } 9087 addFilter(intent); 9088 } 9089 } 9090 9091 public final void removeProvider(PackageParser.Provider p) { 9092 mProviders.remove(p.getComponentName()); 9093 if (DEBUG_SHOW_INFO) { 9094 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9095 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9096 Log.v(TAG, " Class=" + p.info.name); 9097 } 9098 final int NI = p.intents.size(); 9099 int j; 9100 for (j = 0; j < NI; j++) { 9101 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9102 if (DEBUG_SHOW_INFO) { 9103 Log.v(TAG, " IntentFilter:"); 9104 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9105 } 9106 removeFilter(intent); 9107 } 9108 } 9109 9110 @Override 9111 protected boolean allowFilterResult( 9112 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9113 ProviderInfo filterPi = filter.provider.info; 9114 for (int i = dest.size() - 1; i >= 0; i--) { 9115 ProviderInfo destPi = dest.get(i).providerInfo; 9116 if (destPi.name == filterPi.name 9117 && destPi.packageName == filterPi.packageName) { 9118 return false; 9119 } 9120 } 9121 return true; 9122 } 9123 9124 @Override 9125 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9126 return new PackageParser.ProviderIntentInfo[size]; 9127 } 9128 9129 @Override 9130 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9131 if (!sUserManager.exists(userId)) 9132 return true; 9133 PackageParser.Package p = filter.provider.owner; 9134 if (p != null) { 9135 PackageSetting ps = (PackageSetting) p.mExtras; 9136 if (ps != null) { 9137 // System apps are never considered stopped for purposes of 9138 // filtering, because there may be no way for the user to 9139 // actually re-launch them. 9140 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9141 && ps.getStopped(userId); 9142 } 9143 } 9144 return false; 9145 } 9146 9147 @Override 9148 protected boolean isPackageForFilter(String packageName, 9149 PackageParser.ProviderIntentInfo info) { 9150 return packageName.equals(info.provider.owner.packageName); 9151 } 9152 9153 @Override 9154 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9155 int match, int userId) { 9156 if (!sUserManager.exists(userId)) 9157 return null; 9158 final PackageParser.ProviderIntentInfo info = filter; 9159 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9160 return null; 9161 } 9162 final PackageParser.Provider provider = info.provider; 9163 if (mSafeMode && (provider.info.applicationInfo.flags 9164 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9165 return null; 9166 } 9167 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9168 if (ps == null) { 9169 return null; 9170 } 9171 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9172 ps.readUserState(userId), userId); 9173 if (pi == null) { 9174 return null; 9175 } 9176 final ResolveInfo res = new ResolveInfo(); 9177 res.providerInfo = pi; 9178 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9179 res.filter = filter; 9180 } 9181 res.priority = info.getPriority(); 9182 res.preferredOrder = provider.owner.mPreferredOrder; 9183 res.match = match; 9184 res.isDefault = info.hasDefault; 9185 res.labelRes = info.labelRes; 9186 res.nonLocalizedLabel = info.nonLocalizedLabel; 9187 res.icon = info.icon; 9188 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9189 return res; 9190 } 9191 9192 @Override 9193 protected void sortResults(List<ResolveInfo> results) { 9194 Collections.sort(results, mResolvePrioritySorter); 9195 } 9196 9197 @Override 9198 protected void dumpFilter(PrintWriter out, String prefix, 9199 PackageParser.ProviderIntentInfo filter) { 9200 out.print(prefix); 9201 out.print( 9202 Integer.toHexString(System.identityHashCode(filter.provider))); 9203 out.print(' '); 9204 filter.provider.printComponentShortName(out); 9205 out.print(" filter "); 9206 out.println(Integer.toHexString(System.identityHashCode(filter))); 9207 } 9208 9209 @Override 9210 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9211 return filter.provider; 9212 } 9213 9214 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9215 PackageParser.Provider provider = (PackageParser.Provider)label; 9216 out.print(prefix); out.print( 9217 Integer.toHexString(System.identityHashCode(provider))); 9218 out.print(' '); 9219 provider.printComponentShortName(out); 9220 if (count > 1) { 9221 out.print(" ("); out.print(count); out.print(" filters)"); 9222 } 9223 out.println(); 9224 } 9225 9226 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9227 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9228 private int mFlags; 9229 }; 9230 9231 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9232 new Comparator<ResolveInfo>() { 9233 public int compare(ResolveInfo r1, ResolveInfo r2) { 9234 int v1 = r1.priority; 9235 int v2 = r2.priority; 9236 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9237 if (v1 != v2) { 9238 return (v1 > v2) ? -1 : 1; 9239 } 9240 v1 = r1.preferredOrder; 9241 v2 = r2.preferredOrder; 9242 if (v1 != v2) { 9243 return (v1 > v2) ? -1 : 1; 9244 } 9245 if (r1.isDefault != r2.isDefault) { 9246 return r1.isDefault ? -1 : 1; 9247 } 9248 v1 = r1.match; 9249 v2 = r2.match; 9250 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9251 if (v1 != v2) { 9252 return (v1 > v2) ? -1 : 1; 9253 } 9254 if (r1.system != r2.system) { 9255 return r1.system ? -1 : 1; 9256 } 9257 return 0; 9258 } 9259 }; 9260 9261 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9262 new Comparator<ProviderInfo>() { 9263 public int compare(ProviderInfo p1, ProviderInfo p2) { 9264 final int v1 = p1.initOrder; 9265 final int v2 = p2.initOrder; 9266 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9267 } 9268 }; 9269 9270 final void sendPackageBroadcast(final String action, final String pkg, 9271 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9272 final int[] userIds) { 9273 mHandler.post(new Runnable() { 9274 @Override 9275 public void run() { 9276 try { 9277 final IActivityManager am = ActivityManagerNative.getDefault(); 9278 if (am == null) return; 9279 final int[] resolvedUserIds; 9280 if (userIds == null) { 9281 resolvedUserIds = am.getRunningUserIds(); 9282 } else { 9283 resolvedUserIds = userIds; 9284 } 9285 for (int id : resolvedUserIds) { 9286 final Intent intent = new Intent(action, 9287 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9288 if (extras != null) { 9289 intent.putExtras(extras); 9290 } 9291 if (targetPkg != null) { 9292 intent.setPackage(targetPkg); 9293 } 9294 // Modify the UID when posting to other users 9295 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9296 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9297 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9298 intent.putExtra(Intent.EXTRA_UID, uid); 9299 } 9300 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9301 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9302 if (DEBUG_BROADCASTS) { 9303 RuntimeException here = new RuntimeException("here"); 9304 here.fillInStackTrace(); 9305 Slog.d(TAG, "Sending to user " + id + ": " 9306 + intent.toShortString(false, true, false, false) 9307 + " " + intent.getExtras(), here); 9308 } 9309 am.broadcastIntent(null, intent, null, finishedReceiver, 9310 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9311 null, finishedReceiver != null, false, id); 9312 } 9313 } catch (RemoteException ex) { 9314 } 9315 } 9316 }); 9317 } 9318 9319 /** 9320 * Check if the external storage media is available. This is true if there 9321 * is a mounted external storage medium or if the external storage is 9322 * emulated. 9323 */ 9324 private boolean isExternalMediaAvailable() { 9325 return mMediaMounted || Environment.isExternalStorageEmulated(); 9326 } 9327 9328 @Override 9329 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9330 // writer 9331 synchronized (mPackages) { 9332 if (!isExternalMediaAvailable()) { 9333 // If the external storage is no longer mounted at this point, 9334 // the caller may not have been able to delete all of this 9335 // packages files and can not delete any more. Bail. 9336 return null; 9337 } 9338 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9339 if (lastPackage != null) { 9340 pkgs.remove(lastPackage); 9341 } 9342 if (pkgs.size() > 0) { 9343 return pkgs.get(0); 9344 } 9345 } 9346 return null; 9347 } 9348 9349 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9350 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9351 userId, andCode ? 1 : 0, packageName); 9352 if (mSystemReady) { 9353 msg.sendToTarget(); 9354 } else { 9355 if (mPostSystemReadyMessages == null) { 9356 mPostSystemReadyMessages = new ArrayList<>(); 9357 } 9358 mPostSystemReadyMessages.add(msg); 9359 } 9360 } 9361 9362 void startCleaningPackages() { 9363 // reader 9364 synchronized (mPackages) { 9365 if (!isExternalMediaAvailable()) { 9366 return; 9367 } 9368 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9369 return; 9370 } 9371 } 9372 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9373 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9374 IActivityManager am = ActivityManagerNative.getDefault(); 9375 if (am != null) { 9376 try { 9377 am.startService(null, intent, null, mContext.getOpPackageName(), 9378 UserHandle.USER_OWNER); 9379 } catch (RemoteException e) { 9380 } 9381 } 9382 } 9383 9384 @Override 9385 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9386 int installFlags, String installerPackageName, VerificationParams verificationParams, 9387 String packageAbiOverride) { 9388 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9389 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9390 } 9391 9392 @Override 9393 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9394 int installFlags, String installerPackageName, VerificationParams verificationParams, 9395 String packageAbiOverride, int userId) { 9396 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9397 9398 final int callingUid = Binder.getCallingUid(); 9399 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9400 9401 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9402 try { 9403 if (observer != null) { 9404 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9405 } 9406 } catch (RemoteException re) { 9407 } 9408 return; 9409 } 9410 9411 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9412 installFlags |= PackageManager.INSTALL_FROM_ADB; 9413 9414 } else { 9415 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9416 // about installerPackageName. 9417 9418 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9419 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9420 } 9421 9422 UserHandle user; 9423 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9424 user = UserHandle.ALL; 9425 } else { 9426 user = new UserHandle(userId); 9427 } 9428 9429 // Only system components can circumvent runtime permissions when installing. 9430 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9431 && mContext.checkCallingOrSelfPermission(Manifest.permission 9432 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9433 throw new SecurityException("You need the " 9434 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9435 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9436 } 9437 9438 verificationParams.setInstallerUid(callingUid); 9439 9440 final File originFile = new File(originPath); 9441 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9442 9443 final Message msg = mHandler.obtainMessage(INIT_COPY); 9444 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9445 null, verificationParams, user, packageAbiOverride); 9446 mHandler.sendMessage(msg); 9447 } 9448 9449 void installStage(String packageName, File stagedDir, String stagedCid, 9450 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9451 String installerPackageName, int installerUid, UserHandle user) { 9452 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9453 params.referrerUri, installerUid, null); 9454 verifParams.setInstallerUid(installerUid); 9455 9456 final OriginInfo origin; 9457 if (stagedDir != null) { 9458 origin = OriginInfo.fromStagedFile(stagedDir); 9459 } else { 9460 origin = OriginInfo.fromStagedContainer(stagedCid); 9461 } 9462 9463 final Message msg = mHandler.obtainMessage(INIT_COPY); 9464 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9465 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9466 mHandler.sendMessage(msg); 9467 } 9468 9469 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9470 Bundle extras = new Bundle(1); 9471 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9472 9473 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9474 packageName, extras, null, null, new int[] {userId}); 9475 try { 9476 IActivityManager am = ActivityManagerNative.getDefault(); 9477 final boolean isSystem = 9478 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9479 if (isSystem && am.isUserRunning(userId, false)) { 9480 // The just-installed/enabled app is bundled on the system, so presumed 9481 // to be able to run automatically without needing an explicit launch. 9482 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9483 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9484 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9485 .setPackage(packageName); 9486 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9487 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9488 } 9489 } catch (RemoteException e) { 9490 // shouldn't happen 9491 Slog.w(TAG, "Unable to bootstrap installed package", e); 9492 } 9493 } 9494 9495 @Override 9496 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9497 int userId) { 9498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9499 PackageSetting pkgSetting; 9500 final int uid = Binder.getCallingUid(); 9501 enforceCrossUserPermission(uid, userId, true, true, 9502 "setApplicationHiddenSetting for user " + userId); 9503 9504 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9505 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9506 return false; 9507 } 9508 9509 long callingId = Binder.clearCallingIdentity(); 9510 try { 9511 boolean sendAdded = false; 9512 boolean sendRemoved = false; 9513 // writer 9514 synchronized (mPackages) { 9515 pkgSetting = mSettings.mPackages.get(packageName); 9516 if (pkgSetting == null) { 9517 return false; 9518 } 9519 if (pkgSetting.getHidden(userId) != hidden) { 9520 pkgSetting.setHidden(hidden, userId); 9521 mSettings.writePackageRestrictionsLPr(userId); 9522 if (hidden) { 9523 sendRemoved = true; 9524 } else { 9525 sendAdded = true; 9526 } 9527 } 9528 } 9529 if (sendAdded) { 9530 sendPackageAddedForUser(packageName, pkgSetting, userId); 9531 return true; 9532 } 9533 if (sendRemoved) { 9534 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9535 "hiding pkg"); 9536 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9537 } 9538 } finally { 9539 Binder.restoreCallingIdentity(callingId); 9540 } 9541 return false; 9542 } 9543 9544 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9545 int userId) { 9546 final PackageRemovedInfo info = new PackageRemovedInfo(); 9547 info.removedPackage = packageName; 9548 info.removedUsers = new int[] {userId}; 9549 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9550 info.sendBroadcast(false, false, false); 9551 } 9552 9553 /** 9554 * Returns true if application is not found or there was an error. Otherwise it returns 9555 * the hidden state of the package for the given user. 9556 */ 9557 @Override 9558 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9559 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9560 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9561 false, "getApplicationHidden for user " + userId); 9562 PackageSetting pkgSetting; 9563 long callingId = Binder.clearCallingIdentity(); 9564 try { 9565 // writer 9566 synchronized (mPackages) { 9567 pkgSetting = mSettings.mPackages.get(packageName); 9568 if (pkgSetting == null) { 9569 return true; 9570 } 9571 return pkgSetting.getHidden(userId); 9572 } 9573 } finally { 9574 Binder.restoreCallingIdentity(callingId); 9575 } 9576 } 9577 9578 /** 9579 * @hide 9580 */ 9581 @Override 9582 public int installExistingPackageAsUser(String packageName, int userId) { 9583 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9584 null); 9585 PackageSetting pkgSetting; 9586 final int uid = Binder.getCallingUid(); 9587 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9588 + userId); 9589 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9590 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9591 } 9592 9593 long callingId = Binder.clearCallingIdentity(); 9594 try { 9595 boolean sendAdded = false; 9596 9597 // writer 9598 synchronized (mPackages) { 9599 pkgSetting = mSettings.mPackages.get(packageName); 9600 if (pkgSetting == null) { 9601 return PackageManager.INSTALL_FAILED_INVALID_URI; 9602 } 9603 if (!pkgSetting.getInstalled(userId)) { 9604 pkgSetting.setInstalled(true, userId); 9605 pkgSetting.setHidden(false, userId); 9606 mSettings.writePackageRestrictionsLPr(userId); 9607 sendAdded = true; 9608 } 9609 } 9610 9611 if (sendAdded) { 9612 sendPackageAddedForUser(packageName, pkgSetting, userId); 9613 } 9614 } finally { 9615 Binder.restoreCallingIdentity(callingId); 9616 } 9617 9618 return PackageManager.INSTALL_SUCCEEDED; 9619 } 9620 9621 boolean isUserRestricted(int userId, String restrictionKey) { 9622 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9623 if (restrictions.getBoolean(restrictionKey, false)) { 9624 Log.w(TAG, "User is restricted: " + restrictionKey); 9625 return true; 9626 } 9627 return false; 9628 } 9629 9630 @Override 9631 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9632 mContext.enforceCallingOrSelfPermission( 9633 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9634 "Only package verification agents can verify applications"); 9635 9636 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9637 final PackageVerificationResponse response = new PackageVerificationResponse( 9638 verificationCode, Binder.getCallingUid()); 9639 msg.arg1 = id; 9640 msg.obj = response; 9641 mHandler.sendMessage(msg); 9642 } 9643 9644 @Override 9645 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9646 long millisecondsToDelay) { 9647 mContext.enforceCallingOrSelfPermission( 9648 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9649 "Only package verification agents can extend verification timeouts"); 9650 9651 final PackageVerificationState state = mPendingVerification.get(id); 9652 final PackageVerificationResponse response = new PackageVerificationResponse( 9653 verificationCodeAtTimeout, Binder.getCallingUid()); 9654 9655 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9656 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9657 } 9658 if (millisecondsToDelay < 0) { 9659 millisecondsToDelay = 0; 9660 } 9661 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9662 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9663 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9664 } 9665 9666 if ((state != null) && !state.timeoutExtended()) { 9667 state.extendTimeout(); 9668 9669 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9670 msg.arg1 = id; 9671 msg.obj = response; 9672 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9673 } 9674 } 9675 9676 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9677 int verificationCode, UserHandle user) { 9678 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9679 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9680 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9681 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9682 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9683 9684 mContext.sendBroadcastAsUser(intent, user, 9685 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9686 } 9687 9688 private ComponentName matchComponentForVerifier(String packageName, 9689 List<ResolveInfo> receivers) { 9690 ActivityInfo targetReceiver = null; 9691 9692 final int NR = receivers.size(); 9693 for (int i = 0; i < NR; i++) { 9694 final ResolveInfo info = receivers.get(i); 9695 if (info.activityInfo == null) { 9696 continue; 9697 } 9698 9699 if (packageName.equals(info.activityInfo.packageName)) { 9700 targetReceiver = info.activityInfo; 9701 break; 9702 } 9703 } 9704 9705 if (targetReceiver == null) { 9706 return null; 9707 } 9708 9709 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9710 } 9711 9712 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9713 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9714 if (pkgInfo.verifiers.length == 0) { 9715 return null; 9716 } 9717 9718 final int N = pkgInfo.verifiers.length; 9719 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9720 for (int i = 0; i < N; i++) { 9721 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9722 9723 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9724 receivers); 9725 if (comp == null) { 9726 continue; 9727 } 9728 9729 final int verifierUid = getUidForVerifier(verifierInfo); 9730 if (verifierUid == -1) { 9731 continue; 9732 } 9733 9734 if (DEBUG_VERIFY) { 9735 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9736 + " with the correct signature"); 9737 } 9738 sufficientVerifiers.add(comp); 9739 verificationState.addSufficientVerifier(verifierUid); 9740 } 9741 9742 return sufficientVerifiers; 9743 } 9744 9745 private int getUidForVerifier(VerifierInfo verifierInfo) { 9746 synchronized (mPackages) { 9747 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9748 if (pkg == null) { 9749 return -1; 9750 } else if (pkg.mSignatures.length != 1) { 9751 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9752 + " has more than one signature; ignoring"); 9753 return -1; 9754 } 9755 9756 /* 9757 * If the public key of the package's signature does not match 9758 * our expected public key, then this is a different package and 9759 * we should skip. 9760 */ 9761 9762 final byte[] expectedPublicKey; 9763 try { 9764 final Signature verifierSig = pkg.mSignatures[0]; 9765 final PublicKey publicKey = verifierSig.getPublicKey(); 9766 expectedPublicKey = publicKey.getEncoded(); 9767 } catch (CertificateException e) { 9768 return -1; 9769 } 9770 9771 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9772 9773 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9774 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9775 + " does not have the expected public key; ignoring"); 9776 return -1; 9777 } 9778 9779 return pkg.applicationInfo.uid; 9780 } 9781 } 9782 9783 @Override 9784 public void finishPackageInstall(int token) { 9785 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9786 9787 if (DEBUG_INSTALL) { 9788 Slog.v(TAG, "BM finishing package install for " + token); 9789 } 9790 9791 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9792 mHandler.sendMessage(msg); 9793 } 9794 9795 /** 9796 * Get the verification agent timeout. 9797 * 9798 * @return verification timeout in milliseconds 9799 */ 9800 private long getVerificationTimeout() { 9801 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9802 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9803 DEFAULT_VERIFICATION_TIMEOUT); 9804 } 9805 9806 /** 9807 * Get the default verification agent response code. 9808 * 9809 * @return default verification response code 9810 */ 9811 private int getDefaultVerificationResponse() { 9812 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9813 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9814 DEFAULT_VERIFICATION_RESPONSE); 9815 } 9816 9817 /** 9818 * Check whether or not package verification has been enabled. 9819 * 9820 * @return true if verification should be performed 9821 */ 9822 private boolean isVerificationEnabled(int userId, int installFlags) { 9823 if (!DEFAULT_VERIFY_ENABLE) { 9824 return false; 9825 } 9826 9827 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9828 9829 // Check if installing from ADB 9830 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9831 // Do not run verification in a test harness environment 9832 if (ActivityManager.isRunningInTestHarness()) { 9833 return false; 9834 } 9835 if (ensureVerifyAppsEnabled) { 9836 return true; 9837 } 9838 // Check if the developer does not want package verification for ADB installs 9839 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9840 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9841 return false; 9842 } 9843 } 9844 9845 if (ensureVerifyAppsEnabled) { 9846 return true; 9847 } 9848 9849 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9850 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9851 } 9852 9853 @Override 9854 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9855 throws RemoteException { 9856 mContext.enforceCallingOrSelfPermission( 9857 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9858 "Only intentfilter verification agents can verify applications"); 9859 9860 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9861 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9862 Binder.getCallingUid(), verificationCode, failedDomains); 9863 msg.arg1 = id; 9864 msg.obj = response; 9865 mHandler.sendMessage(msg); 9866 } 9867 9868 @Override 9869 public int getIntentVerificationStatus(String packageName, int userId) { 9870 synchronized (mPackages) { 9871 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9872 } 9873 } 9874 9875 @Override 9876 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9877 mContext.enforceCallingOrSelfPermission( 9878 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9879 9880 boolean result = false; 9881 synchronized (mPackages) { 9882 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9883 } 9884 if (result) { 9885 scheduleWritePackageRestrictionsLocked(userId); 9886 } 9887 return result; 9888 } 9889 9890 @Override 9891 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9892 synchronized (mPackages) { 9893 return mSettings.getIntentFilterVerificationsLPr(packageName); 9894 } 9895 } 9896 9897 @Override 9898 public List<IntentFilter> getAllIntentFilters(String packageName) { 9899 if (TextUtils.isEmpty(packageName)) { 9900 return Collections.<IntentFilter>emptyList(); 9901 } 9902 synchronized (mPackages) { 9903 PackageParser.Package pkg = mPackages.get(packageName); 9904 if (pkg == null || pkg.activities == null) { 9905 return Collections.<IntentFilter>emptyList(); 9906 } 9907 final int count = pkg.activities.size(); 9908 ArrayList<IntentFilter> result = new ArrayList<>(); 9909 for (int n=0; n<count; n++) { 9910 PackageParser.Activity activity = pkg.activities.get(n); 9911 if (activity.intents != null || activity.intents.size() > 0) { 9912 result.addAll(activity.intents); 9913 } 9914 } 9915 return result; 9916 } 9917 } 9918 9919 @Override 9920 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9921 mContext.enforceCallingOrSelfPermission( 9922 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9923 9924 synchronized (mPackages) { 9925 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9926 if (packageName != null) { 9927 result |= updateIntentVerificationStatus(packageName, 9928 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9929 userId); 9930 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9931 packageName, userId); 9932 } 9933 return result; 9934 } 9935 } 9936 9937 @Override 9938 public String getDefaultBrowserPackageName(int userId) { 9939 synchronized (mPackages) { 9940 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9941 } 9942 } 9943 9944 /** 9945 * Get the "allow unknown sources" setting. 9946 * 9947 * @return the current "allow unknown sources" setting 9948 */ 9949 private int getUnknownSourcesSettings() { 9950 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9951 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9952 -1); 9953 } 9954 9955 @Override 9956 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9957 final int uid = Binder.getCallingUid(); 9958 // writer 9959 synchronized (mPackages) { 9960 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9961 if (targetPackageSetting == null) { 9962 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9963 } 9964 9965 PackageSetting installerPackageSetting; 9966 if (installerPackageName != null) { 9967 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9968 if (installerPackageSetting == null) { 9969 throw new IllegalArgumentException("Unknown installer package: " 9970 + installerPackageName); 9971 } 9972 } else { 9973 installerPackageSetting = null; 9974 } 9975 9976 Signature[] callerSignature; 9977 Object obj = mSettings.getUserIdLPr(uid); 9978 if (obj != null) { 9979 if (obj instanceof SharedUserSetting) { 9980 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9981 } else if (obj instanceof PackageSetting) { 9982 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9983 } else { 9984 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9985 } 9986 } else { 9987 throw new SecurityException("Unknown calling uid " + uid); 9988 } 9989 9990 // Verify: can't set installerPackageName to a package that is 9991 // not signed with the same cert as the caller. 9992 if (installerPackageSetting != null) { 9993 if (compareSignatures(callerSignature, 9994 installerPackageSetting.signatures.mSignatures) 9995 != PackageManager.SIGNATURE_MATCH) { 9996 throw new SecurityException( 9997 "Caller does not have same cert as new installer package " 9998 + installerPackageName); 9999 } 10000 } 10001 10002 // Verify: if target already has an installer package, it must 10003 // be signed with the same cert as the caller. 10004 if (targetPackageSetting.installerPackageName != null) { 10005 PackageSetting setting = mSettings.mPackages.get( 10006 targetPackageSetting.installerPackageName); 10007 // If the currently set package isn't valid, then it's always 10008 // okay to change it. 10009 if (setting != null) { 10010 if (compareSignatures(callerSignature, 10011 setting.signatures.mSignatures) 10012 != PackageManager.SIGNATURE_MATCH) { 10013 throw new SecurityException( 10014 "Caller does not have same cert as old installer package " 10015 + targetPackageSetting.installerPackageName); 10016 } 10017 } 10018 } 10019 10020 // Okay! 10021 targetPackageSetting.installerPackageName = installerPackageName; 10022 scheduleWriteSettingsLocked(); 10023 } 10024 } 10025 10026 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10027 // Queue up an async operation since the package installation may take a little while. 10028 mHandler.post(new Runnable() { 10029 public void run() { 10030 mHandler.removeCallbacks(this); 10031 // Result object to be returned 10032 PackageInstalledInfo res = new PackageInstalledInfo(); 10033 res.returnCode = currentStatus; 10034 res.uid = -1; 10035 res.pkg = null; 10036 res.removedInfo = new PackageRemovedInfo(); 10037 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10038 args.doPreInstall(res.returnCode); 10039 synchronized (mInstallLock) { 10040 installPackageLI(args, res); 10041 } 10042 args.doPostInstall(res.returnCode, res.uid); 10043 } 10044 10045 // A restore should be performed at this point if (a) the install 10046 // succeeded, (b) the operation is not an update, and (c) the new 10047 // package has not opted out of backup participation. 10048 final boolean update = res.removedInfo.removedPackage != null; 10049 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10050 boolean doRestore = !update 10051 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10052 10053 // Set up the post-install work request bookkeeping. This will be used 10054 // and cleaned up by the post-install event handling regardless of whether 10055 // there's a restore pass performed. Token values are >= 1. 10056 int token; 10057 if (mNextInstallToken < 0) mNextInstallToken = 1; 10058 token = mNextInstallToken++; 10059 10060 PostInstallData data = new PostInstallData(args, res); 10061 mRunningInstalls.put(token, data); 10062 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10063 10064 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10065 // Pass responsibility to the Backup Manager. It will perform a 10066 // restore if appropriate, then pass responsibility back to the 10067 // Package Manager to run the post-install observer callbacks 10068 // and broadcasts. 10069 IBackupManager bm = IBackupManager.Stub.asInterface( 10070 ServiceManager.getService(Context.BACKUP_SERVICE)); 10071 if (bm != null) { 10072 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10073 + " to BM for possible restore"); 10074 try { 10075 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10076 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10077 } else { 10078 doRestore = false; 10079 } 10080 } catch (RemoteException e) { 10081 // can't happen; the backup manager is local 10082 } catch (Exception e) { 10083 Slog.e(TAG, "Exception trying to enqueue restore", e); 10084 doRestore = false; 10085 } 10086 } else { 10087 Slog.e(TAG, "Backup Manager not found!"); 10088 doRestore = false; 10089 } 10090 } 10091 10092 if (!doRestore) { 10093 // No restore possible, or the Backup Manager was mysteriously not 10094 // available -- just fire the post-install work request directly. 10095 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10096 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10097 mHandler.sendMessage(msg); 10098 } 10099 } 10100 }); 10101 } 10102 10103 private abstract class HandlerParams { 10104 private static final int MAX_RETRIES = 4; 10105 10106 /** 10107 * Number of times startCopy() has been attempted and had a non-fatal 10108 * error. 10109 */ 10110 private int mRetries = 0; 10111 10112 /** User handle for the user requesting the information or installation. */ 10113 private final UserHandle mUser; 10114 10115 HandlerParams(UserHandle user) { 10116 mUser = user; 10117 } 10118 10119 UserHandle getUser() { 10120 return mUser; 10121 } 10122 10123 final boolean startCopy() { 10124 boolean res; 10125 try { 10126 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10127 10128 if (++mRetries > MAX_RETRIES) { 10129 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10130 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10131 handleServiceError(); 10132 return false; 10133 } else { 10134 handleStartCopy(); 10135 res = true; 10136 } 10137 } catch (RemoteException e) { 10138 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10139 mHandler.sendEmptyMessage(MCS_RECONNECT); 10140 res = false; 10141 } 10142 handleReturnCode(); 10143 return res; 10144 } 10145 10146 final void serviceError() { 10147 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10148 handleServiceError(); 10149 handleReturnCode(); 10150 } 10151 10152 abstract void handleStartCopy() throws RemoteException; 10153 abstract void handleServiceError(); 10154 abstract void handleReturnCode(); 10155 } 10156 10157 class MeasureParams extends HandlerParams { 10158 private final PackageStats mStats; 10159 private boolean mSuccess; 10160 10161 private final IPackageStatsObserver mObserver; 10162 10163 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10164 super(new UserHandle(stats.userHandle)); 10165 mObserver = observer; 10166 mStats = stats; 10167 } 10168 10169 @Override 10170 public String toString() { 10171 return "MeasureParams{" 10172 + Integer.toHexString(System.identityHashCode(this)) 10173 + " " + mStats.packageName + "}"; 10174 } 10175 10176 @Override 10177 void handleStartCopy() throws RemoteException { 10178 synchronized (mInstallLock) { 10179 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10180 } 10181 10182 if (mSuccess) { 10183 final boolean mounted; 10184 if (Environment.isExternalStorageEmulated()) { 10185 mounted = true; 10186 } else { 10187 final String status = Environment.getExternalStorageState(); 10188 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10189 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10190 } 10191 10192 if (mounted) { 10193 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10194 10195 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10196 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10197 10198 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10199 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10200 10201 // Always subtract cache size, since it's a subdirectory 10202 mStats.externalDataSize -= mStats.externalCacheSize; 10203 10204 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10205 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10206 10207 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10208 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10209 } 10210 } 10211 } 10212 10213 @Override 10214 void handleReturnCode() { 10215 if (mObserver != null) { 10216 try { 10217 mObserver.onGetStatsCompleted(mStats, mSuccess); 10218 } catch (RemoteException e) { 10219 Slog.i(TAG, "Observer no longer exists."); 10220 } 10221 } 10222 } 10223 10224 @Override 10225 void handleServiceError() { 10226 Slog.e(TAG, "Could not measure application " + mStats.packageName 10227 + " external storage"); 10228 } 10229 } 10230 10231 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10232 throws RemoteException { 10233 long result = 0; 10234 for (File path : paths) { 10235 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10236 } 10237 return result; 10238 } 10239 10240 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10241 for (File path : paths) { 10242 try { 10243 mcs.clearDirectory(path.getAbsolutePath()); 10244 } catch (RemoteException e) { 10245 } 10246 } 10247 } 10248 10249 static class OriginInfo { 10250 /** 10251 * Location where install is coming from, before it has been 10252 * copied/renamed into place. This could be a single monolithic APK 10253 * file, or a cluster directory. This location may be untrusted. 10254 */ 10255 final File file; 10256 final String cid; 10257 10258 /** 10259 * Flag indicating that {@link #file} or {@link #cid} has already been 10260 * staged, meaning downstream users don't need to defensively copy the 10261 * contents. 10262 */ 10263 final boolean staged; 10264 10265 /** 10266 * Flag indicating that {@link #file} or {@link #cid} is an already 10267 * installed app that is being moved. 10268 */ 10269 final boolean existing; 10270 10271 final String resolvedPath; 10272 final File resolvedFile; 10273 10274 static OriginInfo fromNothing() { 10275 return new OriginInfo(null, null, false, false); 10276 } 10277 10278 static OriginInfo fromUntrustedFile(File file) { 10279 return new OriginInfo(file, null, false, false); 10280 } 10281 10282 static OriginInfo fromExistingFile(File file) { 10283 return new OriginInfo(file, null, false, true); 10284 } 10285 10286 static OriginInfo fromStagedFile(File file) { 10287 return new OriginInfo(file, null, true, false); 10288 } 10289 10290 static OriginInfo fromStagedContainer(String cid) { 10291 return new OriginInfo(null, cid, true, false); 10292 } 10293 10294 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10295 this.file = file; 10296 this.cid = cid; 10297 this.staged = staged; 10298 this.existing = existing; 10299 10300 if (cid != null) { 10301 resolvedPath = PackageHelper.getSdDir(cid); 10302 resolvedFile = new File(resolvedPath); 10303 } else if (file != null) { 10304 resolvedPath = file.getAbsolutePath(); 10305 resolvedFile = file; 10306 } else { 10307 resolvedPath = null; 10308 resolvedFile = null; 10309 } 10310 } 10311 } 10312 10313 class MoveInfo { 10314 final int moveId; 10315 final String fromUuid; 10316 final String toUuid; 10317 final String packageName; 10318 final String dataAppName; 10319 final int appId; 10320 final String seinfo; 10321 10322 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10323 String dataAppName, int appId, String seinfo) { 10324 this.moveId = moveId; 10325 this.fromUuid = fromUuid; 10326 this.toUuid = toUuid; 10327 this.packageName = packageName; 10328 this.dataAppName = dataAppName; 10329 this.appId = appId; 10330 this.seinfo = seinfo; 10331 } 10332 } 10333 10334 class InstallParams extends HandlerParams { 10335 final OriginInfo origin; 10336 final MoveInfo move; 10337 final IPackageInstallObserver2 observer; 10338 int installFlags; 10339 final String installerPackageName; 10340 final String volumeUuid; 10341 final VerificationParams verificationParams; 10342 private InstallArgs mArgs; 10343 private int mRet; 10344 final String packageAbiOverride; 10345 10346 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10347 int installFlags, String installerPackageName, String volumeUuid, 10348 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10349 super(user); 10350 this.origin = origin; 10351 this.move = move; 10352 this.observer = observer; 10353 this.installFlags = installFlags; 10354 this.installerPackageName = installerPackageName; 10355 this.volumeUuid = volumeUuid; 10356 this.verificationParams = verificationParams; 10357 this.packageAbiOverride = packageAbiOverride; 10358 } 10359 10360 @Override 10361 public String toString() { 10362 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10363 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10364 } 10365 10366 public ManifestDigest getManifestDigest() { 10367 if (verificationParams == null) { 10368 return null; 10369 } 10370 return verificationParams.getManifestDigest(); 10371 } 10372 10373 private int installLocationPolicy(PackageInfoLite pkgLite) { 10374 String packageName = pkgLite.packageName; 10375 int installLocation = pkgLite.installLocation; 10376 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10377 // reader 10378 synchronized (mPackages) { 10379 PackageParser.Package pkg = mPackages.get(packageName); 10380 if (pkg != null) { 10381 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10382 // Check for downgrading. 10383 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10384 try { 10385 checkDowngrade(pkg, pkgLite); 10386 } catch (PackageManagerException e) { 10387 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10388 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10389 } 10390 } 10391 // Check for updated system application. 10392 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10393 if (onSd) { 10394 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10395 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10396 } 10397 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10398 } else { 10399 if (onSd) { 10400 // Install flag overrides everything. 10401 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10402 } 10403 // If current upgrade specifies particular preference 10404 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10405 // Application explicitly specified internal. 10406 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10407 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10408 // App explictly prefers external. Let policy decide 10409 } else { 10410 // Prefer previous location 10411 if (isExternal(pkg)) { 10412 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10413 } 10414 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10415 } 10416 } 10417 } else { 10418 // Invalid install. Return error code 10419 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10420 } 10421 } 10422 } 10423 // All the special cases have been taken care of. 10424 // Return result based on recommended install location. 10425 if (onSd) { 10426 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10427 } 10428 return pkgLite.recommendedInstallLocation; 10429 } 10430 10431 /* 10432 * Invoke remote method to get package information and install 10433 * location values. Override install location based on default 10434 * policy if needed and then create install arguments based 10435 * on the install location. 10436 */ 10437 public void handleStartCopy() throws RemoteException { 10438 int ret = PackageManager.INSTALL_SUCCEEDED; 10439 10440 // If we're already staged, we've firmly committed to an install location 10441 if (origin.staged) { 10442 if (origin.file != null) { 10443 installFlags |= PackageManager.INSTALL_INTERNAL; 10444 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10445 } else if (origin.cid != null) { 10446 installFlags |= PackageManager.INSTALL_EXTERNAL; 10447 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10448 } else { 10449 throw new IllegalStateException("Invalid stage location"); 10450 } 10451 } 10452 10453 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10454 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10455 10456 PackageInfoLite pkgLite = null; 10457 10458 if (onInt && onSd) { 10459 // Check if both bits are set. 10460 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10461 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10462 } else { 10463 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10464 packageAbiOverride); 10465 10466 /* 10467 * If we have too little free space, try to free cache 10468 * before giving up. 10469 */ 10470 if (!origin.staged && pkgLite.recommendedInstallLocation 10471 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10472 // TODO: focus freeing disk space on the target device 10473 final StorageManager storage = StorageManager.from(mContext); 10474 final long lowThreshold = storage.getStorageLowBytes( 10475 Environment.getDataDirectory()); 10476 10477 final long sizeBytes = mContainerService.calculateInstalledSize( 10478 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10479 10480 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10481 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10482 installFlags, packageAbiOverride); 10483 } 10484 10485 /* 10486 * The cache free must have deleted the file we 10487 * downloaded to install. 10488 * 10489 * TODO: fix the "freeCache" call to not delete 10490 * the file we care about. 10491 */ 10492 if (pkgLite.recommendedInstallLocation 10493 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10494 pkgLite.recommendedInstallLocation 10495 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10496 } 10497 } 10498 } 10499 10500 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10501 int loc = pkgLite.recommendedInstallLocation; 10502 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10503 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10504 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10505 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10506 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10507 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10508 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10509 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10510 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10511 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10512 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10513 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10514 } else { 10515 // Override with defaults if needed. 10516 loc = installLocationPolicy(pkgLite); 10517 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10518 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10519 } else if (!onSd && !onInt) { 10520 // Override install location with flags 10521 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10522 // Set the flag to install on external media. 10523 installFlags |= PackageManager.INSTALL_EXTERNAL; 10524 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10525 } else { 10526 // Make sure the flag for installing on external 10527 // media is unset 10528 installFlags |= PackageManager.INSTALL_INTERNAL; 10529 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10530 } 10531 } 10532 } 10533 } 10534 10535 final InstallArgs args = createInstallArgs(this); 10536 mArgs = args; 10537 10538 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10539 /* 10540 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10541 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10542 */ 10543 int userIdentifier = getUser().getIdentifier(); 10544 if (userIdentifier == UserHandle.USER_ALL 10545 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10546 userIdentifier = UserHandle.USER_OWNER; 10547 } 10548 10549 /* 10550 * Determine if we have any installed package verifiers. If we 10551 * do, then we'll defer to them to verify the packages. 10552 */ 10553 final int requiredUid = mRequiredVerifierPackage == null ? -1 10554 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10555 if (!origin.existing && requiredUid != -1 10556 && isVerificationEnabled(userIdentifier, installFlags)) { 10557 final Intent verification = new Intent( 10558 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10559 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10560 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10561 PACKAGE_MIME_TYPE); 10562 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10563 10564 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10565 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10566 0 /* TODO: Which userId? */); 10567 10568 if (DEBUG_VERIFY) { 10569 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10570 + verification.toString() + " with " + pkgLite.verifiers.length 10571 + " optional verifiers"); 10572 } 10573 10574 final int verificationId = mPendingVerificationToken++; 10575 10576 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10577 10578 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10579 installerPackageName); 10580 10581 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10582 installFlags); 10583 10584 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10585 pkgLite.packageName); 10586 10587 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10588 pkgLite.versionCode); 10589 10590 if (verificationParams != null) { 10591 if (verificationParams.getVerificationURI() != null) { 10592 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10593 verificationParams.getVerificationURI()); 10594 } 10595 if (verificationParams.getOriginatingURI() != null) { 10596 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10597 verificationParams.getOriginatingURI()); 10598 } 10599 if (verificationParams.getReferrer() != null) { 10600 verification.putExtra(Intent.EXTRA_REFERRER, 10601 verificationParams.getReferrer()); 10602 } 10603 if (verificationParams.getOriginatingUid() >= 0) { 10604 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10605 verificationParams.getOriginatingUid()); 10606 } 10607 if (verificationParams.getInstallerUid() >= 0) { 10608 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10609 verificationParams.getInstallerUid()); 10610 } 10611 } 10612 10613 final PackageVerificationState verificationState = new PackageVerificationState( 10614 requiredUid, args); 10615 10616 mPendingVerification.append(verificationId, verificationState); 10617 10618 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10619 receivers, verificationState); 10620 10621 // Apps installed for "all" users use the device owner to verify the app 10622 UserHandle verifierUser = getUser(); 10623 if (verifierUser == UserHandle.ALL) { 10624 verifierUser = UserHandle.OWNER; 10625 } 10626 10627 /* 10628 * If any sufficient verifiers were listed in the package 10629 * manifest, attempt to ask them. 10630 */ 10631 if (sufficientVerifiers != null) { 10632 final int N = sufficientVerifiers.size(); 10633 if (N == 0) { 10634 Slog.i(TAG, "Additional verifiers required, but none installed."); 10635 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10636 } else { 10637 for (int i = 0; i < N; i++) { 10638 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10639 10640 final Intent sufficientIntent = new Intent(verification); 10641 sufficientIntent.setComponent(verifierComponent); 10642 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 10643 } 10644 } 10645 } 10646 10647 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10648 mRequiredVerifierPackage, receivers); 10649 if (ret == PackageManager.INSTALL_SUCCEEDED 10650 && mRequiredVerifierPackage != null) { 10651 /* 10652 * Send the intent to the required verification agent, 10653 * but only start the verification timeout after the 10654 * target BroadcastReceivers have run. 10655 */ 10656 verification.setComponent(requiredVerifierComponent); 10657 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 10658 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10659 new BroadcastReceiver() { 10660 @Override 10661 public void onReceive(Context context, Intent intent) { 10662 final Message msg = mHandler 10663 .obtainMessage(CHECK_PENDING_VERIFICATION); 10664 msg.arg1 = verificationId; 10665 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10666 } 10667 }, null, 0, null, null); 10668 10669 /* 10670 * We don't want the copy to proceed until verification 10671 * succeeds, so null out this field. 10672 */ 10673 mArgs = null; 10674 } 10675 } else { 10676 /* 10677 * No package verification is enabled, so immediately start 10678 * the remote call to initiate copy using temporary file. 10679 */ 10680 ret = args.copyApk(mContainerService, true); 10681 } 10682 } 10683 10684 mRet = ret; 10685 } 10686 10687 @Override 10688 void handleReturnCode() { 10689 // If mArgs is null, then MCS couldn't be reached. When it 10690 // reconnects, it will try again to install. At that point, this 10691 // will succeed. 10692 if (mArgs != null) { 10693 processPendingInstall(mArgs, mRet); 10694 } 10695 } 10696 10697 @Override 10698 void handleServiceError() { 10699 mArgs = createInstallArgs(this); 10700 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10701 } 10702 10703 public boolean isForwardLocked() { 10704 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10705 } 10706 } 10707 10708 /** 10709 * Used during creation of InstallArgs 10710 * 10711 * @param installFlags package installation flags 10712 * @return true if should be installed on external storage 10713 */ 10714 private static boolean installOnExternalAsec(int installFlags) { 10715 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10716 return false; 10717 } 10718 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10719 return true; 10720 } 10721 return false; 10722 } 10723 10724 /** 10725 * Used during creation of InstallArgs 10726 * 10727 * @param installFlags package installation flags 10728 * @return true if should be installed as forward locked 10729 */ 10730 private static boolean installForwardLocked(int installFlags) { 10731 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10732 } 10733 10734 private InstallArgs createInstallArgs(InstallParams params) { 10735 if (params.move != null) { 10736 return new MoveInstallArgs(params); 10737 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10738 return new AsecInstallArgs(params); 10739 } else { 10740 return new FileInstallArgs(params); 10741 } 10742 } 10743 10744 /** 10745 * Create args that describe an existing installed package. Typically used 10746 * when cleaning up old installs, or used as a move source. 10747 */ 10748 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10749 String resourcePath, String[] instructionSets) { 10750 final boolean isInAsec; 10751 if (installOnExternalAsec(installFlags)) { 10752 /* Apps on SD card are always in ASEC containers. */ 10753 isInAsec = true; 10754 } else if (installForwardLocked(installFlags) 10755 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10756 /* 10757 * Forward-locked apps are only in ASEC containers if they're the 10758 * new style 10759 */ 10760 isInAsec = true; 10761 } else { 10762 isInAsec = false; 10763 } 10764 10765 if (isInAsec) { 10766 return new AsecInstallArgs(codePath, instructionSets, 10767 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10768 } else { 10769 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10770 } 10771 } 10772 10773 static abstract class InstallArgs { 10774 /** @see InstallParams#origin */ 10775 final OriginInfo origin; 10776 /** @see InstallParams#move */ 10777 final MoveInfo move; 10778 10779 final IPackageInstallObserver2 observer; 10780 // Always refers to PackageManager flags only 10781 final int installFlags; 10782 final String installerPackageName; 10783 final String volumeUuid; 10784 final ManifestDigest manifestDigest; 10785 final UserHandle user; 10786 final String abiOverride; 10787 10788 // The list of instruction sets supported by this app. This is currently 10789 // only used during the rmdex() phase to clean up resources. We can get rid of this 10790 // if we move dex files under the common app path. 10791 /* nullable */ String[] instructionSets; 10792 10793 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10794 int installFlags, String installerPackageName, String volumeUuid, 10795 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10796 String abiOverride) { 10797 this.origin = origin; 10798 this.move = move; 10799 this.installFlags = installFlags; 10800 this.observer = observer; 10801 this.installerPackageName = installerPackageName; 10802 this.volumeUuid = volumeUuid; 10803 this.manifestDigest = manifestDigest; 10804 this.user = user; 10805 this.instructionSets = instructionSets; 10806 this.abiOverride = abiOverride; 10807 } 10808 10809 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10810 abstract int doPreInstall(int status); 10811 10812 /** 10813 * Rename package into final resting place. All paths on the given 10814 * scanned package should be updated to reflect the rename. 10815 */ 10816 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10817 abstract int doPostInstall(int status, int uid); 10818 10819 /** @see PackageSettingBase#codePathString */ 10820 abstract String getCodePath(); 10821 /** @see PackageSettingBase#resourcePathString */ 10822 abstract String getResourcePath(); 10823 10824 // Need installer lock especially for dex file removal. 10825 abstract void cleanUpResourcesLI(); 10826 abstract boolean doPostDeleteLI(boolean delete); 10827 10828 /** 10829 * Called before the source arguments are copied. This is used mostly 10830 * for MoveParams when it needs to read the source file to put it in the 10831 * destination. 10832 */ 10833 int doPreCopy() { 10834 return PackageManager.INSTALL_SUCCEEDED; 10835 } 10836 10837 /** 10838 * Called after the source arguments are copied. This is used mostly for 10839 * MoveParams when it needs to read the source file to put it in the 10840 * destination. 10841 * 10842 * @return 10843 */ 10844 int doPostCopy(int uid) { 10845 return PackageManager.INSTALL_SUCCEEDED; 10846 } 10847 10848 protected boolean isFwdLocked() { 10849 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10850 } 10851 10852 protected boolean isExternalAsec() { 10853 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10854 } 10855 10856 UserHandle getUser() { 10857 return user; 10858 } 10859 } 10860 10861 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10862 if (!allCodePaths.isEmpty()) { 10863 if (instructionSets == null) { 10864 throw new IllegalStateException("instructionSet == null"); 10865 } 10866 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10867 for (String codePath : allCodePaths) { 10868 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10869 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10870 if (retCode < 0) { 10871 Slog.w(TAG, "Couldn't remove dex file for package: " 10872 + " at location " + codePath + ", retcode=" + retCode); 10873 // we don't consider this to be a failure of the core package deletion 10874 } 10875 } 10876 } 10877 } 10878 } 10879 10880 /** 10881 * Logic to handle installation of non-ASEC applications, including copying 10882 * and renaming logic. 10883 */ 10884 class FileInstallArgs extends InstallArgs { 10885 private File codeFile; 10886 private File resourceFile; 10887 10888 // Example topology: 10889 // /data/app/com.example/base.apk 10890 // /data/app/com.example/split_foo.apk 10891 // /data/app/com.example/lib/arm/libfoo.so 10892 // /data/app/com.example/lib/arm64/libfoo.so 10893 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10894 10895 /** New install */ 10896 FileInstallArgs(InstallParams params) { 10897 super(params.origin, params.move, params.observer, params.installFlags, 10898 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10899 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10900 if (isFwdLocked()) { 10901 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10902 } 10903 } 10904 10905 /** Existing install */ 10906 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10907 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10908 null); 10909 this.codeFile = (codePath != null) ? new File(codePath) : null; 10910 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10911 } 10912 10913 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10914 if (origin.staged) { 10915 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10916 codeFile = origin.file; 10917 resourceFile = origin.file; 10918 return PackageManager.INSTALL_SUCCEEDED; 10919 } 10920 10921 try { 10922 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10923 codeFile = tempDir; 10924 resourceFile = tempDir; 10925 } catch (IOException e) { 10926 Slog.w(TAG, "Failed to create copy file: " + e); 10927 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10928 } 10929 10930 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10931 @Override 10932 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10933 if (!FileUtils.isValidExtFilename(name)) { 10934 throw new IllegalArgumentException("Invalid filename: " + name); 10935 } 10936 try { 10937 final File file = new File(codeFile, name); 10938 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10939 O_RDWR | O_CREAT, 0644); 10940 Os.chmod(file.getAbsolutePath(), 0644); 10941 return new ParcelFileDescriptor(fd); 10942 } catch (ErrnoException e) { 10943 throw new RemoteException("Failed to open: " + e.getMessage()); 10944 } 10945 } 10946 }; 10947 10948 int ret = PackageManager.INSTALL_SUCCEEDED; 10949 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10950 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10951 Slog.e(TAG, "Failed to copy package"); 10952 return ret; 10953 } 10954 10955 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10956 NativeLibraryHelper.Handle handle = null; 10957 try { 10958 handle = NativeLibraryHelper.Handle.create(codeFile); 10959 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10960 abiOverride); 10961 } catch (IOException e) { 10962 Slog.e(TAG, "Copying native libraries failed", e); 10963 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10964 } finally { 10965 IoUtils.closeQuietly(handle); 10966 } 10967 10968 return ret; 10969 } 10970 10971 int doPreInstall(int status) { 10972 if (status != PackageManager.INSTALL_SUCCEEDED) { 10973 cleanUp(); 10974 } 10975 return status; 10976 } 10977 10978 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10979 if (status != PackageManager.INSTALL_SUCCEEDED) { 10980 cleanUp(); 10981 return false; 10982 } 10983 10984 final File targetDir = codeFile.getParentFile(); 10985 final File beforeCodeFile = codeFile; 10986 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10987 10988 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10989 try { 10990 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10991 } catch (ErrnoException e) { 10992 Slog.w(TAG, "Failed to rename", e); 10993 return false; 10994 } 10995 10996 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10997 Slog.w(TAG, "Failed to restorecon"); 10998 return false; 10999 } 11000 11001 // Reflect the rename internally 11002 codeFile = afterCodeFile; 11003 resourceFile = afterCodeFile; 11004 11005 // Reflect the rename in scanned details 11006 pkg.codePath = afterCodeFile.getAbsolutePath(); 11007 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11008 pkg.baseCodePath); 11009 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11010 pkg.splitCodePaths); 11011 11012 // Reflect the rename in app info 11013 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11014 pkg.applicationInfo.setCodePath(pkg.codePath); 11015 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11016 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11017 pkg.applicationInfo.setResourcePath(pkg.codePath); 11018 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11019 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11020 11021 return true; 11022 } 11023 11024 int doPostInstall(int status, int uid) { 11025 if (status != PackageManager.INSTALL_SUCCEEDED) { 11026 cleanUp(); 11027 } 11028 return status; 11029 } 11030 11031 @Override 11032 String getCodePath() { 11033 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11034 } 11035 11036 @Override 11037 String getResourcePath() { 11038 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11039 } 11040 11041 private boolean cleanUp() { 11042 if (codeFile == null || !codeFile.exists()) { 11043 return false; 11044 } 11045 11046 if (codeFile.isDirectory()) { 11047 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11048 } else { 11049 codeFile.delete(); 11050 } 11051 11052 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11053 resourceFile.delete(); 11054 } 11055 11056 return true; 11057 } 11058 11059 void cleanUpResourcesLI() { 11060 // Try enumerating all code paths before deleting 11061 List<String> allCodePaths = Collections.EMPTY_LIST; 11062 if (codeFile != null && codeFile.exists()) { 11063 try { 11064 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11065 allCodePaths = pkg.getAllCodePaths(); 11066 } catch (PackageParserException e) { 11067 // Ignored; we tried our best 11068 } 11069 } 11070 11071 cleanUp(); 11072 removeDexFiles(allCodePaths, instructionSets); 11073 } 11074 11075 boolean doPostDeleteLI(boolean delete) { 11076 // XXX err, shouldn't we respect the delete flag? 11077 cleanUpResourcesLI(); 11078 return true; 11079 } 11080 } 11081 11082 private boolean isAsecExternal(String cid) { 11083 final String asecPath = PackageHelper.getSdFilesystem(cid); 11084 return !asecPath.startsWith(mAsecInternalPath); 11085 } 11086 11087 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11088 PackageManagerException { 11089 if (copyRet < 0) { 11090 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11091 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11092 throw new PackageManagerException(copyRet, message); 11093 } 11094 } 11095 } 11096 11097 /** 11098 * Extract the MountService "container ID" from the full code path of an 11099 * .apk. 11100 */ 11101 static String cidFromCodePath(String fullCodePath) { 11102 int eidx = fullCodePath.lastIndexOf("/"); 11103 String subStr1 = fullCodePath.substring(0, eidx); 11104 int sidx = subStr1.lastIndexOf("/"); 11105 return subStr1.substring(sidx+1, eidx); 11106 } 11107 11108 /** 11109 * Logic to handle installation of ASEC applications, including copying and 11110 * renaming logic. 11111 */ 11112 class AsecInstallArgs extends InstallArgs { 11113 static final String RES_FILE_NAME = "pkg.apk"; 11114 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11115 11116 String cid; 11117 String packagePath; 11118 String resourcePath; 11119 11120 /** New install */ 11121 AsecInstallArgs(InstallParams params) { 11122 super(params.origin, params.move, params.observer, params.installFlags, 11123 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11124 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11125 } 11126 11127 /** Existing install */ 11128 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11129 boolean isExternal, boolean isForwardLocked) { 11130 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11131 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11132 instructionSets, null); 11133 // Hackily pretend we're still looking at a full code path 11134 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11135 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11136 } 11137 11138 // Extract cid from fullCodePath 11139 int eidx = fullCodePath.lastIndexOf("/"); 11140 String subStr1 = fullCodePath.substring(0, eidx); 11141 int sidx = subStr1.lastIndexOf("/"); 11142 cid = subStr1.substring(sidx+1, eidx); 11143 setMountPath(subStr1); 11144 } 11145 11146 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11147 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11148 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11149 instructionSets, null); 11150 this.cid = cid; 11151 setMountPath(PackageHelper.getSdDir(cid)); 11152 } 11153 11154 void createCopyFile() { 11155 cid = mInstallerService.allocateExternalStageCidLegacy(); 11156 } 11157 11158 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11159 if (origin.staged) { 11160 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11161 cid = origin.cid; 11162 setMountPath(PackageHelper.getSdDir(cid)); 11163 return PackageManager.INSTALL_SUCCEEDED; 11164 } 11165 11166 if (temp) { 11167 createCopyFile(); 11168 } else { 11169 /* 11170 * Pre-emptively destroy the container since it's destroyed if 11171 * copying fails due to it existing anyway. 11172 */ 11173 PackageHelper.destroySdDir(cid); 11174 } 11175 11176 final String newMountPath = imcs.copyPackageToContainer( 11177 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11178 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11179 11180 if (newMountPath != null) { 11181 setMountPath(newMountPath); 11182 return PackageManager.INSTALL_SUCCEEDED; 11183 } else { 11184 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11185 } 11186 } 11187 11188 @Override 11189 String getCodePath() { 11190 return packagePath; 11191 } 11192 11193 @Override 11194 String getResourcePath() { 11195 return resourcePath; 11196 } 11197 11198 int doPreInstall(int status) { 11199 if (status != PackageManager.INSTALL_SUCCEEDED) { 11200 // Destroy container 11201 PackageHelper.destroySdDir(cid); 11202 } else { 11203 boolean mounted = PackageHelper.isContainerMounted(cid); 11204 if (!mounted) { 11205 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11206 Process.SYSTEM_UID); 11207 if (newMountPath != null) { 11208 setMountPath(newMountPath); 11209 } else { 11210 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11211 } 11212 } 11213 } 11214 return status; 11215 } 11216 11217 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11218 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11219 String newMountPath = null; 11220 if (PackageHelper.isContainerMounted(cid)) { 11221 // Unmount the container 11222 if (!PackageHelper.unMountSdDir(cid)) { 11223 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11224 return false; 11225 } 11226 } 11227 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11228 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11229 " which might be stale. Will try to clean up."); 11230 // Clean up the stale container and proceed to recreate. 11231 if (!PackageHelper.destroySdDir(newCacheId)) { 11232 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11233 return false; 11234 } 11235 // Successfully cleaned up stale container. Try to rename again. 11236 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11237 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11238 + " inspite of cleaning it up."); 11239 return false; 11240 } 11241 } 11242 if (!PackageHelper.isContainerMounted(newCacheId)) { 11243 Slog.w(TAG, "Mounting container " + newCacheId); 11244 newMountPath = PackageHelper.mountSdDir(newCacheId, 11245 getEncryptKey(), Process.SYSTEM_UID); 11246 } else { 11247 newMountPath = PackageHelper.getSdDir(newCacheId); 11248 } 11249 if (newMountPath == null) { 11250 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11251 return false; 11252 } 11253 Log.i(TAG, "Succesfully renamed " + cid + 11254 " to " + newCacheId + 11255 " at new path: " + newMountPath); 11256 cid = newCacheId; 11257 11258 final File beforeCodeFile = new File(packagePath); 11259 setMountPath(newMountPath); 11260 final File afterCodeFile = new File(packagePath); 11261 11262 // Reflect the rename in scanned details 11263 pkg.codePath = afterCodeFile.getAbsolutePath(); 11264 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11265 pkg.baseCodePath); 11266 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11267 pkg.splitCodePaths); 11268 11269 // Reflect the rename in app info 11270 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11271 pkg.applicationInfo.setCodePath(pkg.codePath); 11272 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11273 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11274 pkg.applicationInfo.setResourcePath(pkg.codePath); 11275 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11276 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11277 11278 return true; 11279 } 11280 11281 private void setMountPath(String mountPath) { 11282 final File mountFile = new File(mountPath); 11283 11284 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11285 if (monolithicFile.exists()) { 11286 packagePath = monolithicFile.getAbsolutePath(); 11287 if (isFwdLocked()) { 11288 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11289 } else { 11290 resourcePath = packagePath; 11291 } 11292 } else { 11293 packagePath = mountFile.getAbsolutePath(); 11294 resourcePath = packagePath; 11295 } 11296 } 11297 11298 int doPostInstall(int status, int uid) { 11299 if (status != PackageManager.INSTALL_SUCCEEDED) { 11300 cleanUp(); 11301 } else { 11302 final int groupOwner; 11303 final String protectedFile; 11304 if (isFwdLocked()) { 11305 groupOwner = UserHandle.getSharedAppGid(uid); 11306 protectedFile = RES_FILE_NAME; 11307 } else { 11308 groupOwner = -1; 11309 protectedFile = null; 11310 } 11311 11312 if (uid < Process.FIRST_APPLICATION_UID 11313 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11314 Slog.e(TAG, "Failed to finalize " + cid); 11315 PackageHelper.destroySdDir(cid); 11316 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11317 } 11318 11319 boolean mounted = PackageHelper.isContainerMounted(cid); 11320 if (!mounted) { 11321 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11322 } 11323 } 11324 return status; 11325 } 11326 11327 private void cleanUp() { 11328 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11329 11330 // Destroy secure container 11331 PackageHelper.destroySdDir(cid); 11332 } 11333 11334 private List<String> getAllCodePaths() { 11335 final File codeFile = new File(getCodePath()); 11336 if (codeFile != null && codeFile.exists()) { 11337 try { 11338 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11339 return pkg.getAllCodePaths(); 11340 } catch (PackageParserException e) { 11341 // Ignored; we tried our best 11342 } 11343 } 11344 return Collections.EMPTY_LIST; 11345 } 11346 11347 void cleanUpResourcesLI() { 11348 // Enumerate all code paths before deleting 11349 cleanUpResourcesLI(getAllCodePaths()); 11350 } 11351 11352 private void cleanUpResourcesLI(List<String> allCodePaths) { 11353 cleanUp(); 11354 removeDexFiles(allCodePaths, instructionSets); 11355 } 11356 11357 String getPackageName() { 11358 return getAsecPackageName(cid); 11359 } 11360 11361 boolean doPostDeleteLI(boolean delete) { 11362 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11363 final List<String> allCodePaths = getAllCodePaths(); 11364 boolean mounted = PackageHelper.isContainerMounted(cid); 11365 if (mounted) { 11366 // Unmount first 11367 if (PackageHelper.unMountSdDir(cid)) { 11368 mounted = false; 11369 } 11370 } 11371 if (!mounted && delete) { 11372 cleanUpResourcesLI(allCodePaths); 11373 } 11374 return !mounted; 11375 } 11376 11377 @Override 11378 int doPreCopy() { 11379 if (isFwdLocked()) { 11380 if (!PackageHelper.fixSdPermissions(cid, 11381 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11382 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11383 } 11384 } 11385 11386 return PackageManager.INSTALL_SUCCEEDED; 11387 } 11388 11389 @Override 11390 int doPostCopy(int uid) { 11391 if (isFwdLocked()) { 11392 if (uid < Process.FIRST_APPLICATION_UID 11393 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11394 RES_FILE_NAME)) { 11395 Slog.e(TAG, "Failed to finalize " + cid); 11396 PackageHelper.destroySdDir(cid); 11397 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11398 } 11399 } 11400 11401 return PackageManager.INSTALL_SUCCEEDED; 11402 } 11403 } 11404 11405 /** 11406 * Logic to handle movement of existing installed applications. 11407 */ 11408 class MoveInstallArgs extends InstallArgs { 11409 private File codeFile; 11410 private File resourceFile; 11411 11412 /** New install */ 11413 MoveInstallArgs(InstallParams params) { 11414 super(params.origin, params.move, params.observer, params.installFlags, 11415 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11416 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11417 } 11418 11419 int copyApk(IMediaContainerService imcs, boolean temp) { 11420 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11421 + move.fromUuid + " to " + move.toUuid); 11422 synchronized (mInstaller) { 11423 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11424 move.dataAppName, move.appId, move.seinfo) != 0) { 11425 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11426 } 11427 } 11428 11429 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11430 resourceFile = codeFile; 11431 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11432 11433 return PackageManager.INSTALL_SUCCEEDED; 11434 } 11435 11436 int doPreInstall(int status) { 11437 if (status != PackageManager.INSTALL_SUCCEEDED) { 11438 cleanUp(move.toUuid); 11439 } 11440 return status; 11441 } 11442 11443 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11444 if (status != PackageManager.INSTALL_SUCCEEDED) { 11445 cleanUp(move.toUuid); 11446 return false; 11447 } 11448 11449 // Reflect the move in app info 11450 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11451 pkg.applicationInfo.setCodePath(pkg.codePath); 11452 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11453 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11454 pkg.applicationInfo.setResourcePath(pkg.codePath); 11455 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11456 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11457 11458 return true; 11459 } 11460 11461 int doPostInstall(int status, int uid) { 11462 if (status == PackageManager.INSTALL_SUCCEEDED) { 11463 cleanUp(move.fromUuid); 11464 } else { 11465 cleanUp(move.toUuid); 11466 } 11467 return status; 11468 } 11469 11470 @Override 11471 String getCodePath() { 11472 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11473 } 11474 11475 @Override 11476 String getResourcePath() { 11477 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11478 } 11479 11480 private boolean cleanUp(String volumeUuid) { 11481 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11482 move.dataAppName); 11483 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11484 synchronized (mInstallLock) { 11485 // Clean up both app data and code 11486 removeDataDirsLI(volumeUuid, move.packageName); 11487 if (codeFile.isDirectory()) { 11488 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11489 } else { 11490 codeFile.delete(); 11491 } 11492 } 11493 return true; 11494 } 11495 11496 void cleanUpResourcesLI() { 11497 throw new UnsupportedOperationException(); 11498 } 11499 11500 boolean doPostDeleteLI(boolean delete) { 11501 throw new UnsupportedOperationException(); 11502 } 11503 } 11504 11505 static String getAsecPackageName(String packageCid) { 11506 int idx = packageCid.lastIndexOf("-"); 11507 if (idx == -1) { 11508 return packageCid; 11509 } 11510 return packageCid.substring(0, idx); 11511 } 11512 11513 // Utility method used to create code paths based on package name and available index. 11514 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11515 String idxStr = ""; 11516 int idx = 1; 11517 // Fall back to default value of idx=1 if prefix is not 11518 // part of oldCodePath 11519 if (oldCodePath != null) { 11520 String subStr = oldCodePath; 11521 // Drop the suffix right away 11522 if (suffix != null && subStr.endsWith(suffix)) { 11523 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11524 } 11525 // If oldCodePath already contains prefix find out the 11526 // ending index to either increment or decrement. 11527 int sidx = subStr.lastIndexOf(prefix); 11528 if (sidx != -1) { 11529 subStr = subStr.substring(sidx + prefix.length()); 11530 if (subStr != null) { 11531 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11532 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11533 } 11534 try { 11535 idx = Integer.parseInt(subStr); 11536 if (idx <= 1) { 11537 idx++; 11538 } else { 11539 idx--; 11540 } 11541 } catch(NumberFormatException e) { 11542 } 11543 } 11544 } 11545 } 11546 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11547 return prefix + idxStr; 11548 } 11549 11550 private File getNextCodePath(File targetDir, String packageName) { 11551 int suffix = 1; 11552 File result; 11553 do { 11554 result = new File(targetDir, packageName + "-" + suffix); 11555 suffix++; 11556 } while (result.exists()); 11557 return result; 11558 } 11559 11560 // Utility method that returns the relative package path with respect 11561 // to the installation directory. Like say for /data/data/com.test-1.apk 11562 // string com.test-1 is returned. 11563 static String deriveCodePathName(String codePath) { 11564 if (codePath == null) { 11565 return null; 11566 } 11567 final File codeFile = new File(codePath); 11568 final String name = codeFile.getName(); 11569 if (codeFile.isDirectory()) { 11570 return name; 11571 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11572 final int lastDot = name.lastIndexOf('.'); 11573 return name.substring(0, lastDot); 11574 } else { 11575 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11576 return null; 11577 } 11578 } 11579 11580 class PackageInstalledInfo { 11581 String name; 11582 int uid; 11583 // The set of users that originally had this package installed. 11584 int[] origUsers; 11585 // The set of users that now have this package installed. 11586 int[] newUsers; 11587 PackageParser.Package pkg; 11588 int returnCode; 11589 String returnMsg; 11590 PackageRemovedInfo removedInfo; 11591 11592 public void setError(int code, String msg) { 11593 returnCode = code; 11594 returnMsg = msg; 11595 Slog.w(TAG, msg); 11596 } 11597 11598 public void setError(String msg, PackageParserException e) { 11599 returnCode = e.error; 11600 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11601 Slog.w(TAG, msg, e); 11602 } 11603 11604 public void setError(String msg, PackageManagerException e) { 11605 returnCode = e.error; 11606 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11607 Slog.w(TAG, msg, e); 11608 } 11609 11610 // In some error cases we want to convey more info back to the observer 11611 String origPackage; 11612 String origPermission; 11613 } 11614 11615 /* 11616 * Install a non-existing package. 11617 */ 11618 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11619 UserHandle user, String installerPackageName, String volumeUuid, 11620 PackageInstalledInfo res) { 11621 // Remember this for later, in case we need to rollback this install 11622 String pkgName = pkg.packageName; 11623 11624 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11625 final boolean dataDirExists = Environment 11626 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11627 synchronized(mPackages) { 11628 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11629 // A package with the same name is already installed, though 11630 // it has been renamed to an older name. The package we 11631 // are trying to install should be installed as an update to 11632 // the existing one, but that has not been requested, so bail. 11633 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11634 + " without first uninstalling package running as " 11635 + mSettings.mRenamedPackages.get(pkgName)); 11636 return; 11637 } 11638 if (mPackages.containsKey(pkgName)) { 11639 // Don't allow installation over an existing package with the same name. 11640 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11641 + " without first uninstalling."); 11642 return; 11643 } 11644 } 11645 11646 try { 11647 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11648 System.currentTimeMillis(), user); 11649 11650 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11651 // delete the partially installed application. the data directory will have to be 11652 // restored if it was already existing 11653 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11654 // remove package from internal structures. Note that we want deletePackageX to 11655 // delete the package data and cache directories that it created in 11656 // scanPackageLocked, unless those directories existed before we even tried to 11657 // install. 11658 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11659 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11660 res.removedInfo, true); 11661 } 11662 11663 } catch (PackageManagerException e) { 11664 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11665 } 11666 } 11667 11668 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11669 // Can't rotate keys during boot or if sharedUser. 11670 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11671 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11672 return false; 11673 } 11674 // app is using upgradeKeySets; make sure all are valid 11675 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11676 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11677 for (int i = 0; i < upgradeKeySets.length; i++) { 11678 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11679 Slog.wtf(TAG, "Package " 11680 + (oldPs.name != null ? oldPs.name : "<null>") 11681 + " contains upgrade-key-set reference to unknown key-set: " 11682 + upgradeKeySets[i] 11683 + " reverting to signatures check."); 11684 return false; 11685 } 11686 } 11687 return true; 11688 } 11689 11690 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11691 // Upgrade keysets are being used. Determine if new package has a superset of the 11692 // required keys. 11693 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11694 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11695 for (int i = 0; i < upgradeKeySets.length; i++) { 11696 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11697 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11698 return true; 11699 } 11700 } 11701 return false; 11702 } 11703 11704 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11705 UserHandle user, String installerPackageName, String volumeUuid, 11706 PackageInstalledInfo res) { 11707 final PackageParser.Package oldPackage; 11708 final String pkgName = pkg.packageName; 11709 final int[] allUsers; 11710 final boolean[] perUserInstalled; 11711 final boolean weFroze; 11712 11713 // First find the old package info and check signatures 11714 synchronized(mPackages) { 11715 oldPackage = mPackages.get(pkgName); 11716 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11717 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11718 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11719 if(!checkUpgradeKeySetLP(ps, pkg)) { 11720 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11721 "New package not signed by keys specified by upgrade-keysets: " 11722 + pkgName); 11723 return; 11724 } 11725 } else { 11726 // default to original signature matching 11727 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11728 != PackageManager.SIGNATURE_MATCH) { 11729 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11730 "New package has a different signature: " + pkgName); 11731 return; 11732 } 11733 } 11734 11735 // In case of rollback, remember per-user/profile install state 11736 allUsers = sUserManager.getUserIds(); 11737 perUserInstalled = new boolean[allUsers.length]; 11738 for (int i = 0; i < allUsers.length; i++) { 11739 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11740 } 11741 11742 // Mark the app as frozen to prevent launching during the upgrade 11743 // process, and then kill all running instances 11744 if (!ps.frozen) { 11745 ps.frozen = true; 11746 weFroze = true; 11747 } else { 11748 weFroze = false; 11749 } 11750 } 11751 11752 // Now that we're guarded by frozen state, kill app during upgrade 11753 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11754 11755 try { 11756 boolean sysPkg = (isSystemApp(oldPackage)); 11757 if (sysPkg) { 11758 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11759 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11760 } else { 11761 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11762 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11763 } 11764 } finally { 11765 // Regardless of success or failure of upgrade steps above, always 11766 // unfreeze the package if we froze it 11767 if (weFroze) { 11768 unfreezePackage(pkgName); 11769 } 11770 } 11771 } 11772 11773 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11774 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11775 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11776 String volumeUuid, PackageInstalledInfo res) { 11777 String pkgName = deletedPackage.packageName; 11778 boolean deletedPkg = true; 11779 boolean updatedSettings = false; 11780 11781 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11782 + deletedPackage); 11783 long origUpdateTime; 11784 if (pkg.mExtras != null) { 11785 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11786 } else { 11787 origUpdateTime = 0; 11788 } 11789 11790 // First delete the existing package while retaining the data directory 11791 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11792 res.removedInfo, true)) { 11793 // If the existing package wasn't successfully deleted 11794 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11795 deletedPkg = false; 11796 } else { 11797 // Successfully deleted the old package; proceed with replace. 11798 11799 // If deleted package lived in a container, give users a chance to 11800 // relinquish resources before killing. 11801 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11802 if (DEBUG_INSTALL) { 11803 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11804 } 11805 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11806 final ArrayList<String> pkgList = new ArrayList<String>(1); 11807 pkgList.add(deletedPackage.applicationInfo.packageName); 11808 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11809 } 11810 11811 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11812 try { 11813 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11814 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11815 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11816 perUserInstalled, res, user); 11817 updatedSettings = true; 11818 } catch (PackageManagerException e) { 11819 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11820 } 11821 } 11822 11823 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11824 // remove package from internal structures. Note that we want deletePackageX to 11825 // delete the package data and cache directories that it created in 11826 // scanPackageLocked, unless those directories existed before we even tried to 11827 // install. 11828 if(updatedSettings) { 11829 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11830 deletePackageLI( 11831 pkgName, null, true, allUsers, perUserInstalled, 11832 PackageManager.DELETE_KEEP_DATA, 11833 res.removedInfo, true); 11834 } 11835 // Since we failed to install the new package we need to restore the old 11836 // package that we deleted. 11837 if (deletedPkg) { 11838 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11839 File restoreFile = new File(deletedPackage.codePath); 11840 // Parse old package 11841 boolean oldExternal = isExternal(deletedPackage); 11842 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11843 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11844 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11845 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11846 try { 11847 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11848 } catch (PackageManagerException e) { 11849 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11850 + e.getMessage()); 11851 return; 11852 } 11853 // Restore of old package succeeded. Update permissions. 11854 // writer 11855 synchronized (mPackages) { 11856 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11857 UPDATE_PERMISSIONS_ALL); 11858 // can downgrade to reader 11859 mSettings.writeLPr(); 11860 } 11861 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11862 } 11863 } 11864 } 11865 11866 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11867 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11868 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11869 String volumeUuid, PackageInstalledInfo res) { 11870 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11871 + ", old=" + deletedPackage); 11872 boolean disabledSystem = false; 11873 boolean updatedSettings = false; 11874 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11875 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11876 != 0) { 11877 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11878 } 11879 String packageName = deletedPackage.packageName; 11880 if (packageName == null) { 11881 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11882 "Attempt to delete null packageName."); 11883 return; 11884 } 11885 PackageParser.Package oldPkg; 11886 PackageSetting oldPkgSetting; 11887 // reader 11888 synchronized (mPackages) { 11889 oldPkg = mPackages.get(packageName); 11890 oldPkgSetting = mSettings.mPackages.get(packageName); 11891 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11892 (oldPkgSetting == null)) { 11893 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11894 "Couldn't find package:" + packageName + " information"); 11895 return; 11896 } 11897 } 11898 11899 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11900 res.removedInfo.removedPackage = packageName; 11901 // Remove existing system package 11902 removePackageLI(oldPkgSetting, true); 11903 // writer 11904 synchronized (mPackages) { 11905 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11906 if (!disabledSystem && deletedPackage != null) { 11907 // We didn't need to disable the .apk as a current system package, 11908 // which means we are replacing another update that is already 11909 // installed. We need to make sure to delete the older one's .apk. 11910 res.removedInfo.args = createInstallArgsForExisting(0, 11911 deletedPackage.applicationInfo.getCodePath(), 11912 deletedPackage.applicationInfo.getResourcePath(), 11913 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11914 } else { 11915 res.removedInfo.args = null; 11916 } 11917 } 11918 11919 // Successfully disabled the old package. Now proceed with re-installation 11920 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11921 11922 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11923 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11924 11925 PackageParser.Package newPackage = null; 11926 try { 11927 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11928 if (newPackage.mExtras != null) { 11929 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11930 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11931 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11932 11933 // is the update attempting to change shared user? that isn't going to work... 11934 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11935 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11936 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11937 + " to " + newPkgSetting.sharedUser); 11938 updatedSettings = true; 11939 } 11940 } 11941 11942 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11943 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11944 perUserInstalled, res, user); 11945 updatedSettings = true; 11946 } 11947 11948 } catch (PackageManagerException e) { 11949 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11950 } 11951 11952 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11953 // Re installation failed. Restore old information 11954 // Remove new pkg information 11955 if (newPackage != null) { 11956 removeInstalledPackageLI(newPackage, true); 11957 } 11958 // Add back the old system package 11959 try { 11960 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11961 } catch (PackageManagerException e) { 11962 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11963 } 11964 // Restore the old system information in Settings 11965 synchronized (mPackages) { 11966 if (disabledSystem) { 11967 mSettings.enableSystemPackageLPw(packageName); 11968 } 11969 if (updatedSettings) { 11970 mSettings.setInstallerPackageName(packageName, 11971 oldPkgSetting.installerPackageName); 11972 } 11973 mSettings.writeLPr(); 11974 } 11975 } 11976 } 11977 11978 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11979 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11980 UserHandle user) { 11981 String pkgName = newPackage.packageName; 11982 synchronized (mPackages) { 11983 //write settings. the installStatus will be incomplete at this stage. 11984 //note that the new package setting would have already been 11985 //added to mPackages. It hasn't been persisted yet. 11986 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11987 mSettings.writeLPr(); 11988 } 11989 11990 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11991 11992 synchronized (mPackages) { 11993 updatePermissionsLPw(newPackage.packageName, newPackage, 11994 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11995 ? UPDATE_PERMISSIONS_ALL : 0)); 11996 // For system-bundled packages, we assume that installing an upgraded version 11997 // of the package implies that the user actually wants to run that new code, 11998 // so we enable the package. 11999 PackageSetting ps = mSettings.mPackages.get(pkgName); 12000 if (ps != null) { 12001 if (isSystemApp(newPackage)) { 12002 // NB: implicit assumption that system package upgrades apply to all users 12003 if (DEBUG_INSTALL) { 12004 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12005 } 12006 if (res.origUsers != null) { 12007 for (int userHandle : res.origUsers) { 12008 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12009 userHandle, installerPackageName); 12010 } 12011 } 12012 // Also convey the prior install/uninstall state 12013 if (allUsers != null && perUserInstalled != null) { 12014 for (int i = 0; i < allUsers.length; i++) { 12015 if (DEBUG_INSTALL) { 12016 Slog.d(TAG, " user " + allUsers[i] 12017 + " => " + perUserInstalled[i]); 12018 } 12019 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12020 } 12021 // these install state changes will be persisted in the 12022 // upcoming call to mSettings.writeLPr(). 12023 } 12024 } 12025 // It's implied that when a user requests installation, they want the app to be 12026 // installed and enabled. 12027 int userId = user.getIdentifier(); 12028 if (userId != UserHandle.USER_ALL) { 12029 ps.setInstalled(true, userId); 12030 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12031 } 12032 } 12033 res.name = pkgName; 12034 res.uid = newPackage.applicationInfo.uid; 12035 res.pkg = newPackage; 12036 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12037 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12038 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12039 //to update install status 12040 mSettings.writeLPr(); 12041 } 12042 } 12043 12044 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12045 final int installFlags = args.installFlags; 12046 final String installerPackageName = args.installerPackageName; 12047 final String volumeUuid = args.volumeUuid; 12048 final File tmpPackageFile = new File(args.getCodePath()); 12049 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12050 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12051 || (args.volumeUuid != null)); 12052 boolean replace = false; 12053 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12054 if (args.move != null) { 12055 // moving a complete application; perfom an initial scan on the new install location 12056 scanFlags |= SCAN_INITIAL; 12057 } 12058 // Result object to be returned 12059 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12060 12061 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12062 // Retrieve PackageSettings and parse package 12063 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12064 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12065 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12066 PackageParser pp = new PackageParser(); 12067 pp.setSeparateProcesses(mSeparateProcesses); 12068 pp.setDisplayMetrics(mMetrics); 12069 12070 final PackageParser.Package pkg; 12071 try { 12072 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12073 } catch (PackageParserException e) { 12074 res.setError("Failed parse during installPackageLI", e); 12075 return; 12076 } 12077 12078 // Mark that we have an install time CPU ABI override. 12079 pkg.cpuAbiOverride = args.abiOverride; 12080 12081 String pkgName = res.name = pkg.packageName; 12082 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12083 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12084 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12085 return; 12086 } 12087 } 12088 12089 try { 12090 pp.collectCertificates(pkg, parseFlags); 12091 pp.collectManifestDigest(pkg); 12092 } catch (PackageParserException e) { 12093 res.setError("Failed collect during installPackageLI", e); 12094 return; 12095 } 12096 12097 /* If the installer passed in a manifest digest, compare it now. */ 12098 if (args.manifestDigest != null) { 12099 if (DEBUG_INSTALL) { 12100 final String parsedManifest = pkg.manifestDigest == null ? "null" 12101 : pkg.manifestDigest.toString(); 12102 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12103 + parsedManifest); 12104 } 12105 12106 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12107 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12108 return; 12109 } 12110 } else if (DEBUG_INSTALL) { 12111 final String parsedManifest = pkg.manifestDigest == null 12112 ? "null" : pkg.manifestDigest.toString(); 12113 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12114 } 12115 12116 // Get rid of all references to package scan path via parser. 12117 pp = null; 12118 String oldCodePath = null; 12119 boolean systemApp = false; 12120 synchronized (mPackages) { 12121 // Check if installing already existing package 12122 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12123 String oldName = mSettings.mRenamedPackages.get(pkgName); 12124 if (pkg.mOriginalPackages != null 12125 && pkg.mOriginalPackages.contains(oldName) 12126 && mPackages.containsKey(oldName)) { 12127 // This package is derived from an original package, 12128 // and this device has been updating from that original 12129 // name. We must continue using the original name, so 12130 // rename the new package here. 12131 pkg.setPackageName(oldName); 12132 pkgName = pkg.packageName; 12133 replace = true; 12134 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12135 + oldName + " pkgName=" + pkgName); 12136 } else if (mPackages.containsKey(pkgName)) { 12137 // This package, under its official name, already exists 12138 // on the device; we should replace it. 12139 replace = true; 12140 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12141 } 12142 12143 // Prevent apps opting out from runtime permissions 12144 if (replace) { 12145 PackageParser.Package oldPackage = mPackages.get(pkgName); 12146 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12147 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12148 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12149 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12150 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12151 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12152 + " doesn't support runtime permissions but the old" 12153 + " target SDK " + oldTargetSdk + " does."); 12154 return; 12155 } 12156 } 12157 } 12158 12159 PackageSetting ps = mSettings.mPackages.get(pkgName); 12160 if (ps != null) { 12161 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12162 12163 // Quick sanity check that we're signed correctly if updating; 12164 // we'll check this again later when scanning, but we want to 12165 // bail early here before tripping over redefined permissions. 12166 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12167 if (!checkUpgradeKeySetLP(ps, pkg)) { 12168 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12169 + pkg.packageName + " upgrade keys do not match the " 12170 + "previously installed version"); 12171 return; 12172 } 12173 } else { 12174 try { 12175 verifySignaturesLP(ps, pkg); 12176 } catch (PackageManagerException e) { 12177 res.setError(e.error, e.getMessage()); 12178 return; 12179 } 12180 } 12181 12182 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12183 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12184 systemApp = (ps.pkg.applicationInfo.flags & 12185 ApplicationInfo.FLAG_SYSTEM) != 0; 12186 } 12187 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12188 } 12189 12190 // Check whether the newly-scanned package wants to define an already-defined perm 12191 int N = pkg.permissions.size(); 12192 for (int i = N-1; i >= 0; i--) { 12193 PackageParser.Permission perm = pkg.permissions.get(i); 12194 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12195 if (bp != null) { 12196 // If the defining package is signed with our cert, it's okay. This 12197 // also includes the "updating the same package" case, of course. 12198 // "updating same package" could also involve key-rotation. 12199 final boolean sigsOk; 12200 if (bp.sourcePackage.equals(pkg.packageName) 12201 && (bp.packageSetting instanceof PackageSetting) 12202 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12203 scanFlags))) { 12204 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12205 } else { 12206 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12207 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12208 } 12209 if (!sigsOk) { 12210 // If the owning package is the system itself, we log but allow 12211 // install to proceed; we fail the install on all other permission 12212 // redefinitions. 12213 if (!bp.sourcePackage.equals("android")) { 12214 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12215 + pkg.packageName + " attempting to redeclare permission " 12216 + perm.info.name + " already owned by " + bp.sourcePackage); 12217 res.origPermission = perm.info.name; 12218 res.origPackage = bp.sourcePackage; 12219 return; 12220 } else { 12221 Slog.w(TAG, "Package " + pkg.packageName 12222 + " attempting to redeclare system permission " 12223 + perm.info.name + "; ignoring new declaration"); 12224 pkg.permissions.remove(i); 12225 } 12226 } 12227 } 12228 } 12229 12230 } 12231 12232 if (systemApp && onExternal) { 12233 // Disable updates to system apps on sdcard 12234 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12235 "Cannot install updates to system apps on sdcard"); 12236 return; 12237 } 12238 12239 if (args.move != null) { 12240 // We did an in-place move, so dex is ready to roll 12241 scanFlags |= SCAN_NO_DEX; 12242 scanFlags |= SCAN_MOVE; 12243 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12244 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12245 scanFlags |= SCAN_NO_DEX; 12246 12247 try { 12248 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12249 true /* extract libs */); 12250 } catch (PackageManagerException pme) { 12251 Slog.e(TAG, "Error deriving application ABI", pme); 12252 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12253 return; 12254 } 12255 12256 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12257 int result = mPackageDexOptimizer 12258 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12259 false /* defer */, false /* inclDependencies */); 12260 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12261 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12262 return; 12263 } 12264 } 12265 12266 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12267 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12268 return; 12269 } 12270 12271 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12272 12273 if (replace) { 12274 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12275 installerPackageName, volumeUuid, res); 12276 } else { 12277 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12278 args.user, installerPackageName, volumeUuid, res); 12279 } 12280 synchronized (mPackages) { 12281 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12282 if (ps != null) { 12283 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12284 } 12285 } 12286 } 12287 12288 private void startIntentFilterVerifications(int userId, boolean replacing, 12289 PackageParser.Package pkg) { 12290 if (mIntentFilterVerifierComponent == null) { 12291 Slog.w(TAG, "No IntentFilter verification will not be done as " 12292 + "there is no IntentFilterVerifier available!"); 12293 return; 12294 } 12295 12296 final int verifierUid = getPackageUid( 12297 mIntentFilterVerifierComponent.getPackageName(), 12298 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12299 12300 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12301 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12302 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12303 mHandler.sendMessage(msg); 12304 } 12305 12306 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12307 PackageParser.Package pkg) { 12308 int size = pkg.activities.size(); 12309 if (size == 0) { 12310 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12311 "No activity, so no need to verify any IntentFilter!"); 12312 return; 12313 } 12314 12315 final boolean hasDomainURLs = hasDomainURLs(pkg); 12316 if (!hasDomainURLs) { 12317 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12318 "No domain URLs, so no need to verify any IntentFilter!"); 12319 return; 12320 } 12321 12322 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12323 + " if any IntentFilter from the " + size 12324 + " Activities needs verification ..."); 12325 12326 int count = 0; 12327 final String packageName = pkg.packageName; 12328 12329 synchronized (mPackages) { 12330 // If this is a new install and we see that we've already run verification for this 12331 // package, we have nothing to do: it means the state was restored from backup. 12332 if (!replacing) { 12333 IntentFilterVerificationInfo ivi = 12334 mSettings.getIntentFilterVerificationLPr(packageName); 12335 if (ivi != null) { 12336 if (DEBUG_DOMAIN_VERIFICATION) { 12337 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12338 + ivi.getStatusString()); 12339 } 12340 return; 12341 } 12342 } 12343 12344 // If any filters need to be verified, then all need to be. 12345 boolean needToVerify = false; 12346 for (PackageParser.Activity a : pkg.activities) { 12347 for (ActivityIntentInfo filter : a.intents) { 12348 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12349 if (DEBUG_DOMAIN_VERIFICATION) { 12350 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12351 } 12352 needToVerify = true; 12353 break; 12354 } 12355 } 12356 } 12357 12358 if (needToVerify) { 12359 final int verificationId = mIntentFilterVerificationToken++; 12360 for (PackageParser.Activity a : pkg.activities) { 12361 for (ActivityIntentInfo filter : a.intents) { 12362 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12363 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12364 "Verification needed for IntentFilter:" + filter.toString()); 12365 mIntentFilterVerifier.addOneIntentFilterVerification( 12366 verifierUid, userId, verificationId, filter, packageName); 12367 count++; 12368 } 12369 } 12370 } 12371 } 12372 } 12373 12374 if (count > 0) { 12375 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12376 + " IntentFilter verification" + (count > 1 ? "s" : "") 12377 + " for userId:" + userId); 12378 mIntentFilterVerifier.startVerifications(userId); 12379 } else { 12380 if (DEBUG_DOMAIN_VERIFICATION) { 12381 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12382 } 12383 } 12384 } 12385 12386 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12387 final ComponentName cn = filter.activity.getComponentName(); 12388 final String packageName = cn.getPackageName(); 12389 12390 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12391 packageName); 12392 if (ivi == null) { 12393 return true; 12394 } 12395 int status = ivi.getStatus(); 12396 switch (status) { 12397 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12398 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12399 return true; 12400 12401 default: 12402 // Nothing to do 12403 return false; 12404 } 12405 } 12406 12407 private static boolean isMultiArch(PackageSetting ps) { 12408 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12409 } 12410 12411 private static boolean isMultiArch(ApplicationInfo info) { 12412 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12413 } 12414 12415 private static boolean isExternal(PackageParser.Package pkg) { 12416 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12417 } 12418 12419 private static boolean isExternal(PackageSetting ps) { 12420 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12421 } 12422 12423 private static boolean isExternal(ApplicationInfo info) { 12424 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12425 } 12426 12427 private static boolean isSystemApp(PackageParser.Package pkg) { 12428 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12429 } 12430 12431 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12432 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12433 } 12434 12435 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12436 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12437 } 12438 12439 private static boolean isSystemApp(PackageSetting ps) { 12440 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12441 } 12442 12443 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12444 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12445 } 12446 12447 private int packageFlagsToInstallFlags(PackageSetting ps) { 12448 int installFlags = 0; 12449 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12450 // This existing package was an external ASEC install when we have 12451 // the external flag without a UUID 12452 installFlags |= PackageManager.INSTALL_EXTERNAL; 12453 } 12454 if (ps.isForwardLocked()) { 12455 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12456 } 12457 return installFlags; 12458 } 12459 12460 private void deleteTempPackageFiles() { 12461 final FilenameFilter filter = new FilenameFilter() { 12462 public boolean accept(File dir, String name) { 12463 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12464 } 12465 }; 12466 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12467 file.delete(); 12468 } 12469 } 12470 12471 @Override 12472 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12473 int flags) { 12474 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12475 flags); 12476 } 12477 12478 @Override 12479 public void deletePackage(final String packageName, 12480 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12481 mContext.enforceCallingOrSelfPermission( 12482 android.Manifest.permission.DELETE_PACKAGES, null); 12483 Preconditions.checkNotNull(packageName); 12484 Preconditions.checkNotNull(observer); 12485 final int uid = Binder.getCallingUid(); 12486 if (UserHandle.getUserId(uid) != userId) { 12487 mContext.enforceCallingPermission( 12488 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12489 "deletePackage for user " + userId); 12490 } 12491 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12492 try { 12493 observer.onPackageDeleted(packageName, 12494 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12495 } catch (RemoteException re) { 12496 } 12497 return; 12498 } 12499 12500 boolean uninstallBlocked = false; 12501 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12502 int[] users = sUserManager.getUserIds(); 12503 for (int i = 0; i < users.length; ++i) { 12504 if (getBlockUninstallForUser(packageName, users[i])) { 12505 uninstallBlocked = true; 12506 break; 12507 } 12508 } 12509 } else { 12510 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12511 } 12512 if (uninstallBlocked) { 12513 try { 12514 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12515 null); 12516 } catch (RemoteException re) { 12517 } 12518 return; 12519 } 12520 12521 if (DEBUG_REMOVE) { 12522 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12523 } 12524 // Queue up an async operation since the package deletion may take a little while. 12525 mHandler.post(new Runnable() { 12526 public void run() { 12527 mHandler.removeCallbacks(this); 12528 final int returnCode = deletePackageX(packageName, userId, flags); 12529 if (observer != null) { 12530 try { 12531 observer.onPackageDeleted(packageName, returnCode, null); 12532 } catch (RemoteException e) { 12533 Log.i(TAG, "Observer no longer exists."); 12534 } //end catch 12535 } //end if 12536 } //end run 12537 }); 12538 } 12539 12540 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12541 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12542 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12543 try { 12544 if (dpm != null) { 12545 if (dpm.isDeviceOwner(packageName)) { 12546 return true; 12547 } 12548 int[] users; 12549 if (userId == UserHandle.USER_ALL) { 12550 users = sUserManager.getUserIds(); 12551 } else { 12552 users = new int[]{userId}; 12553 } 12554 for (int i = 0; i < users.length; ++i) { 12555 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12556 return true; 12557 } 12558 } 12559 } 12560 } catch (RemoteException e) { 12561 } 12562 return false; 12563 } 12564 12565 /** 12566 * This method is an internal method that could be get invoked either 12567 * to delete an installed package or to clean up a failed installation. 12568 * After deleting an installed package, a broadcast is sent to notify any 12569 * listeners that the package has been installed. For cleaning up a failed 12570 * installation, the broadcast is not necessary since the package's 12571 * installation wouldn't have sent the initial broadcast either 12572 * The key steps in deleting a package are 12573 * deleting the package information in internal structures like mPackages, 12574 * deleting the packages base directories through installd 12575 * updating mSettings to reflect current status 12576 * persisting settings for later use 12577 * sending a broadcast if necessary 12578 */ 12579 private int deletePackageX(String packageName, int userId, int flags) { 12580 final PackageRemovedInfo info = new PackageRemovedInfo(); 12581 final boolean res; 12582 12583 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12584 ? UserHandle.ALL : new UserHandle(userId); 12585 12586 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12587 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12588 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12589 } 12590 12591 boolean removedForAllUsers = false; 12592 boolean systemUpdate = false; 12593 12594 // for the uninstall-updates case and restricted profiles, remember the per- 12595 // userhandle installed state 12596 int[] allUsers; 12597 boolean[] perUserInstalled; 12598 synchronized (mPackages) { 12599 PackageSetting ps = mSettings.mPackages.get(packageName); 12600 allUsers = sUserManager.getUserIds(); 12601 perUserInstalled = new boolean[allUsers.length]; 12602 for (int i = 0; i < allUsers.length; i++) { 12603 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12604 } 12605 } 12606 12607 synchronized (mInstallLock) { 12608 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12609 res = deletePackageLI(packageName, removeForUser, 12610 true, allUsers, perUserInstalled, 12611 flags | REMOVE_CHATTY, info, true); 12612 systemUpdate = info.isRemovedPackageSystemUpdate; 12613 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12614 removedForAllUsers = true; 12615 } 12616 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12617 + " removedForAllUsers=" + removedForAllUsers); 12618 } 12619 12620 if (res) { 12621 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12622 12623 // If the removed package was a system update, the old system package 12624 // was re-enabled; we need to broadcast this information 12625 if (systemUpdate) { 12626 Bundle extras = new Bundle(1); 12627 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12628 ? info.removedAppId : info.uid); 12629 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12630 12631 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12632 extras, null, null, null); 12633 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12634 extras, null, null, null); 12635 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12636 null, packageName, null, null); 12637 } 12638 } 12639 // Force a gc here. 12640 Runtime.getRuntime().gc(); 12641 // Delete the resources here after sending the broadcast to let 12642 // other processes clean up before deleting resources. 12643 if (info.args != null) { 12644 synchronized (mInstallLock) { 12645 info.args.doPostDeleteLI(true); 12646 } 12647 } 12648 12649 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12650 } 12651 12652 class PackageRemovedInfo { 12653 String removedPackage; 12654 int uid = -1; 12655 int removedAppId = -1; 12656 int[] removedUsers = null; 12657 boolean isRemovedPackageSystemUpdate = false; 12658 // Clean up resources deleted packages. 12659 InstallArgs args = null; 12660 12661 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12662 Bundle extras = new Bundle(1); 12663 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12664 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12665 if (replacing) { 12666 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12667 } 12668 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12669 if (removedPackage != null) { 12670 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12671 extras, null, null, removedUsers); 12672 if (fullRemove && !replacing) { 12673 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12674 extras, null, null, removedUsers); 12675 } 12676 } 12677 if (removedAppId >= 0) { 12678 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12679 removedUsers); 12680 } 12681 } 12682 } 12683 12684 /* 12685 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12686 * flag is not set, the data directory is removed as well. 12687 * make sure this flag is set for partially installed apps. If not its meaningless to 12688 * delete a partially installed application. 12689 */ 12690 private void removePackageDataLI(PackageSetting ps, 12691 int[] allUserHandles, boolean[] perUserInstalled, 12692 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12693 String packageName = ps.name; 12694 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12695 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12696 // Retrieve object to delete permissions for shared user later on 12697 final PackageSetting deletedPs; 12698 // reader 12699 synchronized (mPackages) { 12700 deletedPs = mSettings.mPackages.get(packageName); 12701 if (outInfo != null) { 12702 outInfo.removedPackage = packageName; 12703 outInfo.removedUsers = deletedPs != null 12704 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12705 : null; 12706 } 12707 } 12708 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12709 removeDataDirsLI(ps.volumeUuid, packageName); 12710 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12711 } 12712 // writer 12713 synchronized (mPackages) { 12714 if (deletedPs != null) { 12715 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12716 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12717 clearDefaultBrowserIfNeeded(packageName); 12718 if (outInfo != null) { 12719 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12720 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12721 } 12722 updatePermissionsLPw(deletedPs.name, null, 0); 12723 if (deletedPs.sharedUser != null) { 12724 // Remove permissions associated with package. Since runtime 12725 // permissions are per user we have to kill the removed package 12726 // or packages running under the shared user of the removed 12727 // package if revoking the permissions requested only by the removed 12728 // package is successful and this causes a change in gids. 12729 for (int userId : UserManagerService.getInstance().getUserIds()) { 12730 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12731 userId); 12732 if (userIdToKill == UserHandle.USER_ALL 12733 || userIdToKill >= UserHandle.USER_OWNER) { 12734 // If gids changed for this user, kill all affected packages. 12735 mHandler.post(new Runnable() { 12736 @Override 12737 public void run() { 12738 // This has to happen with no lock held. 12739 killSettingPackagesForUser(deletedPs, userIdToKill, 12740 KILL_APP_REASON_GIDS_CHANGED); 12741 } 12742 }); 12743 break; 12744 } 12745 } 12746 } 12747 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12748 } 12749 // make sure to preserve per-user disabled state if this removal was just 12750 // a downgrade of a system app to the factory package 12751 if (allUserHandles != null && perUserInstalled != null) { 12752 if (DEBUG_REMOVE) { 12753 Slog.d(TAG, "Propagating install state across downgrade"); 12754 } 12755 for (int i = 0; i < allUserHandles.length; i++) { 12756 if (DEBUG_REMOVE) { 12757 Slog.d(TAG, " user " + allUserHandles[i] 12758 + " => " + perUserInstalled[i]); 12759 } 12760 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12761 } 12762 } 12763 } 12764 // can downgrade to reader 12765 if (writeSettings) { 12766 // Save settings now 12767 mSettings.writeLPr(); 12768 } 12769 } 12770 if (outInfo != null) { 12771 // A user ID was deleted here. Go through all users and remove it 12772 // from KeyStore. 12773 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12774 } 12775 } 12776 12777 static boolean locationIsPrivileged(File path) { 12778 try { 12779 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12780 .getCanonicalPath(); 12781 return path.getCanonicalPath().startsWith(privilegedAppDir); 12782 } catch (IOException e) { 12783 Slog.e(TAG, "Unable to access code path " + path); 12784 } 12785 return false; 12786 } 12787 12788 /* 12789 * Tries to delete system package. 12790 */ 12791 private boolean deleteSystemPackageLI(PackageSetting newPs, 12792 int[] allUserHandles, boolean[] perUserInstalled, 12793 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12794 final boolean applyUserRestrictions 12795 = (allUserHandles != null) && (perUserInstalled != null); 12796 PackageSetting disabledPs = null; 12797 // Confirm if the system package has been updated 12798 // An updated system app can be deleted. This will also have to restore 12799 // the system pkg from system partition 12800 // reader 12801 synchronized (mPackages) { 12802 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12803 } 12804 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12805 + " disabledPs=" + disabledPs); 12806 if (disabledPs == null) { 12807 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12808 return false; 12809 } else if (DEBUG_REMOVE) { 12810 Slog.d(TAG, "Deleting system pkg from data partition"); 12811 } 12812 if (DEBUG_REMOVE) { 12813 if (applyUserRestrictions) { 12814 Slog.d(TAG, "Remembering install states:"); 12815 for (int i = 0; i < allUserHandles.length; i++) { 12816 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12817 } 12818 } 12819 } 12820 // Delete the updated package 12821 outInfo.isRemovedPackageSystemUpdate = true; 12822 if (disabledPs.versionCode < newPs.versionCode) { 12823 // Delete data for downgrades 12824 flags &= ~PackageManager.DELETE_KEEP_DATA; 12825 } else { 12826 // Preserve data by setting flag 12827 flags |= PackageManager.DELETE_KEEP_DATA; 12828 } 12829 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12830 allUserHandles, perUserInstalled, outInfo, writeSettings); 12831 if (!ret) { 12832 return false; 12833 } 12834 // writer 12835 synchronized (mPackages) { 12836 // Reinstate the old system package 12837 mSettings.enableSystemPackageLPw(newPs.name); 12838 // Remove any native libraries from the upgraded package. 12839 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12840 } 12841 // Install the system package 12842 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12843 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12844 if (locationIsPrivileged(disabledPs.codePath)) { 12845 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12846 } 12847 12848 final PackageParser.Package newPkg; 12849 try { 12850 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12851 } catch (PackageManagerException e) { 12852 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12853 return false; 12854 } 12855 12856 // writer 12857 synchronized (mPackages) { 12858 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12859 12860 // Propagate the permissions state as we do want to drop on the floor 12861 // runtime permissions. The update permissions method below will take 12862 // care of removing obsolete permissions and grant install permissions. 12863 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12864 updatePermissionsLPw(newPkg.packageName, newPkg, 12865 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12866 12867 if (applyUserRestrictions) { 12868 if (DEBUG_REMOVE) { 12869 Slog.d(TAG, "Propagating install state across reinstall"); 12870 } 12871 for (int i = 0; i < allUserHandles.length; i++) { 12872 if (DEBUG_REMOVE) { 12873 Slog.d(TAG, " user " + allUserHandles[i] 12874 + " => " + perUserInstalled[i]); 12875 } 12876 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12877 } 12878 // Regardless of writeSettings we need to ensure that this restriction 12879 // state propagation is persisted 12880 mSettings.writeAllUsersPackageRestrictionsLPr(); 12881 } 12882 // can downgrade to reader here 12883 if (writeSettings) { 12884 mSettings.writeLPr(); 12885 } 12886 } 12887 return true; 12888 } 12889 12890 private boolean deleteInstalledPackageLI(PackageSetting ps, 12891 boolean deleteCodeAndResources, int flags, 12892 int[] allUserHandles, boolean[] perUserInstalled, 12893 PackageRemovedInfo outInfo, boolean writeSettings) { 12894 if (outInfo != null) { 12895 outInfo.uid = ps.appId; 12896 } 12897 12898 // Delete package data from internal structures and also remove data if flag is set 12899 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12900 12901 // Delete application code and resources 12902 if (deleteCodeAndResources && (outInfo != null)) { 12903 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12904 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12905 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12906 } 12907 return true; 12908 } 12909 12910 @Override 12911 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12912 int userId) { 12913 mContext.enforceCallingOrSelfPermission( 12914 android.Manifest.permission.DELETE_PACKAGES, null); 12915 synchronized (mPackages) { 12916 PackageSetting ps = mSettings.mPackages.get(packageName); 12917 if (ps == null) { 12918 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12919 return false; 12920 } 12921 if (!ps.getInstalled(userId)) { 12922 // Can't block uninstall for an app that is not installed or enabled. 12923 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12924 return false; 12925 } 12926 ps.setBlockUninstall(blockUninstall, userId); 12927 mSettings.writePackageRestrictionsLPr(userId); 12928 } 12929 return true; 12930 } 12931 12932 @Override 12933 public boolean getBlockUninstallForUser(String packageName, int userId) { 12934 synchronized (mPackages) { 12935 PackageSetting ps = mSettings.mPackages.get(packageName); 12936 if (ps == null) { 12937 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12938 return false; 12939 } 12940 return ps.getBlockUninstall(userId); 12941 } 12942 } 12943 12944 /* 12945 * This method handles package deletion in general 12946 */ 12947 private boolean deletePackageLI(String packageName, UserHandle user, 12948 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12949 int flags, PackageRemovedInfo outInfo, 12950 boolean writeSettings) { 12951 if (packageName == null) { 12952 Slog.w(TAG, "Attempt to delete null packageName."); 12953 return false; 12954 } 12955 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12956 PackageSetting ps; 12957 boolean dataOnly = false; 12958 int removeUser = -1; 12959 int appId = -1; 12960 synchronized (mPackages) { 12961 ps = mSettings.mPackages.get(packageName); 12962 if (ps == null) { 12963 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12964 return false; 12965 } 12966 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12967 && user.getIdentifier() != UserHandle.USER_ALL) { 12968 // The caller is asking that the package only be deleted for a single 12969 // user. To do this, we just mark its uninstalled state and delete 12970 // its data. If this is a system app, we only allow this to happen if 12971 // they have set the special DELETE_SYSTEM_APP which requests different 12972 // semantics than normal for uninstalling system apps. 12973 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12974 ps.setUserState(user.getIdentifier(), 12975 COMPONENT_ENABLED_STATE_DEFAULT, 12976 false, //installed 12977 true, //stopped 12978 true, //notLaunched 12979 false, //hidden 12980 null, null, null, 12981 false, // blockUninstall 12982 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 12983 if (!isSystemApp(ps)) { 12984 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12985 // Other user still have this package installed, so all 12986 // we need to do is clear this user's data and save that 12987 // it is uninstalled. 12988 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12989 removeUser = user.getIdentifier(); 12990 appId = ps.appId; 12991 scheduleWritePackageRestrictionsLocked(removeUser); 12992 } else { 12993 // We need to set it back to 'installed' so the uninstall 12994 // broadcasts will be sent correctly. 12995 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12996 ps.setInstalled(true, user.getIdentifier()); 12997 } 12998 } else { 12999 // This is a system app, so we assume that the 13000 // other users still have this package installed, so all 13001 // we need to do is clear this user's data and save that 13002 // it is uninstalled. 13003 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13004 removeUser = user.getIdentifier(); 13005 appId = ps.appId; 13006 scheduleWritePackageRestrictionsLocked(removeUser); 13007 } 13008 } 13009 } 13010 13011 if (removeUser >= 0) { 13012 // From above, we determined that we are deleting this only 13013 // for a single user. Continue the work here. 13014 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13015 if (outInfo != null) { 13016 outInfo.removedPackage = packageName; 13017 outInfo.removedAppId = appId; 13018 outInfo.removedUsers = new int[] {removeUser}; 13019 } 13020 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13021 removeKeystoreDataIfNeeded(removeUser, appId); 13022 schedulePackageCleaning(packageName, removeUser, false); 13023 synchronized (mPackages) { 13024 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13025 scheduleWritePackageRestrictionsLocked(removeUser); 13026 } 13027 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13028 } 13029 return true; 13030 } 13031 13032 if (dataOnly) { 13033 // Delete application data first 13034 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13035 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13036 return true; 13037 } 13038 13039 boolean ret = false; 13040 if (isSystemApp(ps)) { 13041 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13042 // When an updated system application is deleted we delete the existing resources as well and 13043 // fall back to existing code in system partition 13044 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13045 flags, outInfo, writeSettings); 13046 } else { 13047 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13048 // Kill application pre-emptively especially for apps on sd. 13049 killApplication(packageName, ps.appId, "uninstall pkg"); 13050 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13051 allUserHandles, perUserInstalled, 13052 outInfo, writeSettings); 13053 } 13054 13055 return ret; 13056 } 13057 13058 private final class ClearStorageConnection implements ServiceConnection { 13059 IMediaContainerService mContainerService; 13060 13061 @Override 13062 public void onServiceConnected(ComponentName name, IBinder service) { 13063 synchronized (this) { 13064 mContainerService = IMediaContainerService.Stub.asInterface(service); 13065 notifyAll(); 13066 } 13067 } 13068 13069 @Override 13070 public void onServiceDisconnected(ComponentName name) { 13071 } 13072 } 13073 13074 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13075 final boolean mounted; 13076 if (Environment.isExternalStorageEmulated()) { 13077 mounted = true; 13078 } else { 13079 final String status = Environment.getExternalStorageState(); 13080 13081 mounted = status.equals(Environment.MEDIA_MOUNTED) 13082 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13083 } 13084 13085 if (!mounted) { 13086 return; 13087 } 13088 13089 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13090 int[] users; 13091 if (userId == UserHandle.USER_ALL) { 13092 users = sUserManager.getUserIds(); 13093 } else { 13094 users = new int[] { userId }; 13095 } 13096 final ClearStorageConnection conn = new ClearStorageConnection(); 13097 if (mContext.bindServiceAsUser( 13098 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13099 try { 13100 for (int curUser : users) { 13101 long timeout = SystemClock.uptimeMillis() + 5000; 13102 synchronized (conn) { 13103 long now = SystemClock.uptimeMillis(); 13104 while (conn.mContainerService == null && now < timeout) { 13105 try { 13106 conn.wait(timeout - now); 13107 } catch (InterruptedException e) { 13108 } 13109 } 13110 } 13111 if (conn.mContainerService == null) { 13112 return; 13113 } 13114 13115 final UserEnvironment userEnv = new UserEnvironment(curUser); 13116 clearDirectory(conn.mContainerService, 13117 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13118 if (allData) { 13119 clearDirectory(conn.mContainerService, 13120 userEnv.buildExternalStorageAppDataDirs(packageName)); 13121 clearDirectory(conn.mContainerService, 13122 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13123 } 13124 } 13125 } finally { 13126 mContext.unbindService(conn); 13127 } 13128 } 13129 } 13130 13131 @Override 13132 public void clearApplicationUserData(final String packageName, 13133 final IPackageDataObserver observer, final int userId) { 13134 mContext.enforceCallingOrSelfPermission( 13135 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13136 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13137 // Queue up an async operation since the package deletion may take a little while. 13138 mHandler.post(new Runnable() { 13139 public void run() { 13140 mHandler.removeCallbacks(this); 13141 final boolean succeeded; 13142 synchronized (mInstallLock) { 13143 succeeded = clearApplicationUserDataLI(packageName, userId); 13144 } 13145 clearExternalStorageDataSync(packageName, userId, true); 13146 if (succeeded) { 13147 // invoke DeviceStorageMonitor's update method to clear any notifications 13148 DeviceStorageMonitorInternal 13149 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13150 if (dsm != null) { 13151 dsm.checkMemory(); 13152 } 13153 } 13154 if(observer != null) { 13155 try { 13156 observer.onRemoveCompleted(packageName, succeeded); 13157 } catch (RemoteException e) { 13158 Log.i(TAG, "Observer no longer exists."); 13159 } 13160 } //end if observer 13161 } //end run 13162 }); 13163 } 13164 13165 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13166 if (packageName == null) { 13167 Slog.w(TAG, "Attempt to delete null packageName."); 13168 return false; 13169 } 13170 13171 // Try finding details about the requested package 13172 PackageParser.Package pkg; 13173 synchronized (mPackages) { 13174 pkg = mPackages.get(packageName); 13175 if (pkg == null) { 13176 final PackageSetting ps = mSettings.mPackages.get(packageName); 13177 if (ps != null) { 13178 pkg = ps.pkg; 13179 } 13180 } 13181 13182 if (pkg == null) { 13183 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13184 return false; 13185 } 13186 13187 PackageSetting ps = (PackageSetting) pkg.mExtras; 13188 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13189 } 13190 13191 // Always delete data directories for package, even if we found no other 13192 // record of app. This helps users recover from UID mismatches without 13193 // resorting to a full data wipe. 13194 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13195 if (retCode < 0) { 13196 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13197 return false; 13198 } 13199 13200 final int appId = pkg.applicationInfo.uid; 13201 removeKeystoreDataIfNeeded(userId, appId); 13202 13203 // Create a native library symlink only if we have native libraries 13204 // and if the native libraries are 32 bit libraries. We do not provide 13205 // this symlink for 64 bit libraries. 13206 if (pkg.applicationInfo.primaryCpuAbi != null && 13207 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13208 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13209 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13210 nativeLibPath, userId) < 0) { 13211 Slog.w(TAG, "Failed linking native library dir"); 13212 return false; 13213 } 13214 } 13215 13216 return true; 13217 } 13218 13219 /** 13220 * Reverts user permission state changes (permissions and flags). 13221 * 13222 * @param ps The package for which to reset. 13223 * @param userId The device user for which to do a reset. 13224 */ 13225 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13226 final PackageSetting ps, final int userId) { 13227 if (ps.pkg == null) { 13228 return; 13229 } 13230 13231 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13232 | FLAG_PERMISSION_USER_FIXED 13233 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13234 13235 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13236 | FLAG_PERMISSION_POLICY_FIXED; 13237 13238 boolean writeInstallPermissions = false; 13239 boolean writeRuntimePermissions = false; 13240 13241 final int permissionCount = ps.pkg.requestedPermissions.size(); 13242 for (int i = 0; i < permissionCount; i++) { 13243 String permission = ps.pkg.requestedPermissions.get(i); 13244 13245 BasePermission bp = mSettings.mPermissions.get(permission); 13246 if (bp == null) { 13247 continue; 13248 } 13249 13250 // If shared user we just reset the state to which only this app contributed. 13251 if (ps.sharedUser != null) { 13252 boolean used = false; 13253 final int packageCount = ps.sharedUser.packages.size(); 13254 for (int j = 0; j < packageCount; j++) { 13255 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13256 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13257 && pkg.pkg.requestedPermissions.contains(permission)) { 13258 used = true; 13259 break; 13260 } 13261 } 13262 if (used) { 13263 continue; 13264 } 13265 } 13266 13267 PermissionsState permissionsState = ps.getPermissionsState(); 13268 13269 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13270 13271 // Always clear the user settable flags. 13272 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13273 bp.name) != null; 13274 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13275 if (hasInstallState) { 13276 writeInstallPermissions = true; 13277 } else { 13278 writeRuntimePermissions = true; 13279 } 13280 } 13281 13282 // Below is only runtime permission handling. 13283 if (!bp.isRuntime()) { 13284 continue; 13285 } 13286 13287 // Never clobber system or policy. 13288 if ((oldFlags & policyOrSystemFlags) != 0) { 13289 continue; 13290 } 13291 13292 // If this permission was granted by default, make sure it is. 13293 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13294 if (permissionsState.grantRuntimePermission(bp, userId) 13295 != PERMISSION_OPERATION_FAILURE) { 13296 writeRuntimePermissions = true; 13297 } 13298 } else { 13299 // Otherwise, reset the permission. 13300 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13301 switch (revokeResult) { 13302 case PERMISSION_OPERATION_SUCCESS: { 13303 writeRuntimePermissions = true; 13304 } break; 13305 13306 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13307 writeRuntimePermissions = true; 13308 // If gids changed for this user, kill all affected packages. 13309 mHandler.post(new Runnable() { 13310 @Override 13311 public void run() { 13312 // This has to happen with no lock held. 13313 killSettingPackagesForUser(ps, userId, 13314 KILL_APP_REASON_GIDS_CHANGED); 13315 } 13316 }); 13317 } break; 13318 } 13319 } 13320 } 13321 13322 // Synchronously write as we are taking permissions away. 13323 if (writeRuntimePermissions) { 13324 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13325 } 13326 13327 // Synchronously write as we are taking permissions away. 13328 if (writeInstallPermissions) { 13329 mSettings.writeLPr(); 13330 } 13331 } 13332 13333 /** 13334 * Remove entries from the keystore daemon. Will only remove it if the 13335 * {@code appId} is valid. 13336 */ 13337 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13338 if (appId < 0) { 13339 return; 13340 } 13341 13342 final KeyStore keyStore = KeyStore.getInstance(); 13343 if (keyStore != null) { 13344 if (userId == UserHandle.USER_ALL) { 13345 for (final int individual : sUserManager.getUserIds()) { 13346 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13347 } 13348 } else { 13349 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13350 } 13351 } else { 13352 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13353 } 13354 } 13355 13356 @Override 13357 public void deleteApplicationCacheFiles(final String packageName, 13358 final IPackageDataObserver observer) { 13359 mContext.enforceCallingOrSelfPermission( 13360 android.Manifest.permission.DELETE_CACHE_FILES, null); 13361 // Queue up an async operation since the package deletion may take a little while. 13362 final int userId = UserHandle.getCallingUserId(); 13363 mHandler.post(new Runnable() { 13364 public void run() { 13365 mHandler.removeCallbacks(this); 13366 final boolean succeded; 13367 synchronized (mInstallLock) { 13368 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13369 } 13370 clearExternalStorageDataSync(packageName, userId, false); 13371 if (observer != null) { 13372 try { 13373 observer.onRemoveCompleted(packageName, succeded); 13374 } catch (RemoteException e) { 13375 Log.i(TAG, "Observer no longer exists."); 13376 } 13377 } //end if observer 13378 } //end run 13379 }); 13380 } 13381 13382 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13383 if (packageName == null) { 13384 Slog.w(TAG, "Attempt to delete null packageName."); 13385 return false; 13386 } 13387 PackageParser.Package p; 13388 synchronized (mPackages) { 13389 p = mPackages.get(packageName); 13390 } 13391 if (p == null) { 13392 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13393 return false; 13394 } 13395 final ApplicationInfo applicationInfo = p.applicationInfo; 13396 if (applicationInfo == null) { 13397 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13398 return false; 13399 } 13400 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13401 if (retCode < 0) { 13402 Slog.w(TAG, "Couldn't remove cache files for package: " 13403 + packageName + " u" + userId); 13404 return false; 13405 } 13406 return true; 13407 } 13408 13409 @Override 13410 public void getPackageSizeInfo(final String packageName, int userHandle, 13411 final IPackageStatsObserver observer) { 13412 mContext.enforceCallingOrSelfPermission( 13413 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13414 if (packageName == null) { 13415 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13416 } 13417 13418 PackageStats stats = new PackageStats(packageName, userHandle); 13419 13420 /* 13421 * Queue up an async operation since the package measurement may take a 13422 * little while. 13423 */ 13424 Message msg = mHandler.obtainMessage(INIT_COPY); 13425 msg.obj = new MeasureParams(stats, observer); 13426 mHandler.sendMessage(msg); 13427 } 13428 13429 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13430 PackageStats pStats) { 13431 if (packageName == null) { 13432 Slog.w(TAG, "Attempt to get size of null packageName."); 13433 return false; 13434 } 13435 PackageParser.Package p; 13436 boolean dataOnly = false; 13437 String libDirRoot = null; 13438 String asecPath = null; 13439 PackageSetting ps = null; 13440 synchronized (mPackages) { 13441 p = mPackages.get(packageName); 13442 ps = mSettings.mPackages.get(packageName); 13443 if(p == null) { 13444 dataOnly = true; 13445 if((ps == null) || (ps.pkg == null)) { 13446 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13447 return false; 13448 } 13449 p = ps.pkg; 13450 } 13451 if (ps != null) { 13452 libDirRoot = ps.legacyNativeLibraryPathString; 13453 } 13454 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13455 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13456 if (secureContainerId != null) { 13457 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13458 } 13459 } 13460 } 13461 String publicSrcDir = null; 13462 if(!dataOnly) { 13463 final ApplicationInfo applicationInfo = p.applicationInfo; 13464 if (applicationInfo == null) { 13465 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13466 return false; 13467 } 13468 if (p.isForwardLocked()) { 13469 publicSrcDir = applicationInfo.getBaseResourcePath(); 13470 } 13471 } 13472 // TODO: extend to measure size of split APKs 13473 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13474 // not just the first level. 13475 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13476 // just the primary. 13477 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13478 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13479 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13480 if (res < 0) { 13481 return false; 13482 } 13483 13484 // Fix-up for forward-locked applications in ASEC containers. 13485 if (!isExternal(p)) { 13486 pStats.codeSize += pStats.externalCodeSize; 13487 pStats.externalCodeSize = 0L; 13488 } 13489 13490 return true; 13491 } 13492 13493 13494 @Override 13495 public void addPackageToPreferred(String packageName) { 13496 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13497 } 13498 13499 @Override 13500 public void removePackageFromPreferred(String packageName) { 13501 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13502 } 13503 13504 @Override 13505 public List<PackageInfo> getPreferredPackages(int flags) { 13506 return new ArrayList<PackageInfo>(); 13507 } 13508 13509 private int getUidTargetSdkVersionLockedLPr(int uid) { 13510 Object obj = mSettings.getUserIdLPr(uid); 13511 if (obj instanceof SharedUserSetting) { 13512 final SharedUserSetting sus = (SharedUserSetting) obj; 13513 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13514 final Iterator<PackageSetting> it = sus.packages.iterator(); 13515 while (it.hasNext()) { 13516 final PackageSetting ps = it.next(); 13517 if (ps.pkg != null) { 13518 int v = ps.pkg.applicationInfo.targetSdkVersion; 13519 if (v < vers) vers = v; 13520 } 13521 } 13522 return vers; 13523 } else if (obj instanceof PackageSetting) { 13524 final PackageSetting ps = (PackageSetting) obj; 13525 if (ps.pkg != null) { 13526 return ps.pkg.applicationInfo.targetSdkVersion; 13527 } 13528 } 13529 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13530 } 13531 13532 @Override 13533 public void addPreferredActivity(IntentFilter filter, int match, 13534 ComponentName[] set, ComponentName activity, int userId) { 13535 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13536 "Adding preferred"); 13537 } 13538 13539 private void addPreferredActivityInternal(IntentFilter filter, int match, 13540 ComponentName[] set, ComponentName activity, boolean always, int userId, 13541 String opname) { 13542 // writer 13543 int callingUid = Binder.getCallingUid(); 13544 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13545 if (filter.countActions() == 0) { 13546 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13547 return; 13548 } 13549 synchronized (mPackages) { 13550 if (mContext.checkCallingOrSelfPermission( 13551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13552 != PackageManager.PERMISSION_GRANTED) { 13553 if (getUidTargetSdkVersionLockedLPr(callingUid) 13554 < Build.VERSION_CODES.FROYO) { 13555 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13556 + callingUid); 13557 return; 13558 } 13559 mContext.enforceCallingOrSelfPermission( 13560 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13561 } 13562 13563 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13564 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13565 + userId + ":"); 13566 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13567 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13568 scheduleWritePackageRestrictionsLocked(userId); 13569 } 13570 } 13571 13572 @Override 13573 public void replacePreferredActivity(IntentFilter filter, int match, 13574 ComponentName[] set, ComponentName activity, int userId) { 13575 if (filter.countActions() != 1) { 13576 throw new IllegalArgumentException( 13577 "replacePreferredActivity expects filter to have only 1 action."); 13578 } 13579 if (filter.countDataAuthorities() != 0 13580 || filter.countDataPaths() != 0 13581 || filter.countDataSchemes() > 1 13582 || filter.countDataTypes() != 0) { 13583 throw new IllegalArgumentException( 13584 "replacePreferredActivity expects filter to have no data authorities, " + 13585 "paths, or types; and at most one scheme."); 13586 } 13587 13588 final int callingUid = Binder.getCallingUid(); 13589 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13590 synchronized (mPackages) { 13591 if (mContext.checkCallingOrSelfPermission( 13592 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13593 != PackageManager.PERMISSION_GRANTED) { 13594 if (getUidTargetSdkVersionLockedLPr(callingUid) 13595 < Build.VERSION_CODES.FROYO) { 13596 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13597 + Binder.getCallingUid()); 13598 return; 13599 } 13600 mContext.enforceCallingOrSelfPermission( 13601 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13602 } 13603 13604 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13605 if (pir != null) { 13606 // Get all of the existing entries that exactly match this filter. 13607 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13608 if (existing != null && existing.size() == 1) { 13609 PreferredActivity cur = existing.get(0); 13610 if (DEBUG_PREFERRED) { 13611 Slog.i(TAG, "Checking replace of preferred:"); 13612 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13613 if (!cur.mPref.mAlways) { 13614 Slog.i(TAG, " -- CUR; not mAlways!"); 13615 } else { 13616 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13617 Slog.i(TAG, " -- CUR: mSet=" 13618 + Arrays.toString(cur.mPref.mSetComponents)); 13619 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13620 Slog.i(TAG, " -- NEW: mMatch=" 13621 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13622 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13623 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13624 } 13625 } 13626 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13627 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13628 && cur.mPref.sameSet(set)) { 13629 // Setting the preferred activity to what it happens to be already 13630 if (DEBUG_PREFERRED) { 13631 Slog.i(TAG, "Replacing with same preferred activity " 13632 + cur.mPref.mShortComponent + " for user " 13633 + userId + ":"); 13634 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13635 } 13636 return; 13637 } 13638 } 13639 13640 if (existing != null) { 13641 if (DEBUG_PREFERRED) { 13642 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13643 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13644 } 13645 for (int i = 0; i < existing.size(); i++) { 13646 PreferredActivity pa = existing.get(i); 13647 if (DEBUG_PREFERRED) { 13648 Slog.i(TAG, "Removing existing preferred activity " 13649 + pa.mPref.mComponent + ":"); 13650 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13651 } 13652 pir.removeFilter(pa); 13653 } 13654 } 13655 } 13656 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13657 "Replacing preferred"); 13658 } 13659 } 13660 13661 @Override 13662 public void clearPackagePreferredActivities(String packageName) { 13663 final int uid = Binder.getCallingUid(); 13664 // writer 13665 synchronized (mPackages) { 13666 PackageParser.Package pkg = mPackages.get(packageName); 13667 if (pkg == null || pkg.applicationInfo.uid != uid) { 13668 if (mContext.checkCallingOrSelfPermission( 13669 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13670 != PackageManager.PERMISSION_GRANTED) { 13671 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13672 < Build.VERSION_CODES.FROYO) { 13673 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13674 + Binder.getCallingUid()); 13675 return; 13676 } 13677 mContext.enforceCallingOrSelfPermission( 13678 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13679 } 13680 } 13681 13682 int user = UserHandle.getCallingUserId(); 13683 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13684 scheduleWritePackageRestrictionsLocked(user); 13685 } 13686 } 13687 } 13688 13689 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13690 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13691 ArrayList<PreferredActivity> removed = null; 13692 boolean changed = false; 13693 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13694 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13695 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13696 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13697 continue; 13698 } 13699 Iterator<PreferredActivity> it = pir.filterIterator(); 13700 while (it.hasNext()) { 13701 PreferredActivity pa = it.next(); 13702 // Mark entry for removal only if it matches the package name 13703 // and the entry is of type "always". 13704 if (packageName == null || 13705 (pa.mPref.mComponent.getPackageName().equals(packageName) 13706 && pa.mPref.mAlways)) { 13707 if (removed == null) { 13708 removed = new ArrayList<PreferredActivity>(); 13709 } 13710 removed.add(pa); 13711 } 13712 } 13713 if (removed != null) { 13714 for (int j=0; j<removed.size(); j++) { 13715 PreferredActivity pa = removed.get(j); 13716 pir.removeFilter(pa); 13717 } 13718 changed = true; 13719 } 13720 } 13721 return changed; 13722 } 13723 13724 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13725 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13726 if (userId == UserHandle.USER_ALL) { 13727 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13728 sUserManager.getUserIds())) { 13729 for (int oneUserId : sUserManager.getUserIds()) { 13730 scheduleWritePackageRestrictionsLocked(oneUserId); 13731 } 13732 } 13733 } else { 13734 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13735 scheduleWritePackageRestrictionsLocked(userId); 13736 } 13737 } 13738 } 13739 13740 13741 void clearDefaultBrowserIfNeeded(String packageName) { 13742 for (int oneUserId : sUserManager.getUserIds()) { 13743 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13744 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13745 if (packageName.equals(defaultBrowserPackageName)) { 13746 setDefaultBrowserPackageName(null, oneUserId); 13747 } 13748 } 13749 } 13750 13751 @Override 13752 public void resetPreferredActivities(int userId) { 13753 mContext.enforceCallingOrSelfPermission( 13754 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13755 // writer 13756 synchronized (mPackages) { 13757 clearPackagePreferredActivitiesLPw(null, userId); 13758 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13759 applyFactoryDefaultBrowserLPw(userId); 13760 primeDomainVerificationsLPw(userId); 13761 13762 scheduleWritePackageRestrictionsLocked(userId); 13763 } 13764 } 13765 13766 @Override 13767 public int getPreferredActivities(List<IntentFilter> outFilters, 13768 List<ComponentName> outActivities, String packageName) { 13769 13770 int num = 0; 13771 final int userId = UserHandle.getCallingUserId(); 13772 // reader 13773 synchronized (mPackages) { 13774 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13775 if (pir != null) { 13776 final Iterator<PreferredActivity> it = pir.filterIterator(); 13777 while (it.hasNext()) { 13778 final PreferredActivity pa = it.next(); 13779 if (packageName == null 13780 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13781 && pa.mPref.mAlways)) { 13782 if (outFilters != null) { 13783 outFilters.add(new IntentFilter(pa)); 13784 } 13785 if (outActivities != null) { 13786 outActivities.add(pa.mPref.mComponent); 13787 } 13788 } 13789 } 13790 } 13791 } 13792 13793 return num; 13794 } 13795 13796 @Override 13797 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13798 int userId) { 13799 int callingUid = Binder.getCallingUid(); 13800 if (callingUid != Process.SYSTEM_UID) { 13801 throw new SecurityException( 13802 "addPersistentPreferredActivity can only be run by the system"); 13803 } 13804 if (filter.countActions() == 0) { 13805 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13806 return; 13807 } 13808 synchronized (mPackages) { 13809 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13810 " :"); 13811 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13812 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13813 new PersistentPreferredActivity(filter, activity)); 13814 scheduleWritePackageRestrictionsLocked(userId); 13815 } 13816 } 13817 13818 @Override 13819 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13820 int callingUid = Binder.getCallingUid(); 13821 if (callingUid != Process.SYSTEM_UID) { 13822 throw new SecurityException( 13823 "clearPackagePersistentPreferredActivities can only be run by the system"); 13824 } 13825 ArrayList<PersistentPreferredActivity> removed = null; 13826 boolean changed = false; 13827 synchronized (mPackages) { 13828 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13829 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13830 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13831 .valueAt(i); 13832 if (userId != thisUserId) { 13833 continue; 13834 } 13835 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13836 while (it.hasNext()) { 13837 PersistentPreferredActivity ppa = it.next(); 13838 // Mark entry for removal only if it matches the package name. 13839 if (ppa.mComponent.getPackageName().equals(packageName)) { 13840 if (removed == null) { 13841 removed = new ArrayList<PersistentPreferredActivity>(); 13842 } 13843 removed.add(ppa); 13844 } 13845 } 13846 if (removed != null) { 13847 for (int j=0; j<removed.size(); j++) { 13848 PersistentPreferredActivity ppa = removed.get(j); 13849 ppir.removeFilter(ppa); 13850 } 13851 changed = true; 13852 } 13853 } 13854 13855 if (changed) { 13856 scheduleWritePackageRestrictionsLocked(userId); 13857 } 13858 } 13859 } 13860 13861 /** 13862 * Common machinery for picking apart a restored XML blob and passing 13863 * it to a caller-supplied functor to be applied to the running system. 13864 */ 13865 private void restoreFromXml(XmlPullParser parser, int userId, 13866 String expectedStartTag, BlobXmlRestorer functor) 13867 throws IOException, XmlPullParserException { 13868 int type; 13869 while ((type = parser.next()) != XmlPullParser.START_TAG 13870 && type != XmlPullParser.END_DOCUMENT) { 13871 } 13872 if (type != XmlPullParser.START_TAG) { 13873 // oops didn't find a start tag?! 13874 if (DEBUG_BACKUP) { 13875 Slog.e(TAG, "Didn't find start tag during restore"); 13876 } 13877 return; 13878 } 13879 13880 // this is supposed to be TAG_PREFERRED_BACKUP 13881 if (!expectedStartTag.equals(parser.getName())) { 13882 if (DEBUG_BACKUP) { 13883 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13884 } 13885 return; 13886 } 13887 13888 // skip interfering stuff, then we're aligned with the backing implementation 13889 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13890 functor.apply(parser, userId); 13891 } 13892 13893 private interface BlobXmlRestorer { 13894 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13895 } 13896 13897 /** 13898 * Non-Binder method, support for the backup/restore mechanism: write the 13899 * full set of preferred activities in its canonical XML format. Returns the 13900 * XML output as a byte array, or null if there is none. 13901 */ 13902 @Override 13903 public byte[] getPreferredActivityBackup(int userId) { 13904 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13905 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13906 } 13907 13908 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13909 try { 13910 final XmlSerializer serializer = new FastXmlSerializer(); 13911 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13912 serializer.startDocument(null, true); 13913 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13914 13915 synchronized (mPackages) { 13916 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13917 } 13918 13919 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13920 serializer.endDocument(); 13921 serializer.flush(); 13922 } catch (Exception e) { 13923 if (DEBUG_BACKUP) { 13924 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13925 } 13926 return null; 13927 } 13928 13929 return dataStream.toByteArray(); 13930 } 13931 13932 @Override 13933 public void restorePreferredActivities(byte[] backup, int userId) { 13934 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13935 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13936 } 13937 13938 try { 13939 final XmlPullParser parser = Xml.newPullParser(); 13940 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13941 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13942 new BlobXmlRestorer() { 13943 @Override 13944 public void apply(XmlPullParser parser, int userId) 13945 throws XmlPullParserException, IOException { 13946 synchronized (mPackages) { 13947 mSettings.readPreferredActivitiesLPw(parser, userId); 13948 } 13949 } 13950 } ); 13951 } catch (Exception e) { 13952 if (DEBUG_BACKUP) { 13953 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13954 } 13955 } 13956 } 13957 13958 /** 13959 * Non-Binder method, support for the backup/restore mechanism: write the 13960 * default browser (etc) settings in its canonical XML format. Returns the default 13961 * browser XML representation as a byte array, or null if there is none. 13962 */ 13963 @Override 13964 public byte[] getDefaultAppsBackup(int userId) { 13965 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13966 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13967 } 13968 13969 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13970 try { 13971 final XmlSerializer serializer = new FastXmlSerializer(); 13972 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13973 serializer.startDocument(null, true); 13974 serializer.startTag(null, TAG_DEFAULT_APPS); 13975 13976 synchronized (mPackages) { 13977 mSettings.writeDefaultAppsLPr(serializer, userId); 13978 } 13979 13980 serializer.endTag(null, TAG_DEFAULT_APPS); 13981 serializer.endDocument(); 13982 serializer.flush(); 13983 } catch (Exception e) { 13984 if (DEBUG_BACKUP) { 13985 Slog.e(TAG, "Unable to write default apps for backup", e); 13986 } 13987 return null; 13988 } 13989 13990 return dataStream.toByteArray(); 13991 } 13992 13993 @Override 13994 public void restoreDefaultApps(byte[] backup, int userId) { 13995 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13996 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13997 } 13998 13999 try { 14000 final XmlPullParser parser = Xml.newPullParser(); 14001 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14002 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14003 new BlobXmlRestorer() { 14004 @Override 14005 public void apply(XmlPullParser parser, int userId) 14006 throws XmlPullParserException, IOException { 14007 synchronized (mPackages) { 14008 mSettings.readDefaultAppsLPw(parser, userId); 14009 } 14010 } 14011 } ); 14012 } catch (Exception e) { 14013 if (DEBUG_BACKUP) { 14014 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14015 } 14016 } 14017 } 14018 14019 @Override 14020 public byte[] getIntentFilterVerificationBackup(int userId) { 14021 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14022 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14023 } 14024 14025 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14026 try { 14027 final XmlSerializer serializer = new FastXmlSerializer(); 14028 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14029 serializer.startDocument(null, true); 14030 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14031 14032 synchronized (mPackages) { 14033 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14034 } 14035 14036 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14037 serializer.endDocument(); 14038 serializer.flush(); 14039 } catch (Exception e) { 14040 if (DEBUG_BACKUP) { 14041 Slog.e(TAG, "Unable to write default apps for backup", e); 14042 } 14043 return null; 14044 } 14045 14046 return dataStream.toByteArray(); 14047 } 14048 14049 @Override 14050 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14051 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14052 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14053 } 14054 14055 try { 14056 final XmlPullParser parser = Xml.newPullParser(); 14057 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14058 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14059 new BlobXmlRestorer() { 14060 @Override 14061 public void apply(XmlPullParser parser, int userId) 14062 throws XmlPullParserException, IOException { 14063 synchronized (mPackages) { 14064 mSettings.readAllDomainVerificationsLPr(parser, userId); 14065 mSettings.writeLPr(); 14066 } 14067 } 14068 } ); 14069 } catch (Exception e) { 14070 if (DEBUG_BACKUP) { 14071 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14072 } 14073 } 14074 } 14075 14076 @Override 14077 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14078 int sourceUserId, int targetUserId, int flags) { 14079 mContext.enforceCallingOrSelfPermission( 14080 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14081 int callingUid = Binder.getCallingUid(); 14082 enforceOwnerRights(ownerPackage, callingUid); 14083 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14084 if (intentFilter.countActions() == 0) { 14085 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14086 return; 14087 } 14088 synchronized (mPackages) { 14089 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14090 ownerPackage, targetUserId, flags); 14091 CrossProfileIntentResolver resolver = 14092 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14093 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14094 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14095 if (existing != null) { 14096 int size = existing.size(); 14097 for (int i = 0; i < size; i++) { 14098 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14099 return; 14100 } 14101 } 14102 } 14103 resolver.addFilter(newFilter); 14104 scheduleWritePackageRestrictionsLocked(sourceUserId); 14105 } 14106 } 14107 14108 @Override 14109 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14110 mContext.enforceCallingOrSelfPermission( 14111 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14112 int callingUid = Binder.getCallingUid(); 14113 enforceOwnerRights(ownerPackage, callingUid); 14114 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14115 synchronized (mPackages) { 14116 CrossProfileIntentResolver resolver = 14117 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14118 ArraySet<CrossProfileIntentFilter> set = 14119 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14120 for (CrossProfileIntentFilter filter : set) { 14121 if (filter.getOwnerPackage().equals(ownerPackage)) { 14122 resolver.removeFilter(filter); 14123 } 14124 } 14125 scheduleWritePackageRestrictionsLocked(sourceUserId); 14126 } 14127 } 14128 14129 // Enforcing that callingUid is owning pkg on userId 14130 private void enforceOwnerRights(String pkg, int callingUid) { 14131 // The system owns everything. 14132 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14133 return; 14134 } 14135 int callingUserId = UserHandle.getUserId(callingUid); 14136 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14137 if (pi == null) { 14138 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14139 + callingUserId); 14140 } 14141 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14142 throw new SecurityException("Calling uid " + callingUid 14143 + " does not own package " + pkg); 14144 } 14145 } 14146 14147 @Override 14148 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14149 Intent intent = new Intent(Intent.ACTION_MAIN); 14150 intent.addCategory(Intent.CATEGORY_HOME); 14151 14152 final int callingUserId = UserHandle.getCallingUserId(); 14153 List<ResolveInfo> list = queryIntentActivities(intent, null, 14154 PackageManager.GET_META_DATA, callingUserId); 14155 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14156 true, false, false, callingUserId); 14157 14158 allHomeCandidates.clear(); 14159 if (list != null) { 14160 for (ResolveInfo ri : list) { 14161 allHomeCandidates.add(ri); 14162 } 14163 } 14164 return (preferred == null || preferred.activityInfo == null) 14165 ? null 14166 : new ComponentName(preferred.activityInfo.packageName, 14167 preferred.activityInfo.name); 14168 } 14169 14170 @Override 14171 public void setApplicationEnabledSetting(String appPackageName, 14172 int newState, int flags, int userId, String callingPackage) { 14173 if (!sUserManager.exists(userId)) return; 14174 if (callingPackage == null) { 14175 callingPackage = Integer.toString(Binder.getCallingUid()); 14176 } 14177 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14178 } 14179 14180 @Override 14181 public void setComponentEnabledSetting(ComponentName componentName, 14182 int newState, int flags, int userId) { 14183 if (!sUserManager.exists(userId)) return; 14184 setEnabledSetting(componentName.getPackageName(), 14185 componentName.getClassName(), newState, flags, userId, null); 14186 } 14187 14188 private void setEnabledSetting(final String packageName, String className, int newState, 14189 final int flags, int userId, String callingPackage) { 14190 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14191 || newState == COMPONENT_ENABLED_STATE_ENABLED 14192 || newState == COMPONENT_ENABLED_STATE_DISABLED 14193 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14194 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14195 throw new IllegalArgumentException("Invalid new component state: " 14196 + newState); 14197 } 14198 PackageSetting pkgSetting; 14199 final int uid = Binder.getCallingUid(); 14200 final int permission = mContext.checkCallingOrSelfPermission( 14201 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14202 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14203 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14204 boolean sendNow = false; 14205 boolean isApp = (className == null); 14206 String componentName = isApp ? packageName : className; 14207 int packageUid = -1; 14208 ArrayList<String> components; 14209 14210 // writer 14211 synchronized (mPackages) { 14212 pkgSetting = mSettings.mPackages.get(packageName); 14213 if (pkgSetting == null) { 14214 if (className == null) { 14215 throw new IllegalArgumentException( 14216 "Unknown package: " + packageName); 14217 } 14218 throw new IllegalArgumentException( 14219 "Unknown component: " + packageName 14220 + "/" + className); 14221 } 14222 // Allow root and verify that userId is not being specified by a different user 14223 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14224 throw new SecurityException( 14225 "Permission Denial: attempt to change component state from pid=" 14226 + Binder.getCallingPid() 14227 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14228 } 14229 if (className == null) { 14230 // We're dealing with an application/package level state change 14231 if (pkgSetting.getEnabled(userId) == newState) { 14232 // Nothing to do 14233 return; 14234 } 14235 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14236 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14237 // Don't care about who enables an app. 14238 callingPackage = null; 14239 } 14240 pkgSetting.setEnabled(newState, userId, callingPackage); 14241 // pkgSetting.pkg.mSetEnabled = newState; 14242 } else { 14243 // We're dealing with a component level state change 14244 // First, verify that this is a valid class name. 14245 PackageParser.Package pkg = pkgSetting.pkg; 14246 if (pkg == null || !pkg.hasComponentClassName(className)) { 14247 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14248 throw new IllegalArgumentException("Component class " + className 14249 + " does not exist in " + packageName); 14250 } else { 14251 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14252 + className + " does not exist in " + packageName); 14253 } 14254 } 14255 switch (newState) { 14256 case COMPONENT_ENABLED_STATE_ENABLED: 14257 if (!pkgSetting.enableComponentLPw(className, userId)) { 14258 return; 14259 } 14260 break; 14261 case COMPONENT_ENABLED_STATE_DISABLED: 14262 if (!pkgSetting.disableComponentLPw(className, userId)) { 14263 return; 14264 } 14265 break; 14266 case COMPONENT_ENABLED_STATE_DEFAULT: 14267 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14268 return; 14269 } 14270 break; 14271 default: 14272 Slog.e(TAG, "Invalid new component state: " + newState); 14273 return; 14274 } 14275 } 14276 scheduleWritePackageRestrictionsLocked(userId); 14277 components = mPendingBroadcasts.get(userId, packageName); 14278 final boolean newPackage = components == null; 14279 if (newPackage) { 14280 components = new ArrayList<String>(); 14281 } 14282 if (!components.contains(componentName)) { 14283 components.add(componentName); 14284 } 14285 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14286 sendNow = true; 14287 // Purge entry from pending broadcast list if another one exists already 14288 // since we are sending one right away. 14289 mPendingBroadcasts.remove(userId, packageName); 14290 } else { 14291 if (newPackage) { 14292 mPendingBroadcasts.put(userId, packageName, components); 14293 } 14294 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14295 // Schedule a message 14296 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14297 } 14298 } 14299 } 14300 14301 long callingId = Binder.clearCallingIdentity(); 14302 try { 14303 if (sendNow) { 14304 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14305 sendPackageChangedBroadcast(packageName, 14306 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14307 } 14308 } finally { 14309 Binder.restoreCallingIdentity(callingId); 14310 } 14311 } 14312 14313 private void sendPackageChangedBroadcast(String packageName, 14314 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14315 if (DEBUG_INSTALL) 14316 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14317 + componentNames); 14318 Bundle extras = new Bundle(4); 14319 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14320 String nameList[] = new String[componentNames.size()]; 14321 componentNames.toArray(nameList); 14322 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14323 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14324 extras.putInt(Intent.EXTRA_UID, packageUid); 14325 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14326 new int[] {UserHandle.getUserId(packageUid)}); 14327 } 14328 14329 @Override 14330 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14331 if (!sUserManager.exists(userId)) return; 14332 final int uid = Binder.getCallingUid(); 14333 final int permission = mContext.checkCallingOrSelfPermission( 14334 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14335 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14336 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14337 // writer 14338 synchronized (mPackages) { 14339 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14340 allowedByPermission, uid, userId)) { 14341 scheduleWritePackageRestrictionsLocked(userId); 14342 } 14343 } 14344 } 14345 14346 @Override 14347 public String getInstallerPackageName(String packageName) { 14348 // reader 14349 synchronized (mPackages) { 14350 return mSettings.getInstallerPackageNameLPr(packageName); 14351 } 14352 } 14353 14354 @Override 14355 public int getApplicationEnabledSetting(String packageName, int userId) { 14356 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14357 int uid = Binder.getCallingUid(); 14358 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14359 // reader 14360 synchronized (mPackages) { 14361 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14362 } 14363 } 14364 14365 @Override 14366 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14367 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14368 int uid = Binder.getCallingUid(); 14369 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14370 // reader 14371 synchronized (mPackages) { 14372 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14373 } 14374 } 14375 14376 @Override 14377 public void enterSafeMode() { 14378 enforceSystemOrRoot("Only the system can request entering safe mode"); 14379 14380 if (!mSystemReady) { 14381 mSafeMode = true; 14382 } 14383 } 14384 14385 @Override 14386 public void systemReady() { 14387 mSystemReady = true; 14388 14389 // Read the compatibilty setting when the system is ready. 14390 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14391 mContext.getContentResolver(), 14392 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14393 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14394 if (DEBUG_SETTINGS) { 14395 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14396 } 14397 14398 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14399 14400 synchronized (mPackages) { 14401 // Verify that all of the preferred activity components actually 14402 // exist. It is possible for applications to be updated and at 14403 // that point remove a previously declared activity component that 14404 // had been set as a preferred activity. We try to clean this up 14405 // the next time we encounter that preferred activity, but it is 14406 // possible for the user flow to never be able to return to that 14407 // situation so here we do a sanity check to make sure we haven't 14408 // left any junk around. 14409 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14410 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14411 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14412 removed.clear(); 14413 for (PreferredActivity pa : pir.filterSet()) { 14414 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14415 removed.add(pa); 14416 } 14417 } 14418 if (removed.size() > 0) { 14419 for (int r=0; r<removed.size(); r++) { 14420 PreferredActivity pa = removed.get(r); 14421 Slog.w(TAG, "Removing dangling preferred activity: " 14422 + pa.mPref.mComponent); 14423 pir.removeFilter(pa); 14424 } 14425 mSettings.writePackageRestrictionsLPr( 14426 mSettings.mPreferredActivities.keyAt(i)); 14427 } 14428 } 14429 14430 for (int userId : UserManagerService.getInstance().getUserIds()) { 14431 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14432 grantPermissionsUserIds = ArrayUtils.appendInt( 14433 grantPermissionsUserIds, userId); 14434 } 14435 } 14436 } 14437 sUserManager.systemReady(); 14438 14439 // If we upgraded grant all default permissions before kicking off. 14440 for (int userId : grantPermissionsUserIds) { 14441 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14442 } 14443 14444 // Kick off any messages waiting for system ready 14445 if (mPostSystemReadyMessages != null) { 14446 for (Message msg : mPostSystemReadyMessages) { 14447 msg.sendToTarget(); 14448 } 14449 mPostSystemReadyMessages = null; 14450 } 14451 14452 // Watch for external volumes that come and go over time 14453 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14454 storage.registerListener(mStorageListener); 14455 14456 mInstallerService.systemReady(); 14457 mPackageDexOptimizer.systemReady(); 14458 14459 MountServiceInternal mountServiceInternal = LocalServices.getService( 14460 MountServiceInternal.class); 14461 mountServiceInternal.addExternalStoragePolicy( 14462 new MountServiceInternal.ExternalStorageMountPolicy() { 14463 @Override 14464 public int getMountMode(int uid, String packageName) { 14465 if (Process.isIsolated(uid)) { 14466 return Zygote.MOUNT_EXTERNAL_NONE; 14467 } 14468 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 14469 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14470 } 14471 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14472 return Zygote.MOUNT_EXTERNAL_DEFAULT; 14473 } 14474 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 14475 return Zygote.MOUNT_EXTERNAL_READ; 14476 } 14477 return Zygote.MOUNT_EXTERNAL_WRITE; 14478 } 14479 14480 @Override 14481 public boolean hasExternalStorage(int uid, String packageName) { 14482 return true; 14483 } 14484 }); 14485 } 14486 14487 @Override 14488 public boolean isSafeMode() { 14489 return mSafeMode; 14490 } 14491 14492 @Override 14493 public boolean hasSystemUidErrors() { 14494 return mHasSystemUidErrors; 14495 } 14496 14497 static String arrayToString(int[] array) { 14498 StringBuffer buf = new StringBuffer(128); 14499 buf.append('['); 14500 if (array != null) { 14501 for (int i=0; i<array.length; i++) { 14502 if (i > 0) buf.append(", "); 14503 buf.append(array[i]); 14504 } 14505 } 14506 buf.append(']'); 14507 return buf.toString(); 14508 } 14509 14510 static class DumpState { 14511 public static final int DUMP_LIBS = 1 << 0; 14512 public static final int DUMP_FEATURES = 1 << 1; 14513 public static final int DUMP_RESOLVERS = 1 << 2; 14514 public static final int DUMP_PERMISSIONS = 1 << 3; 14515 public static final int DUMP_PACKAGES = 1 << 4; 14516 public static final int DUMP_SHARED_USERS = 1 << 5; 14517 public static final int DUMP_MESSAGES = 1 << 6; 14518 public static final int DUMP_PROVIDERS = 1 << 7; 14519 public static final int DUMP_VERIFIERS = 1 << 8; 14520 public static final int DUMP_PREFERRED = 1 << 9; 14521 public static final int DUMP_PREFERRED_XML = 1 << 10; 14522 public static final int DUMP_KEYSETS = 1 << 11; 14523 public static final int DUMP_VERSION = 1 << 12; 14524 public static final int DUMP_INSTALLS = 1 << 13; 14525 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14526 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14527 14528 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14529 14530 private int mTypes; 14531 14532 private int mOptions; 14533 14534 private boolean mTitlePrinted; 14535 14536 private SharedUserSetting mSharedUser; 14537 14538 public boolean isDumping(int type) { 14539 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14540 return true; 14541 } 14542 14543 return (mTypes & type) != 0; 14544 } 14545 14546 public void setDump(int type) { 14547 mTypes |= type; 14548 } 14549 14550 public boolean isOptionEnabled(int option) { 14551 return (mOptions & option) != 0; 14552 } 14553 14554 public void setOptionEnabled(int option) { 14555 mOptions |= option; 14556 } 14557 14558 public boolean onTitlePrinted() { 14559 final boolean printed = mTitlePrinted; 14560 mTitlePrinted = true; 14561 return printed; 14562 } 14563 14564 public boolean getTitlePrinted() { 14565 return mTitlePrinted; 14566 } 14567 14568 public void setTitlePrinted(boolean enabled) { 14569 mTitlePrinted = enabled; 14570 } 14571 14572 public SharedUserSetting getSharedUser() { 14573 return mSharedUser; 14574 } 14575 14576 public void setSharedUser(SharedUserSetting user) { 14577 mSharedUser = user; 14578 } 14579 } 14580 14581 @Override 14582 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14583 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14584 != PackageManager.PERMISSION_GRANTED) { 14585 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14586 + Binder.getCallingPid() 14587 + ", uid=" + Binder.getCallingUid() 14588 + " without permission " 14589 + android.Manifest.permission.DUMP); 14590 return; 14591 } 14592 14593 DumpState dumpState = new DumpState(); 14594 boolean fullPreferred = false; 14595 boolean checkin = false; 14596 14597 String packageName = null; 14598 ArraySet<String> permissionNames = null; 14599 14600 int opti = 0; 14601 while (opti < args.length) { 14602 String opt = args[opti]; 14603 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14604 break; 14605 } 14606 opti++; 14607 14608 if ("-a".equals(opt)) { 14609 // Right now we only know how to print all. 14610 } else if ("-h".equals(opt)) { 14611 pw.println("Package manager dump options:"); 14612 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14613 pw.println(" --checkin: dump for a checkin"); 14614 pw.println(" -f: print details of intent filters"); 14615 pw.println(" -h: print this help"); 14616 pw.println(" cmd may be one of:"); 14617 pw.println(" l[ibraries]: list known shared libraries"); 14618 pw.println(" f[ibraries]: list device features"); 14619 pw.println(" k[eysets]: print known keysets"); 14620 pw.println(" r[esolvers]: dump intent resolvers"); 14621 pw.println(" perm[issions]: dump permissions"); 14622 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14623 pw.println(" pref[erred]: print preferred package settings"); 14624 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14625 pw.println(" prov[iders]: dump content providers"); 14626 pw.println(" p[ackages]: dump installed packages"); 14627 pw.println(" s[hared-users]: dump shared user IDs"); 14628 pw.println(" m[essages]: print collected runtime messages"); 14629 pw.println(" v[erifiers]: print package verifier info"); 14630 pw.println(" version: print database version info"); 14631 pw.println(" write: write current settings now"); 14632 pw.println(" <package.name>: info about given package"); 14633 pw.println(" installs: details about install sessions"); 14634 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14635 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14636 return; 14637 } else if ("--checkin".equals(opt)) { 14638 checkin = true; 14639 } else if ("-f".equals(opt)) { 14640 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14641 } else { 14642 pw.println("Unknown argument: " + opt + "; use -h for help"); 14643 } 14644 } 14645 14646 // Is the caller requesting to dump a particular piece of data? 14647 if (opti < args.length) { 14648 String cmd = args[opti]; 14649 opti++; 14650 // Is this a package name? 14651 if ("android".equals(cmd) || cmd.contains(".")) { 14652 packageName = cmd; 14653 // When dumping a single package, we always dump all of its 14654 // filter information since the amount of data will be reasonable. 14655 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14656 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14657 dumpState.setDump(DumpState.DUMP_LIBS); 14658 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14659 dumpState.setDump(DumpState.DUMP_FEATURES); 14660 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14661 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14662 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14663 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14664 } else if ("permission".equals(cmd)) { 14665 if (opti >= args.length) { 14666 pw.println("Error: permission requires permission name"); 14667 return; 14668 } 14669 permissionNames = new ArraySet<>(); 14670 while (opti < args.length) { 14671 permissionNames.add(args[opti]); 14672 opti++; 14673 } 14674 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14675 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14676 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14677 dumpState.setDump(DumpState.DUMP_PREFERRED); 14678 } else if ("preferred-xml".equals(cmd)) { 14679 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14680 if (opti < args.length && "--full".equals(args[opti])) { 14681 fullPreferred = true; 14682 opti++; 14683 } 14684 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14685 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14686 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14687 dumpState.setDump(DumpState.DUMP_PACKAGES); 14688 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14689 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14690 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14691 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14692 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14693 dumpState.setDump(DumpState.DUMP_MESSAGES); 14694 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14695 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14696 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14697 || "intent-filter-verifiers".equals(cmd)) { 14698 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14699 } else if ("version".equals(cmd)) { 14700 dumpState.setDump(DumpState.DUMP_VERSION); 14701 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14702 dumpState.setDump(DumpState.DUMP_KEYSETS); 14703 } else if ("installs".equals(cmd)) { 14704 dumpState.setDump(DumpState.DUMP_INSTALLS); 14705 } else if ("write".equals(cmd)) { 14706 synchronized (mPackages) { 14707 mSettings.writeLPr(); 14708 pw.println("Settings written."); 14709 return; 14710 } 14711 } 14712 } 14713 14714 if (checkin) { 14715 pw.println("vers,1"); 14716 } 14717 14718 // reader 14719 synchronized (mPackages) { 14720 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14721 if (!checkin) { 14722 if (dumpState.onTitlePrinted()) 14723 pw.println(); 14724 pw.println("Database versions:"); 14725 pw.print(" SDK Version:"); 14726 pw.print(" internal="); 14727 pw.print(mSettings.mInternalSdkPlatform); 14728 pw.print(" external="); 14729 pw.println(mSettings.mExternalSdkPlatform); 14730 pw.print(" DB Version:"); 14731 pw.print(" internal="); 14732 pw.print(mSettings.mInternalDatabaseVersion); 14733 pw.print(" external="); 14734 pw.println(mSettings.mExternalDatabaseVersion); 14735 } 14736 } 14737 14738 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14739 if (!checkin) { 14740 if (dumpState.onTitlePrinted()) 14741 pw.println(); 14742 pw.println("Verifiers:"); 14743 pw.print(" Required: "); 14744 pw.print(mRequiredVerifierPackage); 14745 pw.print(" (uid="); 14746 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14747 pw.println(")"); 14748 } else if (mRequiredVerifierPackage != null) { 14749 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14750 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14751 } 14752 } 14753 14754 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14755 packageName == null) { 14756 if (mIntentFilterVerifierComponent != null) { 14757 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14758 if (!checkin) { 14759 if (dumpState.onTitlePrinted()) 14760 pw.println(); 14761 pw.println("Intent Filter Verifier:"); 14762 pw.print(" Using: "); 14763 pw.print(verifierPackageName); 14764 pw.print(" (uid="); 14765 pw.print(getPackageUid(verifierPackageName, 0)); 14766 pw.println(")"); 14767 } else if (verifierPackageName != null) { 14768 pw.print("ifv,"); pw.print(verifierPackageName); 14769 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14770 } 14771 } else { 14772 pw.println(); 14773 pw.println("No Intent Filter Verifier available!"); 14774 } 14775 } 14776 14777 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14778 boolean printedHeader = false; 14779 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14780 while (it.hasNext()) { 14781 String name = it.next(); 14782 SharedLibraryEntry ent = mSharedLibraries.get(name); 14783 if (!checkin) { 14784 if (!printedHeader) { 14785 if (dumpState.onTitlePrinted()) 14786 pw.println(); 14787 pw.println("Libraries:"); 14788 printedHeader = true; 14789 } 14790 pw.print(" "); 14791 } else { 14792 pw.print("lib,"); 14793 } 14794 pw.print(name); 14795 if (!checkin) { 14796 pw.print(" -> "); 14797 } 14798 if (ent.path != null) { 14799 if (!checkin) { 14800 pw.print("(jar) "); 14801 pw.print(ent.path); 14802 } else { 14803 pw.print(",jar,"); 14804 pw.print(ent.path); 14805 } 14806 } else { 14807 if (!checkin) { 14808 pw.print("(apk) "); 14809 pw.print(ent.apk); 14810 } else { 14811 pw.print(",apk,"); 14812 pw.print(ent.apk); 14813 } 14814 } 14815 pw.println(); 14816 } 14817 } 14818 14819 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14820 if (dumpState.onTitlePrinted()) 14821 pw.println(); 14822 if (!checkin) { 14823 pw.println("Features:"); 14824 } 14825 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14826 while (it.hasNext()) { 14827 String name = it.next(); 14828 if (!checkin) { 14829 pw.print(" "); 14830 } else { 14831 pw.print("feat,"); 14832 } 14833 pw.println(name); 14834 } 14835 } 14836 14837 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14838 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14839 : "Activity Resolver Table:", " ", packageName, 14840 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14841 dumpState.setTitlePrinted(true); 14842 } 14843 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14844 : "Receiver Resolver Table:", " ", packageName, 14845 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14846 dumpState.setTitlePrinted(true); 14847 } 14848 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14849 : "Service Resolver Table:", " ", packageName, 14850 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14851 dumpState.setTitlePrinted(true); 14852 } 14853 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14854 : "Provider Resolver Table:", " ", packageName, 14855 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14856 dumpState.setTitlePrinted(true); 14857 } 14858 } 14859 14860 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14861 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14862 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14863 int user = mSettings.mPreferredActivities.keyAt(i); 14864 if (pir.dump(pw, 14865 dumpState.getTitlePrinted() 14866 ? "\nPreferred Activities User " + user + ":" 14867 : "Preferred Activities User " + user + ":", " ", 14868 packageName, true, false)) { 14869 dumpState.setTitlePrinted(true); 14870 } 14871 } 14872 } 14873 14874 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14875 pw.flush(); 14876 FileOutputStream fout = new FileOutputStream(fd); 14877 BufferedOutputStream str = new BufferedOutputStream(fout); 14878 XmlSerializer serializer = new FastXmlSerializer(); 14879 try { 14880 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14881 serializer.startDocument(null, true); 14882 serializer.setFeature( 14883 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14884 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14885 serializer.endDocument(); 14886 serializer.flush(); 14887 } catch (IllegalArgumentException e) { 14888 pw.println("Failed writing: " + e); 14889 } catch (IllegalStateException e) { 14890 pw.println("Failed writing: " + e); 14891 } catch (IOException e) { 14892 pw.println("Failed writing: " + e); 14893 } 14894 } 14895 14896 if (!checkin 14897 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14898 && packageName == null) { 14899 pw.println(); 14900 int count = mSettings.mPackages.size(); 14901 if (count == 0) { 14902 pw.println("No applications!"); 14903 pw.println(); 14904 } else { 14905 final String prefix = " "; 14906 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14907 if (allPackageSettings.size() == 0) { 14908 pw.println("No domain preferred apps!"); 14909 pw.println(); 14910 } else { 14911 pw.println("App verification status:"); 14912 pw.println(); 14913 count = 0; 14914 for (PackageSetting ps : allPackageSettings) { 14915 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14916 if (ivi == null || ivi.getPackageName() == null) continue; 14917 pw.println(prefix + "Package: " + ivi.getPackageName()); 14918 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14919 pw.println(prefix + "Status: " + ivi.getStatusString()); 14920 pw.println(); 14921 count++; 14922 } 14923 if (count == 0) { 14924 pw.println(prefix + "No app verification established."); 14925 pw.println(); 14926 } 14927 for (int userId : sUserManager.getUserIds()) { 14928 pw.println("App linkages for user " + userId + ":"); 14929 pw.println(); 14930 count = 0; 14931 for (PackageSetting ps : allPackageSettings) { 14932 final long status = ps.getDomainVerificationStatusForUser(userId); 14933 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14934 continue; 14935 } 14936 pw.println(prefix + "Package: " + ps.name); 14937 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14938 String statusStr = IntentFilterVerificationInfo. 14939 getStatusStringFromValue(status); 14940 pw.println(prefix + "Status: " + statusStr); 14941 pw.println(); 14942 count++; 14943 } 14944 if (count == 0) { 14945 pw.println(prefix + "No configured app linkages."); 14946 pw.println(); 14947 } 14948 } 14949 } 14950 } 14951 } 14952 14953 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14954 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14955 if (packageName == null && permissionNames == null) { 14956 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14957 if (iperm == 0) { 14958 if (dumpState.onTitlePrinted()) 14959 pw.println(); 14960 pw.println("AppOp Permissions:"); 14961 } 14962 pw.print(" AppOp Permission "); 14963 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14964 pw.println(":"); 14965 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14966 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14967 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14968 } 14969 } 14970 } 14971 } 14972 14973 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14974 boolean printedSomething = false; 14975 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14976 if (packageName != null && !packageName.equals(p.info.packageName)) { 14977 continue; 14978 } 14979 if (!printedSomething) { 14980 if (dumpState.onTitlePrinted()) 14981 pw.println(); 14982 pw.println("Registered ContentProviders:"); 14983 printedSomething = true; 14984 } 14985 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14986 pw.print(" "); pw.println(p.toString()); 14987 } 14988 printedSomething = false; 14989 for (Map.Entry<String, PackageParser.Provider> entry : 14990 mProvidersByAuthority.entrySet()) { 14991 PackageParser.Provider p = entry.getValue(); 14992 if (packageName != null && !packageName.equals(p.info.packageName)) { 14993 continue; 14994 } 14995 if (!printedSomething) { 14996 if (dumpState.onTitlePrinted()) 14997 pw.println(); 14998 pw.println("ContentProvider Authorities:"); 14999 printedSomething = true; 15000 } 15001 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15002 pw.print(" "); pw.println(p.toString()); 15003 if (p.info != null && p.info.applicationInfo != null) { 15004 final String appInfo = p.info.applicationInfo.toString(); 15005 pw.print(" applicationInfo="); pw.println(appInfo); 15006 } 15007 } 15008 } 15009 15010 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15011 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15012 } 15013 15014 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15015 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15016 } 15017 15018 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15019 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15020 } 15021 15022 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15023 // XXX should handle packageName != null by dumping only install data that 15024 // the given package is involved with. 15025 if (dumpState.onTitlePrinted()) pw.println(); 15026 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15027 } 15028 15029 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15030 if (dumpState.onTitlePrinted()) pw.println(); 15031 mSettings.dumpReadMessagesLPr(pw, dumpState); 15032 15033 pw.println(); 15034 pw.println("Package warning messages:"); 15035 BufferedReader in = null; 15036 String line = null; 15037 try { 15038 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15039 while ((line = in.readLine()) != null) { 15040 if (line.contains("ignored: updated version")) continue; 15041 pw.println(line); 15042 } 15043 } catch (IOException ignored) { 15044 } finally { 15045 IoUtils.closeQuietly(in); 15046 } 15047 } 15048 15049 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15050 BufferedReader in = null; 15051 String line = null; 15052 try { 15053 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15054 while ((line = in.readLine()) != null) { 15055 if (line.contains("ignored: updated version")) continue; 15056 pw.print("msg,"); 15057 pw.println(line); 15058 } 15059 } catch (IOException ignored) { 15060 } finally { 15061 IoUtils.closeQuietly(in); 15062 } 15063 } 15064 } 15065 } 15066 15067 private String dumpDomainString(String packageName) { 15068 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15069 List<IntentFilter> filters = getAllIntentFilters(packageName); 15070 15071 ArraySet<String> result = new ArraySet<>(); 15072 if (iviList.size() > 0) { 15073 for (IntentFilterVerificationInfo ivi : iviList) { 15074 for (String host : ivi.getDomains()) { 15075 result.add(host); 15076 } 15077 } 15078 } 15079 if (filters != null && filters.size() > 0) { 15080 for (IntentFilter filter : filters) { 15081 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 15082 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15083 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 15084 result.addAll(filter.getHostsList()); 15085 } 15086 } 15087 } 15088 15089 StringBuilder sb = new StringBuilder(result.size() * 16); 15090 for (String domain : result) { 15091 if (sb.length() > 0) sb.append(" "); 15092 sb.append(domain); 15093 } 15094 return sb.toString(); 15095 } 15096 15097 // ------- apps on sdcard specific code ------- 15098 static final boolean DEBUG_SD_INSTALL = false; 15099 15100 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15101 15102 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15103 15104 private boolean mMediaMounted = false; 15105 15106 static String getEncryptKey() { 15107 try { 15108 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15109 SD_ENCRYPTION_KEYSTORE_NAME); 15110 if (sdEncKey == null) { 15111 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15112 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15113 if (sdEncKey == null) { 15114 Slog.e(TAG, "Failed to create encryption keys"); 15115 return null; 15116 } 15117 } 15118 return sdEncKey; 15119 } catch (NoSuchAlgorithmException nsae) { 15120 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15121 return null; 15122 } catch (IOException ioe) { 15123 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15124 return null; 15125 } 15126 } 15127 15128 /* 15129 * Update media status on PackageManager. 15130 */ 15131 @Override 15132 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15133 int callingUid = Binder.getCallingUid(); 15134 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15135 throw new SecurityException("Media status can only be updated by the system"); 15136 } 15137 // reader; this apparently protects mMediaMounted, but should probably 15138 // be a different lock in that case. 15139 synchronized (mPackages) { 15140 Log.i(TAG, "Updating external media status from " 15141 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15142 + (mediaStatus ? "mounted" : "unmounted")); 15143 if (DEBUG_SD_INSTALL) 15144 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15145 + ", mMediaMounted=" + mMediaMounted); 15146 if (mediaStatus == mMediaMounted) { 15147 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15148 : 0, -1); 15149 mHandler.sendMessage(msg); 15150 return; 15151 } 15152 mMediaMounted = mediaStatus; 15153 } 15154 // Queue up an async operation since the package installation may take a 15155 // little while. 15156 mHandler.post(new Runnable() { 15157 public void run() { 15158 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15159 } 15160 }); 15161 } 15162 15163 /** 15164 * Called by MountService when the initial ASECs to scan are available. 15165 * Should block until all the ASEC containers are finished being scanned. 15166 */ 15167 public void scanAvailableAsecs() { 15168 updateExternalMediaStatusInner(true, false, false); 15169 if (mShouldRestoreconData) { 15170 SELinuxMMAC.setRestoreconDone(); 15171 mShouldRestoreconData = false; 15172 } 15173 } 15174 15175 /* 15176 * Collect information of applications on external media, map them against 15177 * existing containers and update information based on current mount status. 15178 * Please note that we always have to report status if reportStatus has been 15179 * set to true especially when unloading packages. 15180 */ 15181 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15182 boolean externalStorage) { 15183 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15184 int[] uidArr = EmptyArray.INT; 15185 15186 final String[] list = PackageHelper.getSecureContainerList(); 15187 if (ArrayUtils.isEmpty(list)) { 15188 Log.i(TAG, "No secure containers found"); 15189 } else { 15190 // Process list of secure containers and categorize them 15191 // as active or stale based on their package internal state. 15192 15193 // reader 15194 synchronized (mPackages) { 15195 for (String cid : list) { 15196 // Leave stages untouched for now; installer service owns them 15197 if (PackageInstallerService.isStageName(cid)) continue; 15198 15199 if (DEBUG_SD_INSTALL) 15200 Log.i(TAG, "Processing container " + cid); 15201 String pkgName = getAsecPackageName(cid); 15202 if (pkgName == null) { 15203 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15204 continue; 15205 } 15206 if (DEBUG_SD_INSTALL) 15207 Log.i(TAG, "Looking for pkg : " + pkgName); 15208 15209 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15210 if (ps == null) { 15211 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15212 continue; 15213 } 15214 15215 /* 15216 * Skip packages that are not external if we're unmounting 15217 * external storage. 15218 */ 15219 if (externalStorage && !isMounted && !isExternal(ps)) { 15220 continue; 15221 } 15222 15223 final AsecInstallArgs args = new AsecInstallArgs(cid, 15224 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15225 // The package status is changed only if the code path 15226 // matches between settings and the container id. 15227 if (ps.codePathString != null 15228 && ps.codePathString.startsWith(args.getCodePath())) { 15229 if (DEBUG_SD_INSTALL) { 15230 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15231 + " at code path: " + ps.codePathString); 15232 } 15233 15234 // We do have a valid package installed on sdcard 15235 processCids.put(args, ps.codePathString); 15236 final int uid = ps.appId; 15237 if (uid != -1) { 15238 uidArr = ArrayUtils.appendInt(uidArr, uid); 15239 } 15240 } else { 15241 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15242 + ps.codePathString); 15243 } 15244 } 15245 } 15246 15247 Arrays.sort(uidArr); 15248 } 15249 15250 // Process packages with valid entries. 15251 if (isMounted) { 15252 if (DEBUG_SD_INSTALL) 15253 Log.i(TAG, "Loading packages"); 15254 loadMediaPackages(processCids, uidArr); 15255 startCleaningPackages(); 15256 mInstallerService.onSecureContainersAvailable(); 15257 } else { 15258 if (DEBUG_SD_INSTALL) 15259 Log.i(TAG, "Unloading packages"); 15260 unloadMediaPackages(processCids, uidArr, reportStatus); 15261 } 15262 } 15263 15264 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15265 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15266 final int size = infos.size(); 15267 final String[] packageNames = new String[size]; 15268 final int[] packageUids = new int[size]; 15269 for (int i = 0; i < size; i++) { 15270 final ApplicationInfo info = infos.get(i); 15271 packageNames[i] = info.packageName; 15272 packageUids[i] = info.uid; 15273 } 15274 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15275 finishedReceiver); 15276 } 15277 15278 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15279 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15280 sendResourcesChangedBroadcast(mediaStatus, replacing, 15281 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15282 } 15283 15284 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15285 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15286 int size = pkgList.length; 15287 if (size > 0) { 15288 // Send broadcasts here 15289 Bundle extras = new Bundle(); 15290 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15291 if (uidArr != null) { 15292 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15293 } 15294 if (replacing) { 15295 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15296 } 15297 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15298 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15299 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15300 } 15301 } 15302 15303 /* 15304 * Look at potentially valid container ids from processCids If package 15305 * information doesn't match the one on record or package scanning fails, 15306 * the cid is added to list of removeCids. We currently don't delete stale 15307 * containers. 15308 */ 15309 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15310 ArrayList<String> pkgList = new ArrayList<String>(); 15311 Set<AsecInstallArgs> keys = processCids.keySet(); 15312 15313 for (AsecInstallArgs args : keys) { 15314 String codePath = processCids.get(args); 15315 if (DEBUG_SD_INSTALL) 15316 Log.i(TAG, "Loading container : " + args.cid); 15317 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15318 try { 15319 // Make sure there are no container errors first. 15320 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15321 Slog.e(TAG, "Failed to mount cid : " + args.cid 15322 + " when installing from sdcard"); 15323 continue; 15324 } 15325 // Check code path here. 15326 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15327 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15328 + " does not match one in settings " + codePath); 15329 continue; 15330 } 15331 // Parse package 15332 int parseFlags = mDefParseFlags; 15333 if (args.isExternalAsec()) { 15334 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15335 } 15336 if (args.isFwdLocked()) { 15337 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15338 } 15339 15340 synchronized (mInstallLock) { 15341 PackageParser.Package pkg = null; 15342 try { 15343 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15344 } catch (PackageManagerException e) { 15345 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15346 } 15347 // Scan the package 15348 if (pkg != null) { 15349 /* 15350 * TODO why is the lock being held? doPostInstall is 15351 * called in other places without the lock. This needs 15352 * to be straightened out. 15353 */ 15354 // writer 15355 synchronized (mPackages) { 15356 retCode = PackageManager.INSTALL_SUCCEEDED; 15357 pkgList.add(pkg.packageName); 15358 // Post process args 15359 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15360 pkg.applicationInfo.uid); 15361 } 15362 } else { 15363 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15364 } 15365 } 15366 15367 } finally { 15368 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15369 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15370 } 15371 } 15372 } 15373 // writer 15374 synchronized (mPackages) { 15375 // If the platform SDK has changed since the last time we booted, 15376 // we need to re-grant app permission to catch any new ones that 15377 // appear. This is really a hack, and means that apps can in some 15378 // cases get permissions that the user didn't initially explicitly 15379 // allow... it would be nice to have some better way to handle 15380 // this situation. 15381 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15382 if (regrantPermissions) 15383 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15384 + mSdkVersion + "; regranting permissions for external storage"); 15385 mSettings.mExternalSdkPlatform = mSdkVersion; 15386 15387 // Make sure group IDs have been assigned, and any permission 15388 // changes in other apps are accounted for 15389 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15390 | (regrantPermissions 15391 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15392 : 0)); 15393 15394 mSettings.updateExternalDatabaseVersion(); 15395 15396 // can downgrade to reader 15397 // Persist settings 15398 mSettings.writeLPr(); 15399 } 15400 // Send a broadcast to let everyone know we are done processing 15401 if (pkgList.size() > 0) { 15402 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15403 } 15404 } 15405 15406 /* 15407 * Utility method to unload a list of specified containers 15408 */ 15409 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15410 // Just unmount all valid containers. 15411 for (AsecInstallArgs arg : cidArgs) { 15412 synchronized (mInstallLock) { 15413 arg.doPostDeleteLI(false); 15414 } 15415 } 15416 } 15417 15418 /* 15419 * Unload packages mounted on external media. This involves deleting package 15420 * data from internal structures, sending broadcasts about diabled packages, 15421 * gc'ing to free up references, unmounting all secure containers 15422 * corresponding to packages on external media, and posting a 15423 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15424 * that we always have to post this message if status has been requested no 15425 * matter what. 15426 */ 15427 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15428 final boolean reportStatus) { 15429 if (DEBUG_SD_INSTALL) 15430 Log.i(TAG, "unloading media packages"); 15431 ArrayList<String> pkgList = new ArrayList<String>(); 15432 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15433 final Set<AsecInstallArgs> keys = processCids.keySet(); 15434 for (AsecInstallArgs args : keys) { 15435 String pkgName = args.getPackageName(); 15436 if (DEBUG_SD_INSTALL) 15437 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15438 // Delete package internally 15439 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15440 synchronized (mInstallLock) { 15441 boolean res = deletePackageLI(pkgName, null, false, null, null, 15442 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15443 if (res) { 15444 pkgList.add(pkgName); 15445 } else { 15446 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15447 failedList.add(args); 15448 } 15449 } 15450 } 15451 15452 // reader 15453 synchronized (mPackages) { 15454 // We didn't update the settings after removing each package; 15455 // write them now for all packages. 15456 mSettings.writeLPr(); 15457 } 15458 15459 // We have to absolutely send UPDATED_MEDIA_STATUS only 15460 // after confirming that all the receivers processed the ordered 15461 // broadcast when packages get disabled, force a gc to clean things up. 15462 // and unload all the containers. 15463 if (pkgList.size() > 0) { 15464 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15465 new IIntentReceiver.Stub() { 15466 public void performReceive(Intent intent, int resultCode, String data, 15467 Bundle extras, boolean ordered, boolean sticky, 15468 int sendingUser) throws RemoteException { 15469 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15470 reportStatus ? 1 : 0, 1, keys); 15471 mHandler.sendMessage(msg); 15472 } 15473 }); 15474 } else { 15475 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15476 keys); 15477 mHandler.sendMessage(msg); 15478 } 15479 } 15480 15481 private void loadPrivatePackages(VolumeInfo vol) { 15482 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15483 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15484 synchronized (mInstallLock) { 15485 synchronized (mPackages) { 15486 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15487 for (PackageSetting ps : packages) { 15488 final PackageParser.Package pkg; 15489 try { 15490 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15491 loaded.add(pkg.applicationInfo); 15492 } catch (PackageManagerException e) { 15493 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15494 } 15495 } 15496 15497 // TODO: regrant any permissions that changed based since original install 15498 15499 mSettings.writeLPr(); 15500 } 15501 } 15502 15503 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15504 sendResourcesChangedBroadcast(true, false, loaded, null); 15505 } 15506 15507 private void unloadPrivatePackages(VolumeInfo vol) { 15508 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15509 synchronized (mInstallLock) { 15510 synchronized (mPackages) { 15511 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15512 for (PackageSetting ps : packages) { 15513 if (ps.pkg == null) continue; 15514 15515 final ApplicationInfo info = ps.pkg.applicationInfo; 15516 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15517 if (deletePackageLI(ps.name, null, false, null, null, 15518 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15519 unloaded.add(info); 15520 } else { 15521 Slog.w(TAG, "Failed to unload " + ps.codePath); 15522 } 15523 } 15524 15525 mSettings.writeLPr(); 15526 } 15527 } 15528 15529 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15530 sendResourcesChangedBroadcast(false, false, unloaded, null); 15531 } 15532 15533 /** 15534 * Examine all users present on given mounted volume, and destroy data 15535 * belonging to users that are no longer valid, or whose user ID has been 15536 * recycled. 15537 */ 15538 private void reconcileUsers(String volumeUuid) { 15539 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15540 if (ArrayUtils.isEmpty(files)) { 15541 Slog.d(TAG, "No users found on " + volumeUuid); 15542 return; 15543 } 15544 15545 for (File file : files) { 15546 if (!file.isDirectory()) continue; 15547 15548 final int userId; 15549 final UserInfo info; 15550 try { 15551 userId = Integer.parseInt(file.getName()); 15552 info = sUserManager.getUserInfo(userId); 15553 } catch (NumberFormatException e) { 15554 Slog.w(TAG, "Invalid user directory " + file); 15555 continue; 15556 } 15557 15558 boolean destroyUser = false; 15559 if (info == null) { 15560 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15561 + " because no matching user was found"); 15562 destroyUser = true; 15563 } else { 15564 try { 15565 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15566 } catch (IOException e) { 15567 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15568 + " because we failed to enforce serial number: " + e); 15569 destroyUser = true; 15570 } 15571 } 15572 15573 if (destroyUser) { 15574 synchronized (mInstallLock) { 15575 mInstaller.removeUserDataDirs(volumeUuid, userId); 15576 } 15577 } 15578 } 15579 15580 final UserManager um = mContext.getSystemService(UserManager.class); 15581 for (UserInfo user : um.getUsers()) { 15582 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15583 if (userDir.exists()) continue; 15584 15585 try { 15586 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15587 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15588 } catch (IOException e) { 15589 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15590 } 15591 } 15592 } 15593 15594 /** 15595 * Examine all apps present on given mounted volume, and destroy apps that 15596 * aren't expected, either due to uninstallation or reinstallation on 15597 * another volume. 15598 */ 15599 private void reconcileApps(String volumeUuid) { 15600 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15601 if (ArrayUtils.isEmpty(files)) { 15602 Slog.d(TAG, "No apps found on " + volumeUuid); 15603 return; 15604 } 15605 15606 for (File file : files) { 15607 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15608 && !PackageInstallerService.isStageName(file.getName()); 15609 if (!isPackage) { 15610 // Ignore entries which are not packages 15611 continue; 15612 } 15613 15614 boolean destroyApp = false; 15615 String packageName = null; 15616 try { 15617 final PackageLite pkg = PackageParser.parsePackageLite(file, 15618 PackageParser.PARSE_MUST_BE_APK); 15619 packageName = pkg.packageName; 15620 15621 synchronized (mPackages) { 15622 final PackageSetting ps = mSettings.mPackages.get(packageName); 15623 if (ps == null) { 15624 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15625 + volumeUuid + " because we found no install record"); 15626 destroyApp = true; 15627 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15628 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15629 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15630 destroyApp = true; 15631 } 15632 } 15633 15634 } catch (PackageParserException e) { 15635 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15636 destroyApp = true; 15637 } 15638 15639 if (destroyApp) { 15640 synchronized (mInstallLock) { 15641 if (packageName != null) { 15642 removeDataDirsLI(volumeUuid, packageName); 15643 } 15644 if (file.isDirectory()) { 15645 mInstaller.rmPackageDir(file.getAbsolutePath()); 15646 } else { 15647 file.delete(); 15648 } 15649 } 15650 } 15651 } 15652 } 15653 15654 private void unfreezePackage(String packageName) { 15655 synchronized (mPackages) { 15656 final PackageSetting ps = mSettings.mPackages.get(packageName); 15657 if (ps != null) { 15658 ps.frozen = false; 15659 } 15660 } 15661 } 15662 15663 @Override 15664 public int movePackage(final String packageName, final String volumeUuid) { 15665 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15666 15667 final int moveId = mNextMoveId.getAndIncrement(); 15668 try { 15669 movePackageInternal(packageName, volumeUuid, moveId); 15670 } catch (PackageManagerException e) { 15671 Slog.w(TAG, "Failed to move " + packageName, e); 15672 mMoveCallbacks.notifyStatusChanged(moveId, 15673 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15674 } 15675 return moveId; 15676 } 15677 15678 private void movePackageInternal(final String packageName, final String volumeUuid, 15679 final int moveId) throws PackageManagerException { 15680 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15681 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15682 final PackageManager pm = mContext.getPackageManager(); 15683 15684 final boolean currentAsec; 15685 final String currentVolumeUuid; 15686 final File codeFile; 15687 final String installerPackageName; 15688 final String packageAbiOverride; 15689 final int appId; 15690 final String seinfo; 15691 final String label; 15692 15693 // reader 15694 synchronized (mPackages) { 15695 final PackageParser.Package pkg = mPackages.get(packageName); 15696 final PackageSetting ps = mSettings.mPackages.get(packageName); 15697 if (pkg == null || ps == null) { 15698 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15699 } 15700 15701 if (pkg.applicationInfo.isSystemApp()) { 15702 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15703 "Cannot move system application"); 15704 } 15705 15706 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15707 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15708 "Package already moved to " + volumeUuid); 15709 } 15710 15711 final File probe = new File(pkg.codePath); 15712 final File probeOat = new File(probe, "oat"); 15713 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15714 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15715 "Move only supported for modern cluster style installs"); 15716 } 15717 15718 if (ps.frozen) { 15719 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15720 "Failed to move already frozen package"); 15721 } 15722 ps.frozen = true; 15723 15724 currentAsec = pkg.applicationInfo.isForwardLocked() 15725 || pkg.applicationInfo.isExternalAsec(); 15726 currentVolumeUuid = ps.volumeUuid; 15727 codeFile = new File(pkg.codePath); 15728 installerPackageName = ps.installerPackageName; 15729 packageAbiOverride = ps.cpuAbiOverrideString; 15730 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15731 seinfo = pkg.applicationInfo.seinfo; 15732 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15733 } 15734 15735 // Now that we're guarded by frozen state, kill app during move 15736 killApplication(packageName, appId, "move pkg"); 15737 15738 final Bundle extras = new Bundle(); 15739 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15740 extras.putString(Intent.EXTRA_TITLE, label); 15741 mMoveCallbacks.notifyCreated(moveId, extras); 15742 15743 int installFlags; 15744 final boolean moveCompleteApp; 15745 final File measurePath; 15746 15747 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15748 installFlags = INSTALL_INTERNAL; 15749 moveCompleteApp = !currentAsec; 15750 measurePath = Environment.getDataAppDirectory(volumeUuid); 15751 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15752 installFlags = INSTALL_EXTERNAL; 15753 moveCompleteApp = false; 15754 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15755 } else { 15756 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15757 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15758 || !volume.isMountedWritable()) { 15759 unfreezePackage(packageName); 15760 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15761 "Move location not mounted private volume"); 15762 } 15763 15764 Preconditions.checkState(!currentAsec); 15765 15766 installFlags = INSTALL_INTERNAL; 15767 moveCompleteApp = true; 15768 measurePath = Environment.getDataAppDirectory(volumeUuid); 15769 } 15770 15771 final PackageStats stats = new PackageStats(null, -1); 15772 synchronized (mInstaller) { 15773 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15774 unfreezePackage(packageName); 15775 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15776 "Failed to measure package size"); 15777 } 15778 } 15779 15780 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15781 + stats.dataSize); 15782 15783 final long startFreeBytes = measurePath.getFreeSpace(); 15784 final long sizeBytes; 15785 if (moveCompleteApp) { 15786 sizeBytes = stats.codeSize + stats.dataSize; 15787 } else { 15788 sizeBytes = stats.codeSize; 15789 } 15790 15791 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15792 unfreezePackage(packageName); 15793 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15794 "Not enough free space to move"); 15795 } 15796 15797 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15798 15799 final CountDownLatch installedLatch = new CountDownLatch(1); 15800 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15801 @Override 15802 public void onUserActionRequired(Intent intent) throws RemoteException { 15803 throw new IllegalStateException(); 15804 } 15805 15806 @Override 15807 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15808 Bundle extras) throws RemoteException { 15809 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15810 + PackageManager.installStatusToString(returnCode, msg)); 15811 15812 installedLatch.countDown(); 15813 15814 // Regardless of success or failure of the move operation, 15815 // always unfreeze the package 15816 unfreezePackage(packageName); 15817 15818 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15819 switch (status) { 15820 case PackageInstaller.STATUS_SUCCESS: 15821 mMoveCallbacks.notifyStatusChanged(moveId, 15822 PackageManager.MOVE_SUCCEEDED); 15823 break; 15824 case PackageInstaller.STATUS_FAILURE_STORAGE: 15825 mMoveCallbacks.notifyStatusChanged(moveId, 15826 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15827 break; 15828 default: 15829 mMoveCallbacks.notifyStatusChanged(moveId, 15830 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15831 break; 15832 } 15833 } 15834 }; 15835 15836 final MoveInfo move; 15837 if (moveCompleteApp) { 15838 // Kick off a thread to report progress estimates 15839 new Thread() { 15840 @Override 15841 public void run() { 15842 while (true) { 15843 try { 15844 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15845 break; 15846 } 15847 } catch (InterruptedException ignored) { 15848 } 15849 15850 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15851 final int progress = 10 + (int) MathUtils.constrain( 15852 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15853 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15854 } 15855 } 15856 }.start(); 15857 15858 final String dataAppName = codeFile.getName(); 15859 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15860 dataAppName, appId, seinfo); 15861 } else { 15862 move = null; 15863 } 15864 15865 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15866 15867 final Message msg = mHandler.obtainMessage(INIT_COPY); 15868 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15869 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15870 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15871 mHandler.sendMessage(msg); 15872 } 15873 15874 @Override 15875 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15876 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15877 15878 final int realMoveId = mNextMoveId.getAndIncrement(); 15879 final Bundle extras = new Bundle(); 15880 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15881 mMoveCallbacks.notifyCreated(realMoveId, extras); 15882 15883 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15884 @Override 15885 public void onCreated(int moveId, Bundle extras) { 15886 // Ignored 15887 } 15888 15889 @Override 15890 public void onStatusChanged(int moveId, int status, long estMillis) { 15891 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15892 } 15893 }; 15894 15895 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15896 storage.setPrimaryStorageUuid(volumeUuid, callback); 15897 return realMoveId; 15898 } 15899 15900 @Override 15901 public int getMoveStatus(int moveId) { 15902 mContext.enforceCallingOrSelfPermission( 15903 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15904 return mMoveCallbacks.mLastStatus.get(moveId); 15905 } 15906 15907 @Override 15908 public void registerMoveCallback(IPackageMoveObserver callback) { 15909 mContext.enforceCallingOrSelfPermission( 15910 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15911 mMoveCallbacks.register(callback); 15912 } 15913 15914 @Override 15915 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15916 mContext.enforceCallingOrSelfPermission( 15917 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15918 mMoveCallbacks.unregister(callback); 15919 } 15920 15921 @Override 15922 public boolean setInstallLocation(int loc) { 15923 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15924 null); 15925 if (getInstallLocation() == loc) { 15926 return true; 15927 } 15928 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15929 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15930 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15931 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15932 return true; 15933 } 15934 return false; 15935 } 15936 15937 @Override 15938 public int getInstallLocation() { 15939 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15940 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15941 PackageHelper.APP_INSTALL_AUTO); 15942 } 15943 15944 /** Called by UserManagerService */ 15945 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15946 mDirtyUsers.remove(userHandle); 15947 mSettings.removeUserLPw(userHandle); 15948 mPendingBroadcasts.remove(userHandle); 15949 if (mInstaller != null) { 15950 // Technically, we shouldn't be doing this with the package lock 15951 // held. However, this is very rare, and there is already so much 15952 // other disk I/O going on, that we'll let it slide for now. 15953 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15954 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15955 final String volumeUuid = vol.getFsUuid(); 15956 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15957 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15958 } 15959 } 15960 mUserNeedsBadging.delete(userHandle); 15961 removeUnusedPackagesLILPw(userManager, userHandle); 15962 } 15963 15964 /** 15965 * We're removing userHandle and would like to remove any downloaded packages 15966 * that are no longer in use by any other user. 15967 * @param userHandle the user being removed 15968 */ 15969 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15970 final boolean DEBUG_CLEAN_APKS = false; 15971 int [] users = userManager.getUserIdsLPr(); 15972 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15973 while (psit.hasNext()) { 15974 PackageSetting ps = psit.next(); 15975 if (ps.pkg == null) { 15976 continue; 15977 } 15978 final String packageName = ps.pkg.packageName; 15979 // Skip over if system app 15980 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15981 continue; 15982 } 15983 if (DEBUG_CLEAN_APKS) { 15984 Slog.i(TAG, "Checking package " + packageName); 15985 } 15986 boolean keep = false; 15987 for (int i = 0; i < users.length; i++) { 15988 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15989 keep = true; 15990 if (DEBUG_CLEAN_APKS) { 15991 Slog.i(TAG, " Keeping package " + packageName + " for user " 15992 + users[i]); 15993 } 15994 break; 15995 } 15996 } 15997 if (!keep) { 15998 if (DEBUG_CLEAN_APKS) { 15999 Slog.i(TAG, " Removing package " + packageName); 16000 } 16001 mHandler.post(new Runnable() { 16002 public void run() { 16003 deletePackageX(packageName, userHandle, 0); 16004 } //end run 16005 }); 16006 } 16007 } 16008 } 16009 16010 /** Called by UserManagerService */ 16011 void createNewUserLILPw(int userHandle) { 16012 if (mInstaller != null) { 16013 mInstaller.createUserConfig(userHandle); 16014 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 16015 applyFactoryDefaultBrowserLPw(userHandle); 16016 primeDomainVerificationsLPw(userHandle); 16017 } 16018 } 16019 16020 void newUserCreated(final int userHandle) { 16021 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 16022 } 16023 16024 @Override 16025 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 16026 mContext.enforceCallingOrSelfPermission( 16027 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 16028 "Only package verification agents can read the verifier device identity"); 16029 16030 synchronized (mPackages) { 16031 return mSettings.getVerifierDeviceIdentityLPw(); 16032 } 16033 } 16034 16035 @Override 16036 public void setPermissionEnforced(String permission, boolean enforced) { 16037 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 16038 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16039 synchronized (mPackages) { 16040 if (mSettings.mReadExternalStorageEnforced == null 16041 || mSettings.mReadExternalStorageEnforced != enforced) { 16042 mSettings.mReadExternalStorageEnforced = enforced; 16043 mSettings.writeLPr(); 16044 } 16045 } 16046 // kill any non-foreground processes so we restart them and 16047 // grant/revoke the GID. 16048 final IActivityManager am = ActivityManagerNative.getDefault(); 16049 if (am != null) { 16050 final long token = Binder.clearCallingIdentity(); 16051 try { 16052 am.killProcessesBelowForeground("setPermissionEnforcement"); 16053 } catch (RemoteException e) { 16054 } finally { 16055 Binder.restoreCallingIdentity(token); 16056 } 16057 } 16058 } else { 16059 throw new IllegalArgumentException("No selective enforcement for " + permission); 16060 } 16061 } 16062 16063 @Override 16064 @Deprecated 16065 public boolean isPermissionEnforced(String permission) { 16066 return true; 16067 } 16068 16069 @Override 16070 public boolean isStorageLow() { 16071 final long token = Binder.clearCallingIdentity(); 16072 try { 16073 final DeviceStorageMonitorInternal 16074 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16075 if (dsm != null) { 16076 return dsm.isMemoryLow(); 16077 } else { 16078 return false; 16079 } 16080 } finally { 16081 Binder.restoreCallingIdentity(token); 16082 } 16083 } 16084 16085 @Override 16086 public IPackageInstaller getPackageInstaller() { 16087 return mInstallerService; 16088 } 16089 16090 private boolean userNeedsBadging(int userId) { 16091 int index = mUserNeedsBadging.indexOfKey(userId); 16092 if (index < 0) { 16093 final UserInfo userInfo; 16094 final long token = Binder.clearCallingIdentity(); 16095 try { 16096 userInfo = sUserManager.getUserInfo(userId); 16097 } finally { 16098 Binder.restoreCallingIdentity(token); 16099 } 16100 final boolean b; 16101 if (userInfo != null && userInfo.isManagedProfile()) { 16102 b = true; 16103 } else { 16104 b = false; 16105 } 16106 mUserNeedsBadging.put(userId, b); 16107 return b; 16108 } 16109 return mUserNeedsBadging.valueAt(index); 16110 } 16111 16112 @Override 16113 public KeySet getKeySetByAlias(String packageName, String alias) { 16114 if (packageName == null || alias == null) { 16115 return null; 16116 } 16117 synchronized(mPackages) { 16118 final PackageParser.Package pkg = mPackages.get(packageName); 16119 if (pkg == null) { 16120 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16121 throw new IllegalArgumentException("Unknown package: " + packageName); 16122 } 16123 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16124 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16125 } 16126 } 16127 16128 @Override 16129 public KeySet getSigningKeySet(String packageName) { 16130 if (packageName == null) { 16131 return null; 16132 } 16133 synchronized(mPackages) { 16134 final PackageParser.Package pkg = mPackages.get(packageName); 16135 if (pkg == null) { 16136 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16137 throw new IllegalArgumentException("Unknown package: " + packageName); 16138 } 16139 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16140 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16141 throw new SecurityException("May not access signing KeySet of other apps."); 16142 } 16143 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16144 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16145 } 16146 } 16147 16148 @Override 16149 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16150 if (packageName == null || ks == null) { 16151 return false; 16152 } 16153 synchronized(mPackages) { 16154 final PackageParser.Package pkg = mPackages.get(packageName); 16155 if (pkg == null) { 16156 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16157 throw new IllegalArgumentException("Unknown package: " + packageName); 16158 } 16159 IBinder ksh = ks.getToken(); 16160 if (ksh instanceof KeySetHandle) { 16161 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16162 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16163 } 16164 return false; 16165 } 16166 } 16167 16168 @Override 16169 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16170 if (packageName == null || ks == null) { 16171 return false; 16172 } 16173 synchronized(mPackages) { 16174 final PackageParser.Package pkg = mPackages.get(packageName); 16175 if (pkg == null) { 16176 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16177 throw new IllegalArgumentException("Unknown package: " + packageName); 16178 } 16179 IBinder ksh = ks.getToken(); 16180 if (ksh instanceof KeySetHandle) { 16181 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16182 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16183 } 16184 return false; 16185 } 16186 } 16187 16188 public void getUsageStatsIfNoPackageUsageInfo() { 16189 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16190 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16191 if (usm == null) { 16192 throw new IllegalStateException("UsageStatsManager must be initialized"); 16193 } 16194 long now = System.currentTimeMillis(); 16195 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16196 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16197 String packageName = entry.getKey(); 16198 PackageParser.Package pkg = mPackages.get(packageName); 16199 if (pkg == null) { 16200 continue; 16201 } 16202 UsageStats usage = entry.getValue(); 16203 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16204 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16205 } 16206 } 16207 } 16208 16209 /** 16210 * Check and throw if the given before/after packages would be considered a 16211 * downgrade. 16212 */ 16213 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16214 throws PackageManagerException { 16215 if (after.versionCode < before.mVersionCode) { 16216 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16217 "Update version code " + after.versionCode + " is older than current " 16218 + before.mVersionCode); 16219 } else if (after.versionCode == before.mVersionCode) { 16220 if (after.baseRevisionCode < before.baseRevisionCode) { 16221 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16222 "Update base revision code " + after.baseRevisionCode 16223 + " is older than current " + before.baseRevisionCode); 16224 } 16225 16226 if (!ArrayUtils.isEmpty(after.splitNames)) { 16227 for (int i = 0; i < after.splitNames.length; i++) { 16228 final String splitName = after.splitNames[i]; 16229 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16230 if (j != -1) { 16231 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16232 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16233 "Update split " + splitName + " revision code " 16234 + after.splitRevisionCodes[i] + " is older than current " 16235 + before.splitRevisionCodes[j]); 16236 } 16237 } 16238 } 16239 } 16240 } 16241 } 16242 16243 private static class MoveCallbacks extends Handler { 16244 private static final int MSG_CREATED = 1; 16245 private static final int MSG_STATUS_CHANGED = 2; 16246 16247 private final RemoteCallbackList<IPackageMoveObserver> 16248 mCallbacks = new RemoteCallbackList<>(); 16249 16250 private final SparseIntArray mLastStatus = new SparseIntArray(); 16251 16252 public MoveCallbacks(Looper looper) { 16253 super(looper); 16254 } 16255 16256 public void register(IPackageMoveObserver callback) { 16257 mCallbacks.register(callback); 16258 } 16259 16260 public void unregister(IPackageMoveObserver callback) { 16261 mCallbacks.unregister(callback); 16262 } 16263 16264 @Override 16265 public void handleMessage(Message msg) { 16266 final SomeArgs args = (SomeArgs) msg.obj; 16267 final int n = mCallbacks.beginBroadcast(); 16268 for (int i = 0; i < n; i++) { 16269 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16270 try { 16271 invokeCallback(callback, msg.what, args); 16272 } catch (RemoteException ignored) { 16273 } 16274 } 16275 mCallbacks.finishBroadcast(); 16276 args.recycle(); 16277 } 16278 16279 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16280 throws RemoteException { 16281 switch (what) { 16282 case MSG_CREATED: { 16283 callback.onCreated(args.argi1, (Bundle) args.arg2); 16284 break; 16285 } 16286 case MSG_STATUS_CHANGED: { 16287 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16288 break; 16289 } 16290 } 16291 } 16292 16293 private void notifyCreated(int moveId, Bundle extras) { 16294 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16295 16296 final SomeArgs args = SomeArgs.obtain(); 16297 args.argi1 = moveId; 16298 args.arg2 = extras; 16299 obtainMessage(MSG_CREATED, args).sendToTarget(); 16300 } 16301 16302 private void notifyStatusChanged(int moveId, int status) { 16303 notifyStatusChanged(moveId, status, -1); 16304 } 16305 16306 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16307 Slog.v(TAG, "Move " + moveId + " status " + status); 16308 16309 final SomeArgs args = SomeArgs.obtain(); 16310 args.argi1 = moveId; 16311 args.argi2 = status; 16312 args.arg3 = estMillis; 16313 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16314 16315 synchronized (mLastStatus) { 16316 mLastStatus.put(moveId, status); 16317 } 16318 } 16319 } 16320 16321 private final class OnPermissionChangeListeners extends Handler { 16322 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16323 16324 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16325 new RemoteCallbackList<>(); 16326 16327 public OnPermissionChangeListeners(Looper looper) { 16328 super(looper); 16329 } 16330 16331 @Override 16332 public void handleMessage(Message msg) { 16333 switch (msg.what) { 16334 case MSG_ON_PERMISSIONS_CHANGED: { 16335 final int uid = msg.arg1; 16336 handleOnPermissionsChanged(uid); 16337 } break; 16338 } 16339 } 16340 16341 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16342 mPermissionListeners.register(listener); 16343 16344 } 16345 16346 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16347 mPermissionListeners.unregister(listener); 16348 } 16349 16350 public void onPermissionsChanged(int uid) { 16351 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16352 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16353 } 16354 } 16355 16356 private void handleOnPermissionsChanged(int uid) { 16357 final int count = mPermissionListeners.beginBroadcast(); 16358 try { 16359 for (int i = 0; i < count; i++) { 16360 IOnPermissionsChangeListener callback = mPermissionListeners 16361 .getBroadcastItem(i); 16362 try { 16363 callback.onPermissionsChanged(uid); 16364 } catch (RemoteException e) { 16365 Log.e(TAG, "Permission listener is dead", e); 16366 } 16367 } 16368 } finally { 16369 mPermissionListeners.finishBroadcast(); 16370 } 16371 } 16372 } 16373 16374 private class PackageManagerInternalImpl extends PackageManagerInternal { 16375 @Override 16376 public void setLocationPackagesProvider(PackagesProvider provider) { 16377 synchronized (mPackages) { 16378 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16379 } 16380 } 16381 16382 @Override 16383 public void setImePackagesProvider(PackagesProvider provider) { 16384 synchronized (mPackages) { 16385 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16386 } 16387 } 16388 16389 @Override 16390 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16391 synchronized (mPackages) { 16392 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16393 } 16394 } 16395 16396 @Override 16397 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16398 synchronized (mPackages) { 16399 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16400 } 16401 } 16402 16403 @Override 16404 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16405 synchronized (mPackages) { 16406 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16407 } 16408 } 16409 16410 @Override 16411 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16412 synchronized (mPackages) { 16413 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 16414 } 16415 } 16416 16417 @Override 16418 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16419 synchronized (mPackages) { 16420 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16421 packageName, userId); 16422 } 16423 } 16424 16425 @Override 16426 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16427 synchronized (mPackages) { 16428 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16429 packageName, userId); 16430 } 16431 } 16432 } 16433 16434 @Override 16435 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16436 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16437 synchronized (mPackages) { 16438 final long identity = Binder.clearCallingIdentity(); 16439 try { 16440 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16441 packageNames, userId); 16442 } finally { 16443 Binder.restoreCallingIdentity(identity); 16444 } 16445 } 16446 } 16447 16448 private static void enforceSystemOrPhoneCaller(String tag) { 16449 int callingUid = Binder.getCallingUid(); 16450 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16451 throw new SecurityException( 16452 "Cannot call " + tag + " from UID " + callingUid); 16453 } 16454 } 16455} 16456