PackageManagerService.java revision 4fd798768245f07064a1001a594fa2f4558efb9e
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_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Binder; 147import android.os.Build; 148import android.os.Bundle; 149import android.os.Environment; 150import android.os.Environment.UserEnvironment; 151import android.os.FileUtils; 152import android.os.Handler; 153import android.os.IBinder; 154import android.os.Looper; 155import android.os.Message; 156import android.os.Parcel; 157import android.os.ParcelFileDescriptor; 158import android.os.Process; 159import android.os.RemoteCallbackList; 160import android.os.RemoteException; 161import android.os.SELinux; 162import android.os.ServiceManager; 163import android.os.SystemClock; 164import android.os.SystemProperties; 165import android.os.UserHandle; 166import android.os.UserManager; 167import android.os.storage.IMountService; 168import android.os.storage.StorageEventListener; 169import android.os.storage.StorageManager; 170import android.os.storage.VolumeInfo; 171import android.os.storage.VolumeRecord; 172import android.security.KeyStore; 173import android.security.SystemKeyStore; 174import android.system.ErrnoException; 175import android.system.Os; 176import android.system.StructStat; 177import android.text.TextUtils; 178import android.text.format.DateUtils; 179import android.util.ArrayMap; 180import android.util.ArraySet; 181import android.util.AtomicFile; 182import android.util.DisplayMetrics; 183import android.util.EventLog; 184import android.util.ExceptionUtils; 185import android.util.Log; 186import android.util.LogPrinter; 187import android.util.MathUtils; 188import android.util.PrintStreamPrinter; 189import android.util.Slog; 190import android.util.SparseArray; 191import android.util.SparseBooleanArray; 192import android.util.SparseIntArray; 193import android.util.Xml; 194import android.view.Display; 195 196import dalvik.system.DexFile; 197import dalvik.system.VMRuntime; 198 199import libcore.io.IoUtils; 200import libcore.util.EmptyArray; 201 202import com.android.internal.R; 203import com.android.internal.annotations.GuardedBy; 204import com.android.internal.app.IMediaContainerService; 205import com.android.internal.app.ResolverActivity; 206import com.android.internal.content.NativeLibraryHelper; 207import com.android.internal.content.PackageHelper; 208import com.android.internal.os.IParcelFileDescriptorFactory; 209import com.android.internal.os.SomeArgs; 210import com.android.internal.os.Zygote; 211import com.android.internal.util.ArrayUtils; 212import com.android.internal.util.FastPrintWriter; 213import com.android.internal.util.FastXmlSerializer; 214import com.android.internal.util.IndentingPrintWriter; 215import com.android.internal.util.Preconditions; 216import com.android.server.EventLogTags; 217import com.android.server.FgThread; 218import com.android.server.IntentResolver; 219import com.android.server.LocalServices; 220import com.android.server.ServiceThread; 221import com.android.server.SystemConfig; 222import com.android.server.Watchdog; 223import com.android.server.pm.PermissionsState.PermissionState; 224import com.android.server.pm.Settings.DatabaseVersion; 225import com.android.server.storage.DeviceStorageMonitorInternal; 226 227import org.xmlpull.v1.XmlPullParser; 228import org.xmlpull.v1.XmlPullParserException; 229import org.xmlpull.v1.XmlSerializer; 230 231import java.io.BufferedInputStream; 232import java.io.BufferedOutputStream; 233import java.io.BufferedReader; 234import java.io.ByteArrayInputStream; 235import java.io.ByteArrayOutputStream; 236import java.io.File; 237import java.io.FileDescriptor; 238import java.io.FileNotFoundException; 239import java.io.FileOutputStream; 240import java.io.FileReader; 241import java.io.FilenameFilter; 242import java.io.IOException; 243import java.io.InputStream; 244import java.io.PrintWriter; 245import java.nio.charset.StandardCharsets; 246import java.security.NoSuchAlgorithmException; 247import java.security.PublicKey; 248import java.security.cert.CertificateEncodingException; 249import java.security.cert.CertificateException; 250import java.text.SimpleDateFormat; 251import java.util.ArrayList; 252import java.util.Arrays; 253import java.util.Collection; 254import java.util.Collections; 255import java.util.Comparator; 256import java.util.Date; 257import java.util.Iterator; 258import java.util.List; 259import java.util.Map; 260import java.util.Objects; 261import java.util.Set; 262import java.util.concurrent.CountDownLatch; 263import java.util.concurrent.TimeUnit; 264import java.util.concurrent.atomic.AtomicBoolean; 265import java.util.concurrent.atomic.AtomicInteger; 266import java.util.concurrent.atomic.AtomicLong; 267 268/** 269 * Keep track of all those .apks everywhere. 270 * 271 * This is very central to the platform's security; please run the unit 272 * tests whenever making modifications here: 273 * 274runtest -c android.content.pm.PackageManagerTests frameworks-core 275 * 276 * {@hide} 277 */ 278public class PackageManagerService extends IPackageManager.Stub { 279 static final String TAG = "PackageManager"; 280 static final boolean DEBUG_SETTINGS = false; 281 static final boolean DEBUG_PREFERRED = false; 282 static final boolean DEBUG_UPGRADE = false; 283 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 284 private static final boolean DEBUG_BACKUP = false; 285 private static final boolean DEBUG_INSTALL = false; 286 private static final boolean DEBUG_REMOVE = false; 287 private static final boolean DEBUG_BROADCASTS = false; 288 private static final boolean DEBUG_SHOW_INFO = false; 289 private static final boolean DEBUG_PACKAGE_INFO = false; 290 private static final boolean DEBUG_INTENT_MATCHING = false; 291 private static final boolean DEBUG_PACKAGE_SCANNING = false; 292 private static final boolean DEBUG_VERIFY = false; 293 private static final boolean DEBUG_DEXOPT = false; 294 private static final boolean DEBUG_ABI_SELECTION = false; 295 296 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 297 298 private static final int RADIO_UID = Process.PHONE_UID; 299 private static final int LOG_UID = Process.LOG_UID; 300 private static final int NFC_UID = Process.NFC_UID; 301 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 302 private static final int SHELL_UID = Process.SHELL_UID; 303 304 // Cap the size of permission trees that 3rd party apps can define 305 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 306 307 // Suffix used during package installation when copying/moving 308 // package apks to install directory. 309 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 310 311 static final int SCAN_NO_DEX = 1<<1; 312 static final int SCAN_FORCE_DEX = 1<<2; 313 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 314 static final int SCAN_NEW_INSTALL = 1<<4; 315 static final int SCAN_NO_PATHS = 1<<5; 316 static final int SCAN_UPDATE_TIME = 1<<6; 317 static final int SCAN_DEFER_DEX = 1<<7; 318 static final int SCAN_BOOTING = 1<<8; 319 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 320 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 321 static final int SCAN_REQUIRE_KNOWN = 1<<12; 322 static final int SCAN_MOVE = 1<<13; 323 static final int SCAN_INITIAL = 1<<14; 324 325 static final int REMOVE_CHATTY = 1<<16; 326 327 private static final int[] EMPTY_INT_ARRAY = new int[0]; 328 329 /** 330 * Timeout (in milliseconds) after which the watchdog should declare that 331 * our handler thread is wedged. The usual default for such things is one 332 * minute but we sometimes do very lengthy I/O operations on this thread, 333 * such as installing multi-gigabyte applications, so ours needs to be longer. 334 */ 335 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 336 337 /** 338 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 339 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 340 * settings entry if available, otherwise we use the hardcoded default. If it's been 341 * more than this long since the last fstrim, we force one during the boot sequence. 342 * 343 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 344 * one gets run at the next available charging+idle time. This final mandatory 345 * no-fstrim check kicks in only of the other scheduling criteria is never met. 346 */ 347 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 348 349 /** 350 * Whether verification is enabled by default. 351 */ 352 private static final boolean DEFAULT_VERIFY_ENABLE = true; 353 354 /** 355 * The default maximum time to wait for the verification agent to return in 356 * milliseconds. 357 */ 358 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 359 360 /** 361 * The default response for package verification timeout. 362 * 363 * This can be either PackageManager.VERIFICATION_ALLOW or 364 * PackageManager.VERIFICATION_REJECT. 365 */ 366 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 367 368 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 369 370 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 371 DEFAULT_CONTAINER_PACKAGE, 372 "com.android.defcontainer.DefaultContainerService"); 373 374 private static final String KILL_APP_REASON_GIDS_CHANGED = 375 "permission grant or revoke changed gids"; 376 377 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 378 "permissions revoked"; 379 380 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 381 382 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 383 384 /** Permission grant: not grant the permission. */ 385 private static final int GRANT_DENIED = 1; 386 387 /** Permission grant: grant the permission as an install permission. */ 388 private static final int GRANT_INSTALL = 2; 389 390 /** Permission grant: grant the permission as an install permission for a legacy app. */ 391 private static final int GRANT_INSTALL_LEGACY = 3; 392 393 /** Permission grant: grant the permission as a runtime one. */ 394 private static final int GRANT_RUNTIME = 4; 395 396 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 397 private static final int GRANT_UPGRADE = 5; 398 399 /** Canonical intent used to identify what counts as a "web browser" app */ 400 private static final Intent sBrowserIntent; 401 static { 402 sBrowserIntent = new Intent(); 403 sBrowserIntent.setAction(Intent.ACTION_VIEW); 404 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 405 sBrowserIntent.setData(Uri.parse("http:")); 406 } 407 408 final ServiceThread mHandlerThread; 409 410 final PackageHandler mHandler; 411 412 /** 413 * Messages for {@link #mHandler} that need to wait for system ready before 414 * being dispatched. 415 */ 416 private ArrayList<Message> mPostSystemReadyMessages; 417 418 final int mSdkVersion = Build.VERSION.SDK_INT; 419 420 final Context mContext; 421 final boolean mFactoryTest; 422 final boolean mOnlyCore; 423 final boolean mLazyDexOpt; 424 final long mDexOptLRUThresholdInMills; 425 final DisplayMetrics mMetrics; 426 final int mDefParseFlags; 427 final String[] mSeparateProcesses; 428 final boolean mIsUpgrade; 429 430 // This is where all application persistent data goes. 431 final File mAppDataDir; 432 433 // This is where all application persistent data goes for secondary users. 434 final File mUserAppDataDir; 435 436 /** The location for ASEC container files on internal storage. */ 437 final String mAsecInternalPath; 438 439 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 440 // LOCK HELD. Can be called with mInstallLock held. 441 @GuardedBy("mInstallLock") 442 final Installer mInstaller; 443 444 /** Directory where installed third-party apps stored */ 445 final File mAppInstallDir; 446 447 /** 448 * Directory to which applications installed internally have their 449 * 32 bit native libraries copied. 450 */ 451 private File mAppLib32InstallDir; 452 453 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 454 // apps. 455 final File mDrmAppPrivateInstallDir; 456 457 // ---------------------------------------------------------------- 458 459 // Lock for state used when installing and doing other long running 460 // operations. Methods that must be called with this lock held have 461 // the suffix "LI". 462 final Object mInstallLock = new Object(); 463 464 // ---------------------------------------------------------------- 465 466 // Keys are String (package name), values are Package. This also serves 467 // as the lock for the global state. Methods that must be called with 468 // this lock held have the prefix "LP". 469 @GuardedBy("mPackages") 470 final ArrayMap<String, PackageParser.Package> mPackages = 471 new ArrayMap<String, PackageParser.Package>(); 472 473 // Tracks available target package names -> overlay package paths. 474 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 475 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 476 477 /** 478 * Tracks new system packages [receiving in an OTA] that we expect to 479 * find updated user-installed versions. Keys are package name, values 480 * are package location. 481 */ 482 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 483 484 final Settings mSettings; 485 boolean mRestoredSettings; 486 487 // System configuration read by SystemConfig. 488 final int[] mGlobalGids; 489 final SparseArray<ArraySet<String>> mSystemPermissions; 490 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 491 492 // If mac_permissions.xml was found for seinfo labeling. 493 boolean mFoundPolicyFile; 494 495 // If a recursive restorecon of /data/data/<pkg> is needed. 496 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 497 498 public static final class SharedLibraryEntry { 499 public final String path; 500 public final String apk; 501 502 SharedLibraryEntry(String _path, String _apk) { 503 path = _path; 504 apk = _apk; 505 } 506 } 507 508 // Currently known shared libraries. 509 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 510 new ArrayMap<String, SharedLibraryEntry>(); 511 512 // All available activities, for your resolving pleasure. 513 final ActivityIntentResolver mActivities = 514 new ActivityIntentResolver(); 515 516 // All available receivers, for your resolving pleasure. 517 final ActivityIntentResolver mReceivers = 518 new ActivityIntentResolver(); 519 520 // All available services, for your resolving pleasure. 521 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 522 523 // All available providers, for your resolving pleasure. 524 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 525 526 // Mapping from provider base names (first directory in content URI codePath) 527 // to the provider information. 528 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 529 new ArrayMap<String, PackageParser.Provider>(); 530 531 // Mapping from instrumentation class names to info about them. 532 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 533 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 534 535 // Mapping from permission names to info about them. 536 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 537 new ArrayMap<String, PackageParser.PermissionGroup>(); 538 539 // Packages whose data we have transfered into another package, thus 540 // should no longer exist. 541 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 542 543 // Broadcast actions that are only available to the system. 544 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 545 546 /** List of packages waiting for verification. */ 547 final SparseArray<PackageVerificationState> mPendingVerification 548 = new SparseArray<PackageVerificationState>(); 549 550 /** Set of packages associated with each app op permission. */ 551 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 552 553 final PackageInstallerService mInstallerService; 554 555 private final PackageDexOptimizer mPackageDexOptimizer; 556 557 private AtomicInteger mNextMoveId = new AtomicInteger(); 558 private final MoveCallbacks mMoveCallbacks; 559 560 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 561 562 // Cache of users who need badging. 563 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 564 565 /** Token for keys in mPendingVerification. */ 566 private int mPendingVerificationToken = 0; 567 568 volatile boolean mSystemReady; 569 volatile boolean mSafeMode; 570 volatile boolean mHasSystemUidErrors; 571 572 ApplicationInfo mAndroidApplication; 573 final ActivityInfo mResolveActivity = new ActivityInfo(); 574 final ResolveInfo mResolveInfo = new ResolveInfo(); 575 ComponentName mResolveComponentName; 576 PackageParser.Package mPlatformPackage; 577 ComponentName mCustomResolverComponentName; 578 579 boolean mResolverReplaced = false; 580 581 private final ComponentName mIntentFilterVerifierComponent; 582 private int mIntentFilterVerificationToken = 0; 583 584 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 585 = new SparseArray<IntentFilterVerificationState>(); 586 587 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 588 new DefaultPermissionGrantPolicy(this); 589 590 private static class IFVerificationParams { 591 PackageParser.Package pkg; 592 boolean replacing; 593 int userId; 594 int verifierUid; 595 596 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 597 int _userId, int _verifierUid) { 598 pkg = _pkg; 599 replacing = _replacing; 600 userId = _userId; 601 replacing = _replacing; 602 verifierUid = _verifierUid; 603 } 604 } 605 606 private interface IntentFilterVerifier<T extends IntentFilter> { 607 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 608 T filter, String packageName); 609 void startVerifications(int userId); 610 void receiveVerificationResponse(int verificationId); 611 } 612 613 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 614 private Context mContext; 615 private ComponentName mIntentFilterVerifierComponent; 616 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 617 618 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 619 mContext = context; 620 mIntentFilterVerifierComponent = verifierComponent; 621 } 622 623 private String getDefaultScheme() { 624 return IntentFilter.SCHEME_HTTPS; 625 } 626 627 @Override 628 public void startVerifications(int userId) { 629 // Launch verifications requests 630 int count = mCurrentIntentFilterVerifications.size(); 631 for (int n=0; n<count; n++) { 632 int verificationId = mCurrentIntentFilterVerifications.get(n); 633 final IntentFilterVerificationState ivs = 634 mIntentFilterVerificationStates.get(verificationId); 635 636 String packageName = ivs.getPackageName(); 637 638 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 639 final int filterCount = filters.size(); 640 ArraySet<String> domainsSet = new ArraySet<>(); 641 for (int m=0; m<filterCount; m++) { 642 PackageParser.ActivityIntentInfo filter = filters.get(m); 643 domainsSet.addAll(filter.getHostsList()); 644 } 645 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 646 synchronized (mPackages) { 647 if (mSettings.createIntentFilterVerificationIfNeededLPw( 648 packageName, domainsList) != null) { 649 scheduleWriteSettingsLocked(); 650 } 651 } 652 sendVerificationRequest(userId, verificationId, ivs); 653 } 654 mCurrentIntentFilterVerifications.clear(); 655 } 656 657 private void sendVerificationRequest(int userId, int verificationId, 658 IntentFilterVerificationState ivs) { 659 660 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 661 verificationIntent.putExtra( 662 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 663 verificationId); 664 verificationIntent.putExtra( 665 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 666 getDefaultScheme()); 667 verificationIntent.putExtra( 668 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 669 ivs.getHostsString()); 670 verificationIntent.putExtra( 671 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 672 ivs.getPackageName()); 673 verificationIntent.setComponent(mIntentFilterVerifierComponent); 674 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 675 676 UserHandle user = new UserHandle(userId); 677 mContext.sendBroadcastAsUser(verificationIntent, user); 678 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 679 "Sending IntentFilter verification broadcast"); 680 } 681 682 public void receiveVerificationResponse(int verificationId) { 683 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 684 685 final boolean verified = ivs.isVerified(); 686 687 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 688 final int count = filters.size(); 689 if (DEBUG_DOMAIN_VERIFICATION) { 690 Slog.i(TAG, "Received verification response " + verificationId 691 + " for " + count + " filters, verified=" + verified); 692 } 693 for (int n=0; n<count; n++) { 694 PackageParser.ActivityIntentInfo filter = filters.get(n); 695 filter.setVerified(verified); 696 697 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 698 + " verified with result:" + verified + " and hosts:" 699 + ivs.getHostsString()); 700 } 701 702 mIntentFilterVerificationStates.remove(verificationId); 703 704 final String packageName = ivs.getPackageName(); 705 IntentFilterVerificationInfo ivi = null; 706 707 synchronized (mPackages) { 708 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 709 } 710 if (ivi == null) { 711 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 712 + verificationId + " packageName:" + packageName); 713 return; 714 } 715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 716 "Updating IntentFilterVerificationInfo for package " + packageName 717 +" verificationId:" + verificationId); 718 719 synchronized (mPackages) { 720 if (verified) { 721 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 722 } else { 723 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 724 } 725 scheduleWriteSettingsLocked(); 726 727 final int userId = ivs.getUserId(); 728 if (userId != UserHandle.USER_ALL) { 729 final int userStatus = 730 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 731 732 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 733 boolean needUpdate = false; 734 735 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 736 // already been set by the User thru the Disambiguation dialog 737 switch (userStatus) { 738 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 739 if (verified) { 740 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 741 } else { 742 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 743 } 744 needUpdate = true; 745 break; 746 747 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 748 if (verified) { 749 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 750 needUpdate = true; 751 } 752 break; 753 754 default: 755 // Nothing to do 756 } 757 758 if (needUpdate) { 759 mSettings.updateIntentFilterVerificationStatusLPw( 760 packageName, updatedStatus, userId); 761 scheduleWritePackageRestrictionsLocked(userId); 762 } 763 } 764 } 765 } 766 767 @Override 768 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 769 ActivityIntentInfo filter, String packageName) { 770 if (!hasValidDomains(filter)) { 771 return false; 772 } 773 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 774 if (ivs == null) { 775 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 776 packageName); 777 } 778 if (DEBUG_DOMAIN_VERIFICATION) { 779 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 780 } 781 ivs.addFilter(filter); 782 return true; 783 } 784 785 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 786 int userId, int verificationId, String packageName) { 787 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 788 verifierUid, userId, packageName); 789 ivs.setPendingState(); 790 synchronized (mPackages) { 791 mIntentFilterVerificationStates.append(verificationId, ivs); 792 mCurrentIntentFilterVerifications.add(verificationId); 793 } 794 return ivs; 795 } 796 } 797 798 private static boolean hasValidDomains(ActivityIntentInfo filter) { 799 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 800 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 801 if (!hasHTTPorHTTPS) { 802 return false; 803 } 804 return true; 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 @Override 2728 public int getMountExternalMode(int uid) { 2729 if (Process.isIsolated(uid)) { 2730 return Zygote.MOUNT_EXTERNAL_NONE; 2731 } else { 2732 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2733 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2734 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2735 return Zygote.MOUNT_EXTERNAL_WRITE; 2736 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2737 return Zygote.MOUNT_EXTERNAL_READ; 2738 } else { 2739 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2740 } 2741 } 2742 } 2743 2744 static PermissionInfo generatePermissionInfo( 2745 BasePermission bp, int flags) { 2746 if (bp.perm != null) { 2747 return PackageParser.generatePermissionInfo(bp.perm, flags); 2748 } 2749 PermissionInfo pi = new PermissionInfo(); 2750 pi.name = bp.name; 2751 pi.packageName = bp.sourcePackage; 2752 pi.nonLocalizedLabel = bp.name; 2753 pi.protectionLevel = bp.protectionLevel; 2754 return pi; 2755 } 2756 2757 @Override 2758 public PermissionInfo getPermissionInfo(String name, int flags) { 2759 // reader 2760 synchronized (mPackages) { 2761 final BasePermission p = mSettings.mPermissions.get(name); 2762 if (p != null) { 2763 return generatePermissionInfo(p, flags); 2764 } 2765 return null; 2766 } 2767 } 2768 2769 @Override 2770 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2771 // reader 2772 synchronized (mPackages) { 2773 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2774 for (BasePermission p : mSettings.mPermissions.values()) { 2775 if (group == null) { 2776 if (p.perm == null || p.perm.info.group == null) { 2777 out.add(generatePermissionInfo(p, flags)); 2778 } 2779 } else { 2780 if (p.perm != null && group.equals(p.perm.info.group)) { 2781 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2782 } 2783 } 2784 } 2785 2786 if (out.size() > 0) { 2787 return out; 2788 } 2789 return mPermissionGroups.containsKey(group) ? out : null; 2790 } 2791 } 2792 2793 @Override 2794 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2795 // reader 2796 synchronized (mPackages) { 2797 return PackageParser.generatePermissionGroupInfo( 2798 mPermissionGroups.get(name), flags); 2799 } 2800 } 2801 2802 @Override 2803 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2804 // reader 2805 synchronized (mPackages) { 2806 final int N = mPermissionGroups.size(); 2807 ArrayList<PermissionGroupInfo> out 2808 = new ArrayList<PermissionGroupInfo>(N); 2809 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2810 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2811 } 2812 return out; 2813 } 2814 } 2815 2816 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2817 int userId) { 2818 if (!sUserManager.exists(userId)) return null; 2819 PackageSetting ps = mSettings.mPackages.get(packageName); 2820 if (ps != null) { 2821 if (ps.pkg == null) { 2822 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2823 flags, userId); 2824 if (pInfo != null) { 2825 return pInfo.applicationInfo; 2826 } 2827 return null; 2828 } 2829 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2830 ps.readUserState(userId), userId); 2831 } 2832 return null; 2833 } 2834 2835 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2836 int userId) { 2837 if (!sUserManager.exists(userId)) return null; 2838 PackageSetting ps = mSettings.mPackages.get(packageName); 2839 if (ps != null) { 2840 PackageParser.Package pkg = ps.pkg; 2841 if (pkg == null) { 2842 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2843 return null; 2844 } 2845 // Only data remains, so we aren't worried about code paths 2846 pkg = new PackageParser.Package(packageName); 2847 pkg.applicationInfo.packageName = packageName; 2848 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2849 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2850 pkg.applicationInfo.dataDir = Environment 2851 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2852 .getAbsolutePath(); 2853 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2854 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2855 } 2856 return generatePackageInfo(pkg, flags, userId); 2857 } 2858 return null; 2859 } 2860 2861 @Override 2862 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2863 if (!sUserManager.exists(userId)) return null; 2864 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2865 // writer 2866 synchronized (mPackages) { 2867 PackageParser.Package p = mPackages.get(packageName); 2868 if (DEBUG_PACKAGE_INFO) Log.v( 2869 TAG, "getApplicationInfo " + packageName 2870 + ": " + p); 2871 if (p != null) { 2872 PackageSetting ps = mSettings.mPackages.get(packageName); 2873 if (ps == null) return null; 2874 // Note: isEnabledLP() does not apply here - always return info 2875 return PackageParser.generateApplicationInfo( 2876 p, flags, ps.readUserState(userId), userId); 2877 } 2878 if ("android".equals(packageName)||"system".equals(packageName)) { 2879 return mAndroidApplication; 2880 } 2881 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2882 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2883 } 2884 } 2885 return null; 2886 } 2887 2888 @Override 2889 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2890 final IPackageDataObserver observer) { 2891 mContext.enforceCallingOrSelfPermission( 2892 android.Manifest.permission.CLEAR_APP_CACHE, null); 2893 // Queue up an async operation since clearing cache may take a little while. 2894 mHandler.post(new Runnable() { 2895 public void run() { 2896 mHandler.removeCallbacks(this); 2897 int retCode = -1; 2898 synchronized (mInstallLock) { 2899 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2900 if (retCode < 0) { 2901 Slog.w(TAG, "Couldn't clear application caches"); 2902 } 2903 } 2904 if (observer != null) { 2905 try { 2906 observer.onRemoveCompleted(null, (retCode >= 0)); 2907 } catch (RemoteException e) { 2908 Slog.w(TAG, "RemoveException when invoking call back"); 2909 } 2910 } 2911 } 2912 }); 2913 } 2914 2915 @Override 2916 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2917 final IntentSender pi) { 2918 mContext.enforceCallingOrSelfPermission( 2919 android.Manifest.permission.CLEAR_APP_CACHE, null); 2920 // Queue up an async operation since clearing cache may take a little while. 2921 mHandler.post(new Runnable() { 2922 public void run() { 2923 mHandler.removeCallbacks(this); 2924 int retCode = -1; 2925 synchronized (mInstallLock) { 2926 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2927 if (retCode < 0) { 2928 Slog.w(TAG, "Couldn't clear application caches"); 2929 } 2930 } 2931 if(pi != null) { 2932 try { 2933 // Callback via pending intent 2934 int code = (retCode >= 0) ? 1 : 0; 2935 pi.sendIntent(null, code, null, 2936 null, null); 2937 } catch (SendIntentException e1) { 2938 Slog.i(TAG, "Failed to send pending intent"); 2939 } 2940 } 2941 } 2942 }); 2943 } 2944 2945 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2946 synchronized (mInstallLock) { 2947 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2948 throw new IOException("Failed to free enough space"); 2949 } 2950 } 2951 } 2952 2953 @Override 2954 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2955 if (!sUserManager.exists(userId)) return null; 2956 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2957 synchronized (mPackages) { 2958 PackageParser.Activity a = mActivities.mActivities.get(component); 2959 2960 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2961 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2962 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2963 if (ps == null) return null; 2964 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2965 userId); 2966 } 2967 if (mResolveComponentName.equals(component)) { 2968 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2969 new PackageUserState(), userId); 2970 } 2971 } 2972 return null; 2973 } 2974 2975 @Override 2976 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2977 String resolvedType) { 2978 synchronized (mPackages) { 2979 PackageParser.Activity a = mActivities.mActivities.get(component); 2980 if (a == null) { 2981 return false; 2982 } 2983 for (int i=0; i<a.intents.size(); i++) { 2984 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2985 intent.getData(), intent.getCategories(), TAG) >= 0) { 2986 return true; 2987 } 2988 } 2989 return false; 2990 } 2991 } 2992 2993 @Override 2994 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2995 if (!sUserManager.exists(userId)) return null; 2996 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2997 synchronized (mPackages) { 2998 PackageParser.Activity a = mReceivers.mActivities.get(component); 2999 if (DEBUG_PACKAGE_INFO) Log.v( 3000 TAG, "getReceiverInfo " + component + ": " + a); 3001 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 3002 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3003 if (ps == null) return null; 3004 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3005 userId); 3006 } 3007 } 3008 return null; 3009 } 3010 3011 @Override 3012 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3013 if (!sUserManager.exists(userId)) return null; 3014 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3015 synchronized (mPackages) { 3016 PackageParser.Service s = mServices.mServices.get(component); 3017 if (DEBUG_PACKAGE_INFO) Log.v( 3018 TAG, "getServiceInfo " + component + ": " + s); 3019 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3020 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3021 if (ps == null) return null; 3022 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3023 userId); 3024 } 3025 } 3026 return null; 3027 } 3028 3029 @Override 3030 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3031 if (!sUserManager.exists(userId)) return null; 3032 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3033 synchronized (mPackages) { 3034 PackageParser.Provider p = mProviders.mProviders.get(component); 3035 if (DEBUG_PACKAGE_INFO) Log.v( 3036 TAG, "getProviderInfo " + component + ": " + p); 3037 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3038 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3039 if (ps == null) return null; 3040 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3041 userId); 3042 } 3043 } 3044 return null; 3045 } 3046 3047 @Override 3048 public String[] getSystemSharedLibraryNames() { 3049 Set<String> libSet; 3050 synchronized (mPackages) { 3051 libSet = mSharedLibraries.keySet(); 3052 int size = libSet.size(); 3053 if (size > 0) { 3054 String[] libs = new String[size]; 3055 libSet.toArray(libs); 3056 return libs; 3057 } 3058 } 3059 return null; 3060 } 3061 3062 /** 3063 * @hide 3064 */ 3065 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3066 synchronized (mPackages) { 3067 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3068 if (lib != null && lib.apk != null) { 3069 return mPackages.get(lib.apk); 3070 } 3071 } 3072 return null; 3073 } 3074 3075 @Override 3076 public FeatureInfo[] getSystemAvailableFeatures() { 3077 Collection<FeatureInfo> featSet; 3078 synchronized (mPackages) { 3079 featSet = mAvailableFeatures.values(); 3080 int size = featSet.size(); 3081 if (size > 0) { 3082 FeatureInfo[] features = new FeatureInfo[size+1]; 3083 featSet.toArray(features); 3084 FeatureInfo fi = new FeatureInfo(); 3085 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3086 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3087 features[size] = fi; 3088 return features; 3089 } 3090 } 3091 return null; 3092 } 3093 3094 @Override 3095 public boolean hasSystemFeature(String name) { 3096 synchronized (mPackages) { 3097 return mAvailableFeatures.containsKey(name); 3098 } 3099 } 3100 3101 private void checkValidCaller(int uid, int userId) { 3102 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3103 return; 3104 3105 throw new SecurityException("Caller uid=" + uid 3106 + " is not privileged to communicate with user=" + userId); 3107 } 3108 3109 @Override 3110 public int checkPermission(String permName, String pkgName, int userId) { 3111 if (!sUserManager.exists(userId)) { 3112 return PackageManager.PERMISSION_DENIED; 3113 } 3114 3115 synchronized (mPackages) { 3116 final PackageParser.Package p = mPackages.get(pkgName); 3117 if (p != null && p.mExtras != null) { 3118 final PackageSetting ps = (PackageSetting) p.mExtras; 3119 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3120 return PackageManager.PERMISSION_GRANTED; 3121 } 3122 } 3123 } 3124 3125 return PackageManager.PERMISSION_DENIED; 3126 } 3127 3128 @Override 3129 public int checkUidPermission(String permName, int uid) { 3130 final int userId = UserHandle.getUserId(uid); 3131 3132 if (!sUserManager.exists(userId)) { 3133 return PackageManager.PERMISSION_DENIED; 3134 } 3135 3136 synchronized (mPackages) { 3137 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3138 if (obj != null) { 3139 final SettingBase ps = (SettingBase) obj; 3140 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3141 return PackageManager.PERMISSION_GRANTED; 3142 } 3143 } else { 3144 ArraySet<String> perms = mSystemPermissions.get(uid); 3145 if (perms != null && perms.contains(permName)) { 3146 return PackageManager.PERMISSION_GRANTED; 3147 } 3148 } 3149 } 3150 3151 return PackageManager.PERMISSION_DENIED; 3152 } 3153 3154 @Override 3155 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3156 if (UserHandle.getCallingUserId() != userId) { 3157 mContext.enforceCallingPermission( 3158 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3159 "isPermissionRevokedByPolicy for user " + userId); 3160 } 3161 3162 if (checkPermission(permission, packageName, userId) 3163 == PackageManager.PERMISSION_GRANTED) { 3164 return false; 3165 } 3166 3167 final long identity = Binder.clearCallingIdentity(); 3168 try { 3169 final int flags = getPermissionFlags(permission, packageName, userId); 3170 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3171 } finally { 3172 Binder.restoreCallingIdentity(identity); 3173 } 3174 } 3175 3176 /** 3177 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3178 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3179 * @param checkShell TODO(yamasani): 3180 * @param message the message to log on security exception 3181 */ 3182 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3183 boolean checkShell, String message) { 3184 if (userId < 0) { 3185 throw new IllegalArgumentException("Invalid userId " + userId); 3186 } 3187 if (checkShell) { 3188 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3189 } 3190 if (userId == UserHandle.getUserId(callingUid)) return; 3191 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3192 if (requireFullPermission) { 3193 mContext.enforceCallingOrSelfPermission( 3194 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3195 } else { 3196 try { 3197 mContext.enforceCallingOrSelfPermission( 3198 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3199 } catch (SecurityException se) { 3200 mContext.enforceCallingOrSelfPermission( 3201 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3202 } 3203 } 3204 } 3205 } 3206 3207 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3208 if (callingUid == Process.SHELL_UID) { 3209 if (userHandle >= 0 3210 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3211 throw new SecurityException("Shell does not have permission to access user " 3212 + userHandle); 3213 } else if (userHandle < 0) { 3214 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3215 + Debug.getCallers(3)); 3216 } 3217 } 3218 } 3219 3220 private BasePermission findPermissionTreeLP(String permName) { 3221 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3222 if (permName.startsWith(bp.name) && 3223 permName.length() > bp.name.length() && 3224 permName.charAt(bp.name.length()) == '.') { 3225 return bp; 3226 } 3227 } 3228 return null; 3229 } 3230 3231 private BasePermission checkPermissionTreeLP(String permName) { 3232 if (permName != null) { 3233 BasePermission bp = findPermissionTreeLP(permName); 3234 if (bp != null) { 3235 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3236 return bp; 3237 } 3238 throw new SecurityException("Calling uid " 3239 + Binder.getCallingUid() 3240 + " is not allowed to add to permission tree " 3241 + bp.name + " owned by uid " + bp.uid); 3242 } 3243 } 3244 throw new SecurityException("No permission tree found for " + permName); 3245 } 3246 3247 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3248 if (s1 == null) { 3249 return s2 == null; 3250 } 3251 if (s2 == null) { 3252 return false; 3253 } 3254 if (s1.getClass() != s2.getClass()) { 3255 return false; 3256 } 3257 return s1.equals(s2); 3258 } 3259 3260 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3261 if (pi1.icon != pi2.icon) return false; 3262 if (pi1.logo != pi2.logo) return false; 3263 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3264 if (!compareStrings(pi1.name, pi2.name)) return false; 3265 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3266 // We'll take care of setting this one. 3267 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3268 // These are not currently stored in settings. 3269 //if (!compareStrings(pi1.group, pi2.group)) return false; 3270 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3271 //if (pi1.labelRes != pi2.labelRes) return false; 3272 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3273 return true; 3274 } 3275 3276 int permissionInfoFootprint(PermissionInfo info) { 3277 int size = info.name.length(); 3278 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3279 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3280 return size; 3281 } 3282 3283 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3284 int size = 0; 3285 for (BasePermission perm : mSettings.mPermissions.values()) { 3286 if (perm.uid == tree.uid) { 3287 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3288 } 3289 } 3290 return size; 3291 } 3292 3293 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3294 // We calculate the max size of permissions defined by this uid and throw 3295 // if that plus the size of 'info' would exceed our stated maximum. 3296 if (tree.uid != Process.SYSTEM_UID) { 3297 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3298 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3299 throw new SecurityException("Permission tree size cap exceeded"); 3300 } 3301 } 3302 } 3303 3304 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3305 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3306 throw new SecurityException("Label must be specified in permission"); 3307 } 3308 BasePermission tree = checkPermissionTreeLP(info.name); 3309 BasePermission bp = mSettings.mPermissions.get(info.name); 3310 boolean added = bp == null; 3311 boolean changed = true; 3312 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3313 if (added) { 3314 enforcePermissionCapLocked(info, tree); 3315 bp = new BasePermission(info.name, tree.sourcePackage, 3316 BasePermission.TYPE_DYNAMIC); 3317 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3318 throw new SecurityException( 3319 "Not allowed to modify non-dynamic permission " 3320 + info.name); 3321 } else { 3322 if (bp.protectionLevel == fixedLevel 3323 && bp.perm.owner.equals(tree.perm.owner) 3324 && bp.uid == tree.uid 3325 && comparePermissionInfos(bp.perm.info, info)) { 3326 changed = false; 3327 } 3328 } 3329 bp.protectionLevel = fixedLevel; 3330 info = new PermissionInfo(info); 3331 info.protectionLevel = fixedLevel; 3332 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3333 bp.perm.info.packageName = tree.perm.info.packageName; 3334 bp.uid = tree.uid; 3335 if (added) { 3336 mSettings.mPermissions.put(info.name, bp); 3337 } 3338 if (changed) { 3339 if (!async) { 3340 mSettings.writeLPr(); 3341 } else { 3342 scheduleWriteSettingsLocked(); 3343 } 3344 } 3345 return added; 3346 } 3347 3348 @Override 3349 public boolean addPermission(PermissionInfo info) { 3350 synchronized (mPackages) { 3351 return addPermissionLocked(info, false); 3352 } 3353 } 3354 3355 @Override 3356 public boolean addPermissionAsync(PermissionInfo info) { 3357 synchronized (mPackages) { 3358 return addPermissionLocked(info, true); 3359 } 3360 } 3361 3362 @Override 3363 public void removePermission(String name) { 3364 synchronized (mPackages) { 3365 checkPermissionTreeLP(name); 3366 BasePermission bp = mSettings.mPermissions.get(name); 3367 if (bp != null) { 3368 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3369 throw new SecurityException( 3370 "Not allowed to modify non-dynamic permission " 3371 + name); 3372 } 3373 mSettings.mPermissions.remove(name); 3374 mSettings.writeLPr(); 3375 } 3376 } 3377 } 3378 3379 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3380 BasePermission bp) { 3381 int index = pkg.requestedPermissions.indexOf(bp.name); 3382 if (index == -1) { 3383 throw new SecurityException("Package " + pkg.packageName 3384 + " has not requested permission " + bp.name); 3385 } 3386 if (!bp.isRuntime()) { 3387 throw new SecurityException("Permission " + bp.name 3388 + " is not a changeable permission type"); 3389 } 3390 } 3391 3392 @Override 3393 public void grantRuntimePermission(String packageName, String name, final int userId) { 3394 if (!sUserManager.exists(userId)) { 3395 Log.e(TAG, "No such user:" + userId); 3396 return; 3397 } 3398 3399 mContext.enforceCallingOrSelfPermission( 3400 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3401 "grantRuntimePermission"); 3402 3403 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3404 "grantRuntimePermission"); 3405 3406 final int uid; 3407 final SettingBase sb; 3408 3409 synchronized (mPackages) { 3410 final PackageParser.Package pkg = mPackages.get(packageName); 3411 if (pkg == null) { 3412 throw new IllegalArgumentException("Unknown package: " + packageName); 3413 } 3414 3415 final BasePermission bp = mSettings.mPermissions.get(name); 3416 if (bp == null) { 3417 throw new IllegalArgumentException("Unknown permission: " + name); 3418 } 3419 3420 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3421 3422 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3423 sb = (SettingBase) pkg.mExtras; 3424 if (sb == null) { 3425 throw new IllegalArgumentException("Unknown package: " + packageName); 3426 } 3427 3428 final PermissionsState permissionsState = sb.getPermissionsState(); 3429 3430 final int flags = permissionsState.getPermissionFlags(name, userId); 3431 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3432 throw new SecurityException("Cannot grant system fixed permission: " 3433 + name + " for package: " + packageName); 3434 } 3435 3436 final int result = permissionsState.grantRuntimePermission(bp, userId); 3437 switch (result) { 3438 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3439 return; 3440 } 3441 3442 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3443 mHandler.post(new Runnable() { 3444 @Override 3445 public void run() { 3446 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3447 } 3448 }); 3449 } break; 3450 } 3451 3452 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3453 3454 // Not critical if that is lost - app has to request again. 3455 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3456 } 3457 3458 // Only need to do this if user is initialized. Otherwise it's a new user 3459 // and there are no processes running as the user yet and there's no need 3460 // to make an expensive call to remount processes for the changed permissions. 3461 if (READ_EXTERNAL_STORAGE.equals(name) 3462 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3463 final long token = Binder.clearCallingIdentity(); 3464 try { 3465 if (sUserManager.isInitialized(userId)) { 3466 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3467 storage.remountUid(uid); 3468 } 3469 } finally { 3470 Binder.restoreCallingIdentity(token); 3471 } 3472 } 3473 } 3474 3475 @Override 3476 public void revokeRuntimePermission(String packageName, String name, int userId) { 3477 if (!sUserManager.exists(userId)) { 3478 Log.e(TAG, "No such user:" + userId); 3479 return; 3480 } 3481 3482 mContext.enforceCallingOrSelfPermission( 3483 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3484 "revokeRuntimePermission"); 3485 3486 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3487 "revokeRuntimePermission"); 3488 3489 final SettingBase sb; 3490 3491 synchronized (mPackages) { 3492 final PackageParser.Package pkg = mPackages.get(packageName); 3493 if (pkg == null) { 3494 throw new IllegalArgumentException("Unknown package: " + packageName); 3495 } 3496 3497 final BasePermission bp = mSettings.mPermissions.get(name); 3498 if (bp == null) { 3499 throw new IllegalArgumentException("Unknown permission: " + name); 3500 } 3501 3502 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3503 3504 sb = (SettingBase) pkg.mExtras; 3505 if (sb == null) { 3506 throw new IllegalArgumentException("Unknown package: " + packageName); 3507 } 3508 3509 final PermissionsState permissionsState = sb.getPermissionsState(); 3510 3511 final int flags = permissionsState.getPermissionFlags(name, userId); 3512 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3513 throw new SecurityException("Cannot revoke system fixed permission: " 3514 + name + " for package: " + packageName); 3515 } 3516 3517 if (permissionsState.revokeRuntimePermission(bp, userId) == 3518 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3519 return; 3520 } 3521 3522 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3523 3524 // Critical, after this call app should never have the permission. 3525 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3526 } 3527 3528 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3529 } 3530 3531 @Override 3532 public void resetRuntimePermissions() { 3533 mContext.enforceCallingOrSelfPermission( 3534 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3535 "revokeRuntimePermission"); 3536 3537 int callingUid = Binder.getCallingUid(); 3538 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3539 mContext.enforceCallingOrSelfPermission( 3540 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3541 "resetRuntimePermissions"); 3542 } 3543 3544 final int[] userIds; 3545 3546 synchronized (mPackages) { 3547 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3548 final int userCount = UserManagerService.getInstance().getUserIds().length; 3549 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3550 } 3551 3552 for (int userId : userIds) { 3553 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3554 } 3555 } 3556 3557 @Override 3558 public int getPermissionFlags(String name, String packageName, int userId) { 3559 if (!sUserManager.exists(userId)) { 3560 return 0; 3561 } 3562 3563 mContext.enforceCallingOrSelfPermission( 3564 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3565 "getPermissionFlags"); 3566 3567 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3568 "getPermissionFlags"); 3569 3570 synchronized (mPackages) { 3571 final PackageParser.Package pkg = mPackages.get(packageName); 3572 if (pkg == null) { 3573 throw new IllegalArgumentException("Unknown package: " + packageName); 3574 } 3575 3576 final BasePermission bp = mSettings.mPermissions.get(name); 3577 if (bp == null) { 3578 throw new IllegalArgumentException("Unknown permission: " + name); 3579 } 3580 3581 SettingBase sb = (SettingBase) pkg.mExtras; 3582 if (sb == null) { 3583 throw new IllegalArgumentException("Unknown package: " + packageName); 3584 } 3585 3586 PermissionsState permissionsState = sb.getPermissionsState(); 3587 return permissionsState.getPermissionFlags(name, userId); 3588 } 3589 } 3590 3591 @Override 3592 public void updatePermissionFlags(String name, String packageName, int flagMask, 3593 int flagValues, int userId) { 3594 if (!sUserManager.exists(userId)) { 3595 return; 3596 } 3597 3598 mContext.enforceCallingOrSelfPermission( 3599 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3600 "updatePermissionFlags"); 3601 3602 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3603 "updatePermissionFlags"); 3604 3605 // Only the system can change system fixed flags. 3606 if (getCallingUid() != Process.SYSTEM_UID) { 3607 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3608 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3609 } 3610 3611 synchronized (mPackages) { 3612 final PackageParser.Package pkg = mPackages.get(packageName); 3613 if (pkg == null) { 3614 throw new IllegalArgumentException("Unknown package: " + packageName); 3615 } 3616 3617 final BasePermission bp = mSettings.mPermissions.get(name); 3618 if (bp == null) { 3619 throw new IllegalArgumentException("Unknown permission: " + name); 3620 } 3621 3622 SettingBase sb = (SettingBase) pkg.mExtras; 3623 if (sb == null) { 3624 throw new IllegalArgumentException("Unknown package: " + packageName); 3625 } 3626 3627 PermissionsState permissionsState = sb.getPermissionsState(); 3628 3629 // Only the package manager can change flags for system component permissions. 3630 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3631 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3632 return; 3633 } 3634 3635 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3636 3637 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3638 // Install and runtime permissions are stored in different places, 3639 // so figure out what permission changed and persist the change. 3640 if (permissionsState.getInstallPermissionState(name) != null) { 3641 scheduleWriteSettingsLocked(); 3642 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3643 || hadState) { 3644 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3645 } 3646 } 3647 } 3648 } 3649 3650 /** 3651 * Update the permission flags for all packages and runtime permissions of a user in order 3652 * to allow device or profile owner to remove POLICY_FIXED. 3653 */ 3654 @Override 3655 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3656 if (!sUserManager.exists(userId)) { 3657 return; 3658 } 3659 3660 mContext.enforceCallingOrSelfPermission( 3661 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3662 "updatePermissionFlagsForAllApps"); 3663 3664 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3665 "updatePermissionFlagsForAllApps"); 3666 3667 // Only the system can change system fixed flags. 3668 if (getCallingUid() != Process.SYSTEM_UID) { 3669 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3670 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3671 } 3672 3673 synchronized (mPackages) { 3674 boolean changed = false; 3675 final int packageCount = mPackages.size(); 3676 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3677 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3678 SettingBase sb = (SettingBase) pkg.mExtras; 3679 if (sb == null) { 3680 continue; 3681 } 3682 PermissionsState permissionsState = sb.getPermissionsState(); 3683 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3684 userId, flagMask, flagValues); 3685 } 3686 if (changed) { 3687 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3688 } 3689 } 3690 } 3691 3692 @Override 3693 public boolean shouldShowRequestPermissionRationale(String permissionName, 3694 String packageName, int userId) { 3695 if (UserHandle.getCallingUserId() != userId) { 3696 mContext.enforceCallingPermission( 3697 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3698 "canShowRequestPermissionRationale for user " + userId); 3699 } 3700 3701 final int uid = getPackageUid(packageName, userId); 3702 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3703 return false; 3704 } 3705 3706 if (checkPermission(permissionName, packageName, userId) 3707 == PackageManager.PERMISSION_GRANTED) { 3708 return false; 3709 } 3710 3711 final int flags; 3712 3713 final long identity = Binder.clearCallingIdentity(); 3714 try { 3715 flags = getPermissionFlags(permissionName, 3716 packageName, userId); 3717 } finally { 3718 Binder.restoreCallingIdentity(identity); 3719 } 3720 3721 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3722 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3723 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3724 3725 if ((flags & fixedFlags) != 0) { 3726 return false; 3727 } 3728 3729 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3730 } 3731 3732 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3733 BasePermission bp = mSettings.mPermissions.get(permission); 3734 if (bp == null) { 3735 throw new SecurityException("Missing " + permission + " permission"); 3736 } 3737 3738 SettingBase sb = (SettingBase) pkg.mExtras; 3739 PermissionsState permissionsState = sb.getPermissionsState(); 3740 3741 if (permissionsState.grantInstallPermission(bp) != 3742 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3743 scheduleWriteSettingsLocked(); 3744 } 3745 } 3746 3747 @Override 3748 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3749 mContext.enforceCallingOrSelfPermission( 3750 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3751 "addOnPermissionsChangeListener"); 3752 3753 synchronized (mPackages) { 3754 mOnPermissionChangeListeners.addListenerLocked(listener); 3755 } 3756 } 3757 3758 @Override 3759 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3760 synchronized (mPackages) { 3761 mOnPermissionChangeListeners.removeListenerLocked(listener); 3762 } 3763 } 3764 3765 @Override 3766 public boolean isProtectedBroadcast(String actionName) { 3767 synchronized (mPackages) { 3768 return mProtectedBroadcasts.contains(actionName); 3769 } 3770 } 3771 3772 @Override 3773 public int checkSignatures(String pkg1, String pkg2) { 3774 synchronized (mPackages) { 3775 final PackageParser.Package p1 = mPackages.get(pkg1); 3776 final PackageParser.Package p2 = mPackages.get(pkg2); 3777 if (p1 == null || p1.mExtras == null 3778 || p2 == null || p2.mExtras == null) { 3779 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3780 } 3781 return compareSignatures(p1.mSignatures, p2.mSignatures); 3782 } 3783 } 3784 3785 @Override 3786 public int checkUidSignatures(int uid1, int uid2) { 3787 // Map to base uids. 3788 uid1 = UserHandle.getAppId(uid1); 3789 uid2 = UserHandle.getAppId(uid2); 3790 // reader 3791 synchronized (mPackages) { 3792 Signature[] s1; 3793 Signature[] s2; 3794 Object obj = mSettings.getUserIdLPr(uid1); 3795 if (obj != null) { 3796 if (obj instanceof SharedUserSetting) { 3797 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3798 } else if (obj instanceof PackageSetting) { 3799 s1 = ((PackageSetting)obj).signatures.mSignatures; 3800 } else { 3801 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3802 } 3803 } else { 3804 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3805 } 3806 obj = mSettings.getUserIdLPr(uid2); 3807 if (obj != null) { 3808 if (obj instanceof SharedUserSetting) { 3809 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3810 } else if (obj instanceof PackageSetting) { 3811 s2 = ((PackageSetting)obj).signatures.mSignatures; 3812 } else { 3813 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3814 } 3815 } else { 3816 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3817 } 3818 return compareSignatures(s1, s2); 3819 } 3820 } 3821 3822 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3823 final long identity = Binder.clearCallingIdentity(); 3824 try { 3825 if (sb instanceof SharedUserSetting) { 3826 SharedUserSetting sus = (SharedUserSetting) sb; 3827 final int packageCount = sus.packages.size(); 3828 for (int i = 0; i < packageCount; i++) { 3829 PackageSetting susPs = sus.packages.valueAt(i); 3830 if (userId == UserHandle.USER_ALL) { 3831 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3832 } else { 3833 final int uid = UserHandle.getUid(userId, susPs.appId); 3834 killUid(uid, reason); 3835 } 3836 } 3837 } else if (sb instanceof PackageSetting) { 3838 PackageSetting ps = (PackageSetting) sb; 3839 if (userId == UserHandle.USER_ALL) { 3840 killApplication(ps.pkg.packageName, ps.appId, reason); 3841 } else { 3842 final int uid = UserHandle.getUid(userId, ps.appId); 3843 killUid(uid, reason); 3844 } 3845 } 3846 } finally { 3847 Binder.restoreCallingIdentity(identity); 3848 } 3849 } 3850 3851 private static void killUid(int uid, String reason) { 3852 IActivityManager am = ActivityManagerNative.getDefault(); 3853 if (am != null) { 3854 try { 3855 am.killUid(uid, reason); 3856 } catch (RemoteException e) { 3857 /* ignore - same process */ 3858 } 3859 } 3860 } 3861 3862 /** 3863 * Compares two sets of signatures. Returns: 3864 * <br /> 3865 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3866 * <br /> 3867 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3868 * <br /> 3869 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3870 * <br /> 3871 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3872 * <br /> 3873 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3874 */ 3875 static int compareSignatures(Signature[] s1, Signature[] s2) { 3876 if (s1 == null) { 3877 return s2 == null 3878 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3879 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3880 } 3881 3882 if (s2 == null) { 3883 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3884 } 3885 3886 if (s1.length != s2.length) { 3887 return PackageManager.SIGNATURE_NO_MATCH; 3888 } 3889 3890 // Since both signature sets are of size 1, we can compare without HashSets. 3891 if (s1.length == 1) { 3892 return s1[0].equals(s2[0]) ? 3893 PackageManager.SIGNATURE_MATCH : 3894 PackageManager.SIGNATURE_NO_MATCH; 3895 } 3896 3897 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3898 for (Signature sig : s1) { 3899 set1.add(sig); 3900 } 3901 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3902 for (Signature sig : s2) { 3903 set2.add(sig); 3904 } 3905 // Make sure s2 contains all signatures in s1. 3906 if (set1.equals(set2)) { 3907 return PackageManager.SIGNATURE_MATCH; 3908 } 3909 return PackageManager.SIGNATURE_NO_MATCH; 3910 } 3911 3912 /** 3913 * If the database version for this type of package (internal storage or 3914 * external storage) is less than the version where package signatures 3915 * were updated, return true. 3916 */ 3917 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3918 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3919 DatabaseVersion.SIGNATURE_END_ENTITY)) 3920 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3921 DatabaseVersion.SIGNATURE_END_ENTITY)); 3922 } 3923 3924 /** 3925 * Used for backward compatibility to make sure any packages with 3926 * certificate chains get upgraded to the new style. {@code existingSigs} 3927 * will be in the old format (since they were stored on disk from before the 3928 * system upgrade) and {@code scannedSigs} will be in the newer format. 3929 */ 3930 private int compareSignaturesCompat(PackageSignatures existingSigs, 3931 PackageParser.Package scannedPkg) { 3932 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3933 return PackageManager.SIGNATURE_NO_MATCH; 3934 } 3935 3936 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3937 for (Signature sig : existingSigs.mSignatures) { 3938 existingSet.add(sig); 3939 } 3940 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3941 for (Signature sig : scannedPkg.mSignatures) { 3942 try { 3943 Signature[] chainSignatures = sig.getChainSignatures(); 3944 for (Signature chainSig : chainSignatures) { 3945 scannedCompatSet.add(chainSig); 3946 } 3947 } catch (CertificateEncodingException e) { 3948 scannedCompatSet.add(sig); 3949 } 3950 } 3951 /* 3952 * Make sure the expanded scanned set contains all signatures in the 3953 * existing one. 3954 */ 3955 if (scannedCompatSet.equals(existingSet)) { 3956 // Migrate the old signatures to the new scheme. 3957 existingSigs.assignSignatures(scannedPkg.mSignatures); 3958 // The new KeySets will be re-added later in the scanning process. 3959 synchronized (mPackages) { 3960 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3961 } 3962 return PackageManager.SIGNATURE_MATCH; 3963 } 3964 return PackageManager.SIGNATURE_NO_MATCH; 3965 } 3966 3967 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3968 if (isExternal(scannedPkg)) { 3969 return mSettings.isExternalDatabaseVersionOlderThan( 3970 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3971 } else { 3972 return mSettings.isInternalDatabaseVersionOlderThan( 3973 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3974 } 3975 } 3976 3977 private int compareSignaturesRecover(PackageSignatures existingSigs, 3978 PackageParser.Package scannedPkg) { 3979 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3980 return PackageManager.SIGNATURE_NO_MATCH; 3981 } 3982 3983 String msg = null; 3984 try { 3985 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3986 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3987 + scannedPkg.packageName); 3988 return PackageManager.SIGNATURE_MATCH; 3989 } 3990 } catch (CertificateException e) { 3991 msg = e.getMessage(); 3992 } 3993 3994 logCriticalInfo(Log.INFO, 3995 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3996 return PackageManager.SIGNATURE_NO_MATCH; 3997 } 3998 3999 @Override 4000 public String[] getPackagesForUid(int uid) { 4001 uid = UserHandle.getAppId(uid); 4002 // reader 4003 synchronized (mPackages) { 4004 Object obj = mSettings.getUserIdLPr(uid); 4005 if (obj instanceof SharedUserSetting) { 4006 final SharedUserSetting sus = (SharedUserSetting) obj; 4007 final int N = sus.packages.size(); 4008 final String[] res = new String[N]; 4009 final Iterator<PackageSetting> it = sus.packages.iterator(); 4010 int i = 0; 4011 while (it.hasNext()) { 4012 res[i++] = it.next().name; 4013 } 4014 return res; 4015 } else if (obj instanceof PackageSetting) { 4016 final PackageSetting ps = (PackageSetting) obj; 4017 return new String[] { ps.name }; 4018 } 4019 } 4020 return null; 4021 } 4022 4023 @Override 4024 public String getNameForUid(int uid) { 4025 // reader 4026 synchronized (mPackages) { 4027 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4028 if (obj instanceof SharedUserSetting) { 4029 final SharedUserSetting sus = (SharedUserSetting) obj; 4030 return sus.name + ":" + sus.userId; 4031 } else if (obj instanceof PackageSetting) { 4032 final PackageSetting ps = (PackageSetting) obj; 4033 return ps.name; 4034 } 4035 } 4036 return null; 4037 } 4038 4039 @Override 4040 public int getUidForSharedUser(String sharedUserName) { 4041 if(sharedUserName == null) { 4042 return -1; 4043 } 4044 // reader 4045 synchronized (mPackages) { 4046 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4047 if (suid == null) { 4048 return -1; 4049 } 4050 return suid.userId; 4051 } 4052 } 4053 4054 @Override 4055 public int getFlagsForUid(int uid) { 4056 synchronized (mPackages) { 4057 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4058 if (obj instanceof SharedUserSetting) { 4059 final SharedUserSetting sus = (SharedUserSetting) obj; 4060 return sus.pkgFlags; 4061 } else if (obj instanceof PackageSetting) { 4062 final PackageSetting ps = (PackageSetting) obj; 4063 return ps.pkgFlags; 4064 } 4065 } 4066 return 0; 4067 } 4068 4069 @Override 4070 public int getPrivateFlagsForUid(int uid) { 4071 synchronized (mPackages) { 4072 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4073 if (obj instanceof SharedUserSetting) { 4074 final SharedUserSetting sus = (SharedUserSetting) obj; 4075 return sus.pkgPrivateFlags; 4076 } else if (obj instanceof PackageSetting) { 4077 final PackageSetting ps = (PackageSetting) obj; 4078 return ps.pkgPrivateFlags; 4079 } 4080 } 4081 return 0; 4082 } 4083 4084 @Override 4085 public boolean isUidPrivileged(int uid) { 4086 uid = UserHandle.getAppId(uid); 4087 // reader 4088 synchronized (mPackages) { 4089 Object obj = mSettings.getUserIdLPr(uid); 4090 if (obj instanceof SharedUserSetting) { 4091 final SharedUserSetting sus = (SharedUserSetting) obj; 4092 final Iterator<PackageSetting> it = sus.packages.iterator(); 4093 while (it.hasNext()) { 4094 if (it.next().isPrivileged()) { 4095 return true; 4096 } 4097 } 4098 } else if (obj instanceof PackageSetting) { 4099 final PackageSetting ps = (PackageSetting) obj; 4100 return ps.isPrivileged(); 4101 } 4102 } 4103 return false; 4104 } 4105 4106 @Override 4107 public String[] getAppOpPermissionPackages(String permissionName) { 4108 synchronized (mPackages) { 4109 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4110 if (pkgs == null) { 4111 return null; 4112 } 4113 return pkgs.toArray(new String[pkgs.size()]); 4114 } 4115 } 4116 4117 @Override 4118 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4119 int flags, int userId) { 4120 if (!sUserManager.exists(userId)) return null; 4121 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4122 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4123 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4124 } 4125 4126 @Override 4127 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4128 IntentFilter filter, int match, ComponentName activity) { 4129 final int userId = UserHandle.getCallingUserId(); 4130 if (DEBUG_PREFERRED) { 4131 Log.v(TAG, "setLastChosenActivity intent=" + intent 4132 + " resolvedType=" + resolvedType 4133 + " flags=" + flags 4134 + " filter=" + filter 4135 + " match=" + match 4136 + " activity=" + activity); 4137 filter.dump(new PrintStreamPrinter(System.out), " "); 4138 } 4139 intent.setComponent(null); 4140 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4141 // Find any earlier preferred or last chosen entries and nuke them 4142 findPreferredActivity(intent, resolvedType, 4143 flags, query, 0, false, true, false, userId); 4144 // Add the new activity as the last chosen for this filter 4145 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4146 "Setting last chosen"); 4147 } 4148 4149 @Override 4150 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4151 final int userId = UserHandle.getCallingUserId(); 4152 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4153 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4154 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4155 false, false, false, userId); 4156 } 4157 4158 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4159 int flags, List<ResolveInfo> query, int userId) { 4160 if (query != null) { 4161 final int N = query.size(); 4162 if (N == 1) { 4163 return query.get(0); 4164 } else if (N > 1) { 4165 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4166 // If there is more than one activity with the same priority, 4167 // then let the user decide between them. 4168 ResolveInfo r0 = query.get(0); 4169 ResolveInfo r1 = query.get(1); 4170 if (DEBUG_INTENT_MATCHING || debug) { 4171 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4172 + r1.activityInfo.name + "=" + r1.priority); 4173 } 4174 // If the first activity has a higher priority, or a different 4175 // default, then it is always desireable to pick it. 4176 if (r0.priority != r1.priority 4177 || r0.preferredOrder != r1.preferredOrder 4178 || r0.isDefault != r1.isDefault) { 4179 return query.get(0); 4180 } 4181 // If we have saved a preference for a preferred activity for 4182 // this Intent, use that. 4183 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4184 flags, query, r0.priority, true, false, debug, userId); 4185 if (ri != null) { 4186 return ri; 4187 } 4188 if (userId != 0) { 4189 ri = new ResolveInfo(mResolveInfo); 4190 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4191 ri.activityInfo.applicationInfo = new ApplicationInfo( 4192 ri.activityInfo.applicationInfo); 4193 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4194 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4195 return ri; 4196 } 4197 return mResolveInfo; 4198 } 4199 } 4200 return null; 4201 } 4202 4203 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4204 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4205 final int N = query.size(); 4206 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4207 .get(userId); 4208 // Get the list of persistent preferred activities that handle the intent 4209 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4210 List<PersistentPreferredActivity> pprefs = ppir != null 4211 ? ppir.queryIntent(intent, resolvedType, 4212 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4213 : null; 4214 if (pprefs != null && pprefs.size() > 0) { 4215 final int M = pprefs.size(); 4216 for (int i=0; i<M; i++) { 4217 final PersistentPreferredActivity ppa = pprefs.get(i); 4218 if (DEBUG_PREFERRED || debug) { 4219 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4220 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4221 + "\n component=" + ppa.mComponent); 4222 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4223 } 4224 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4225 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4226 if (DEBUG_PREFERRED || debug) { 4227 Slog.v(TAG, "Found persistent preferred activity:"); 4228 if (ai != null) { 4229 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4230 } else { 4231 Slog.v(TAG, " null"); 4232 } 4233 } 4234 if (ai == null) { 4235 // This previously registered persistent preferred activity 4236 // component is no longer known. Ignore it and do NOT remove it. 4237 continue; 4238 } 4239 for (int j=0; j<N; j++) { 4240 final ResolveInfo ri = query.get(j); 4241 if (!ri.activityInfo.applicationInfo.packageName 4242 .equals(ai.applicationInfo.packageName)) { 4243 continue; 4244 } 4245 if (!ri.activityInfo.name.equals(ai.name)) { 4246 continue; 4247 } 4248 // Found a persistent preference that can handle the intent. 4249 if (DEBUG_PREFERRED || debug) { 4250 Slog.v(TAG, "Returning persistent preferred activity: " + 4251 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4252 } 4253 return ri; 4254 } 4255 } 4256 } 4257 return null; 4258 } 4259 4260 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4261 List<ResolveInfo> query, int priority, boolean always, 4262 boolean removeMatches, boolean debug, int userId) { 4263 if (!sUserManager.exists(userId)) return null; 4264 // writer 4265 synchronized (mPackages) { 4266 if (intent.getSelector() != null) { 4267 intent = intent.getSelector(); 4268 } 4269 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4270 4271 // Try to find a matching persistent preferred activity. 4272 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4273 debug, userId); 4274 4275 // If a persistent preferred activity matched, use it. 4276 if (pri != null) { 4277 return pri; 4278 } 4279 4280 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4281 // Get the list of preferred activities that handle the intent 4282 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4283 List<PreferredActivity> prefs = pir != null 4284 ? pir.queryIntent(intent, resolvedType, 4285 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4286 : null; 4287 if (prefs != null && prefs.size() > 0) { 4288 boolean changed = false; 4289 try { 4290 // First figure out how good the original match set is. 4291 // We will only allow preferred activities that came 4292 // from the same match quality. 4293 int match = 0; 4294 4295 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4296 4297 final int N = query.size(); 4298 for (int j=0; j<N; j++) { 4299 final ResolveInfo ri = query.get(j); 4300 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4301 + ": 0x" + Integer.toHexString(match)); 4302 if (ri.match > match) { 4303 match = ri.match; 4304 } 4305 } 4306 4307 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4308 + Integer.toHexString(match)); 4309 4310 match &= IntentFilter.MATCH_CATEGORY_MASK; 4311 final int M = prefs.size(); 4312 for (int i=0; i<M; i++) { 4313 final PreferredActivity pa = prefs.get(i); 4314 if (DEBUG_PREFERRED || debug) { 4315 Slog.v(TAG, "Checking PreferredActivity ds=" 4316 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4317 + "\n component=" + pa.mPref.mComponent); 4318 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4319 } 4320 if (pa.mPref.mMatch != match) { 4321 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4322 + Integer.toHexString(pa.mPref.mMatch)); 4323 continue; 4324 } 4325 // If it's not an "always" type preferred activity and that's what we're 4326 // looking for, skip it. 4327 if (always && !pa.mPref.mAlways) { 4328 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4329 continue; 4330 } 4331 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4332 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4333 if (DEBUG_PREFERRED || debug) { 4334 Slog.v(TAG, "Found preferred activity:"); 4335 if (ai != null) { 4336 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4337 } else { 4338 Slog.v(TAG, " null"); 4339 } 4340 } 4341 if (ai == null) { 4342 // This previously registered preferred activity 4343 // component is no longer known. Most likely an update 4344 // to the app was installed and in the new version this 4345 // component no longer exists. Clean it up by removing 4346 // it from the preferred activities list, and skip it. 4347 Slog.w(TAG, "Removing dangling preferred activity: " 4348 + pa.mPref.mComponent); 4349 pir.removeFilter(pa); 4350 changed = true; 4351 continue; 4352 } 4353 for (int j=0; j<N; j++) { 4354 final ResolveInfo ri = query.get(j); 4355 if (!ri.activityInfo.applicationInfo.packageName 4356 .equals(ai.applicationInfo.packageName)) { 4357 continue; 4358 } 4359 if (!ri.activityInfo.name.equals(ai.name)) { 4360 continue; 4361 } 4362 4363 if (removeMatches) { 4364 pir.removeFilter(pa); 4365 changed = true; 4366 if (DEBUG_PREFERRED) { 4367 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4368 } 4369 break; 4370 } 4371 4372 // Okay we found a previously set preferred or last chosen app. 4373 // If the result set is different from when this 4374 // was created, we need to clear it and re-ask the 4375 // user their preference, if we're looking for an "always" type entry. 4376 if (always && !pa.mPref.sameSet(query)) { 4377 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4378 + intent + " type " + resolvedType); 4379 if (DEBUG_PREFERRED) { 4380 Slog.v(TAG, "Removing preferred activity since set changed " 4381 + pa.mPref.mComponent); 4382 } 4383 pir.removeFilter(pa); 4384 // Re-add the filter as a "last chosen" entry (!always) 4385 PreferredActivity lastChosen = new PreferredActivity( 4386 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4387 pir.addFilter(lastChosen); 4388 changed = true; 4389 return null; 4390 } 4391 4392 // Yay! Either the set matched or we're looking for the last chosen 4393 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4394 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4395 return ri; 4396 } 4397 } 4398 } finally { 4399 if (changed) { 4400 if (DEBUG_PREFERRED) { 4401 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4402 } 4403 scheduleWritePackageRestrictionsLocked(userId); 4404 } 4405 } 4406 } 4407 } 4408 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4409 return null; 4410 } 4411 4412 /* 4413 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4414 */ 4415 @Override 4416 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4417 int targetUserId) { 4418 mContext.enforceCallingOrSelfPermission( 4419 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4420 List<CrossProfileIntentFilter> matches = 4421 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4422 if (matches != null) { 4423 int size = matches.size(); 4424 for (int i = 0; i < size; i++) { 4425 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4426 } 4427 } 4428 if (hasWebURI(intent)) { 4429 // cross-profile app linking works only towards the parent. 4430 final UserInfo parent = getProfileParent(sourceUserId); 4431 synchronized(mPackages) { 4432 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4433 intent, resolvedType, 0, sourceUserId, parent.id); 4434 return xpDomainInfo != null 4435 && xpDomainInfo.bestDomainVerificationStatus != 4436 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 4437 } 4438 } 4439 return false; 4440 } 4441 4442 private UserInfo getProfileParent(int userId) { 4443 final long identity = Binder.clearCallingIdentity(); 4444 try { 4445 return sUserManager.getProfileParent(userId); 4446 } finally { 4447 Binder.restoreCallingIdentity(identity); 4448 } 4449 } 4450 4451 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4452 String resolvedType, int userId) { 4453 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4454 if (resolver != null) { 4455 return resolver.queryIntent(intent, resolvedType, false, userId); 4456 } 4457 return null; 4458 } 4459 4460 @Override 4461 public List<ResolveInfo> queryIntentActivities(Intent intent, 4462 String resolvedType, int flags, int userId) { 4463 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4464 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4465 ComponentName comp = intent.getComponent(); 4466 if (comp == null) { 4467 if (intent.getSelector() != null) { 4468 intent = intent.getSelector(); 4469 comp = intent.getComponent(); 4470 } 4471 } 4472 4473 if (comp != null) { 4474 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4475 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4476 if (ai != null) { 4477 final ResolveInfo ri = new ResolveInfo(); 4478 ri.activityInfo = ai; 4479 list.add(ri); 4480 } 4481 return list; 4482 } 4483 4484 // reader 4485 synchronized (mPackages) { 4486 final String pkgName = intent.getPackage(); 4487 if (pkgName == null) { 4488 List<CrossProfileIntentFilter> matchingFilters = 4489 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4490 // Check for results that need to skip the current profile. 4491 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4492 resolvedType, flags, userId); 4493 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4494 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4495 result.add(xpResolveInfo); 4496 return filterIfNotPrimaryUser(result, userId); 4497 } 4498 4499 // Check for results in the current profile. 4500 List<ResolveInfo> result = mActivities.queryIntent( 4501 intent, resolvedType, flags, userId); 4502 4503 // Check for cross profile results. 4504 xpResolveInfo = queryCrossProfileIntents( 4505 matchingFilters, intent, resolvedType, flags, userId); 4506 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4507 result.add(xpResolveInfo); 4508 Collections.sort(result, mResolvePrioritySorter); 4509 } 4510 result = filterIfNotPrimaryUser(result, userId); 4511 if (hasWebURI(intent)) { 4512 CrossProfileDomainInfo xpDomainInfo = null; 4513 final UserInfo parent = getProfileParent(userId); 4514 if (parent != null) { 4515 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4516 flags, userId, parent.id); 4517 } 4518 if (xpDomainInfo != null) { 4519 if (xpResolveInfo != null) { 4520 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4521 // in the result. 4522 result.remove(xpResolveInfo); 4523 } 4524 if (result.size() == 0) { 4525 result.add(xpDomainInfo.resolveInfo); 4526 return result; 4527 } 4528 } else if (result.size() <= 1) { 4529 return result; 4530 } 4531 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4532 xpDomainInfo, userId); 4533 Collections.sort(result, mResolvePrioritySorter); 4534 } 4535 return result; 4536 } 4537 final PackageParser.Package pkg = mPackages.get(pkgName); 4538 if (pkg != null) { 4539 return filterIfNotPrimaryUser( 4540 mActivities.queryIntentForPackage( 4541 intent, resolvedType, flags, pkg.activities, userId), 4542 userId); 4543 } 4544 return new ArrayList<ResolveInfo>(); 4545 } 4546 } 4547 4548 private static class CrossProfileDomainInfo { 4549 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4550 ResolveInfo resolveInfo; 4551 /* Best domain verification status of the activities found in the other profile */ 4552 int bestDomainVerificationStatus; 4553 } 4554 4555 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4556 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4557 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4558 sourceUserId)) { 4559 return null; 4560 } 4561 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4562 resolvedType, flags, parentUserId); 4563 4564 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4565 return null; 4566 } 4567 CrossProfileDomainInfo result = null; 4568 int size = resultTargetUser.size(); 4569 for (int i = 0; i < size; i++) { 4570 ResolveInfo riTargetUser = resultTargetUser.get(i); 4571 // Intent filter verification is only for filters that specify a host. So don't return 4572 // those that handle all web uris. 4573 if (riTargetUser.handleAllWebDataURI) { 4574 continue; 4575 } 4576 String packageName = riTargetUser.activityInfo.packageName; 4577 PackageSetting ps = mSettings.mPackages.get(packageName); 4578 if (ps == null) { 4579 continue; 4580 } 4581 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4582 int status = (int)(verificationState >> 32); 4583 if (result == null) { 4584 result = new CrossProfileDomainInfo(); 4585 result.resolveInfo = 4586 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4587 result.bestDomainVerificationStatus = status; 4588 } else { 4589 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4590 result.bestDomainVerificationStatus); 4591 } 4592 } 4593 return result; 4594 } 4595 4596 /** 4597 * Verification statuses are ordered from the worse to the best, except for 4598 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4599 */ 4600 private int bestDomainVerificationStatus(int status1, int status2) { 4601 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4602 return status2; 4603 } 4604 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4605 return status1; 4606 } 4607 return (int) MathUtils.max(status1, status2); 4608 } 4609 4610 private boolean isUserEnabled(int userId) { 4611 long callingId = Binder.clearCallingIdentity(); 4612 try { 4613 UserInfo userInfo = sUserManager.getUserInfo(userId); 4614 return userInfo != null && userInfo.isEnabled(); 4615 } finally { 4616 Binder.restoreCallingIdentity(callingId); 4617 } 4618 } 4619 4620 /** 4621 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4622 * 4623 * @return filtered list 4624 */ 4625 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4626 if (userId == UserHandle.USER_OWNER) { 4627 return resolveInfos; 4628 } 4629 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4630 ResolveInfo info = resolveInfos.get(i); 4631 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4632 resolveInfos.remove(i); 4633 } 4634 } 4635 return resolveInfos; 4636 } 4637 4638 private static boolean hasWebURI(Intent intent) { 4639 if (intent.getData() == null) { 4640 return false; 4641 } 4642 final String scheme = intent.getScheme(); 4643 if (TextUtils.isEmpty(scheme)) { 4644 return false; 4645 } 4646 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4647 } 4648 4649 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4650 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 4651 int userId) { 4652 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4653 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 4654 candidates.size()); 4655 } 4656 4657 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4658 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4659 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4660 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4661 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4662 4663 synchronized (mPackages) { 4664 final int count = candidates.size(); 4665 // First, try to use linked apps. Partition the candidates into four lists: 4666 // one for the final results, one for the "do not use ever", one for "undefined status" 4667 // and finally one for "browser app type". 4668 for (int n=0; n<count; n++) { 4669 ResolveInfo info = candidates.get(n); 4670 String packageName = info.activityInfo.packageName; 4671 PackageSetting ps = mSettings.mPackages.get(packageName); 4672 if (ps != null) { 4673 // Add to the special match all list (Browser use case) 4674 if (info.handleAllWebDataURI) { 4675 matchAllList.add(info); 4676 continue; 4677 } 4678 // Try to get the status from User settings first 4679 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4680 int status = (int)(packedStatus >> 32); 4681 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 4682 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4683 if (DEBUG_DOMAIN_VERIFICATION) { 4684 Slog.i(TAG, " + always: " + info.activityInfo.packageName 4685 + " : linkgen=" + linkGeneration); 4686 } 4687 // Use link-enabled generation as preferredOrder, i.e. 4688 // prefer newly-enabled over earlier-enabled. 4689 info.preferredOrder = linkGeneration; 4690 alwaysList.add(info); 4691 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4692 if (DEBUG_DOMAIN_VERIFICATION) { 4693 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4694 } 4695 neverList.add(info); 4696 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4697 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4698 if (DEBUG_DOMAIN_VERIFICATION) { 4699 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4700 } 4701 undefinedList.add(info); 4702 } 4703 } 4704 } 4705 // First try to add the "always" resolution(s) for the current user, if any 4706 if (alwaysList.size() > 0) { 4707 result.addAll(alwaysList); 4708 // if there is an "always" for the parent user, add it. 4709 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4710 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4711 result.add(xpDomainInfo.resolveInfo); 4712 } else { 4713 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4714 result.addAll(undefinedList); 4715 if (xpDomainInfo != null && ( 4716 xpDomainInfo.bestDomainVerificationStatus 4717 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4718 || xpDomainInfo.bestDomainVerificationStatus 4719 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4720 result.add(xpDomainInfo.resolveInfo); 4721 } 4722 // Also add Browsers (all of them or only the default one) 4723 if ((flags & MATCH_ALL) != 0) { 4724 result.addAll(matchAllList); 4725 } else { 4726 // Try to add the Default Browser if we can 4727 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4728 UserHandle.myUserId()); 4729 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4730 boolean defaultBrowserFound = false; 4731 final int browserCount = matchAllList.size(); 4732 for (int n=0; n<browserCount; n++) { 4733 ResolveInfo browser = matchAllList.get(n); 4734 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4735 result.add(browser); 4736 defaultBrowserFound = true; 4737 break; 4738 } 4739 } 4740 if (!defaultBrowserFound) { 4741 result.addAll(matchAllList); 4742 } 4743 } else { 4744 result.addAll(matchAllList); 4745 } 4746 } 4747 4748 // If there is nothing selected, add all candidates and remove the ones that the user 4749 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4750 if (result.size() == 0) { 4751 result.addAll(candidates); 4752 result.removeAll(neverList); 4753 } 4754 } 4755 } 4756 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4757 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4758 result.size()); 4759 for (ResolveInfo info : result) { 4760 Slog.v(TAG, " + " + info.activityInfo); 4761 } 4762 } 4763 return result; 4764 } 4765 4766 // Returns a packed value as a long: 4767 // 4768 // high 'int'-sized word: link status: undefined/ask/never/always. 4769 // low 'int'-sized word: relative priority among 'always' results. 4770 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4771 long result = ps.getDomainVerificationStatusForUser(userId); 4772 // if none available, get the master status 4773 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4774 if (ps.getIntentFilterVerificationInfo() != null) { 4775 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 4776 } 4777 } 4778 return result; 4779 } 4780 4781 private ResolveInfo querySkipCurrentProfileIntents( 4782 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4783 int flags, int sourceUserId) { 4784 if (matchingFilters != null) { 4785 int size = matchingFilters.size(); 4786 for (int i = 0; i < size; i ++) { 4787 CrossProfileIntentFilter filter = matchingFilters.get(i); 4788 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4789 // Checking if there are activities in the target user that can handle the 4790 // intent. 4791 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4792 flags, sourceUserId); 4793 if (resolveInfo != null) { 4794 return resolveInfo; 4795 } 4796 } 4797 } 4798 } 4799 return null; 4800 } 4801 4802 // Return matching ResolveInfo if any for skip current profile intent filters. 4803 private ResolveInfo queryCrossProfileIntents( 4804 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4805 int flags, int sourceUserId) { 4806 if (matchingFilters != null) { 4807 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4808 // match the same intent. For performance reasons, it is better not to 4809 // run queryIntent twice for the same userId 4810 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4811 int size = matchingFilters.size(); 4812 for (int i = 0; i < size; i++) { 4813 CrossProfileIntentFilter filter = matchingFilters.get(i); 4814 int targetUserId = filter.getTargetUserId(); 4815 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4816 && !alreadyTriedUserIds.get(targetUserId)) { 4817 // Checking if there are activities in the target user that can handle the 4818 // intent. 4819 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4820 flags, sourceUserId); 4821 if (resolveInfo != null) return resolveInfo; 4822 alreadyTriedUserIds.put(targetUserId, true); 4823 } 4824 } 4825 } 4826 return null; 4827 } 4828 4829 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4830 String resolvedType, int flags, int sourceUserId) { 4831 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4832 resolvedType, flags, filter.getTargetUserId()); 4833 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4834 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4835 } 4836 return null; 4837 } 4838 4839 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4840 int sourceUserId, int targetUserId) { 4841 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4842 String className; 4843 if (targetUserId == UserHandle.USER_OWNER) { 4844 className = FORWARD_INTENT_TO_USER_OWNER; 4845 } else { 4846 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4847 } 4848 ComponentName forwardingActivityComponentName = new ComponentName( 4849 mAndroidApplication.packageName, className); 4850 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4851 sourceUserId); 4852 if (targetUserId == UserHandle.USER_OWNER) { 4853 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4854 forwardingResolveInfo.noResourceId = true; 4855 } 4856 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4857 forwardingResolveInfo.priority = 0; 4858 forwardingResolveInfo.preferredOrder = 0; 4859 forwardingResolveInfo.match = 0; 4860 forwardingResolveInfo.isDefault = true; 4861 forwardingResolveInfo.filter = filter; 4862 forwardingResolveInfo.targetUserId = targetUserId; 4863 return forwardingResolveInfo; 4864 } 4865 4866 @Override 4867 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4868 Intent[] specifics, String[] specificTypes, Intent intent, 4869 String resolvedType, int flags, int userId) { 4870 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4871 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4872 false, "query intent activity options"); 4873 final String resultsAction = intent.getAction(); 4874 4875 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4876 | PackageManager.GET_RESOLVED_FILTER, userId); 4877 4878 if (DEBUG_INTENT_MATCHING) { 4879 Log.v(TAG, "Query " + intent + ": " + results); 4880 } 4881 4882 int specificsPos = 0; 4883 int N; 4884 4885 // todo: note that the algorithm used here is O(N^2). This 4886 // isn't a problem in our current environment, but if we start running 4887 // into situations where we have more than 5 or 10 matches then this 4888 // should probably be changed to something smarter... 4889 4890 // First we go through and resolve each of the specific items 4891 // that were supplied, taking care of removing any corresponding 4892 // duplicate items in the generic resolve list. 4893 if (specifics != null) { 4894 for (int i=0; i<specifics.length; i++) { 4895 final Intent sintent = specifics[i]; 4896 if (sintent == null) { 4897 continue; 4898 } 4899 4900 if (DEBUG_INTENT_MATCHING) { 4901 Log.v(TAG, "Specific #" + i + ": " + sintent); 4902 } 4903 4904 String action = sintent.getAction(); 4905 if (resultsAction != null && resultsAction.equals(action)) { 4906 // If this action was explicitly requested, then don't 4907 // remove things that have it. 4908 action = null; 4909 } 4910 4911 ResolveInfo ri = null; 4912 ActivityInfo ai = null; 4913 4914 ComponentName comp = sintent.getComponent(); 4915 if (comp == null) { 4916 ri = resolveIntent( 4917 sintent, 4918 specificTypes != null ? specificTypes[i] : null, 4919 flags, userId); 4920 if (ri == null) { 4921 continue; 4922 } 4923 if (ri == mResolveInfo) { 4924 // ACK! Must do something better with this. 4925 } 4926 ai = ri.activityInfo; 4927 comp = new ComponentName(ai.applicationInfo.packageName, 4928 ai.name); 4929 } else { 4930 ai = getActivityInfo(comp, flags, userId); 4931 if (ai == null) { 4932 continue; 4933 } 4934 } 4935 4936 // Look for any generic query activities that are duplicates 4937 // of this specific one, and remove them from the results. 4938 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4939 N = results.size(); 4940 int j; 4941 for (j=specificsPos; j<N; j++) { 4942 ResolveInfo sri = results.get(j); 4943 if ((sri.activityInfo.name.equals(comp.getClassName()) 4944 && sri.activityInfo.applicationInfo.packageName.equals( 4945 comp.getPackageName())) 4946 || (action != null && sri.filter.matchAction(action))) { 4947 results.remove(j); 4948 if (DEBUG_INTENT_MATCHING) Log.v( 4949 TAG, "Removing duplicate item from " + j 4950 + " due to specific " + specificsPos); 4951 if (ri == null) { 4952 ri = sri; 4953 } 4954 j--; 4955 N--; 4956 } 4957 } 4958 4959 // Add this specific item to its proper place. 4960 if (ri == null) { 4961 ri = new ResolveInfo(); 4962 ri.activityInfo = ai; 4963 } 4964 results.add(specificsPos, ri); 4965 ri.specificIndex = i; 4966 specificsPos++; 4967 } 4968 } 4969 4970 // Now we go through the remaining generic results and remove any 4971 // duplicate actions that are found here. 4972 N = results.size(); 4973 for (int i=specificsPos; i<N-1; i++) { 4974 final ResolveInfo rii = results.get(i); 4975 if (rii.filter == null) { 4976 continue; 4977 } 4978 4979 // Iterate over all of the actions of this result's intent 4980 // filter... typically this should be just one. 4981 final Iterator<String> it = rii.filter.actionsIterator(); 4982 if (it == null) { 4983 continue; 4984 } 4985 while (it.hasNext()) { 4986 final String action = it.next(); 4987 if (resultsAction != null && resultsAction.equals(action)) { 4988 // If this action was explicitly requested, then don't 4989 // remove things that have it. 4990 continue; 4991 } 4992 for (int j=i+1; j<N; j++) { 4993 final ResolveInfo rij = results.get(j); 4994 if (rij.filter != null && rij.filter.hasAction(action)) { 4995 results.remove(j); 4996 if (DEBUG_INTENT_MATCHING) Log.v( 4997 TAG, "Removing duplicate item from " + j 4998 + " due to action " + action + " at " + i); 4999 j--; 5000 N--; 5001 } 5002 } 5003 } 5004 5005 // If the caller didn't request filter information, drop it now 5006 // so we don't have to marshall/unmarshall it. 5007 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5008 rii.filter = null; 5009 } 5010 } 5011 5012 // Filter out the caller activity if so requested. 5013 if (caller != null) { 5014 N = results.size(); 5015 for (int i=0; i<N; i++) { 5016 ActivityInfo ainfo = results.get(i).activityInfo; 5017 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5018 && caller.getClassName().equals(ainfo.name)) { 5019 results.remove(i); 5020 break; 5021 } 5022 } 5023 } 5024 5025 // If the caller didn't request filter information, 5026 // drop them now so we don't have to 5027 // marshall/unmarshall it. 5028 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5029 N = results.size(); 5030 for (int i=0; i<N; i++) { 5031 results.get(i).filter = null; 5032 } 5033 } 5034 5035 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5036 return results; 5037 } 5038 5039 @Override 5040 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5041 int userId) { 5042 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5043 ComponentName comp = intent.getComponent(); 5044 if (comp == null) { 5045 if (intent.getSelector() != null) { 5046 intent = intent.getSelector(); 5047 comp = intent.getComponent(); 5048 } 5049 } 5050 if (comp != null) { 5051 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5052 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5053 if (ai != null) { 5054 ResolveInfo ri = new ResolveInfo(); 5055 ri.activityInfo = ai; 5056 list.add(ri); 5057 } 5058 return list; 5059 } 5060 5061 // reader 5062 synchronized (mPackages) { 5063 String pkgName = intent.getPackage(); 5064 if (pkgName == null) { 5065 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5066 } 5067 final PackageParser.Package pkg = mPackages.get(pkgName); 5068 if (pkg != null) { 5069 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5070 userId); 5071 } 5072 return null; 5073 } 5074 } 5075 5076 @Override 5077 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5078 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5079 if (!sUserManager.exists(userId)) return null; 5080 if (query != null) { 5081 if (query.size() >= 1) { 5082 // If there is more than one service with the same priority, 5083 // just arbitrarily pick the first one. 5084 return query.get(0); 5085 } 5086 } 5087 return null; 5088 } 5089 5090 @Override 5091 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5092 int userId) { 5093 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5094 ComponentName comp = intent.getComponent(); 5095 if (comp == null) { 5096 if (intent.getSelector() != null) { 5097 intent = intent.getSelector(); 5098 comp = intent.getComponent(); 5099 } 5100 } 5101 if (comp != null) { 5102 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5103 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5104 if (si != null) { 5105 final ResolveInfo ri = new ResolveInfo(); 5106 ri.serviceInfo = si; 5107 list.add(ri); 5108 } 5109 return list; 5110 } 5111 5112 // reader 5113 synchronized (mPackages) { 5114 String pkgName = intent.getPackage(); 5115 if (pkgName == null) { 5116 return mServices.queryIntent(intent, resolvedType, flags, userId); 5117 } 5118 final PackageParser.Package pkg = mPackages.get(pkgName); 5119 if (pkg != null) { 5120 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5121 userId); 5122 } 5123 return null; 5124 } 5125 } 5126 5127 @Override 5128 public List<ResolveInfo> queryIntentContentProviders( 5129 Intent intent, String resolvedType, int flags, int userId) { 5130 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5131 ComponentName comp = intent.getComponent(); 5132 if (comp == null) { 5133 if (intent.getSelector() != null) { 5134 intent = intent.getSelector(); 5135 comp = intent.getComponent(); 5136 } 5137 } 5138 if (comp != null) { 5139 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5140 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5141 if (pi != null) { 5142 final ResolveInfo ri = new ResolveInfo(); 5143 ri.providerInfo = pi; 5144 list.add(ri); 5145 } 5146 return list; 5147 } 5148 5149 // reader 5150 synchronized (mPackages) { 5151 String pkgName = intent.getPackage(); 5152 if (pkgName == null) { 5153 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5154 } 5155 final PackageParser.Package pkg = mPackages.get(pkgName); 5156 if (pkg != null) { 5157 return mProviders.queryIntentForPackage( 5158 intent, resolvedType, flags, pkg.providers, userId); 5159 } 5160 return null; 5161 } 5162 } 5163 5164 @Override 5165 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5166 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5167 5168 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5169 5170 // writer 5171 synchronized (mPackages) { 5172 ArrayList<PackageInfo> list; 5173 if (listUninstalled) { 5174 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5175 for (PackageSetting ps : mSettings.mPackages.values()) { 5176 PackageInfo pi; 5177 if (ps.pkg != null) { 5178 pi = generatePackageInfo(ps.pkg, flags, userId); 5179 } else { 5180 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5181 } 5182 if (pi != null) { 5183 list.add(pi); 5184 } 5185 } 5186 } else { 5187 list = new ArrayList<PackageInfo>(mPackages.size()); 5188 for (PackageParser.Package p : mPackages.values()) { 5189 PackageInfo pi = generatePackageInfo(p, flags, userId); 5190 if (pi != null) { 5191 list.add(pi); 5192 } 5193 } 5194 } 5195 5196 return new ParceledListSlice<PackageInfo>(list); 5197 } 5198 } 5199 5200 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5201 String[] permissions, boolean[] tmp, int flags, int userId) { 5202 int numMatch = 0; 5203 final PermissionsState permissionsState = ps.getPermissionsState(); 5204 for (int i=0; i<permissions.length; i++) { 5205 final String permission = permissions[i]; 5206 if (permissionsState.hasPermission(permission, userId)) { 5207 tmp[i] = true; 5208 numMatch++; 5209 } else { 5210 tmp[i] = false; 5211 } 5212 } 5213 if (numMatch == 0) { 5214 return; 5215 } 5216 PackageInfo pi; 5217 if (ps.pkg != null) { 5218 pi = generatePackageInfo(ps.pkg, flags, userId); 5219 } else { 5220 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5221 } 5222 // The above might return null in cases of uninstalled apps or install-state 5223 // skew across users/profiles. 5224 if (pi != null) { 5225 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5226 if (numMatch == permissions.length) { 5227 pi.requestedPermissions = permissions; 5228 } else { 5229 pi.requestedPermissions = new String[numMatch]; 5230 numMatch = 0; 5231 for (int i=0; i<permissions.length; i++) { 5232 if (tmp[i]) { 5233 pi.requestedPermissions[numMatch] = permissions[i]; 5234 numMatch++; 5235 } 5236 } 5237 } 5238 } 5239 list.add(pi); 5240 } 5241 } 5242 5243 @Override 5244 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5245 String[] permissions, int flags, int userId) { 5246 if (!sUserManager.exists(userId)) return null; 5247 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5248 5249 // writer 5250 synchronized (mPackages) { 5251 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5252 boolean[] tmpBools = new boolean[permissions.length]; 5253 if (listUninstalled) { 5254 for (PackageSetting ps : mSettings.mPackages.values()) { 5255 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5256 } 5257 } else { 5258 for (PackageParser.Package pkg : mPackages.values()) { 5259 PackageSetting ps = (PackageSetting)pkg.mExtras; 5260 if (ps != null) { 5261 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5262 userId); 5263 } 5264 } 5265 } 5266 5267 return new ParceledListSlice<PackageInfo>(list); 5268 } 5269 } 5270 5271 @Override 5272 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5273 if (!sUserManager.exists(userId)) return null; 5274 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5275 5276 // writer 5277 synchronized (mPackages) { 5278 ArrayList<ApplicationInfo> list; 5279 if (listUninstalled) { 5280 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5281 for (PackageSetting ps : mSettings.mPackages.values()) { 5282 ApplicationInfo ai; 5283 if (ps.pkg != null) { 5284 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5285 ps.readUserState(userId), userId); 5286 } else { 5287 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5288 } 5289 if (ai != null) { 5290 list.add(ai); 5291 } 5292 } 5293 } else { 5294 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5295 for (PackageParser.Package p : mPackages.values()) { 5296 if (p.mExtras != null) { 5297 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5298 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5299 if (ai != null) { 5300 list.add(ai); 5301 } 5302 } 5303 } 5304 } 5305 5306 return new ParceledListSlice<ApplicationInfo>(list); 5307 } 5308 } 5309 5310 public List<ApplicationInfo> getPersistentApplications(int flags) { 5311 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5312 5313 // reader 5314 synchronized (mPackages) { 5315 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5316 final int userId = UserHandle.getCallingUserId(); 5317 while (i.hasNext()) { 5318 final PackageParser.Package p = i.next(); 5319 if (p.applicationInfo != null 5320 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5321 && (!mSafeMode || isSystemApp(p))) { 5322 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5323 if (ps != null) { 5324 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5325 ps.readUserState(userId), userId); 5326 if (ai != null) { 5327 finalList.add(ai); 5328 } 5329 } 5330 } 5331 } 5332 } 5333 5334 return finalList; 5335 } 5336 5337 @Override 5338 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5339 if (!sUserManager.exists(userId)) return null; 5340 // reader 5341 synchronized (mPackages) { 5342 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5343 PackageSetting ps = provider != null 5344 ? mSettings.mPackages.get(provider.owner.packageName) 5345 : null; 5346 return ps != null 5347 && mSettings.isEnabledLPr(provider.info, flags, userId) 5348 && (!mSafeMode || (provider.info.applicationInfo.flags 5349 &ApplicationInfo.FLAG_SYSTEM) != 0) 5350 ? PackageParser.generateProviderInfo(provider, flags, 5351 ps.readUserState(userId), userId) 5352 : null; 5353 } 5354 } 5355 5356 /** 5357 * @deprecated 5358 */ 5359 @Deprecated 5360 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5361 // reader 5362 synchronized (mPackages) { 5363 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5364 .entrySet().iterator(); 5365 final int userId = UserHandle.getCallingUserId(); 5366 while (i.hasNext()) { 5367 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5368 PackageParser.Provider p = entry.getValue(); 5369 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5370 5371 if (ps != null && p.syncable 5372 && (!mSafeMode || (p.info.applicationInfo.flags 5373 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5374 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5375 ps.readUserState(userId), userId); 5376 if (info != null) { 5377 outNames.add(entry.getKey()); 5378 outInfo.add(info); 5379 } 5380 } 5381 } 5382 } 5383 } 5384 5385 @Override 5386 public List<ProviderInfo> queryContentProviders(String processName, 5387 int uid, int flags) { 5388 ArrayList<ProviderInfo> finalList = null; 5389 // reader 5390 synchronized (mPackages) { 5391 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5392 final int userId = processName != null ? 5393 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5394 while (i.hasNext()) { 5395 final PackageParser.Provider p = i.next(); 5396 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5397 if (ps != null && p.info.authority != null 5398 && (processName == null 5399 || (p.info.processName.equals(processName) 5400 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5401 && mSettings.isEnabledLPr(p.info, flags, userId) 5402 && (!mSafeMode 5403 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5404 if (finalList == null) { 5405 finalList = new ArrayList<ProviderInfo>(3); 5406 } 5407 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5408 ps.readUserState(userId), userId); 5409 if (info != null) { 5410 finalList.add(info); 5411 } 5412 } 5413 } 5414 } 5415 5416 if (finalList != null) { 5417 Collections.sort(finalList, mProviderInitOrderSorter); 5418 } 5419 5420 return finalList; 5421 } 5422 5423 @Override 5424 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5425 int flags) { 5426 // reader 5427 synchronized (mPackages) { 5428 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5429 return PackageParser.generateInstrumentationInfo(i, flags); 5430 } 5431 } 5432 5433 @Override 5434 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5435 int flags) { 5436 ArrayList<InstrumentationInfo> finalList = 5437 new ArrayList<InstrumentationInfo>(); 5438 5439 // reader 5440 synchronized (mPackages) { 5441 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5442 while (i.hasNext()) { 5443 final PackageParser.Instrumentation p = i.next(); 5444 if (targetPackage == null 5445 || targetPackage.equals(p.info.targetPackage)) { 5446 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5447 flags); 5448 if (ii != null) { 5449 finalList.add(ii); 5450 } 5451 } 5452 } 5453 } 5454 5455 return finalList; 5456 } 5457 5458 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5459 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5460 if (overlays == null) { 5461 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5462 return; 5463 } 5464 for (PackageParser.Package opkg : overlays.values()) { 5465 // Not much to do if idmap fails: we already logged the error 5466 // and we certainly don't want to abort installation of pkg simply 5467 // because an overlay didn't fit properly. For these reasons, 5468 // ignore the return value of createIdmapForPackagePairLI. 5469 createIdmapForPackagePairLI(pkg, opkg); 5470 } 5471 } 5472 5473 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5474 PackageParser.Package opkg) { 5475 if (!opkg.mTrustedOverlay) { 5476 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5477 opkg.baseCodePath + ": overlay not trusted"); 5478 return false; 5479 } 5480 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5481 if (overlaySet == null) { 5482 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5483 opkg.baseCodePath + " but target package has no known overlays"); 5484 return false; 5485 } 5486 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5487 // TODO: generate idmap for split APKs 5488 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5489 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5490 + opkg.baseCodePath); 5491 return false; 5492 } 5493 PackageParser.Package[] overlayArray = 5494 overlaySet.values().toArray(new PackageParser.Package[0]); 5495 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5496 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5497 return p1.mOverlayPriority - p2.mOverlayPriority; 5498 } 5499 }; 5500 Arrays.sort(overlayArray, cmp); 5501 5502 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5503 int i = 0; 5504 for (PackageParser.Package p : overlayArray) { 5505 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5506 } 5507 return true; 5508 } 5509 5510 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5511 final File[] files = dir.listFiles(); 5512 if (ArrayUtils.isEmpty(files)) { 5513 Log.d(TAG, "No files in app dir " + dir); 5514 return; 5515 } 5516 5517 if (DEBUG_PACKAGE_SCANNING) { 5518 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5519 + " flags=0x" + Integer.toHexString(parseFlags)); 5520 } 5521 5522 for (File file : files) { 5523 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5524 && !PackageInstallerService.isStageName(file.getName()); 5525 if (!isPackage) { 5526 // Ignore entries which are not packages 5527 continue; 5528 } 5529 try { 5530 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5531 scanFlags, currentTime, null); 5532 } catch (PackageManagerException e) { 5533 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5534 5535 // Delete invalid userdata apps 5536 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5537 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5538 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5539 if (file.isDirectory()) { 5540 mInstaller.rmPackageDir(file.getAbsolutePath()); 5541 } else { 5542 file.delete(); 5543 } 5544 } 5545 } 5546 } 5547 } 5548 5549 private static File getSettingsProblemFile() { 5550 File dataDir = Environment.getDataDirectory(); 5551 File systemDir = new File(dataDir, "system"); 5552 File fname = new File(systemDir, "uiderrors.txt"); 5553 return fname; 5554 } 5555 5556 static void reportSettingsProblem(int priority, String msg) { 5557 logCriticalInfo(priority, msg); 5558 } 5559 5560 static void logCriticalInfo(int priority, String msg) { 5561 Slog.println(priority, TAG, msg); 5562 EventLogTags.writePmCriticalInfo(msg); 5563 try { 5564 File fname = getSettingsProblemFile(); 5565 FileOutputStream out = new FileOutputStream(fname, true); 5566 PrintWriter pw = new FastPrintWriter(out); 5567 SimpleDateFormat formatter = new SimpleDateFormat(); 5568 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5569 pw.println(dateString + ": " + msg); 5570 pw.close(); 5571 FileUtils.setPermissions( 5572 fname.toString(), 5573 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5574 -1, -1); 5575 } catch (java.io.IOException e) { 5576 } 5577 } 5578 5579 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5580 PackageParser.Package pkg, File srcFile, int parseFlags) 5581 throws PackageManagerException { 5582 if (ps != null 5583 && ps.codePath.equals(srcFile) 5584 && ps.timeStamp == srcFile.lastModified() 5585 && !isCompatSignatureUpdateNeeded(pkg) 5586 && !isRecoverSignatureUpdateNeeded(pkg)) { 5587 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5588 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5589 ArraySet<PublicKey> signingKs; 5590 synchronized (mPackages) { 5591 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5592 } 5593 if (ps.signatures.mSignatures != null 5594 && ps.signatures.mSignatures.length != 0 5595 && signingKs != null) { 5596 // Optimization: reuse the existing cached certificates 5597 // if the package appears to be unchanged. 5598 pkg.mSignatures = ps.signatures.mSignatures; 5599 pkg.mSigningKeys = signingKs; 5600 return; 5601 } 5602 5603 Slog.w(TAG, "PackageSetting for " + ps.name 5604 + " is missing signatures. Collecting certs again to recover them."); 5605 } else { 5606 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5607 } 5608 5609 try { 5610 pp.collectCertificates(pkg, parseFlags); 5611 pp.collectManifestDigest(pkg); 5612 } catch (PackageParserException e) { 5613 throw PackageManagerException.from(e); 5614 } 5615 } 5616 5617 /* 5618 * Scan a package and return the newly parsed package. 5619 * Returns null in case of errors and the error code is stored in mLastScanError 5620 */ 5621 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5622 long currentTime, UserHandle user) throws PackageManagerException { 5623 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5624 parseFlags |= mDefParseFlags; 5625 PackageParser pp = new PackageParser(); 5626 pp.setSeparateProcesses(mSeparateProcesses); 5627 pp.setOnlyCoreApps(mOnlyCore); 5628 pp.setDisplayMetrics(mMetrics); 5629 5630 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5631 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5632 } 5633 5634 final PackageParser.Package pkg; 5635 try { 5636 pkg = pp.parsePackage(scanFile, parseFlags); 5637 } catch (PackageParserException e) { 5638 throw PackageManagerException.from(e); 5639 } 5640 5641 PackageSetting ps = null; 5642 PackageSetting updatedPkg; 5643 // reader 5644 synchronized (mPackages) { 5645 // Look to see if we already know about this package. 5646 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5647 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5648 // This package has been renamed to its original name. Let's 5649 // use that. 5650 ps = mSettings.peekPackageLPr(oldName); 5651 } 5652 // If there was no original package, see one for the real package name. 5653 if (ps == null) { 5654 ps = mSettings.peekPackageLPr(pkg.packageName); 5655 } 5656 // Check to see if this package could be hiding/updating a system 5657 // package. Must look for it either under the original or real 5658 // package name depending on our state. 5659 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5660 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5661 } 5662 boolean updatedPkgBetter = false; 5663 // First check if this is a system package that may involve an update 5664 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5665 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5666 // it needs to drop FLAG_PRIVILEGED. 5667 if (locationIsPrivileged(scanFile)) { 5668 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5669 } else { 5670 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5671 } 5672 5673 if (ps != null && !ps.codePath.equals(scanFile)) { 5674 // The path has changed from what was last scanned... check the 5675 // version of the new path against what we have stored to determine 5676 // what to do. 5677 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5678 if (pkg.mVersionCode <= ps.versionCode) { 5679 // The system package has been updated and the code path does not match 5680 // Ignore entry. Skip it. 5681 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5682 + " ignored: updated version " + ps.versionCode 5683 + " better than this " + pkg.mVersionCode); 5684 if (!updatedPkg.codePath.equals(scanFile)) { 5685 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5686 + ps.name + " changing from " + updatedPkg.codePathString 5687 + " to " + scanFile); 5688 updatedPkg.codePath = scanFile; 5689 updatedPkg.codePathString = scanFile.toString(); 5690 updatedPkg.resourcePath = scanFile; 5691 updatedPkg.resourcePathString = scanFile.toString(); 5692 } 5693 updatedPkg.pkg = pkg; 5694 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5695 "Package " + ps.name + " at " + scanFile 5696 + " ignored: updated version " + ps.versionCode 5697 + " better than this " + pkg.mVersionCode); 5698 } else { 5699 // The current app on the system partition is better than 5700 // what we have updated to on the data partition; switch 5701 // back to the system partition version. 5702 // At this point, its safely assumed that package installation for 5703 // apps in system partition will go through. If not there won't be a working 5704 // version of the app 5705 // writer 5706 synchronized (mPackages) { 5707 // Just remove the loaded entries from package lists. 5708 mPackages.remove(ps.name); 5709 } 5710 5711 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5712 + " reverting from " + ps.codePathString 5713 + ": new version " + pkg.mVersionCode 5714 + " better than installed " + ps.versionCode); 5715 5716 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5717 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5718 synchronized (mInstallLock) { 5719 args.cleanUpResourcesLI(); 5720 } 5721 synchronized (mPackages) { 5722 mSettings.enableSystemPackageLPw(ps.name); 5723 } 5724 updatedPkgBetter = true; 5725 } 5726 } 5727 } 5728 5729 if (updatedPkg != null) { 5730 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5731 // initially 5732 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5733 5734 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5735 // flag set initially 5736 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5737 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5738 } 5739 } 5740 5741 // Verify certificates against what was last scanned 5742 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5743 5744 /* 5745 * A new system app appeared, but we already had a non-system one of the 5746 * same name installed earlier. 5747 */ 5748 boolean shouldHideSystemApp = false; 5749 if (updatedPkg == null && ps != null 5750 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5751 /* 5752 * Check to make sure the signatures match first. If they don't, 5753 * wipe the installed application and its data. 5754 */ 5755 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5756 != PackageManager.SIGNATURE_MATCH) { 5757 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5758 + " signatures don't match existing userdata copy; removing"); 5759 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5760 ps = null; 5761 } else { 5762 /* 5763 * If the newly-added system app is an older version than the 5764 * already installed version, hide it. It will be scanned later 5765 * and re-added like an update. 5766 */ 5767 if (pkg.mVersionCode <= ps.versionCode) { 5768 shouldHideSystemApp = true; 5769 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5770 + " but new version " + pkg.mVersionCode + " better than installed " 5771 + ps.versionCode + "; hiding system"); 5772 } else { 5773 /* 5774 * The newly found system app is a newer version that the 5775 * one previously installed. Simply remove the 5776 * already-installed application and replace it with our own 5777 * while keeping the application data. 5778 */ 5779 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5780 + " reverting from " + ps.codePathString + ": new version " 5781 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5782 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5783 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5784 synchronized (mInstallLock) { 5785 args.cleanUpResourcesLI(); 5786 } 5787 } 5788 } 5789 } 5790 5791 // The apk is forward locked (not public) if its code and resources 5792 // are kept in different files. (except for app in either system or 5793 // vendor path). 5794 // TODO grab this value from PackageSettings 5795 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5796 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5797 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5798 } 5799 } 5800 5801 // TODO: extend to support forward-locked splits 5802 String resourcePath = null; 5803 String baseResourcePath = null; 5804 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5805 if (ps != null && ps.resourcePathString != null) { 5806 resourcePath = ps.resourcePathString; 5807 baseResourcePath = ps.resourcePathString; 5808 } else { 5809 // Should not happen at all. Just log an error. 5810 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5811 } 5812 } else { 5813 resourcePath = pkg.codePath; 5814 baseResourcePath = pkg.baseCodePath; 5815 } 5816 5817 // Set application objects path explicitly. 5818 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5819 pkg.applicationInfo.setCodePath(pkg.codePath); 5820 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5821 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5822 pkg.applicationInfo.setResourcePath(resourcePath); 5823 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5824 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5825 5826 // Note that we invoke the following method only if we are about to unpack an application 5827 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5828 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5829 5830 /* 5831 * If the system app should be overridden by a previously installed 5832 * data, hide the system app now and let the /data/app scan pick it up 5833 * again. 5834 */ 5835 if (shouldHideSystemApp) { 5836 synchronized (mPackages) { 5837 /* 5838 * We have to grant systems permissions before we hide, because 5839 * grantPermissions will assume the package update is trying to 5840 * expand its permissions. 5841 */ 5842 grantPermissionsLPw(pkg, true, pkg.packageName); 5843 mSettings.disableSystemPackageLPw(pkg.packageName); 5844 } 5845 } 5846 5847 return scannedPkg; 5848 } 5849 5850 private static String fixProcessName(String defProcessName, 5851 String processName, int uid) { 5852 if (processName == null) { 5853 return defProcessName; 5854 } 5855 return processName; 5856 } 5857 5858 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5859 throws PackageManagerException { 5860 if (pkgSetting.signatures.mSignatures != null) { 5861 // Already existing package. Make sure signatures match 5862 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5863 == PackageManager.SIGNATURE_MATCH; 5864 if (!match) { 5865 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5866 == PackageManager.SIGNATURE_MATCH; 5867 } 5868 if (!match) { 5869 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5870 == PackageManager.SIGNATURE_MATCH; 5871 } 5872 if (!match) { 5873 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5874 + pkg.packageName + " signatures do not match the " 5875 + "previously installed version; ignoring!"); 5876 } 5877 } 5878 5879 // Check for shared user signatures 5880 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5881 // Already existing package. Make sure signatures match 5882 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5883 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5884 if (!match) { 5885 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5886 == PackageManager.SIGNATURE_MATCH; 5887 } 5888 if (!match) { 5889 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5890 == PackageManager.SIGNATURE_MATCH; 5891 } 5892 if (!match) { 5893 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5894 "Package " + pkg.packageName 5895 + " has no signatures that match those in shared user " 5896 + pkgSetting.sharedUser.name + "; ignoring!"); 5897 } 5898 } 5899 } 5900 5901 /** 5902 * Enforces that only the system UID or root's UID can call a method exposed 5903 * via Binder. 5904 * 5905 * @param message used as message if SecurityException is thrown 5906 * @throws SecurityException if the caller is not system or root 5907 */ 5908 private static final void enforceSystemOrRoot(String message) { 5909 final int uid = Binder.getCallingUid(); 5910 if (uid != Process.SYSTEM_UID && uid != 0) { 5911 throw new SecurityException(message); 5912 } 5913 } 5914 5915 @Override 5916 public void performBootDexOpt() { 5917 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5918 5919 // Before everything else, see whether we need to fstrim. 5920 try { 5921 IMountService ms = PackageHelper.getMountService(); 5922 if (ms != null) { 5923 final boolean isUpgrade = isUpgrade(); 5924 boolean doTrim = isUpgrade; 5925 if (doTrim) { 5926 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5927 } else { 5928 final long interval = android.provider.Settings.Global.getLong( 5929 mContext.getContentResolver(), 5930 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5931 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5932 if (interval > 0) { 5933 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5934 if (timeSinceLast > interval) { 5935 doTrim = true; 5936 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5937 + "; running immediately"); 5938 } 5939 } 5940 } 5941 if (doTrim) { 5942 if (!isFirstBoot()) { 5943 try { 5944 ActivityManagerNative.getDefault().showBootMessage( 5945 mContext.getResources().getString( 5946 R.string.android_upgrading_fstrim), true); 5947 } catch (RemoteException e) { 5948 } 5949 } 5950 ms.runMaintenance(); 5951 } 5952 } else { 5953 Slog.e(TAG, "Mount service unavailable!"); 5954 } 5955 } catch (RemoteException e) { 5956 // Can't happen; MountService is local 5957 } 5958 5959 final ArraySet<PackageParser.Package> pkgs; 5960 synchronized (mPackages) { 5961 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5962 } 5963 5964 if (pkgs != null) { 5965 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5966 // in case the device runs out of space. 5967 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5968 // Give priority to core apps. 5969 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5970 PackageParser.Package pkg = it.next(); 5971 if (pkg.coreApp) { 5972 if (DEBUG_DEXOPT) { 5973 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5974 } 5975 sortedPkgs.add(pkg); 5976 it.remove(); 5977 } 5978 } 5979 // Give priority to system apps that listen for pre boot complete. 5980 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5981 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5982 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5983 PackageParser.Package pkg = it.next(); 5984 if (pkgNames.contains(pkg.packageName)) { 5985 if (DEBUG_DEXOPT) { 5986 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5987 } 5988 sortedPkgs.add(pkg); 5989 it.remove(); 5990 } 5991 } 5992 // Give priority to system apps. 5993 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5994 PackageParser.Package pkg = it.next(); 5995 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5996 if (DEBUG_DEXOPT) { 5997 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5998 } 5999 sortedPkgs.add(pkg); 6000 it.remove(); 6001 } 6002 } 6003 // Give priority to updated system apps. 6004 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6005 PackageParser.Package pkg = it.next(); 6006 if (pkg.isUpdatedSystemApp()) { 6007 if (DEBUG_DEXOPT) { 6008 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 6009 } 6010 sortedPkgs.add(pkg); 6011 it.remove(); 6012 } 6013 } 6014 // Give priority to apps that listen for boot complete. 6015 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 6016 pkgNames = getPackageNamesForIntent(intent); 6017 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 6018 PackageParser.Package pkg = it.next(); 6019 if (pkgNames.contains(pkg.packageName)) { 6020 if (DEBUG_DEXOPT) { 6021 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 6022 } 6023 sortedPkgs.add(pkg); 6024 it.remove(); 6025 } 6026 } 6027 // Filter out packages that aren't recently used. 6028 filterRecentlyUsedApps(pkgs); 6029 // Add all remaining apps. 6030 for (PackageParser.Package pkg : pkgs) { 6031 if (DEBUG_DEXOPT) { 6032 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 6033 } 6034 sortedPkgs.add(pkg); 6035 } 6036 6037 // If we want to be lazy, filter everything that wasn't recently used. 6038 if (mLazyDexOpt) { 6039 filterRecentlyUsedApps(sortedPkgs); 6040 } 6041 6042 int i = 0; 6043 int total = sortedPkgs.size(); 6044 File dataDir = Environment.getDataDirectory(); 6045 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 6046 if (lowThreshold == 0) { 6047 throw new IllegalStateException("Invalid low memory threshold"); 6048 } 6049 for (PackageParser.Package pkg : sortedPkgs) { 6050 long usableSpace = dataDir.getUsableSpace(); 6051 if (usableSpace < lowThreshold) { 6052 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6053 break; 6054 } 6055 performBootDexOpt(pkg, ++i, total); 6056 } 6057 } 6058 } 6059 6060 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6061 // Filter out packages that aren't recently used. 6062 // 6063 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6064 // should do a full dexopt. 6065 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6066 int total = pkgs.size(); 6067 int skipped = 0; 6068 long now = System.currentTimeMillis(); 6069 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6070 PackageParser.Package pkg = i.next(); 6071 long then = pkg.mLastPackageUsageTimeInMills; 6072 if (then + mDexOptLRUThresholdInMills < now) { 6073 if (DEBUG_DEXOPT) { 6074 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6075 ((then == 0) ? "never" : new Date(then))); 6076 } 6077 i.remove(); 6078 skipped++; 6079 } 6080 } 6081 if (DEBUG_DEXOPT) { 6082 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6083 } 6084 } 6085 } 6086 6087 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6088 List<ResolveInfo> ris = null; 6089 try { 6090 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6091 intent, null, 0, UserHandle.USER_OWNER); 6092 } catch (RemoteException e) { 6093 } 6094 ArraySet<String> pkgNames = new ArraySet<String>(); 6095 if (ris != null) { 6096 for (ResolveInfo ri : ris) { 6097 pkgNames.add(ri.activityInfo.packageName); 6098 } 6099 } 6100 return pkgNames; 6101 } 6102 6103 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6104 if (DEBUG_DEXOPT) { 6105 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6106 } 6107 if (!isFirstBoot()) { 6108 try { 6109 ActivityManagerNative.getDefault().showBootMessage( 6110 mContext.getResources().getString(R.string.android_upgrading_apk, 6111 curr, total), true); 6112 } catch (RemoteException e) { 6113 } 6114 } 6115 PackageParser.Package p = pkg; 6116 synchronized (mInstallLock) { 6117 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6118 false /* force dex */, false /* defer */, true /* include dependencies */); 6119 } 6120 } 6121 6122 @Override 6123 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6124 return performDexOpt(packageName, instructionSet, false); 6125 } 6126 6127 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6128 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6129 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6130 if (!dexopt && !updateUsage) { 6131 // We aren't going to dexopt or update usage, so bail early. 6132 return false; 6133 } 6134 PackageParser.Package p; 6135 final String targetInstructionSet; 6136 synchronized (mPackages) { 6137 p = mPackages.get(packageName); 6138 if (p == null) { 6139 return false; 6140 } 6141 if (updateUsage) { 6142 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6143 } 6144 mPackageUsage.write(false); 6145 if (!dexopt) { 6146 // We aren't going to dexopt, so bail early. 6147 return false; 6148 } 6149 6150 targetInstructionSet = instructionSet != null ? instructionSet : 6151 getPrimaryInstructionSet(p.applicationInfo); 6152 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6153 return false; 6154 } 6155 } 6156 6157 synchronized (mInstallLock) { 6158 final String[] instructionSets = new String[] { targetInstructionSet }; 6159 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6160 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6161 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6162 } 6163 } 6164 6165 public ArraySet<String> getPackagesThatNeedDexOpt() { 6166 ArraySet<String> pkgs = null; 6167 synchronized (mPackages) { 6168 for (PackageParser.Package p : mPackages.values()) { 6169 if (DEBUG_DEXOPT) { 6170 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6171 } 6172 if (!p.mDexOptPerformed.isEmpty()) { 6173 continue; 6174 } 6175 if (pkgs == null) { 6176 pkgs = new ArraySet<String>(); 6177 } 6178 pkgs.add(p.packageName); 6179 } 6180 } 6181 return pkgs; 6182 } 6183 6184 public void shutdown() { 6185 mPackageUsage.write(true); 6186 } 6187 6188 @Override 6189 public void forceDexOpt(String packageName) { 6190 enforceSystemOrRoot("forceDexOpt"); 6191 6192 PackageParser.Package pkg; 6193 synchronized (mPackages) { 6194 pkg = mPackages.get(packageName); 6195 if (pkg == null) { 6196 throw new IllegalArgumentException("Missing package: " + packageName); 6197 } 6198 } 6199 6200 synchronized (mInstallLock) { 6201 final String[] instructionSets = new String[] { 6202 getPrimaryInstructionSet(pkg.applicationInfo) }; 6203 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6204 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6205 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6206 throw new IllegalStateException("Failed to dexopt: " + res); 6207 } 6208 } 6209 } 6210 6211 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6212 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6213 Slog.w(TAG, "Unable to update from " + oldPkg.name 6214 + " to " + newPkg.packageName 6215 + ": old package not in system partition"); 6216 return false; 6217 } else if (mPackages.get(oldPkg.name) != null) { 6218 Slog.w(TAG, "Unable to update from " + oldPkg.name 6219 + " to " + newPkg.packageName 6220 + ": old package still exists"); 6221 return false; 6222 } 6223 return true; 6224 } 6225 6226 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6227 int[] users = sUserManager.getUserIds(); 6228 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6229 if (res < 0) { 6230 return res; 6231 } 6232 for (int user : users) { 6233 if (user != 0) { 6234 res = mInstaller.createUserData(volumeUuid, packageName, 6235 UserHandle.getUid(user, uid), user, seinfo); 6236 if (res < 0) { 6237 return res; 6238 } 6239 } 6240 } 6241 return res; 6242 } 6243 6244 private int removeDataDirsLI(String volumeUuid, String packageName) { 6245 int[] users = sUserManager.getUserIds(); 6246 int res = 0; 6247 for (int user : users) { 6248 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6249 if (resInner < 0) { 6250 res = resInner; 6251 } 6252 } 6253 6254 return res; 6255 } 6256 6257 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6258 int[] users = sUserManager.getUserIds(); 6259 int res = 0; 6260 for (int user : users) { 6261 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6262 if (resInner < 0) { 6263 res = resInner; 6264 } 6265 } 6266 return res; 6267 } 6268 6269 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6270 PackageParser.Package changingLib) { 6271 if (file.path != null) { 6272 usesLibraryFiles.add(file.path); 6273 return; 6274 } 6275 PackageParser.Package p = mPackages.get(file.apk); 6276 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6277 // If we are doing this while in the middle of updating a library apk, 6278 // then we need to make sure to use that new apk for determining the 6279 // dependencies here. (We haven't yet finished committing the new apk 6280 // to the package manager state.) 6281 if (p == null || p.packageName.equals(changingLib.packageName)) { 6282 p = changingLib; 6283 } 6284 } 6285 if (p != null) { 6286 usesLibraryFiles.addAll(p.getAllCodePaths()); 6287 } 6288 } 6289 6290 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6291 PackageParser.Package changingLib) throws PackageManagerException { 6292 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6293 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6294 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6295 for (int i=0; i<N; i++) { 6296 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6297 if (file == null) { 6298 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6299 "Package " + pkg.packageName + " requires unavailable shared library " 6300 + pkg.usesLibraries.get(i) + "; failing!"); 6301 } 6302 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6303 } 6304 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6305 for (int i=0; i<N; i++) { 6306 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6307 if (file == null) { 6308 Slog.w(TAG, "Package " + pkg.packageName 6309 + " desires unavailable shared library " 6310 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6311 } else { 6312 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6313 } 6314 } 6315 N = usesLibraryFiles.size(); 6316 if (N > 0) { 6317 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6318 } else { 6319 pkg.usesLibraryFiles = null; 6320 } 6321 } 6322 } 6323 6324 private static boolean hasString(List<String> list, List<String> which) { 6325 if (list == null) { 6326 return false; 6327 } 6328 for (int i=list.size()-1; i>=0; i--) { 6329 for (int j=which.size()-1; j>=0; j--) { 6330 if (which.get(j).equals(list.get(i))) { 6331 return true; 6332 } 6333 } 6334 } 6335 return false; 6336 } 6337 6338 private void updateAllSharedLibrariesLPw() { 6339 for (PackageParser.Package pkg : mPackages.values()) { 6340 try { 6341 updateSharedLibrariesLPw(pkg, null); 6342 } catch (PackageManagerException e) { 6343 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6344 } 6345 } 6346 } 6347 6348 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6349 PackageParser.Package changingPkg) { 6350 ArrayList<PackageParser.Package> res = null; 6351 for (PackageParser.Package pkg : mPackages.values()) { 6352 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6353 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6354 if (res == null) { 6355 res = new ArrayList<PackageParser.Package>(); 6356 } 6357 res.add(pkg); 6358 try { 6359 updateSharedLibrariesLPw(pkg, changingPkg); 6360 } catch (PackageManagerException e) { 6361 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6362 } 6363 } 6364 } 6365 return res; 6366 } 6367 6368 /** 6369 * Derive the value of the {@code cpuAbiOverride} based on the provided 6370 * value and an optional stored value from the package settings. 6371 */ 6372 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6373 String cpuAbiOverride = null; 6374 6375 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6376 cpuAbiOverride = null; 6377 } else if (abiOverride != null) { 6378 cpuAbiOverride = abiOverride; 6379 } else if (settings != null) { 6380 cpuAbiOverride = settings.cpuAbiOverrideString; 6381 } 6382 6383 return cpuAbiOverride; 6384 } 6385 6386 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6387 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6388 boolean success = false; 6389 try { 6390 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6391 currentTime, user); 6392 success = true; 6393 return res; 6394 } finally { 6395 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6396 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6397 } 6398 } 6399 } 6400 6401 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6402 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6403 final File scanFile = new File(pkg.codePath); 6404 if (pkg.applicationInfo.getCodePath() == null || 6405 pkg.applicationInfo.getResourcePath() == null) { 6406 // Bail out. The resource and code paths haven't been set. 6407 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6408 "Code and resource paths haven't been set correctly"); 6409 } 6410 6411 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6412 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6413 } else { 6414 // Only allow system apps to be flagged as core apps. 6415 pkg.coreApp = false; 6416 } 6417 6418 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6419 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6420 } 6421 6422 if (mCustomResolverComponentName != null && 6423 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6424 setUpCustomResolverActivity(pkg); 6425 } 6426 6427 if (pkg.packageName.equals("android")) { 6428 synchronized (mPackages) { 6429 if (mAndroidApplication != null) { 6430 Slog.w(TAG, "*************************************************"); 6431 Slog.w(TAG, "Core android package being redefined. Skipping."); 6432 Slog.w(TAG, " file=" + scanFile); 6433 Slog.w(TAG, "*************************************************"); 6434 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6435 "Core android package being redefined. Skipping."); 6436 } 6437 6438 // Set up information for our fall-back user intent resolution activity. 6439 mPlatformPackage = pkg; 6440 pkg.mVersionCode = mSdkVersion; 6441 mAndroidApplication = pkg.applicationInfo; 6442 6443 if (!mResolverReplaced) { 6444 mResolveActivity.applicationInfo = mAndroidApplication; 6445 mResolveActivity.name = ResolverActivity.class.getName(); 6446 mResolveActivity.packageName = mAndroidApplication.packageName; 6447 mResolveActivity.processName = "system:ui"; 6448 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6449 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6450 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6451 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6452 mResolveActivity.exported = true; 6453 mResolveActivity.enabled = true; 6454 mResolveInfo.activityInfo = mResolveActivity; 6455 mResolveInfo.priority = 0; 6456 mResolveInfo.preferredOrder = 0; 6457 mResolveInfo.match = 0; 6458 mResolveComponentName = new ComponentName( 6459 mAndroidApplication.packageName, mResolveActivity.name); 6460 } 6461 } 6462 } 6463 6464 if (DEBUG_PACKAGE_SCANNING) { 6465 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6466 Log.d(TAG, "Scanning package " + pkg.packageName); 6467 } 6468 6469 if (mPackages.containsKey(pkg.packageName) 6470 || mSharedLibraries.containsKey(pkg.packageName)) { 6471 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6472 "Application package " + pkg.packageName 6473 + " already installed. Skipping duplicate."); 6474 } 6475 6476 // If we're only installing presumed-existing packages, require that the 6477 // scanned APK is both already known and at the path previously established 6478 // for it. Previously unknown packages we pick up normally, but if we have an 6479 // a priori expectation about this package's install presence, enforce it. 6480 // With a singular exception for new system packages. When an OTA contains 6481 // a new system package, we allow the codepath to change from a system location 6482 // to the user-installed location. If we don't allow this change, any newer, 6483 // user-installed version of the application will be ignored. 6484 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6485 if (mExpectingBetter.containsKey(pkg.packageName)) { 6486 logCriticalInfo(Log.WARN, 6487 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6488 } else { 6489 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6490 if (known != null) { 6491 if (DEBUG_PACKAGE_SCANNING) { 6492 Log.d(TAG, "Examining " + pkg.codePath 6493 + " and requiring known paths " + known.codePathString 6494 + " & " + known.resourcePathString); 6495 } 6496 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6497 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6498 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6499 "Application package " + pkg.packageName 6500 + " found at " + pkg.applicationInfo.getCodePath() 6501 + " but expected at " + known.codePathString + "; ignoring."); 6502 } 6503 } 6504 } 6505 } 6506 6507 // Initialize package source and resource directories 6508 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6509 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6510 6511 SharedUserSetting suid = null; 6512 PackageSetting pkgSetting = null; 6513 6514 if (!isSystemApp(pkg)) { 6515 // Only system apps can use these features. 6516 pkg.mOriginalPackages = null; 6517 pkg.mRealPackage = null; 6518 pkg.mAdoptPermissions = null; 6519 } 6520 6521 // writer 6522 synchronized (mPackages) { 6523 if (pkg.mSharedUserId != null) { 6524 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6525 if (suid == null) { 6526 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6527 "Creating application package " + pkg.packageName 6528 + " for shared user failed"); 6529 } 6530 if (DEBUG_PACKAGE_SCANNING) { 6531 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6532 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6533 + "): packages=" + suid.packages); 6534 } 6535 } 6536 6537 // Check if we are renaming from an original package name. 6538 PackageSetting origPackage = null; 6539 String realName = null; 6540 if (pkg.mOriginalPackages != null) { 6541 // This package may need to be renamed to a previously 6542 // installed name. Let's check on that... 6543 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6544 if (pkg.mOriginalPackages.contains(renamed)) { 6545 // This package had originally been installed as the 6546 // original name, and we have already taken care of 6547 // transitioning to the new one. Just update the new 6548 // one to continue using the old name. 6549 realName = pkg.mRealPackage; 6550 if (!pkg.packageName.equals(renamed)) { 6551 // Callers into this function may have already taken 6552 // care of renaming the package; only do it here if 6553 // it is not already done. 6554 pkg.setPackageName(renamed); 6555 } 6556 6557 } else { 6558 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6559 if ((origPackage = mSettings.peekPackageLPr( 6560 pkg.mOriginalPackages.get(i))) != null) { 6561 // We do have the package already installed under its 6562 // original name... should we use it? 6563 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6564 // New package is not compatible with original. 6565 origPackage = null; 6566 continue; 6567 } else if (origPackage.sharedUser != null) { 6568 // Make sure uid is compatible between packages. 6569 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6570 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6571 + " to " + pkg.packageName + ": old uid " 6572 + origPackage.sharedUser.name 6573 + " differs from " + pkg.mSharedUserId); 6574 origPackage = null; 6575 continue; 6576 } 6577 } else { 6578 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6579 + pkg.packageName + " to old name " + origPackage.name); 6580 } 6581 break; 6582 } 6583 } 6584 } 6585 } 6586 6587 if (mTransferedPackages.contains(pkg.packageName)) { 6588 Slog.w(TAG, "Package " + pkg.packageName 6589 + " was transferred to another, but its .apk remains"); 6590 } 6591 6592 // Just create the setting, don't add it yet. For already existing packages 6593 // the PkgSetting exists already and doesn't have to be created. 6594 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6595 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6596 pkg.applicationInfo.primaryCpuAbi, 6597 pkg.applicationInfo.secondaryCpuAbi, 6598 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6599 user, false); 6600 if (pkgSetting == null) { 6601 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6602 "Creating application package " + pkg.packageName + " failed"); 6603 } 6604 6605 if (pkgSetting.origPackage != null) { 6606 // If we are first transitioning from an original package, 6607 // fix up the new package's name now. We need to do this after 6608 // looking up the package under its new name, so getPackageLP 6609 // can take care of fiddling things correctly. 6610 pkg.setPackageName(origPackage.name); 6611 6612 // File a report about this. 6613 String msg = "New package " + pkgSetting.realName 6614 + " renamed to replace old package " + pkgSetting.name; 6615 reportSettingsProblem(Log.WARN, msg); 6616 6617 // Make a note of it. 6618 mTransferedPackages.add(origPackage.name); 6619 6620 // No longer need to retain this. 6621 pkgSetting.origPackage = null; 6622 } 6623 6624 if (realName != null) { 6625 // Make a note of it. 6626 mTransferedPackages.add(pkg.packageName); 6627 } 6628 6629 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6630 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6631 } 6632 6633 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6634 // Check all shared libraries and map to their actual file path. 6635 // We only do this here for apps not on a system dir, because those 6636 // are the only ones that can fail an install due to this. We 6637 // will take care of the system apps by updating all of their 6638 // library paths after the scan is done. 6639 updateSharedLibrariesLPw(pkg, null); 6640 } 6641 6642 if (mFoundPolicyFile) { 6643 SELinuxMMAC.assignSeinfoValue(pkg); 6644 } 6645 6646 pkg.applicationInfo.uid = pkgSetting.appId; 6647 pkg.mExtras = pkgSetting; 6648 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6649 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6650 // We just determined the app is signed correctly, so bring 6651 // over the latest parsed certs. 6652 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6653 } else { 6654 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6655 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6656 "Package " + pkg.packageName + " upgrade keys do not match the " 6657 + "previously installed version"); 6658 } else { 6659 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6660 String msg = "System package " + pkg.packageName 6661 + " signature changed; retaining data."; 6662 reportSettingsProblem(Log.WARN, msg); 6663 } 6664 } 6665 } else { 6666 try { 6667 verifySignaturesLP(pkgSetting, pkg); 6668 // We just determined the app is signed correctly, so bring 6669 // over the latest parsed certs. 6670 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6671 } catch (PackageManagerException e) { 6672 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6673 throw e; 6674 } 6675 // The signature has changed, but this package is in the system 6676 // image... let's recover! 6677 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6678 // However... if this package is part of a shared user, but it 6679 // doesn't match the signature of the shared user, let's fail. 6680 // What this means is that you can't change the signatures 6681 // associated with an overall shared user, which doesn't seem all 6682 // that unreasonable. 6683 if (pkgSetting.sharedUser != null) { 6684 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6685 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6686 throw new PackageManagerException( 6687 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6688 "Signature mismatch for shared user : " 6689 + pkgSetting.sharedUser); 6690 } 6691 } 6692 // File a report about this. 6693 String msg = "System package " + pkg.packageName 6694 + " signature changed; retaining data."; 6695 reportSettingsProblem(Log.WARN, msg); 6696 } 6697 } 6698 // Verify that this new package doesn't have any content providers 6699 // that conflict with existing packages. Only do this if the 6700 // package isn't already installed, since we don't want to break 6701 // things that are installed. 6702 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6703 final int N = pkg.providers.size(); 6704 int i; 6705 for (i=0; i<N; i++) { 6706 PackageParser.Provider p = pkg.providers.get(i); 6707 if (p.info.authority != null) { 6708 String names[] = p.info.authority.split(";"); 6709 for (int j = 0; j < names.length; j++) { 6710 if (mProvidersByAuthority.containsKey(names[j])) { 6711 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6712 final String otherPackageName = 6713 ((other != null && other.getComponentName() != null) ? 6714 other.getComponentName().getPackageName() : "?"); 6715 throw new PackageManagerException( 6716 INSTALL_FAILED_CONFLICTING_PROVIDER, 6717 "Can't install because provider name " + names[j] 6718 + " (in package " + pkg.applicationInfo.packageName 6719 + ") is already used by " + otherPackageName); 6720 } 6721 } 6722 } 6723 } 6724 } 6725 6726 if (pkg.mAdoptPermissions != null) { 6727 // This package wants to adopt ownership of permissions from 6728 // another package. 6729 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6730 final String origName = pkg.mAdoptPermissions.get(i); 6731 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6732 if (orig != null) { 6733 if (verifyPackageUpdateLPr(orig, pkg)) { 6734 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6735 + pkg.packageName); 6736 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6737 } 6738 } 6739 } 6740 } 6741 } 6742 6743 final String pkgName = pkg.packageName; 6744 6745 final long scanFileTime = scanFile.lastModified(); 6746 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6747 pkg.applicationInfo.processName = fixProcessName( 6748 pkg.applicationInfo.packageName, 6749 pkg.applicationInfo.processName, 6750 pkg.applicationInfo.uid); 6751 6752 File dataPath; 6753 if (mPlatformPackage == pkg) { 6754 // The system package is special. 6755 dataPath = new File(Environment.getDataDirectory(), "system"); 6756 6757 pkg.applicationInfo.dataDir = dataPath.getPath(); 6758 6759 } else { 6760 // This is a normal package, need to make its data directory. 6761 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6762 UserHandle.USER_OWNER, pkg.packageName); 6763 6764 boolean uidError = false; 6765 if (dataPath.exists()) { 6766 int currentUid = 0; 6767 try { 6768 StructStat stat = Os.stat(dataPath.getPath()); 6769 currentUid = stat.st_uid; 6770 } catch (ErrnoException e) { 6771 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6772 } 6773 6774 // If we have mismatched owners for the data path, we have a problem. 6775 if (currentUid != pkg.applicationInfo.uid) { 6776 boolean recovered = false; 6777 if (currentUid == 0) { 6778 // The directory somehow became owned by root. Wow. 6779 // This is probably because the system was stopped while 6780 // installd was in the middle of messing with its libs 6781 // directory. Ask installd to fix that. 6782 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6783 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6784 if (ret >= 0) { 6785 recovered = true; 6786 String msg = "Package " + pkg.packageName 6787 + " unexpectedly changed to uid 0; recovered to " + 6788 + pkg.applicationInfo.uid; 6789 reportSettingsProblem(Log.WARN, msg); 6790 } 6791 } 6792 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6793 || (scanFlags&SCAN_BOOTING) != 0)) { 6794 // If this is a system app, we can at least delete its 6795 // current data so the application will still work. 6796 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6797 if (ret >= 0) { 6798 // TODO: Kill the processes first 6799 // Old data gone! 6800 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6801 ? "System package " : "Third party package "; 6802 String msg = prefix + pkg.packageName 6803 + " has changed from uid: " 6804 + currentUid + " to " 6805 + pkg.applicationInfo.uid + "; old data erased"; 6806 reportSettingsProblem(Log.WARN, msg); 6807 recovered = true; 6808 6809 // And now re-install the app. 6810 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6811 pkg.applicationInfo.seinfo); 6812 if (ret == -1) { 6813 // Ack should not happen! 6814 msg = prefix + pkg.packageName 6815 + " could not have data directory re-created after delete."; 6816 reportSettingsProblem(Log.WARN, msg); 6817 throw new PackageManagerException( 6818 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6819 } 6820 } 6821 if (!recovered) { 6822 mHasSystemUidErrors = true; 6823 } 6824 } else if (!recovered) { 6825 // If we allow this install to proceed, we will be broken. 6826 // Abort, abort! 6827 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6828 "scanPackageLI"); 6829 } 6830 if (!recovered) { 6831 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6832 + pkg.applicationInfo.uid + "/fs_" 6833 + currentUid; 6834 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6835 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6836 String msg = "Package " + pkg.packageName 6837 + " has mismatched uid: " 6838 + currentUid + " on disk, " 6839 + pkg.applicationInfo.uid + " in settings"; 6840 // writer 6841 synchronized (mPackages) { 6842 mSettings.mReadMessages.append(msg); 6843 mSettings.mReadMessages.append('\n'); 6844 uidError = true; 6845 if (!pkgSetting.uidError) { 6846 reportSettingsProblem(Log.ERROR, msg); 6847 } 6848 } 6849 } 6850 } 6851 pkg.applicationInfo.dataDir = dataPath.getPath(); 6852 if (mShouldRestoreconData) { 6853 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6854 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6855 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6856 } 6857 } else { 6858 if (DEBUG_PACKAGE_SCANNING) { 6859 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6860 Log.v(TAG, "Want this data dir: " + dataPath); 6861 } 6862 //invoke installer to do the actual installation 6863 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6864 pkg.applicationInfo.seinfo); 6865 if (ret < 0) { 6866 // Error from installer 6867 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6868 "Unable to create data dirs [errorCode=" + ret + "]"); 6869 } 6870 6871 if (dataPath.exists()) { 6872 pkg.applicationInfo.dataDir = dataPath.getPath(); 6873 } else { 6874 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6875 pkg.applicationInfo.dataDir = null; 6876 } 6877 } 6878 6879 pkgSetting.uidError = uidError; 6880 } 6881 6882 final String path = scanFile.getPath(); 6883 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6884 6885 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6886 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6887 6888 // Some system apps still use directory structure for native libraries 6889 // in which case we might end up not detecting abi solely based on apk 6890 // structure. Try to detect abi based on directory structure. 6891 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6892 pkg.applicationInfo.primaryCpuAbi == null) { 6893 setBundledAppAbisAndRoots(pkg, pkgSetting); 6894 setNativeLibraryPaths(pkg); 6895 } 6896 6897 } else { 6898 if ((scanFlags & SCAN_MOVE) != 0) { 6899 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6900 // but we already have this packages package info in the PackageSetting. We just 6901 // use that and derive the native library path based on the new codepath. 6902 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6903 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6904 } 6905 6906 // Set native library paths again. For moves, the path will be updated based on the 6907 // ABIs we've determined above. For non-moves, the path will be updated based on the 6908 // ABIs we determined during compilation, but the path will depend on the final 6909 // package path (after the rename away from the stage path). 6910 setNativeLibraryPaths(pkg); 6911 } 6912 6913 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6914 final int[] userIds = sUserManager.getUserIds(); 6915 synchronized (mInstallLock) { 6916 // Make sure all user data directories are ready to roll; we're okay 6917 // if they already exist 6918 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6919 for (int userId : userIds) { 6920 if (userId != 0) { 6921 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6922 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6923 pkg.applicationInfo.seinfo); 6924 } 6925 } 6926 } 6927 6928 // Create a native library symlink only if we have native libraries 6929 // and if the native libraries are 32 bit libraries. We do not provide 6930 // this symlink for 64 bit libraries. 6931 if (pkg.applicationInfo.primaryCpuAbi != null && 6932 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6933 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6934 for (int userId : userIds) { 6935 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6936 nativeLibPath, userId) < 0) { 6937 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6938 "Failed linking native library dir (user=" + userId + ")"); 6939 } 6940 } 6941 } 6942 } 6943 6944 // This is a special case for the "system" package, where the ABI is 6945 // dictated by the zygote configuration (and init.rc). We should keep track 6946 // of this ABI so that we can deal with "normal" applications that run under 6947 // the same UID correctly. 6948 if (mPlatformPackage == pkg) { 6949 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6950 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6951 } 6952 6953 // If there's a mismatch between the abi-override in the package setting 6954 // and the abiOverride specified for the install. Warn about this because we 6955 // would've already compiled the app without taking the package setting into 6956 // account. 6957 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6958 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6959 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6960 " for package: " + pkg.packageName); 6961 } 6962 } 6963 6964 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6965 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6966 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6967 6968 // Copy the derived override back to the parsed package, so that we can 6969 // update the package settings accordingly. 6970 pkg.cpuAbiOverride = cpuAbiOverride; 6971 6972 if (DEBUG_ABI_SELECTION) { 6973 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6974 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6975 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6976 } 6977 6978 // Push the derived path down into PackageSettings so we know what to 6979 // clean up at uninstall time. 6980 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6981 6982 if (DEBUG_ABI_SELECTION) { 6983 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6984 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6985 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6986 } 6987 6988 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6989 // We don't do this here during boot because we can do it all 6990 // at once after scanning all existing packages. 6991 // 6992 // We also do this *before* we perform dexopt on this package, so that 6993 // we can avoid redundant dexopts, and also to make sure we've got the 6994 // code and package path correct. 6995 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6996 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6997 } 6998 6999 if ((scanFlags & SCAN_NO_DEX) == 0) { 7000 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 7001 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 7002 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7003 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 7004 } 7005 } 7006 if (mFactoryTest && pkg.requestedPermissions.contains( 7007 android.Manifest.permission.FACTORY_TEST)) { 7008 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7009 } 7010 7011 ArrayList<PackageParser.Package> clientLibPkgs = null; 7012 7013 // writer 7014 synchronized (mPackages) { 7015 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7016 // Only system apps can add new shared libraries. 7017 if (pkg.libraryNames != null) { 7018 for (int i=0; i<pkg.libraryNames.size(); i++) { 7019 String name = pkg.libraryNames.get(i); 7020 boolean allowed = false; 7021 if (pkg.isUpdatedSystemApp()) { 7022 // New library entries can only be added through the 7023 // system image. This is important to get rid of a lot 7024 // of nasty edge cases: for example if we allowed a non- 7025 // system update of the app to add a library, then uninstalling 7026 // the update would make the library go away, and assumptions 7027 // we made such as through app install filtering would now 7028 // have allowed apps on the device which aren't compatible 7029 // with it. Better to just have the restriction here, be 7030 // conservative, and create many fewer cases that can negatively 7031 // impact the user experience. 7032 final PackageSetting sysPs = mSettings 7033 .getDisabledSystemPkgLPr(pkg.packageName); 7034 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7035 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7036 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7037 allowed = true; 7038 allowed = true; 7039 break; 7040 } 7041 } 7042 } 7043 } else { 7044 allowed = true; 7045 } 7046 if (allowed) { 7047 if (!mSharedLibraries.containsKey(name)) { 7048 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7049 } else if (!name.equals(pkg.packageName)) { 7050 Slog.w(TAG, "Package " + pkg.packageName + " library " 7051 + name + " already exists; skipping"); 7052 } 7053 } else { 7054 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7055 + name + " that is not declared on system image; skipping"); 7056 } 7057 } 7058 if ((scanFlags&SCAN_BOOTING) == 0) { 7059 // If we are not booting, we need to update any applications 7060 // that are clients of our shared library. If we are booting, 7061 // this will all be done once the scan is complete. 7062 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7063 } 7064 } 7065 } 7066 } 7067 7068 // We also need to dexopt any apps that are dependent on this library. Note that 7069 // if these fail, we should abort the install since installing the library will 7070 // result in some apps being broken. 7071 if (clientLibPkgs != null) { 7072 if ((scanFlags & SCAN_NO_DEX) == 0) { 7073 for (int i = 0; i < clientLibPkgs.size(); i++) { 7074 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7075 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7076 null /* instruction sets */, forceDex, 7077 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7078 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7079 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7080 "scanPackageLI failed to dexopt clientLibPkgs"); 7081 } 7082 } 7083 } 7084 } 7085 7086 // Also need to kill any apps that are dependent on the library. 7087 if (clientLibPkgs != null) { 7088 for (int i=0; i<clientLibPkgs.size(); i++) { 7089 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7090 killApplication(clientPkg.applicationInfo.packageName, 7091 clientPkg.applicationInfo.uid, "update lib"); 7092 } 7093 } 7094 7095 // Make sure we're not adding any bogus keyset info 7096 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7097 ksms.assertScannedPackageValid(pkg); 7098 7099 // writer 7100 synchronized (mPackages) { 7101 // We don't expect installation to fail beyond this point 7102 7103 // Add the new setting to mSettings 7104 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7105 // Add the new setting to mPackages 7106 mPackages.put(pkg.applicationInfo.packageName, pkg); 7107 // Make sure we don't accidentally delete its data. 7108 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7109 while (iter.hasNext()) { 7110 PackageCleanItem item = iter.next(); 7111 if (pkgName.equals(item.packageName)) { 7112 iter.remove(); 7113 } 7114 } 7115 7116 // Take care of first install / last update times. 7117 if (currentTime != 0) { 7118 if (pkgSetting.firstInstallTime == 0) { 7119 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7120 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7121 pkgSetting.lastUpdateTime = currentTime; 7122 } 7123 } else if (pkgSetting.firstInstallTime == 0) { 7124 // We need *something*. Take time time stamp of the file. 7125 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7126 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7127 if (scanFileTime != pkgSetting.timeStamp) { 7128 // A package on the system image has changed; consider this 7129 // to be an update. 7130 pkgSetting.lastUpdateTime = scanFileTime; 7131 } 7132 } 7133 7134 // Add the package's KeySets to the global KeySetManagerService 7135 ksms.addScannedPackageLPw(pkg); 7136 7137 int N = pkg.providers.size(); 7138 StringBuilder r = null; 7139 int i; 7140 for (i=0; i<N; i++) { 7141 PackageParser.Provider p = pkg.providers.get(i); 7142 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7143 p.info.processName, pkg.applicationInfo.uid); 7144 mProviders.addProvider(p); 7145 p.syncable = p.info.isSyncable; 7146 if (p.info.authority != null) { 7147 String names[] = p.info.authority.split(";"); 7148 p.info.authority = null; 7149 for (int j = 0; j < names.length; j++) { 7150 if (j == 1 && p.syncable) { 7151 // We only want the first authority for a provider to possibly be 7152 // syncable, so if we already added this provider using a different 7153 // authority clear the syncable flag. We copy the provider before 7154 // changing it because the mProviders object contains a reference 7155 // to a provider that we don't want to change. 7156 // Only do this for the second authority since the resulting provider 7157 // object can be the same for all future authorities for this provider. 7158 p = new PackageParser.Provider(p); 7159 p.syncable = false; 7160 } 7161 if (!mProvidersByAuthority.containsKey(names[j])) { 7162 mProvidersByAuthority.put(names[j], p); 7163 if (p.info.authority == null) { 7164 p.info.authority = names[j]; 7165 } else { 7166 p.info.authority = p.info.authority + ";" + names[j]; 7167 } 7168 if (DEBUG_PACKAGE_SCANNING) { 7169 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7170 Log.d(TAG, "Registered content provider: " + names[j] 7171 + ", className = " + p.info.name + ", isSyncable = " 7172 + p.info.isSyncable); 7173 } 7174 } else { 7175 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7176 Slog.w(TAG, "Skipping provider name " + names[j] + 7177 " (in package " + pkg.applicationInfo.packageName + 7178 "): name already used by " 7179 + ((other != null && other.getComponentName() != null) 7180 ? other.getComponentName().getPackageName() : "?")); 7181 } 7182 } 7183 } 7184 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7185 if (r == null) { 7186 r = new StringBuilder(256); 7187 } else { 7188 r.append(' '); 7189 } 7190 r.append(p.info.name); 7191 } 7192 } 7193 if (r != null) { 7194 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7195 } 7196 7197 N = pkg.services.size(); 7198 r = null; 7199 for (i=0; i<N; i++) { 7200 PackageParser.Service s = pkg.services.get(i); 7201 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7202 s.info.processName, pkg.applicationInfo.uid); 7203 mServices.addService(s); 7204 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7205 if (r == null) { 7206 r = new StringBuilder(256); 7207 } else { 7208 r.append(' '); 7209 } 7210 r.append(s.info.name); 7211 } 7212 } 7213 if (r != null) { 7214 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7215 } 7216 7217 N = pkg.receivers.size(); 7218 r = null; 7219 for (i=0; i<N; i++) { 7220 PackageParser.Activity a = pkg.receivers.get(i); 7221 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7222 a.info.processName, pkg.applicationInfo.uid); 7223 mReceivers.addActivity(a, "receiver"); 7224 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7225 if (r == null) { 7226 r = new StringBuilder(256); 7227 } else { 7228 r.append(' '); 7229 } 7230 r.append(a.info.name); 7231 } 7232 } 7233 if (r != null) { 7234 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7235 } 7236 7237 N = pkg.activities.size(); 7238 r = null; 7239 for (i=0; i<N; i++) { 7240 PackageParser.Activity a = pkg.activities.get(i); 7241 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7242 a.info.processName, pkg.applicationInfo.uid); 7243 mActivities.addActivity(a, "activity"); 7244 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7245 if (r == null) { 7246 r = new StringBuilder(256); 7247 } else { 7248 r.append(' '); 7249 } 7250 r.append(a.info.name); 7251 } 7252 } 7253 if (r != null) { 7254 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7255 } 7256 7257 N = pkg.permissionGroups.size(); 7258 r = null; 7259 for (i=0; i<N; i++) { 7260 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7261 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7262 if (cur == null) { 7263 mPermissionGroups.put(pg.info.name, pg); 7264 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7265 if (r == null) { 7266 r = new StringBuilder(256); 7267 } else { 7268 r.append(' '); 7269 } 7270 r.append(pg.info.name); 7271 } 7272 } else { 7273 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7274 + pg.info.packageName + " ignored: original from " 7275 + cur.info.packageName); 7276 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7277 if (r == null) { 7278 r = new StringBuilder(256); 7279 } else { 7280 r.append(' '); 7281 } 7282 r.append("DUP:"); 7283 r.append(pg.info.name); 7284 } 7285 } 7286 } 7287 if (r != null) { 7288 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7289 } 7290 7291 N = pkg.permissions.size(); 7292 r = null; 7293 for (i=0; i<N; i++) { 7294 PackageParser.Permission p = pkg.permissions.get(i); 7295 7296 // Now that permission groups have a special meaning, we ignore permission 7297 // groups for legacy apps to prevent unexpected behavior. In particular, 7298 // permissions for one app being granted to someone just becuase they happen 7299 // to be in a group defined by another app (before this had no implications). 7300 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7301 p.group = mPermissionGroups.get(p.info.group); 7302 // Warn for a permission in an unknown group. 7303 if (p.info.group != null && p.group == null) { 7304 Slog.w(TAG, "Permission " + p.info.name + " from package " 7305 + p.info.packageName + " in an unknown group " + p.info.group); 7306 } 7307 } 7308 7309 ArrayMap<String, BasePermission> permissionMap = 7310 p.tree ? mSettings.mPermissionTrees 7311 : mSettings.mPermissions; 7312 BasePermission bp = permissionMap.get(p.info.name); 7313 7314 // Allow system apps to redefine non-system permissions 7315 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7316 final boolean currentOwnerIsSystem = (bp.perm != null 7317 && isSystemApp(bp.perm.owner)); 7318 if (isSystemApp(p.owner)) { 7319 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7320 // It's a built-in permission and no owner, take ownership now 7321 bp.packageSetting = pkgSetting; 7322 bp.perm = p; 7323 bp.uid = pkg.applicationInfo.uid; 7324 bp.sourcePackage = p.info.packageName; 7325 } else if (!currentOwnerIsSystem) { 7326 String msg = "New decl " + p.owner + " of permission " 7327 + p.info.name + " is system; overriding " + bp.sourcePackage; 7328 reportSettingsProblem(Log.WARN, msg); 7329 bp = null; 7330 } 7331 } 7332 } 7333 7334 if (bp == null) { 7335 bp = new BasePermission(p.info.name, p.info.packageName, 7336 BasePermission.TYPE_NORMAL); 7337 permissionMap.put(p.info.name, bp); 7338 } 7339 7340 if (bp.perm == null) { 7341 if (bp.sourcePackage == null 7342 || bp.sourcePackage.equals(p.info.packageName)) { 7343 BasePermission tree = findPermissionTreeLP(p.info.name); 7344 if (tree == null 7345 || tree.sourcePackage.equals(p.info.packageName)) { 7346 bp.packageSetting = pkgSetting; 7347 bp.perm = p; 7348 bp.uid = pkg.applicationInfo.uid; 7349 bp.sourcePackage = p.info.packageName; 7350 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7351 if (r == null) { 7352 r = new StringBuilder(256); 7353 } else { 7354 r.append(' '); 7355 } 7356 r.append(p.info.name); 7357 } 7358 } else { 7359 Slog.w(TAG, "Permission " + p.info.name + " from package " 7360 + p.info.packageName + " ignored: base tree " 7361 + tree.name + " is from package " 7362 + tree.sourcePackage); 7363 } 7364 } else { 7365 Slog.w(TAG, "Permission " + p.info.name + " from package " 7366 + p.info.packageName + " ignored: original from " 7367 + bp.sourcePackage); 7368 } 7369 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7370 if (r == null) { 7371 r = new StringBuilder(256); 7372 } else { 7373 r.append(' '); 7374 } 7375 r.append("DUP:"); 7376 r.append(p.info.name); 7377 } 7378 if (bp.perm == p) { 7379 bp.protectionLevel = p.info.protectionLevel; 7380 } 7381 } 7382 7383 if (r != null) { 7384 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7385 } 7386 7387 N = pkg.instrumentation.size(); 7388 r = null; 7389 for (i=0; i<N; i++) { 7390 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7391 a.info.packageName = pkg.applicationInfo.packageName; 7392 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7393 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7394 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7395 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7396 a.info.dataDir = pkg.applicationInfo.dataDir; 7397 7398 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7399 // need other information about the application, like the ABI and what not ? 7400 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7401 mInstrumentation.put(a.getComponentName(), a); 7402 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7403 if (r == null) { 7404 r = new StringBuilder(256); 7405 } else { 7406 r.append(' '); 7407 } 7408 r.append(a.info.name); 7409 } 7410 } 7411 if (r != null) { 7412 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7413 } 7414 7415 if (pkg.protectedBroadcasts != null) { 7416 N = pkg.protectedBroadcasts.size(); 7417 for (i=0; i<N; i++) { 7418 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7419 } 7420 } 7421 7422 pkgSetting.setTimeStamp(scanFileTime); 7423 7424 // Create idmap files for pairs of (packages, overlay packages). 7425 // Note: "android", ie framework-res.apk, is handled by native layers. 7426 if (pkg.mOverlayTarget != null) { 7427 // This is an overlay package. 7428 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7429 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7430 mOverlays.put(pkg.mOverlayTarget, 7431 new ArrayMap<String, PackageParser.Package>()); 7432 } 7433 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7434 map.put(pkg.packageName, pkg); 7435 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7436 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7437 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7438 "scanPackageLI failed to createIdmap"); 7439 } 7440 } 7441 } else if (mOverlays.containsKey(pkg.packageName) && 7442 !pkg.packageName.equals("android")) { 7443 // This is a regular package, with one or more known overlay packages. 7444 createIdmapsForPackageLI(pkg); 7445 } 7446 } 7447 7448 return pkg; 7449 } 7450 7451 /** 7452 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7453 * is derived purely on the basis of the contents of {@code scanFile} and 7454 * {@code cpuAbiOverride}. 7455 * 7456 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7457 */ 7458 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7459 String cpuAbiOverride, boolean extractLibs) 7460 throws PackageManagerException { 7461 // TODO: We can probably be smarter about this stuff. For installed apps, 7462 // we can calculate this information at install time once and for all. For 7463 // system apps, we can probably assume that this information doesn't change 7464 // after the first boot scan. As things stand, we do lots of unnecessary work. 7465 7466 // Give ourselves some initial paths; we'll come back for another 7467 // pass once we've determined ABI below. 7468 setNativeLibraryPaths(pkg); 7469 7470 // We would never need to extract libs for forward-locked and external packages, 7471 // since the container service will do it for us. We shouldn't attempt to 7472 // extract libs from system app when it was not updated. 7473 if (pkg.isForwardLocked() || isExternal(pkg) || 7474 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7475 extractLibs = false; 7476 } 7477 7478 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7479 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7480 7481 NativeLibraryHelper.Handle handle = null; 7482 try { 7483 handle = NativeLibraryHelper.Handle.create(pkg); 7484 // TODO(multiArch): This can be null for apps that didn't go through the 7485 // usual installation process. We can calculate it again, like we 7486 // do during install time. 7487 // 7488 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7489 // unnecessary. 7490 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7491 7492 // Null out the abis so that they can be recalculated. 7493 pkg.applicationInfo.primaryCpuAbi = null; 7494 pkg.applicationInfo.secondaryCpuAbi = null; 7495 if (isMultiArch(pkg.applicationInfo)) { 7496 // Warn if we've set an abiOverride for multi-lib packages.. 7497 // By definition, we need to copy both 32 and 64 bit libraries for 7498 // such packages. 7499 if (pkg.cpuAbiOverride != null 7500 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7501 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7502 } 7503 7504 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7505 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7506 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7507 if (extractLibs) { 7508 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7509 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7510 useIsaSpecificSubdirs); 7511 } else { 7512 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7513 } 7514 } 7515 7516 maybeThrowExceptionForMultiArchCopy( 7517 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7518 7519 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7520 if (extractLibs) { 7521 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7522 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7523 useIsaSpecificSubdirs); 7524 } else { 7525 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7526 } 7527 } 7528 7529 maybeThrowExceptionForMultiArchCopy( 7530 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7531 7532 if (abi64 >= 0) { 7533 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7534 } 7535 7536 if (abi32 >= 0) { 7537 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7538 if (abi64 >= 0) { 7539 pkg.applicationInfo.secondaryCpuAbi = abi; 7540 } else { 7541 pkg.applicationInfo.primaryCpuAbi = abi; 7542 } 7543 } 7544 } else { 7545 String[] abiList = (cpuAbiOverride != null) ? 7546 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7547 7548 // Enable gross and lame hacks for apps that are built with old 7549 // SDK tools. We must scan their APKs for renderscript bitcode and 7550 // not launch them if it's present. Don't bother checking on devices 7551 // that don't have 64 bit support. 7552 boolean needsRenderScriptOverride = false; 7553 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7554 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7555 abiList = Build.SUPPORTED_32_BIT_ABIS; 7556 needsRenderScriptOverride = true; 7557 } 7558 7559 final int copyRet; 7560 if (extractLibs) { 7561 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7562 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7563 } else { 7564 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7565 } 7566 7567 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7568 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7569 "Error unpackaging native libs for app, errorCode=" + copyRet); 7570 } 7571 7572 if (copyRet >= 0) { 7573 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7574 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7575 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7576 } else if (needsRenderScriptOverride) { 7577 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7578 } 7579 } 7580 } catch (IOException ioe) { 7581 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7582 } finally { 7583 IoUtils.closeQuietly(handle); 7584 } 7585 7586 // Now that we've calculated the ABIs and determined if it's an internal app, 7587 // we will go ahead and populate the nativeLibraryPath. 7588 setNativeLibraryPaths(pkg); 7589 } 7590 7591 /** 7592 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7593 * i.e, so that all packages can be run inside a single process if required. 7594 * 7595 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7596 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7597 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7598 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7599 * updating a package that belongs to a shared user. 7600 * 7601 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7602 * adds unnecessary complexity. 7603 */ 7604 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7605 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7606 String requiredInstructionSet = null; 7607 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7608 requiredInstructionSet = VMRuntime.getInstructionSet( 7609 scannedPackage.applicationInfo.primaryCpuAbi); 7610 } 7611 7612 PackageSetting requirer = null; 7613 for (PackageSetting ps : packagesForUser) { 7614 // If packagesForUser contains scannedPackage, we skip it. This will happen 7615 // when scannedPackage is an update of an existing package. Without this check, 7616 // we will never be able to change the ABI of any package belonging to a shared 7617 // user, even if it's compatible with other packages. 7618 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7619 if (ps.primaryCpuAbiString == null) { 7620 continue; 7621 } 7622 7623 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7624 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7625 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7626 // this but there's not much we can do. 7627 String errorMessage = "Instruction set mismatch, " 7628 + ((requirer == null) ? "[caller]" : requirer) 7629 + " requires " + requiredInstructionSet + " whereas " + ps 7630 + " requires " + instructionSet; 7631 Slog.w(TAG, errorMessage); 7632 } 7633 7634 if (requiredInstructionSet == null) { 7635 requiredInstructionSet = instructionSet; 7636 requirer = ps; 7637 } 7638 } 7639 } 7640 7641 if (requiredInstructionSet != null) { 7642 String adjustedAbi; 7643 if (requirer != null) { 7644 // requirer != null implies that either scannedPackage was null or that scannedPackage 7645 // did not require an ABI, in which case we have to adjust scannedPackage to match 7646 // the ABI of the set (which is the same as requirer's ABI) 7647 adjustedAbi = requirer.primaryCpuAbiString; 7648 if (scannedPackage != null) { 7649 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7650 } 7651 } else { 7652 // requirer == null implies that we're updating all ABIs in the set to 7653 // match scannedPackage. 7654 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7655 } 7656 7657 for (PackageSetting ps : packagesForUser) { 7658 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7659 if (ps.primaryCpuAbiString != null) { 7660 continue; 7661 } 7662 7663 ps.primaryCpuAbiString = adjustedAbi; 7664 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7665 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7666 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7667 7668 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7669 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7670 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7671 ps.primaryCpuAbiString = null; 7672 ps.pkg.applicationInfo.primaryCpuAbi = null; 7673 return; 7674 } else { 7675 mInstaller.rmdex(ps.codePathString, 7676 getDexCodeInstructionSet(getPreferredInstructionSet())); 7677 } 7678 } 7679 } 7680 } 7681 } 7682 } 7683 7684 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7685 synchronized (mPackages) { 7686 mResolverReplaced = true; 7687 // Set up information for custom user intent resolution activity. 7688 mResolveActivity.applicationInfo = pkg.applicationInfo; 7689 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7690 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7691 mResolveActivity.processName = pkg.applicationInfo.packageName; 7692 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7693 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7694 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7695 mResolveActivity.theme = 0; 7696 mResolveActivity.exported = true; 7697 mResolveActivity.enabled = true; 7698 mResolveInfo.activityInfo = mResolveActivity; 7699 mResolveInfo.priority = 0; 7700 mResolveInfo.preferredOrder = 0; 7701 mResolveInfo.match = 0; 7702 mResolveComponentName = mCustomResolverComponentName; 7703 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7704 mResolveComponentName); 7705 } 7706 } 7707 7708 private static String calculateBundledApkRoot(final String codePathString) { 7709 final File codePath = new File(codePathString); 7710 final File codeRoot; 7711 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7712 codeRoot = Environment.getRootDirectory(); 7713 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7714 codeRoot = Environment.getOemDirectory(); 7715 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7716 codeRoot = Environment.getVendorDirectory(); 7717 } else { 7718 // Unrecognized code path; take its top real segment as the apk root: 7719 // e.g. /something/app/blah.apk => /something 7720 try { 7721 File f = codePath.getCanonicalFile(); 7722 File parent = f.getParentFile(); // non-null because codePath is a file 7723 File tmp; 7724 while ((tmp = parent.getParentFile()) != null) { 7725 f = parent; 7726 parent = tmp; 7727 } 7728 codeRoot = f; 7729 Slog.w(TAG, "Unrecognized code path " 7730 + codePath + " - using " + codeRoot); 7731 } catch (IOException e) { 7732 // Can't canonicalize the code path -- shenanigans? 7733 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7734 return Environment.getRootDirectory().getPath(); 7735 } 7736 } 7737 return codeRoot.getPath(); 7738 } 7739 7740 /** 7741 * Derive and set the location of native libraries for the given package, 7742 * which varies depending on where and how the package was installed. 7743 */ 7744 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7745 final ApplicationInfo info = pkg.applicationInfo; 7746 final String codePath = pkg.codePath; 7747 final File codeFile = new File(codePath); 7748 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7749 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7750 7751 info.nativeLibraryRootDir = null; 7752 info.nativeLibraryRootRequiresIsa = false; 7753 info.nativeLibraryDir = null; 7754 info.secondaryNativeLibraryDir = null; 7755 7756 if (isApkFile(codeFile)) { 7757 // Monolithic install 7758 if (bundledApp) { 7759 // If "/system/lib64/apkname" exists, assume that is the per-package 7760 // native library directory to use; otherwise use "/system/lib/apkname". 7761 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7762 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7763 getPrimaryInstructionSet(info)); 7764 7765 // This is a bundled system app so choose the path based on the ABI. 7766 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7767 // is just the default path. 7768 final String apkName = deriveCodePathName(codePath); 7769 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7770 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7771 apkName).getAbsolutePath(); 7772 7773 if (info.secondaryCpuAbi != null) { 7774 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7775 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7776 secondaryLibDir, apkName).getAbsolutePath(); 7777 } 7778 } else if (asecApp) { 7779 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7780 .getAbsolutePath(); 7781 } else { 7782 final String apkName = deriveCodePathName(codePath); 7783 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7784 .getAbsolutePath(); 7785 } 7786 7787 info.nativeLibraryRootRequiresIsa = false; 7788 info.nativeLibraryDir = info.nativeLibraryRootDir; 7789 } else { 7790 // Cluster install 7791 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7792 info.nativeLibraryRootRequiresIsa = true; 7793 7794 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7795 getPrimaryInstructionSet(info)).getAbsolutePath(); 7796 7797 if (info.secondaryCpuAbi != null) { 7798 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7799 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7800 } 7801 } 7802 } 7803 7804 /** 7805 * Calculate the abis and roots for a bundled app. These can uniquely 7806 * be determined from the contents of the system partition, i.e whether 7807 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7808 * of this information, and instead assume that the system was built 7809 * sensibly. 7810 */ 7811 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7812 PackageSetting pkgSetting) { 7813 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7814 7815 // If "/system/lib64/apkname" exists, assume that is the per-package 7816 // native library directory to use; otherwise use "/system/lib/apkname". 7817 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7818 setBundledAppAbi(pkg, apkRoot, apkName); 7819 // pkgSetting might be null during rescan following uninstall of updates 7820 // to a bundled app, so accommodate that possibility. The settings in 7821 // that case will be established later from the parsed package. 7822 // 7823 // If the settings aren't null, sync them up with what we've just derived. 7824 // note that apkRoot isn't stored in the package settings. 7825 if (pkgSetting != null) { 7826 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7827 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7828 } 7829 } 7830 7831 /** 7832 * Deduces the ABI of a bundled app and sets the relevant fields on the 7833 * parsed pkg object. 7834 * 7835 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7836 * under which system libraries are installed. 7837 * @param apkName the name of the installed package. 7838 */ 7839 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7840 final File codeFile = new File(pkg.codePath); 7841 7842 final boolean has64BitLibs; 7843 final boolean has32BitLibs; 7844 if (isApkFile(codeFile)) { 7845 // Monolithic install 7846 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7847 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7848 } else { 7849 // Cluster install 7850 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7851 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7852 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7853 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7854 has64BitLibs = (new File(rootDir, isa)).exists(); 7855 } else { 7856 has64BitLibs = false; 7857 } 7858 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7859 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7860 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7861 has32BitLibs = (new File(rootDir, isa)).exists(); 7862 } else { 7863 has32BitLibs = false; 7864 } 7865 } 7866 7867 if (has64BitLibs && !has32BitLibs) { 7868 // The package has 64 bit libs, but not 32 bit libs. Its primary 7869 // ABI should be 64 bit. We can safely assume here that the bundled 7870 // native libraries correspond to the most preferred ABI in the list. 7871 7872 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7873 pkg.applicationInfo.secondaryCpuAbi = null; 7874 } else if (has32BitLibs && !has64BitLibs) { 7875 // The package has 32 bit libs but not 64 bit libs. Its primary 7876 // ABI should be 32 bit. 7877 7878 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7879 pkg.applicationInfo.secondaryCpuAbi = null; 7880 } else if (has32BitLibs && has64BitLibs) { 7881 // The application has both 64 and 32 bit bundled libraries. We check 7882 // here that the app declares multiArch support, and warn if it doesn't. 7883 // 7884 // We will be lenient here and record both ABIs. The primary will be the 7885 // ABI that's higher on the list, i.e, a device that's configured to prefer 7886 // 64 bit apps will see a 64 bit primary ABI, 7887 7888 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7889 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7890 } 7891 7892 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7893 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7894 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7895 } else { 7896 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7897 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7898 } 7899 } else { 7900 pkg.applicationInfo.primaryCpuAbi = null; 7901 pkg.applicationInfo.secondaryCpuAbi = null; 7902 } 7903 } 7904 7905 private void killApplication(String pkgName, int appId, String reason) { 7906 // Request the ActivityManager to kill the process(only for existing packages) 7907 // so that we do not end up in a confused state while the user is still using the older 7908 // version of the application while the new one gets installed. 7909 IActivityManager am = ActivityManagerNative.getDefault(); 7910 if (am != null) { 7911 try { 7912 am.killApplicationWithAppId(pkgName, appId, reason); 7913 } catch (RemoteException e) { 7914 } 7915 } 7916 } 7917 7918 void removePackageLI(PackageSetting ps, boolean chatty) { 7919 if (DEBUG_INSTALL) { 7920 if (chatty) 7921 Log.d(TAG, "Removing package " + ps.name); 7922 } 7923 7924 // writer 7925 synchronized (mPackages) { 7926 mPackages.remove(ps.name); 7927 final PackageParser.Package pkg = ps.pkg; 7928 if (pkg != null) { 7929 cleanPackageDataStructuresLILPw(pkg, chatty); 7930 } 7931 } 7932 } 7933 7934 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7935 if (DEBUG_INSTALL) { 7936 if (chatty) 7937 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7938 } 7939 7940 // writer 7941 synchronized (mPackages) { 7942 mPackages.remove(pkg.applicationInfo.packageName); 7943 cleanPackageDataStructuresLILPw(pkg, chatty); 7944 } 7945 } 7946 7947 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7948 int N = pkg.providers.size(); 7949 StringBuilder r = null; 7950 int i; 7951 for (i=0; i<N; i++) { 7952 PackageParser.Provider p = pkg.providers.get(i); 7953 mProviders.removeProvider(p); 7954 if (p.info.authority == null) { 7955 7956 /* There was another ContentProvider with this authority when 7957 * this app was installed so this authority is null, 7958 * Ignore it as we don't have to unregister the provider. 7959 */ 7960 continue; 7961 } 7962 String names[] = p.info.authority.split(";"); 7963 for (int j = 0; j < names.length; j++) { 7964 if (mProvidersByAuthority.get(names[j]) == p) { 7965 mProvidersByAuthority.remove(names[j]); 7966 if (DEBUG_REMOVE) { 7967 if (chatty) 7968 Log.d(TAG, "Unregistered content provider: " + names[j] 7969 + ", className = " + p.info.name + ", isSyncable = " 7970 + p.info.isSyncable); 7971 } 7972 } 7973 } 7974 if (DEBUG_REMOVE && chatty) { 7975 if (r == null) { 7976 r = new StringBuilder(256); 7977 } else { 7978 r.append(' '); 7979 } 7980 r.append(p.info.name); 7981 } 7982 } 7983 if (r != null) { 7984 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7985 } 7986 7987 N = pkg.services.size(); 7988 r = null; 7989 for (i=0; i<N; i++) { 7990 PackageParser.Service s = pkg.services.get(i); 7991 mServices.removeService(s); 7992 if (chatty) { 7993 if (r == null) { 7994 r = new StringBuilder(256); 7995 } else { 7996 r.append(' '); 7997 } 7998 r.append(s.info.name); 7999 } 8000 } 8001 if (r != null) { 8002 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8003 } 8004 8005 N = pkg.receivers.size(); 8006 r = null; 8007 for (i=0; i<N; i++) { 8008 PackageParser.Activity a = pkg.receivers.get(i); 8009 mReceivers.removeActivity(a, "receiver"); 8010 if (DEBUG_REMOVE && chatty) { 8011 if (r == null) { 8012 r = new StringBuilder(256); 8013 } else { 8014 r.append(' '); 8015 } 8016 r.append(a.info.name); 8017 } 8018 } 8019 if (r != null) { 8020 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8021 } 8022 8023 N = pkg.activities.size(); 8024 r = null; 8025 for (i=0; i<N; i++) { 8026 PackageParser.Activity a = pkg.activities.get(i); 8027 mActivities.removeActivity(a, "activity"); 8028 if (DEBUG_REMOVE && chatty) { 8029 if (r == null) { 8030 r = new StringBuilder(256); 8031 } else { 8032 r.append(' '); 8033 } 8034 r.append(a.info.name); 8035 } 8036 } 8037 if (r != null) { 8038 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8039 } 8040 8041 N = pkg.permissions.size(); 8042 r = null; 8043 for (i=0; i<N; i++) { 8044 PackageParser.Permission p = pkg.permissions.get(i); 8045 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8046 if (bp == null) { 8047 bp = mSettings.mPermissionTrees.get(p.info.name); 8048 } 8049 if (bp != null && bp.perm == p) { 8050 bp.perm = null; 8051 if (DEBUG_REMOVE && chatty) { 8052 if (r == null) { 8053 r = new StringBuilder(256); 8054 } else { 8055 r.append(' '); 8056 } 8057 r.append(p.info.name); 8058 } 8059 } 8060 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8061 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8062 if (appOpPerms != null) { 8063 appOpPerms.remove(pkg.packageName); 8064 } 8065 } 8066 } 8067 if (r != null) { 8068 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8069 } 8070 8071 N = pkg.requestedPermissions.size(); 8072 r = null; 8073 for (i=0; i<N; i++) { 8074 String perm = pkg.requestedPermissions.get(i); 8075 BasePermission bp = mSettings.mPermissions.get(perm); 8076 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8077 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8078 if (appOpPerms != null) { 8079 appOpPerms.remove(pkg.packageName); 8080 if (appOpPerms.isEmpty()) { 8081 mAppOpPermissionPackages.remove(perm); 8082 } 8083 } 8084 } 8085 } 8086 if (r != null) { 8087 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8088 } 8089 8090 N = pkg.instrumentation.size(); 8091 r = null; 8092 for (i=0; i<N; i++) { 8093 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8094 mInstrumentation.remove(a.getComponentName()); 8095 if (DEBUG_REMOVE && chatty) { 8096 if (r == null) { 8097 r = new StringBuilder(256); 8098 } else { 8099 r.append(' '); 8100 } 8101 r.append(a.info.name); 8102 } 8103 } 8104 if (r != null) { 8105 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8106 } 8107 8108 r = null; 8109 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8110 // Only system apps can hold shared libraries. 8111 if (pkg.libraryNames != null) { 8112 for (i=0; i<pkg.libraryNames.size(); i++) { 8113 String name = pkg.libraryNames.get(i); 8114 SharedLibraryEntry cur = mSharedLibraries.get(name); 8115 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8116 mSharedLibraries.remove(name); 8117 if (DEBUG_REMOVE && chatty) { 8118 if (r == null) { 8119 r = new StringBuilder(256); 8120 } else { 8121 r.append(' '); 8122 } 8123 r.append(name); 8124 } 8125 } 8126 } 8127 } 8128 } 8129 if (r != null) { 8130 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8131 } 8132 } 8133 8134 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8135 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8136 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8137 return true; 8138 } 8139 } 8140 return false; 8141 } 8142 8143 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8144 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8145 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8146 8147 private void updatePermissionsLPw(String changingPkg, 8148 PackageParser.Package pkgInfo, int flags) { 8149 // Make sure there are no dangling permission trees. 8150 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8151 while (it.hasNext()) { 8152 final BasePermission bp = it.next(); 8153 if (bp.packageSetting == null) { 8154 // We may not yet have parsed the package, so just see if 8155 // we still know about its settings. 8156 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8157 } 8158 if (bp.packageSetting == null) { 8159 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8160 + " from package " + bp.sourcePackage); 8161 it.remove(); 8162 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8163 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8164 Slog.i(TAG, "Removing old permission tree: " + bp.name 8165 + " from package " + bp.sourcePackage); 8166 flags |= UPDATE_PERMISSIONS_ALL; 8167 it.remove(); 8168 } 8169 } 8170 } 8171 8172 // Make sure all dynamic permissions have been assigned to a package, 8173 // and make sure there are no dangling permissions. 8174 it = mSettings.mPermissions.values().iterator(); 8175 while (it.hasNext()) { 8176 final BasePermission bp = it.next(); 8177 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8178 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8179 + bp.name + " pkg=" + bp.sourcePackage 8180 + " info=" + bp.pendingInfo); 8181 if (bp.packageSetting == null && bp.pendingInfo != null) { 8182 final BasePermission tree = findPermissionTreeLP(bp.name); 8183 if (tree != null && tree.perm != null) { 8184 bp.packageSetting = tree.packageSetting; 8185 bp.perm = new PackageParser.Permission(tree.perm.owner, 8186 new PermissionInfo(bp.pendingInfo)); 8187 bp.perm.info.packageName = tree.perm.info.packageName; 8188 bp.perm.info.name = bp.name; 8189 bp.uid = tree.uid; 8190 } 8191 } 8192 } 8193 if (bp.packageSetting == null) { 8194 // We may not yet have parsed the package, so just see if 8195 // we still know about its settings. 8196 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8197 } 8198 if (bp.packageSetting == null) { 8199 Slog.w(TAG, "Removing dangling permission: " + bp.name 8200 + " from package " + bp.sourcePackage); 8201 it.remove(); 8202 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8203 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8204 Slog.i(TAG, "Removing old permission: " + bp.name 8205 + " from package " + bp.sourcePackage); 8206 flags |= UPDATE_PERMISSIONS_ALL; 8207 it.remove(); 8208 } 8209 } 8210 } 8211 8212 // Now update the permissions for all packages, in particular 8213 // replace the granted permissions of the system packages. 8214 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8215 for (PackageParser.Package pkg : mPackages.values()) { 8216 if (pkg != pkgInfo) { 8217 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8218 changingPkg); 8219 } 8220 } 8221 } 8222 8223 if (pkgInfo != null) { 8224 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8225 } 8226 } 8227 8228 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8229 String packageOfInterest) { 8230 // IMPORTANT: There are two types of permissions: install and runtime. 8231 // Install time permissions are granted when the app is installed to 8232 // all device users and users added in the future. Runtime permissions 8233 // are granted at runtime explicitly to specific users. Normal and signature 8234 // protected permissions are install time permissions. Dangerous permissions 8235 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8236 // otherwise they are runtime permissions. This function does not manage 8237 // runtime permissions except for the case an app targeting Lollipop MR1 8238 // being upgraded to target a newer SDK, in which case dangerous permissions 8239 // are transformed from install time to runtime ones. 8240 8241 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8242 if (ps == null) { 8243 return; 8244 } 8245 8246 PermissionsState permissionsState = ps.getPermissionsState(); 8247 PermissionsState origPermissions = permissionsState; 8248 8249 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8250 8251 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8252 8253 boolean changedInstallPermission = false; 8254 8255 if (replace) { 8256 ps.installPermissionsFixed = false; 8257 if (!ps.isSharedUser()) { 8258 origPermissions = new PermissionsState(permissionsState); 8259 permissionsState.reset(); 8260 } 8261 } 8262 8263 permissionsState.setGlobalGids(mGlobalGids); 8264 8265 final int N = pkg.requestedPermissions.size(); 8266 for (int i=0; i<N; i++) { 8267 final String name = pkg.requestedPermissions.get(i); 8268 final BasePermission bp = mSettings.mPermissions.get(name); 8269 8270 if (DEBUG_INSTALL) { 8271 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8272 } 8273 8274 if (bp == null || bp.packageSetting == null) { 8275 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8276 Slog.w(TAG, "Unknown permission " + name 8277 + " in package " + pkg.packageName); 8278 } 8279 continue; 8280 } 8281 8282 final String perm = bp.name; 8283 boolean allowedSig = false; 8284 int grant = GRANT_DENIED; 8285 8286 // Keep track of app op permissions. 8287 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8288 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8289 if (pkgs == null) { 8290 pkgs = new ArraySet<>(); 8291 mAppOpPermissionPackages.put(bp.name, pkgs); 8292 } 8293 pkgs.add(pkg.packageName); 8294 } 8295 8296 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8297 switch (level) { 8298 case PermissionInfo.PROTECTION_NORMAL: { 8299 // For all apps normal permissions are install time ones. 8300 grant = GRANT_INSTALL; 8301 } break; 8302 8303 case PermissionInfo.PROTECTION_DANGEROUS: { 8304 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8305 // For legacy apps dangerous permissions are install time ones. 8306 grant = GRANT_INSTALL_LEGACY; 8307 } else if (origPermissions.hasInstallPermission(bp.name)) { 8308 // For legacy apps that became modern, install becomes runtime. 8309 grant = GRANT_UPGRADE; 8310 } else { 8311 // For modern apps keep runtime permissions unchanged. 8312 grant = GRANT_RUNTIME; 8313 } 8314 } break; 8315 8316 case PermissionInfo.PROTECTION_SIGNATURE: { 8317 // For all apps signature permissions are install time ones. 8318 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8319 if (allowedSig) { 8320 grant = GRANT_INSTALL; 8321 } 8322 } break; 8323 } 8324 8325 if (DEBUG_INSTALL) { 8326 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8327 } 8328 8329 if (grant != GRANT_DENIED) { 8330 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8331 // If this is an existing, non-system package, then 8332 // we can't add any new permissions to it. 8333 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8334 // Except... if this is a permission that was added 8335 // to the platform (note: need to only do this when 8336 // updating the platform). 8337 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8338 grant = GRANT_DENIED; 8339 } 8340 } 8341 } 8342 8343 switch (grant) { 8344 case GRANT_INSTALL: { 8345 // Revoke this as runtime permission to handle the case of 8346 // a runtime permission being downgraded to an install one. 8347 for (int userId : UserManagerService.getInstance().getUserIds()) { 8348 if (origPermissions.getRuntimePermissionState( 8349 bp.name, userId) != null) { 8350 // Revoke the runtime permission and clear the flags. 8351 origPermissions.revokeRuntimePermission(bp, userId); 8352 origPermissions.updatePermissionFlags(bp, userId, 8353 PackageManager.MASK_PERMISSION_FLAGS, 0); 8354 // If we revoked a permission permission, we have to write. 8355 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8356 changedRuntimePermissionUserIds, userId); 8357 } 8358 } 8359 // Grant an install permission. 8360 if (permissionsState.grantInstallPermission(bp) != 8361 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8362 changedInstallPermission = true; 8363 } 8364 } break; 8365 8366 case GRANT_INSTALL_LEGACY: { 8367 // Grant an install permission. 8368 if (permissionsState.grantInstallPermission(bp) != 8369 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8370 changedInstallPermission = true; 8371 } 8372 } break; 8373 8374 case GRANT_RUNTIME: { 8375 // Grant previously granted runtime permissions. 8376 for (int userId : UserManagerService.getInstance().getUserIds()) { 8377 PermissionState permissionState = origPermissions 8378 .getRuntimePermissionState(bp.name, userId); 8379 final int flags = permissionState != null 8380 ? permissionState.getFlags() : 0; 8381 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8382 if (permissionsState.grantRuntimePermission(bp, userId) == 8383 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8384 // If we cannot put the permission as it was, we have to write. 8385 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8386 changedRuntimePermissionUserIds, userId); 8387 } 8388 } 8389 // Propagate the permission flags. 8390 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8391 } 8392 } break; 8393 8394 case GRANT_UPGRADE: { 8395 // Grant runtime permissions for a previously held install permission. 8396 PermissionState permissionState = origPermissions 8397 .getInstallPermissionState(bp.name); 8398 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8399 8400 if (origPermissions.revokeInstallPermission(bp) 8401 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8402 // We will be transferring the permission flags, so clear them. 8403 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8404 PackageManager.MASK_PERMISSION_FLAGS, 0); 8405 changedInstallPermission = true; 8406 } 8407 8408 // If the permission is not to be promoted to runtime we ignore it and 8409 // also its other flags as they are not applicable to install permissions. 8410 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8411 for (int userId : currentUserIds) { 8412 if (permissionsState.grantRuntimePermission(bp, userId) != 8413 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8414 // Transfer the permission flags. 8415 permissionsState.updatePermissionFlags(bp, userId, 8416 flags, flags); 8417 // If we granted the permission, we have to write. 8418 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8419 changedRuntimePermissionUserIds, userId); 8420 } 8421 } 8422 } 8423 } break; 8424 8425 default: { 8426 if (packageOfInterest == null 8427 || packageOfInterest.equals(pkg.packageName)) { 8428 Slog.w(TAG, "Not granting permission " + perm 8429 + " to package " + pkg.packageName 8430 + " because it was previously installed without"); 8431 } 8432 } break; 8433 } 8434 } else { 8435 if (permissionsState.revokeInstallPermission(bp) != 8436 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8437 // Also drop the permission flags. 8438 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8439 PackageManager.MASK_PERMISSION_FLAGS, 0); 8440 changedInstallPermission = true; 8441 Slog.i(TAG, "Un-granting permission " + perm 8442 + " from package " + pkg.packageName 8443 + " (protectionLevel=" + bp.protectionLevel 8444 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8445 + ")"); 8446 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8447 // Don't print warning for app op permissions, since it is fine for them 8448 // not to be granted, there is a UI for the user to decide. 8449 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8450 Slog.w(TAG, "Not granting permission " + perm 8451 + " to package " + pkg.packageName 8452 + " (protectionLevel=" + bp.protectionLevel 8453 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8454 + ")"); 8455 } 8456 } 8457 } 8458 } 8459 8460 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8461 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8462 // This is the first that we have heard about this package, so the 8463 // permissions we have now selected are fixed until explicitly 8464 // changed. 8465 ps.installPermissionsFixed = true; 8466 } 8467 8468 // Persist the runtime permissions state for users with changes. 8469 for (int userId : changedRuntimePermissionUserIds) { 8470 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8471 } 8472 } 8473 8474 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8475 boolean allowed = false; 8476 final int NP = PackageParser.NEW_PERMISSIONS.length; 8477 for (int ip=0; ip<NP; ip++) { 8478 final PackageParser.NewPermissionInfo npi 8479 = PackageParser.NEW_PERMISSIONS[ip]; 8480 if (npi.name.equals(perm) 8481 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8482 allowed = true; 8483 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8484 + pkg.packageName); 8485 break; 8486 } 8487 } 8488 return allowed; 8489 } 8490 8491 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8492 BasePermission bp, PermissionsState origPermissions) { 8493 boolean allowed; 8494 allowed = (compareSignatures( 8495 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8496 == PackageManager.SIGNATURE_MATCH) 8497 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8498 == PackageManager.SIGNATURE_MATCH); 8499 if (!allowed && (bp.protectionLevel 8500 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8501 if (isSystemApp(pkg)) { 8502 // For updated system applications, a system permission 8503 // is granted only if it had been defined by the original application. 8504 if (pkg.isUpdatedSystemApp()) { 8505 final PackageSetting sysPs = mSettings 8506 .getDisabledSystemPkgLPr(pkg.packageName); 8507 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8508 // If the original was granted this permission, we take 8509 // that grant decision as read and propagate it to the 8510 // update. 8511 if (sysPs.isPrivileged()) { 8512 allowed = true; 8513 } 8514 } else { 8515 // The system apk may have been updated with an older 8516 // version of the one on the data partition, but which 8517 // granted a new system permission that it didn't have 8518 // before. In this case we do want to allow the app to 8519 // now get the new permission if the ancestral apk is 8520 // privileged to get it. 8521 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8522 for (int j=0; 8523 j<sysPs.pkg.requestedPermissions.size(); j++) { 8524 if (perm.equals( 8525 sysPs.pkg.requestedPermissions.get(j))) { 8526 allowed = true; 8527 break; 8528 } 8529 } 8530 } 8531 } 8532 } else { 8533 allowed = isPrivilegedApp(pkg); 8534 } 8535 } 8536 } 8537 if (!allowed) { 8538 if (!allowed && (bp.protectionLevel 8539 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8540 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8541 // If this was a previously normal/dangerous permission that got moved 8542 // to a system permission as part of the runtime permission redesign, then 8543 // we still want to blindly grant it to old apps. 8544 allowed = true; 8545 } 8546 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8547 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8548 // If this permission is to be granted to the system installer and 8549 // this app is an installer, then it gets the permission. 8550 allowed = true; 8551 } 8552 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8553 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8554 // If this permission is to be granted to the system verifier and 8555 // this app is a verifier, then it gets the permission. 8556 allowed = true; 8557 } 8558 if (!allowed && (bp.protectionLevel 8559 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8560 && isSystemApp(pkg)) { 8561 // Any pre-installed system app is allowed to get this permission. 8562 allowed = true; 8563 } 8564 if (!allowed && (bp.protectionLevel 8565 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8566 // For development permissions, a development permission 8567 // is granted only if it was already granted. 8568 allowed = origPermissions.hasInstallPermission(perm); 8569 } 8570 } 8571 return allowed; 8572 } 8573 8574 final class ActivityIntentResolver 8575 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8576 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8577 boolean defaultOnly, int userId) { 8578 if (!sUserManager.exists(userId)) return null; 8579 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8580 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8581 } 8582 8583 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8584 int userId) { 8585 if (!sUserManager.exists(userId)) return null; 8586 mFlags = flags; 8587 return super.queryIntent(intent, resolvedType, 8588 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8589 } 8590 8591 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8592 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8593 if (!sUserManager.exists(userId)) return null; 8594 if (packageActivities == null) { 8595 return null; 8596 } 8597 mFlags = flags; 8598 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8599 final int N = packageActivities.size(); 8600 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8601 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8602 8603 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8604 for (int i = 0; i < N; ++i) { 8605 intentFilters = packageActivities.get(i).intents; 8606 if (intentFilters != null && intentFilters.size() > 0) { 8607 PackageParser.ActivityIntentInfo[] array = 8608 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8609 intentFilters.toArray(array); 8610 listCut.add(array); 8611 } 8612 } 8613 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8614 } 8615 8616 public final void addActivity(PackageParser.Activity a, String type) { 8617 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8618 mActivities.put(a.getComponentName(), a); 8619 if (DEBUG_SHOW_INFO) 8620 Log.v( 8621 TAG, " " + type + " " + 8622 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8623 if (DEBUG_SHOW_INFO) 8624 Log.v(TAG, " Class=" + a.info.name); 8625 final int NI = a.intents.size(); 8626 for (int j=0; j<NI; j++) { 8627 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8628 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8629 intent.setPriority(0); 8630 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8631 + a.className + " with priority > 0, forcing to 0"); 8632 } 8633 if (DEBUG_SHOW_INFO) { 8634 Log.v(TAG, " IntentFilter:"); 8635 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8636 } 8637 if (!intent.debugCheck()) { 8638 Log.w(TAG, "==> For Activity " + a.info.name); 8639 } 8640 addFilter(intent); 8641 } 8642 } 8643 8644 public final void removeActivity(PackageParser.Activity a, String type) { 8645 mActivities.remove(a.getComponentName()); 8646 if (DEBUG_SHOW_INFO) { 8647 Log.v(TAG, " " + type + " " 8648 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8649 : a.info.name) + ":"); 8650 Log.v(TAG, " Class=" + a.info.name); 8651 } 8652 final int NI = a.intents.size(); 8653 for (int j=0; j<NI; j++) { 8654 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8655 if (DEBUG_SHOW_INFO) { 8656 Log.v(TAG, " IntentFilter:"); 8657 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8658 } 8659 removeFilter(intent); 8660 } 8661 } 8662 8663 @Override 8664 protected boolean allowFilterResult( 8665 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8666 ActivityInfo filterAi = filter.activity.info; 8667 for (int i=dest.size()-1; i>=0; i--) { 8668 ActivityInfo destAi = dest.get(i).activityInfo; 8669 if (destAi.name == filterAi.name 8670 && destAi.packageName == filterAi.packageName) { 8671 return false; 8672 } 8673 } 8674 return true; 8675 } 8676 8677 @Override 8678 protected ActivityIntentInfo[] newArray(int size) { 8679 return new ActivityIntentInfo[size]; 8680 } 8681 8682 @Override 8683 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8684 if (!sUserManager.exists(userId)) return true; 8685 PackageParser.Package p = filter.activity.owner; 8686 if (p != null) { 8687 PackageSetting ps = (PackageSetting)p.mExtras; 8688 if (ps != null) { 8689 // System apps are never considered stopped for purposes of 8690 // filtering, because there may be no way for the user to 8691 // actually re-launch them. 8692 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8693 && ps.getStopped(userId); 8694 } 8695 } 8696 return false; 8697 } 8698 8699 @Override 8700 protected boolean isPackageForFilter(String packageName, 8701 PackageParser.ActivityIntentInfo info) { 8702 return packageName.equals(info.activity.owner.packageName); 8703 } 8704 8705 @Override 8706 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8707 int match, int userId) { 8708 if (!sUserManager.exists(userId)) return null; 8709 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8710 return null; 8711 } 8712 final PackageParser.Activity activity = info.activity; 8713 if (mSafeMode && (activity.info.applicationInfo.flags 8714 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8715 return null; 8716 } 8717 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8718 if (ps == null) { 8719 return null; 8720 } 8721 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8722 ps.readUserState(userId), userId); 8723 if (ai == null) { 8724 return null; 8725 } 8726 final ResolveInfo res = new ResolveInfo(); 8727 res.activityInfo = ai; 8728 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8729 res.filter = info; 8730 } 8731 if (info != null) { 8732 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8733 } 8734 res.priority = info.getPriority(); 8735 res.preferredOrder = activity.owner.mPreferredOrder; 8736 //System.out.println("Result: " + res.activityInfo.className + 8737 // " = " + res.priority); 8738 res.match = match; 8739 res.isDefault = info.hasDefault; 8740 res.labelRes = info.labelRes; 8741 res.nonLocalizedLabel = info.nonLocalizedLabel; 8742 if (userNeedsBadging(userId)) { 8743 res.noResourceId = true; 8744 } else { 8745 res.icon = info.icon; 8746 } 8747 res.iconResourceId = info.icon; 8748 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8749 return res; 8750 } 8751 8752 @Override 8753 protected void sortResults(List<ResolveInfo> results) { 8754 Collections.sort(results, mResolvePrioritySorter); 8755 } 8756 8757 @Override 8758 protected void dumpFilter(PrintWriter out, String prefix, 8759 PackageParser.ActivityIntentInfo filter) { 8760 out.print(prefix); out.print( 8761 Integer.toHexString(System.identityHashCode(filter.activity))); 8762 out.print(' '); 8763 filter.activity.printComponentShortName(out); 8764 out.print(" filter "); 8765 out.println(Integer.toHexString(System.identityHashCode(filter))); 8766 } 8767 8768 @Override 8769 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8770 return filter.activity; 8771 } 8772 8773 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8774 PackageParser.Activity activity = (PackageParser.Activity)label; 8775 out.print(prefix); out.print( 8776 Integer.toHexString(System.identityHashCode(activity))); 8777 out.print(' '); 8778 activity.printComponentShortName(out); 8779 if (count > 1) { 8780 out.print(" ("); out.print(count); out.print(" filters)"); 8781 } 8782 out.println(); 8783 } 8784 8785// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8786// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8787// final List<ResolveInfo> retList = Lists.newArrayList(); 8788// while (i.hasNext()) { 8789// final ResolveInfo resolveInfo = i.next(); 8790// if (isEnabledLP(resolveInfo.activityInfo)) { 8791// retList.add(resolveInfo); 8792// } 8793// } 8794// return retList; 8795// } 8796 8797 // Keys are String (activity class name), values are Activity. 8798 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8799 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8800 private int mFlags; 8801 } 8802 8803 private final class ServiceIntentResolver 8804 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8805 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8806 boolean defaultOnly, int userId) { 8807 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8808 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8809 } 8810 8811 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8812 int userId) { 8813 if (!sUserManager.exists(userId)) return null; 8814 mFlags = flags; 8815 return super.queryIntent(intent, resolvedType, 8816 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8817 } 8818 8819 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8820 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8821 if (!sUserManager.exists(userId)) return null; 8822 if (packageServices == null) { 8823 return null; 8824 } 8825 mFlags = flags; 8826 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8827 final int N = packageServices.size(); 8828 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8829 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8830 8831 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8832 for (int i = 0; i < N; ++i) { 8833 intentFilters = packageServices.get(i).intents; 8834 if (intentFilters != null && intentFilters.size() > 0) { 8835 PackageParser.ServiceIntentInfo[] array = 8836 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8837 intentFilters.toArray(array); 8838 listCut.add(array); 8839 } 8840 } 8841 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8842 } 8843 8844 public final void addService(PackageParser.Service s) { 8845 mServices.put(s.getComponentName(), s); 8846 if (DEBUG_SHOW_INFO) { 8847 Log.v(TAG, " " 8848 + (s.info.nonLocalizedLabel != null 8849 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8850 Log.v(TAG, " Class=" + s.info.name); 8851 } 8852 final int NI = s.intents.size(); 8853 int j; 8854 for (j=0; j<NI; j++) { 8855 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8856 if (DEBUG_SHOW_INFO) { 8857 Log.v(TAG, " IntentFilter:"); 8858 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8859 } 8860 if (!intent.debugCheck()) { 8861 Log.w(TAG, "==> For Service " + s.info.name); 8862 } 8863 addFilter(intent); 8864 } 8865 } 8866 8867 public final void removeService(PackageParser.Service s) { 8868 mServices.remove(s.getComponentName()); 8869 if (DEBUG_SHOW_INFO) { 8870 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8871 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8872 Log.v(TAG, " Class=" + s.info.name); 8873 } 8874 final int NI = s.intents.size(); 8875 int j; 8876 for (j=0; j<NI; j++) { 8877 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8878 if (DEBUG_SHOW_INFO) { 8879 Log.v(TAG, " IntentFilter:"); 8880 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8881 } 8882 removeFilter(intent); 8883 } 8884 } 8885 8886 @Override 8887 protected boolean allowFilterResult( 8888 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8889 ServiceInfo filterSi = filter.service.info; 8890 for (int i=dest.size()-1; i>=0; i--) { 8891 ServiceInfo destAi = dest.get(i).serviceInfo; 8892 if (destAi.name == filterSi.name 8893 && destAi.packageName == filterSi.packageName) { 8894 return false; 8895 } 8896 } 8897 return true; 8898 } 8899 8900 @Override 8901 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8902 return new PackageParser.ServiceIntentInfo[size]; 8903 } 8904 8905 @Override 8906 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8907 if (!sUserManager.exists(userId)) return true; 8908 PackageParser.Package p = filter.service.owner; 8909 if (p != null) { 8910 PackageSetting ps = (PackageSetting)p.mExtras; 8911 if (ps != null) { 8912 // System apps are never considered stopped for purposes of 8913 // filtering, because there may be no way for the user to 8914 // actually re-launch them. 8915 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8916 && ps.getStopped(userId); 8917 } 8918 } 8919 return false; 8920 } 8921 8922 @Override 8923 protected boolean isPackageForFilter(String packageName, 8924 PackageParser.ServiceIntentInfo info) { 8925 return packageName.equals(info.service.owner.packageName); 8926 } 8927 8928 @Override 8929 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8930 int match, int userId) { 8931 if (!sUserManager.exists(userId)) return null; 8932 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8933 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8934 return null; 8935 } 8936 final PackageParser.Service service = info.service; 8937 if (mSafeMode && (service.info.applicationInfo.flags 8938 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8939 return null; 8940 } 8941 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8942 if (ps == null) { 8943 return null; 8944 } 8945 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8946 ps.readUserState(userId), userId); 8947 if (si == null) { 8948 return null; 8949 } 8950 final ResolveInfo res = new ResolveInfo(); 8951 res.serviceInfo = si; 8952 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8953 res.filter = filter; 8954 } 8955 res.priority = info.getPriority(); 8956 res.preferredOrder = service.owner.mPreferredOrder; 8957 res.match = match; 8958 res.isDefault = info.hasDefault; 8959 res.labelRes = info.labelRes; 8960 res.nonLocalizedLabel = info.nonLocalizedLabel; 8961 res.icon = info.icon; 8962 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8963 return res; 8964 } 8965 8966 @Override 8967 protected void sortResults(List<ResolveInfo> results) { 8968 Collections.sort(results, mResolvePrioritySorter); 8969 } 8970 8971 @Override 8972 protected void dumpFilter(PrintWriter out, String prefix, 8973 PackageParser.ServiceIntentInfo filter) { 8974 out.print(prefix); out.print( 8975 Integer.toHexString(System.identityHashCode(filter.service))); 8976 out.print(' '); 8977 filter.service.printComponentShortName(out); 8978 out.print(" filter "); 8979 out.println(Integer.toHexString(System.identityHashCode(filter))); 8980 } 8981 8982 @Override 8983 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8984 return filter.service; 8985 } 8986 8987 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8988 PackageParser.Service service = (PackageParser.Service)label; 8989 out.print(prefix); out.print( 8990 Integer.toHexString(System.identityHashCode(service))); 8991 out.print(' '); 8992 service.printComponentShortName(out); 8993 if (count > 1) { 8994 out.print(" ("); out.print(count); out.print(" filters)"); 8995 } 8996 out.println(); 8997 } 8998 8999// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9000// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9001// final List<ResolveInfo> retList = Lists.newArrayList(); 9002// while (i.hasNext()) { 9003// final ResolveInfo resolveInfo = (ResolveInfo) i; 9004// if (isEnabledLP(resolveInfo.serviceInfo)) { 9005// retList.add(resolveInfo); 9006// } 9007// } 9008// return retList; 9009// } 9010 9011 // Keys are String (activity class name), values are Activity. 9012 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9013 = new ArrayMap<ComponentName, PackageParser.Service>(); 9014 private int mFlags; 9015 }; 9016 9017 private final class ProviderIntentResolver 9018 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9019 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9020 boolean defaultOnly, int userId) { 9021 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9022 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9023 } 9024 9025 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9026 int userId) { 9027 if (!sUserManager.exists(userId)) 9028 return null; 9029 mFlags = flags; 9030 return super.queryIntent(intent, resolvedType, 9031 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9032 } 9033 9034 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9035 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9036 if (!sUserManager.exists(userId)) 9037 return null; 9038 if (packageProviders == null) { 9039 return null; 9040 } 9041 mFlags = flags; 9042 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9043 final int N = packageProviders.size(); 9044 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9045 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9046 9047 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9048 for (int i = 0; i < N; ++i) { 9049 intentFilters = packageProviders.get(i).intents; 9050 if (intentFilters != null && intentFilters.size() > 0) { 9051 PackageParser.ProviderIntentInfo[] array = 9052 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9053 intentFilters.toArray(array); 9054 listCut.add(array); 9055 } 9056 } 9057 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9058 } 9059 9060 public final void addProvider(PackageParser.Provider p) { 9061 if (mProviders.containsKey(p.getComponentName())) { 9062 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9063 return; 9064 } 9065 9066 mProviders.put(p.getComponentName(), p); 9067 if (DEBUG_SHOW_INFO) { 9068 Log.v(TAG, " " 9069 + (p.info.nonLocalizedLabel != null 9070 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9071 Log.v(TAG, " Class=" + p.info.name); 9072 } 9073 final int NI = p.intents.size(); 9074 int j; 9075 for (j = 0; j < NI; j++) { 9076 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9077 if (DEBUG_SHOW_INFO) { 9078 Log.v(TAG, " IntentFilter:"); 9079 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9080 } 9081 if (!intent.debugCheck()) { 9082 Log.w(TAG, "==> For Provider " + p.info.name); 9083 } 9084 addFilter(intent); 9085 } 9086 } 9087 9088 public final void removeProvider(PackageParser.Provider p) { 9089 mProviders.remove(p.getComponentName()); 9090 if (DEBUG_SHOW_INFO) { 9091 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9092 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9093 Log.v(TAG, " Class=" + p.info.name); 9094 } 9095 final int NI = p.intents.size(); 9096 int j; 9097 for (j = 0; j < NI; j++) { 9098 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9099 if (DEBUG_SHOW_INFO) { 9100 Log.v(TAG, " IntentFilter:"); 9101 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9102 } 9103 removeFilter(intent); 9104 } 9105 } 9106 9107 @Override 9108 protected boolean allowFilterResult( 9109 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9110 ProviderInfo filterPi = filter.provider.info; 9111 for (int i = dest.size() - 1; i >= 0; i--) { 9112 ProviderInfo destPi = dest.get(i).providerInfo; 9113 if (destPi.name == filterPi.name 9114 && destPi.packageName == filterPi.packageName) { 9115 return false; 9116 } 9117 } 9118 return true; 9119 } 9120 9121 @Override 9122 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9123 return new PackageParser.ProviderIntentInfo[size]; 9124 } 9125 9126 @Override 9127 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9128 if (!sUserManager.exists(userId)) 9129 return true; 9130 PackageParser.Package p = filter.provider.owner; 9131 if (p != null) { 9132 PackageSetting ps = (PackageSetting) p.mExtras; 9133 if (ps != null) { 9134 // System apps are never considered stopped for purposes of 9135 // filtering, because there may be no way for the user to 9136 // actually re-launch them. 9137 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9138 && ps.getStopped(userId); 9139 } 9140 } 9141 return false; 9142 } 9143 9144 @Override 9145 protected boolean isPackageForFilter(String packageName, 9146 PackageParser.ProviderIntentInfo info) { 9147 return packageName.equals(info.provider.owner.packageName); 9148 } 9149 9150 @Override 9151 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9152 int match, int userId) { 9153 if (!sUserManager.exists(userId)) 9154 return null; 9155 final PackageParser.ProviderIntentInfo info = filter; 9156 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9157 return null; 9158 } 9159 final PackageParser.Provider provider = info.provider; 9160 if (mSafeMode && (provider.info.applicationInfo.flags 9161 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9162 return null; 9163 } 9164 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9165 if (ps == null) { 9166 return null; 9167 } 9168 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9169 ps.readUserState(userId), userId); 9170 if (pi == null) { 9171 return null; 9172 } 9173 final ResolveInfo res = new ResolveInfo(); 9174 res.providerInfo = pi; 9175 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9176 res.filter = filter; 9177 } 9178 res.priority = info.getPriority(); 9179 res.preferredOrder = provider.owner.mPreferredOrder; 9180 res.match = match; 9181 res.isDefault = info.hasDefault; 9182 res.labelRes = info.labelRes; 9183 res.nonLocalizedLabel = info.nonLocalizedLabel; 9184 res.icon = info.icon; 9185 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9186 return res; 9187 } 9188 9189 @Override 9190 protected void sortResults(List<ResolveInfo> results) { 9191 Collections.sort(results, mResolvePrioritySorter); 9192 } 9193 9194 @Override 9195 protected void dumpFilter(PrintWriter out, String prefix, 9196 PackageParser.ProviderIntentInfo filter) { 9197 out.print(prefix); 9198 out.print( 9199 Integer.toHexString(System.identityHashCode(filter.provider))); 9200 out.print(' '); 9201 filter.provider.printComponentShortName(out); 9202 out.print(" filter "); 9203 out.println(Integer.toHexString(System.identityHashCode(filter))); 9204 } 9205 9206 @Override 9207 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9208 return filter.provider; 9209 } 9210 9211 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9212 PackageParser.Provider provider = (PackageParser.Provider)label; 9213 out.print(prefix); out.print( 9214 Integer.toHexString(System.identityHashCode(provider))); 9215 out.print(' '); 9216 provider.printComponentShortName(out); 9217 if (count > 1) { 9218 out.print(" ("); out.print(count); out.print(" filters)"); 9219 } 9220 out.println(); 9221 } 9222 9223 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9224 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9225 private int mFlags; 9226 }; 9227 9228 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9229 new Comparator<ResolveInfo>() { 9230 public int compare(ResolveInfo r1, ResolveInfo r2) { 9231 int v1 = r1.priority; 9232 int v2 = r2.priority; 9233 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9234 if (v1 != v2) { 9235 return (v1 > v2) ? -1 : 1; 9236 } 9237 v1 = r1.preferredOrder; 9238 v2 = r2.preferredOrder; 9239 if (v1 != v2) { 9240 return (v1 > v2) ? -1 : 1; 9241 } 9242 if (r1.isDefault != r2.isDefault) { 9243 return r1.isDefault ? -1 : 1; 9244 } 9245 v1 = r1.match; 9246 v2 = r2.match; 9247 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9248 if (v1 != v2) { 9249 return (v1 > v2) ? -1 : 1; 9250 } 9251 if (r1.system != r2.system) { 9252 return r1.system ? -1 : 1; 9253 } 9254 return 0; 9255 } 9256 }; 9257 9258 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9259 new Comparator<ProviderInfo>() { 9260 public int compare(ProviderInfo p1, ProviderInfo p2) { 9261 final int v1 = p1.initOrder; 9262 final int v2 = p2.initOrder; 9263 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9264 } 9265 }; 9266 9267 final void sendPackageBroadcast(final String action, final String pkg, 9268 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9269 final int[] userIds) { 9270 mHandler.post(new Runnable() { 9271 @Override 9272 public void run() { 9273 try { 9274 final IActivityManager am = ActivityManagerNative.getDefault(); 9275 if (am == null) return; 9276 final int[] resolvedUserIds; 9277 if (userIds == null) { 9278 resolvedUserIds = am.getRunningUserIds(); 9279 } else { 9280 resolvedUserIds = userIds; 9281 } 9282 for (int id : resolvedUserIds) { 9283 final Intent intent = new Intent(action, 9284 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9285 if (extras != null) { 9286 intent.putExtras(extras); 9287 } 9288 if (targetPkg != null) { 9289 intent.setPackage(targetPkg); 9290 } 9291 // Modify the UID when posting to other users 9292 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9293 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9294 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9295 intent.putExtra(Intent.EXTRA_UID, uid); 9296 } 9297 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9298 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9299 if (DEBUG_BROADCASTS) { 9300 RuntimeException here = new RuntimeException("here"); 9301 here.fillInStackTrace(); 9302 Slog.d(TAG, "Sending to user " + id + ": " 9303 + intent.toShortString(false, true, false, false) 9304 + " " + intent.getExtras(), here); 9305 } 9306 am.broadcastIntent(null, intent, null, finishedReceiver, 9307 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9308 null, finishedReceiver != null, false, id); 9309 } 9310 } catch (RemoteException ex) { 9311 } 9312 } 9313 }); 9314 } 9315 9316 /** 9317 * Check if the external storage media is available. This is true if there 9318 * is a mounted external storage medium or if the external storage is 9319 * emulated. 9320 */ 9321 private boolean isExternalMediaAvailable() { 9322 return mMediaMounted || Environment.isExternalStorageEmulated(); 9323 } 9324 9325 @Override 9326 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9327 // writer 9328 synchronized (mPackages) { 9329 if (!isExternalMediaAvailable()) { 9330 // If the external storage is no longer mounted at this point, 9331 // the caller may not have been able to delete all of this 9332 // packages files and can not delete any more. Bail. 9333 return null; 9334 } 9335 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9336 if (lastPackage != null) { 9337 pkgs.remove(lastPackage); 9338 } 9339 if (pkgs.size() > 0) { 9340 return pkgs.get(0); 9341 } 9342 } 9343 return null; 9344 } 9345 9346 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9347 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9348 userId, andCode ? 1 : 0, packageName); 9349 if (mSystemReady) { 9350 msg.sendToTarget(); 9351 } else { 9352 if (mPostSystemReadyMessages == null) { 9353 mPostSystemReadyMessages = new ArrayList<>(); 9354 } 9355 mPostSystemReadyMessages.add(msg); 9356 } 9357 } 9358 9359 void startCleaningPackages() { 9360 // reader 9361 synchronized (mPackages) { 9362 if (!isExternalMediaAvailable()) { 9363 return; 9364 } 9365 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9366 return; 9367 } 9368 } 9369 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9370 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9371 IActivityManager am = ActivityManagerNative.getDefault(); 9372 if (am != null) { 9373 try { 9374 am.startService(null, intent, null, mContext.getOpPackageName(), 9375 UserHandle.USER_OWNER); 9376 } catch (RemoteException e) { 9377 } 9378 } 9379 } 9380 9381 @Override 9382 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9383 int installFlags, String installerPackageName, VerificationParams verificationParams, 9384 String packageAbiOverride) { 9385 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9386 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9387 } 9388 9389 @Override 9390 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9391 int installFlags, String installerPackageName, VerificationParams verificationParams, 9392 String packageAbiOverride, int userId) { 9393 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9394 9395 final int callingUid = Binder.getCallingUid(); 9396 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9397 9398 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9399 try { 9400 if (observer != null) { 9401 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9402 } 9403 } catch (RemoteException re) { 9404 } 9405 return; 9406 } 9407 9408 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9409 installFlags |= PackageManager.INSTALL_FROM_ADB; 9410 9411 } else { 9412 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9413 // about installerPackageName. 9414 9415 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9416 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9417 } 9418 9419 UserHandle user; 9420 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9421 user = UserHandle.ALL; 9422 } else { 9423 user = new UserHandle(userId); 9424 } 9425 9426 // Only system components can circumvent runtime permissions when installing. 9427 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9428 && mContext.checkCallingOrSelfPermission(Manifest.permission 9429 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9430 throw new SecurityException("You need the " 9431 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9432 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9433 } 9434 9435 verificationParams.setInstallerUid(callingUid); 9436 9437 final File originFile = new File(originPath); 9438 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9439 9440 final Message msg = mHandler.obtainMessage(INIT_COPY); 9441 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9442 null, verificationParams, user, packageAbiOverride); 9443 mHandler.sendMessage(msg); 9444 } 9445 9446 void installStage(String packageName, File stagedDir, String stagedCid, 9447 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9448 String installerPackageName, int installerUid, UserHandle user) { 9449 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9450 params.referrerUri, installerUid, null); 9451 verifParams.setInstallerUid(installerUid); 9452 9453 final OriginInfo origin; 9454 if (stagedDir != null) { 9455 origin = OriginInfo.fromStagedFile(stagedDir); 9456 } else { 9457 origin = OriginInfo.fromStagedContainer(stagedCid); 9458 } 9459 9460 final Message msg = mHandler.obtainMessage(INIT_COPY); 9461 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9462 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9463 mHandler.sendMessage(msg); 9464 } 9465 9466 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9467 Bundle extras = new Bundle(1); 9468 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9469 9470 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9471 packageName, extras, null, null, new int[] {userId}); 9472 try { 9473 IActivityManager am = ActivityManagerNative.getDefault(); 9474 final boolean isSystem = 9475 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9476 if (isSystem && am.isUserRunning(userId, false)) { 9477 // The just-installed/enabled app is bundled on the system, so presumed 9478 // to be able to run automatically without needing an explicit launch. 9479 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9480 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9481 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9482 .setPackage(packageName); 9483 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9484 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9485 } 9486 } catch (RemoteException e) { 9487 // shouldn't happen 9488 Slog.w(TAG, "Unable to bootstrap installed package", e); 9489 } 9490 } 9491 9492 @Override 9493 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9494 int userId) { 9495 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9496 PackageSetting pkgSetting; 9497 final int uid = Binder.getCallingUid(); 9498 enforceCrossUserPermission(uid, userId, true, true, 9499 "setApplicationHiddenSetting for user " + userId); 9500 9501 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9502 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9503 return false; 9504 } 9505 9506 long callingId = Binder.clearCallingIdentity(); 9507 try { 9508 boolean sendAdded = false; 9509 boolean sendRemoved = false; 9510 // writer 9511 synchronized (mPackages) { 9512 pkgSetting = mSettings.mPackages.get(packageName); 9513 if (pkgSetting == null) { 9514 return false; 9515 } 9516 if (pkgSetting.getHidden(userId) != hidden) { 9517 pkgSetting.setHidden(hidden, userId); 9518 mSettings.writePackageRestrictionsLPr(userId); 9519 if (hidden) { 9520 sendRemoved = true; 9521 } else { 9522 sendAdded = true; 9523 } 9524 } 9525 } 9526 if (sendAdded) { 9527 sendPackageAddedForUser(packageName, pkgSetting, userId); 9528 return true; 9529 } 9530 if (sendRemoved) { 9531 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9532 "hiding pkg"); 9533 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9534 } 9535 } finally { 9536 Binder.restoreCallingIdentity(callingId); 9537 } 9538 return false; 9539 } 9540 9541 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9542 int userId) { 9543 final PackageRemovedInfo info = new PackageRemovedInfo(); 9544 info.removedPackage = packageName; 9545 info.removedUsers = new int[] {userId}; 9546 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9547 info.sendBroadcast(false, false, false); 9548 } 9549 9550 /** 9551 * Returns true if application is not found or there was an error. Otherwise it returns 9552 * the hidden state of the package for the given user. 9553 */ 9554 @Override 9555 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9556 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9557 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9558 false, "getApplicationHidden for user " + userId); 9559 PackageSetting pkgSetting; 9560 long callingId = Binder.clearCallingIdentity(); 9561 try { 9562 // writer 9563 synchronized (mPackages) { 9564 pkgSetting = mSettings.mPackages.get(packageName); 9565 if (pkgSetting == null) { 9566 return true; 9567 } 9568 return pkgSetting.getHidden(userId); 9569 } 9570 } finally { 9571 Binder.restoreCallingIdentity(callingId); 9572 } 9573 } 9574 9575 /** 9576 * @hide 9577 */ 9578 @Override 9579 public int installExistingPackageAsUser(String packageName, int userId) { 9580 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9581 null); 9582 PackageSetting pkgSetting; 9583 final int uid = Binder.getCallingUid(); 9584 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9585 + userId); 9586 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9587 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9588 } 9589 9590 long callingId = Binder.clearCallingIdentity(); 9591 try { 9592 boolean sendAdded = false; 9593 9594 // writer 9595 synchronized (mPackages) { 9596 pkgSetting = mSettings.mPackages.get(packageName); 9597 if (pkgSetting == null) { 9598 return PackageManager.INSTALL_FAILED_INVALID_URI; 9599 } 9600 if (!pkgSetting.getInstalled(userId)) { 9601 pkgSetting.setInstalled(true, userId); 9602 pkgSetting.setHidden(false, userId); 9603 mSettings.writePackageRestrictionsLPr(userId); 9604 sendAdded = true; 9605 } 9606 } 9607 9608 if (sendAdded) { 9609 sendPackageAddedForUser(packageName, pkgSetting, userId); 9610 } 9611 } finally { 9612 Binder.restoreCallingIdentity(callingId); 9613 } 9614 9615 return PackageManager.INSTALL_SUCCEEDED; 9616 } 9617 9618 boolean isUserRestricted(int userId, String restrictionKey) { 9619 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9620 if (restrictions.getBoolean(restrictionKey, false)) { 9621 Log.w(TAG, "User is restricted: " + restrictionKey); 9622 return true; 9623 } 9624 return false; 9625 } 9626 9627 @Override 9628 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9629 mContext.enforceCallingOrSelfPermission( 9630 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9631 "Only package verification agents can verify applications"); 9632 9633 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9634 final PackageVerificationResponse response = new PackageVerificationResponse( 9635 verificationCode, Binder.getCallingUid()); 9636 msg.arg1 = id; 9637 msg.obj = response; 9638 mHandler.sendMessage(msg); 9639 } 9640 9641 @Override 9642 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9643 long millisecondsToDelay) { 9644 mContext.enforceCallingOrSelfPermission( 9645 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9646 "Only package verification agents can extend verification timeouts"); 9647 9648 final PackageVerificationState state = mPendingVerification.get(id); 9649 final PackageVerificationResponse response = new PackageVerificationResponse( 9650 verificationCodeAtTimeout, Binder.getCallingUid()); 9651 9652 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9653 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9654 } 9655 if (millisecondsToDelay < 0) { 9656 millisecondsToDelay = 0; 9657 } 9658 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9659 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9660 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9661 } 9662 9663 if ((state != null) && !state.timeoutExtended()) { 9664 state.extendTimeout(); 9665 9666 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9667 msg.arg1 = id; 9668 msg.obj = response; 9669 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9670 } 9671 } 9672 9673 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9674 int verificationCode, UserHandle user) { 9675 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9676 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9677 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9678 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9679 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9680 9681 mContext.sendBroadcastAsUser(intent, user, 9682 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9683 } 9684 9685 private ComponentName matchComponentForVerifier(String packageName, 9686 List<ResolveInfo> receivers) { 9687 ActivityInfo targetReceiver = null; 9688 9689 final int NR = receivers.size(); 9690 for (int i = 0; i < NR; i++) { 9691 final ResolveInfo info = receivers.get(i); 9692 if (info.activityInfo == null) { 9693 continue; 9694 } 9695 9696 if (packageName.equals(info.activityInfo.packageName)) { 9697 targetReceiver = info.activityInfo; 9698 break; 9699 } 9700 } 9701 9702 if (targetReceiver == null) { 9703 return null; 9704 } 9705 9706 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9707 } 9708 9709 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9710 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9711 if (pkgInfo.verifiers.length == 0) { 9712 return null; 9713 } 9714 9715 final int N = pkgInfo.verifiers.length; 9716 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9717 for (int i = 0; i < N; i++) { 9718 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9719 9720 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9721 receivers); 9722 if (comp == null) { 9723 continue; 9724 } 9725 9726 final int verifierUid = getUidForVerifier(verifierInfo); 9727 if (verifierUid == -1) { 9728 continue; 9729 } 9730 9731 if (DEBUG_VERIFY) { 9732 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9733 + " with the correct signature"); 9734 } 9735 sufficientVerifiers.add(comp); 9736 verificationState.addSufficientVerifier(verifierUid); 9737 } 9738 9739 return sufficientVerifiers; 9740 } 9741 9742 private int getUidForVerifier(VerifierInfo verifierInfo) { 9743 synchronized (mPackages) { 9744 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9745 if (pkg == null) { 9746 return -1; 9747 } else if (pkg.mSignatures.length != 1) { 9748 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9749 + " has more than one signature; ignoring"); 9750 return -1; 9751 } 9752 9753 /* 9754 * If the public key of the package's signature does not match 9755 * our expected public key, then this is a different package and 9756 * we should skip. 9757 */ 9758 9759 final byte[] expectedPublicKey; 9760 try { 9761 final Signature verifierSig = pkg.mSignatures[0]; 9762 final PublicKey publicKey = verifierSig.getPublicKey(); 9763 expectedPublicKey = publicKey.getEncoded(); 9764 } catch (CertificateException e) { 9765 return -1; 9766 } 9767 9768 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9769 9770 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9771 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9772 + " does not have the expected public key; ignoring"); 9773 return -1; 9774 } 9775 9776 return pkg.applicationInfo.uid; 9777 } 9778 } 9779 9780 @Override 9781 public void finishPackageInstall(int token) { 9782 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9783 9784 if (DEBUG_INSTALL) { 9785 Slog.v(TAG, "BM finishing package install for " + token); 9786 } 9787 9788 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9789 mHandler.sendMessage(msg); 9790 } 9791 9792 /** 9793 * Get the verification agent timeout. 9794 * 9795 * @return verification timeout in milliseconds 9796 */ 9797 private long getVerificationTimeout() { 9798 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9799 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9800 DEFAULT_VERIFICATION_TIMEOUT); 9801 } 9802 9803 /** 9804 * Get the default verification agent response code. 9805 * 9806 * @return default verification response code 9807 */ 9808 private int getDefaultVerificationResponse() { 9809 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9810 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9811 DEFAULT_VERIFICATION_RESPONSE); 9812 } 9813 9814 /** 9815 * Check whether or not package verification has been enabled. 9816 * 9817 * @return true if verification should be performed 9818 */ 9819 private boolean isVerificationEnabled(int userId, int installFlags) { 9820 if (!DEFAULT_VERIFY_ENABLE) { 9821 return false; 9822 } 9823 9824 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9825 9826 // Check if installing from ADB 9827 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9828 // Do not run verification in a test harness environment 9829 if (ActivityManager.isRunningInTestHarness()) { 9830 return false; 9831 } 9832 if (ensureVerifyAppsEnabled) { 9833 return true; 9834 } 9835 // Check if the developer does not want package verification for ADB installs 9836 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9837 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9838 return false; 9839 } 9840 } 9841 9842 if (ensureVerifyAppsEnabled) { 9843 return true; 9844 } 9845 9846 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9847 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9848 } 9849 9850 @Override 9851 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9852 throws RemoteException { 9853 mContext.enforceCallingOrSelfPermission( 9854 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9855 "Only intentfilter verification agents can verify applications"); 9856 9857 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9858 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9859 Binder.getCallingUid(), verificationCode, failedDomains); 9860 msg.arg1 = id; 9861 msg.obj = response; 9862 mHandler.sendMessage(msg); 9863 } 9864 9865 @Override 9866 public int getIntentVerificationStatus(String packageName, int userId) { 9867 synchronized (mPackages) { 9868 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9869 } 9870 } 9871 9872 @Override 9873 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9874 mContext.enforceCallingOrSelfPermission( 9875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9876 9877 boolean result = false; 9878 synchronized (mPackages) { 9879 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9880 } 9881 if (result) { 9882 scheduleWritePackageRestrictionsLocked(userId); 9883 } 9884 return result; 9885 } 9886 9887 @Override 9888 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9889 synchronized (mPackages) { 9890 return mSettings.getIntentFilterVerificationsLPr(packageName); 9891 } 9892 } 9893 9894 @Override 9895 public List<IntentFilter> getAllIntentFilters(String packageName) { 9896 if (TextUtils.isEmpty(packageName)) { 9897 return Collections.<IntentFilter>emptyList(); 9898 } 9899 synchronized (mPackages) { 9900 PackageParser.Package pkg = mPackages.get(packageName); 9901 if (pkg == null || pkg.activities == null) { 9902 return Collections.<IntentFilter>emptyList(); 9903 } 9904 final int count = pkg.activities.size(); 9905 ArrayList<IntentFilter> result = new ArrayList<>(); 9906 for (int n=0; n<count; n++) { 9907 PackageParser.Activity activity = pkg.activities.get(n); 9908 if (activity.intents != null || activity.intents.size() > 0) { 9909 result.addAll(activity.intents); 9910 } 9911 } 9912 return result; 9913 } 9914 } 9915 9916 @Override 9917 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9918 mContext.enforceCallingOrSelfPermission( 9919 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9920 9921 synchronized (mPackages) { 9922 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9923 if (packageName != null) { 9924 result |= updateIntentVerificationStatus(packageName, 9925 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9926 UserHandle.myUserId()); 9927 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9928 packageName, userId); 9929 } 9930 return result; 9931 } 9932 } 9933 9934 @Override 9935 public String getDefaultBrowserPackageName(int userId) { 9936 synchronized (mPackages) { 9937 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9938 } 9939 } 9940 9941 /** 9942 * Get the "allow unknown sources" setting. 9943 * 9944 * @return the current "allow unknown sources" setting 9945 */ 9946 private int getUnknownSourcesSettings() { 9947 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9948 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9949 -1); 9950 } 9951 9952 @Override 9953 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9954 final int uid = Binder.getCallingUid(); 9955 // writer 9956 synchronized (mPackages) { 9957 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9958 if (targetPackageSetting == null) { 9959 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9960 } 9961 9962 PackageSetting installerPackageSetting; 9963 if (installerPackageName != null) { 9964 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9965 if (installerPackageSetting == null) { 9966 throw new IllegalArgumentException("Unknown installer package: " 9967 + installerPackageName); 9968 } 9969 } else { 9970 installerPackageSetting = null; 9971 } 9972 9973 Signature[] callerSignature; 9974 Object obj = mSettings.getUserIdLPr(uid); 9975 if (obj != null) { 9976 if (obj instanceof SharedUserSetting) { 9977 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9978 } else if (obj instanceof PackageSetting) { 9979 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9980 } else { 9981 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9982 } 9983 } else { 9984 throw new SecurityException("Unknown calling uid " + uid); 9985 } 9986 9987 // Verify: can't set installerPackageName to a package that is 9988 // not signed with the same cert as the caller. 9989 if (installerPackageSetting != null) { 9990 if (compareSignatures(callerSignature, 9991 installerPackageSetting.signatures.mSignatures) 9992 != PackageManager.SIGNATURE_MATCH) { 9993 throw new SecurityException( 9994 "Caller does not have same cert as new installer package " 9995 + installerPackageName); 9996 } 9997 } 9998 9999 // Verify: if target already has an installer package, it must 10000 // be signed with the same cert as the caller. 10001 if (targetPackageSetting.installerPackageName != null) { 10002 PackageSetting setting = mSettings.mPackages.get( 10003 targetPackageSetting.installerPackageName); 10004 // If the currently set package isn't valid, then it's always 10005 // okay to change it. 10006 if (setting != null) { 10007 if (compareSignatures(callerSignature, 10008 setting.signatures.mSignatures) 10009 != PackageManager.SIGNATURE_MATCH) { 10010 throw new SecurityException( 10011 "Caller does not have same cert as old installer package " 10012 + targetPackageSetting.installerPackageName); 10013 } 10014 } 10015 } 10016 10017 // Okay! 10018 targetPackageSetting.installerPackageName = installerPackageName; 10019 scheduleWriteSettingsLocked(); 10020 } 10021 } 10022 10023 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10024 // Queue up an async operation since the package installation may take a little while. 10025 mHandler.post(new Runnable() { 10026 public void run() { 10027 mHandler.removeCallbacks(this); 10028 // Result object to be returned 10029 PackageInstalledInfo res = new PackageInstalledInfo(); 10030 res.returnCode = currentStatus; 10031 res.uid = -1; 10032 res.pkg = null; 10033 res.removedInfo = new PackageRemovedInfo(); 10034 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10035 args.doPreInstall(res.returnCode); 10036 synchronized (mInstallLock) { 10037 installPackageLI(args, res); 10038 } 10039 args.doPostInstall(res.returnCode, res.uid); 10040 } 10041 10042 // A restore should be performed at this point if (a) the install 10043 // succeeded, (b) the operation is not an update, and (c) the new 10044 // package has not opted out of backup participation. 10045 final boolean update = res.removedInfo.removedPackage != null; 10046 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10047 boolean doRestore = !update 10048 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10049 10050 // Set up the post-install work request bookkeeping. This will be used 10051 // and cleaned up by the post-install event handling regardless of whether 10052 // there's a restore pass performed. Token values are >= 1. 10053 int token; 10054 if (mNextInstallToken < 0) mNextInstallToken = 1; 10055 token = mNextInstallToken++; 10056 10057 PostInstallData data = new PostInstallData(args, res); 10058 mRunningInstalls.put(token, data); 10059 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10060 10061 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10062 // Pass responsibility to the Backup Manager. It will perform a 10063 // restore if appropriate, then pass responsibility back to the 10064 // Package Manager to run the post-install observer callbacks 10065 // and broadcasts. 10066 IBackupManager bm = IBackupManager.Stub.asInterface( 10067 ServiceManager.getService(Context.BACKUP_SERVICE)); 10068 if (bm != null) { 10069 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10070 + " to BM for possible restore"); 10071 try { 10072 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10073 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10074 } else { 10075 doRestore = false; 10076 } 10077 } catch (RemoteException e) { 10078 // can't happen; the backup manager is local 10079 } catch (Exception e) { 10080 Slog.e(TAG, "Exception trying to enqueue restore", e); 10081 doRestore = false; 10082 } 10083 } else { 10084 Slog.e(TAG, "Backup Manager not found!"); 10085 doRestore = false; 10086 } 10087 } 10088 10089 if (!doRestore) { 10090 // No restore possible, or the Backup Manager was mysteriously not 10091 // available -- just fire the post-install work request directly. 10092 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10093 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10094 mHandler.sendMessage(msg); 10095 } 10096 } 10097 }); 10098 } 10099 10100 private abstract class HandlerParams { 10101 private static final int MAX_RETRIES = 4; 10102 10103 /** 10104 * Number of times startCopy() has been attempted and had a non-fatal 10105 * error. 10106 */ 10107 private int mRetries = 0; 10108 10109 /** User handle for the user requesting the information or installation. */ 10110 private final UserHandle mUser; 10111 10112 HandlerParams(UserHandle user) { 10113 mUser = user; 10114 } 10115 10116 UserHandle getUser() { 10117 return mUser; 10118 } 10119 10120 final boolean startCopy() { 10121 boolean res; 10122 try { 10123 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10124 10125 if (++mRetries > MAX_RETRIES) { 10126 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10127 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10128 handleServiceError(); 10129 return false; 10130 } else { 10131 handleStartCopy(); 10132 res = true; 10133 } 10134 } catch (RemoteException e) { 10135 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10136 mHandler.sendEmptyMessage(MCS_RECONNECT); 10137 res = false; 10138 } 10139 handleReturnCode(); 10140 return res; 10141 } 10142 10143 final void serviceError() { 10144 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10145 handleServiceError(); 10146 handleReturnCode(); 10147 } 10148 10149 abstract void handleStartCopy() throws RemoteException; 10150 abstract void handleServiceError(); 10151 abstract void handleReturnCode(); 10152 } 10153 10154 class MeasureParams extends HandlerParams { 10155 private final PackageStats mStats; 10156 private boolean mSuccess; 10157 10158 private final IPackageStatsObserver mObserver; 10159 10160 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10161 super(new UserHandle(stats.userHandle)); 10162 mObserver = observer; 10163 mStats = stats; 10164 } 10165 10166 @Override 10167 public String toString() { 10168 return "MeasureParams{" 10169 + Integer.toHexString(System.identityHashCode(this)) 10170 + " " + mStats.packageName + "}"; 10171 } 10172 10173 @Override 10174 void handleStartCopy() throws RemoteException { 10175 synchronized (mInstallLock) { 10176 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10177 } 10178 10179 if (mSuccess) { 10180 final boolean mounted; 10181 if (Environment.isExternalStorageEmulated()) { 10182 mounted = true; 10183 } else { 10184 final String status = Environment.getExternalStorageState(); 10185 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10186 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10187 } 10188 10189 if (mounted) { 10190 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10191 10192 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10193 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10194 10195 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10196 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10197 10198 // Always subtract cache size, since it's a subdirectory 10199 mStats.externalDataSize -= mStats.externalCacheSize; 10200 10201 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10202 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10203 10204 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10205 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10206 } 10207 } 10208 } 10209 10210 @Override 10211 void handleReturnCode() { 10212 if (mObserver != null) { 10213 try { 10214 mObserver.onGetStatsCompleted(mStats, mSuccess); 10215 } catch (RemoteException e) { 10216 Slog.i(TAG, "Observer no longer exists."); 10217 } 10218 } 10219 } 10220 10221 @Override 10222 void handleServiceError() { 10223 Slog.e(TAG, "Could not measure application " + mStats.packageName 10224 + " external storage"); 10225 } 10226 } 10227 10228 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10229 throws RemoteException { 10230 long result = 0; 10231 for (File path : paths) { 10232 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10233 } 10234 return result; 10235 } 10236 10237 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10238 for (File path : paths) { 10239 try { 10240 mcs.clearDirectory(path.getAbsolutePath()); 10241 } catch (RemoteException e) { 10242 } 10243 } 10244 } 10245 10246 static class OriginInfo { 10247 /** 10248 * Location where install is coming from, before it has been 10249 * copied/renamed into place. This could be a single monolithic APK 10250 * file, or a cluster directory. This location may be untrusted. 10251 */ 10252 final File file; 10253 final String cid; 10254 10255 /** 10256 * Flag indicating that {@link #file} or {@link #cid} has already been 10257 * staged, meaning downstream users don't need to defensively copy the 10258 * contents. 10259 */ 10260 final boolean staged; 10261 10262 /** 10263 * Flag indicating that {@link #file} or {@link #cid} is an already 10264 * installed app that is being moved. 10265 */ 10266 final boolean existing; 10267 10268 final String resolvedPath; 10269 final File resolvedFile; 10270 10271 static OriginInfo fromNothing() { 10272 return new OriginInfo(null, null, false, false); 10273 } 10274 10275 static OriginInfo fromUntrustedFile(File file) { 10276 return new OriginInfo(file, null, false, false); 10277 } 10278 10279 static OriginInfo fromExistingFile(File file) { 10280 return new OriginInfo(file, null, false, true); 10281 } 10282 10283 static OriginInfo fromStagedFile(File file) { 10284 return new OriginInfo(file, null, true, false); 10285 } 10286 10287 static OriginInfo fromStagedContainer(String cid) { 10288 return new OriginInfo(null, cid, true, false); 10289 } 10290 10291 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10292 this.file = file; 10293 this.cid = cid; 10294 this.staged = staged; 10295 this.existing = existing; 10296 10297 if (cid != null) { 10298 resolvedPath = PackageHelper.getSdDir(cid); 10299 resolvedFile = new File(resolvedPath); 10300 } else if (file != null) { 10301 resolvedPath = file.getAbsolutePath(); 10302 resolvedFile = file; 10303 } else { 10304 resolvedPath = null; 10305 resolvedFile = null; 10306 } 10307 } 10308 } 10309 10310 class MoveInfo { 10311 final int moveId; 10312 final String fromUuid; 10313 final String toUuid; 10314 final String packageName; 10315 final String dataAppName; 10316 final int appId; 10317 final String seinfo; 10318 10319 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10320 String dataAppName, int appId, String seinfo) { 10321 this.moveId = moveId; 10322 this.fromUuid = fromUuid; 10323 this.toUuid = toUuid; 10324 this.packageName = packageName; 10325 this.dataAppName = dataAppName; 10326 this.appId = appId; 10327 this.seinfo = seinfo; 10328 } 10329 } 10330 10331 class InstallParams extends HandlerParams { 10332 final OriginInfo origin; 10333 final MoveInfo move; 10334 final IPackageInstallObserver2 observer; 10335 int installFlags; 10336 final String installerPackageName; 10337 final String volumeUuid; 10338 final VerificationParams verificationParams; 10339 private InstallArgs mArgs; 10340 private int mRet; 10341 final String packageAbiOverride; 10342 10343 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10344 int installFlags, String installerPackageName, String volumeUuid, 10345 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10346 super(user); 10347 this.origin = origin; 10348 this.move = move; 10349 this.observer = observer; 10350 this.installFlags = installFlags; 10351 this.installerPackageName = installerPackageName; 10352 this.volumeUuid = volumeUuid; 10353 this.verificationParams = verificationParams; 10354 this.packageAbiOverride = packageAbiOverride; 10355 } 10356 10357 @Override 10358 public String toString() { 10359 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10360 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10361 } 10362 10363 public ManifestDigest getManifestDigest() { 10364 if (verificationParams == null) { 10365 return null; 10366 } 10367 return verificationParams.getManifestDigest(); 10368 } 10369 10370 private int installLocationPolicy(PackageInfoLite pkgLite) { 10371 String packageName = pkgLite.packageName; 10372 int installLocation = pkgLite.installLocation; 10373 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10374 // reader 10375 synchronized (mPackages) { 10376 PackageParser.Package pkg = mPackages.get(packageName); 10377 if (pkg != null) { 10378 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10379 // Check for downgrading. 10380 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10381 try { 10382 checkDowngrade(pkg, pkgLite); 10383 } catch (PackageManagerException e) { 10384 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10385 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10386 } 10387 } 10388 // Check for updated system application. 10389 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10390 if (onSd) { 10391 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10392 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10393 } 10394 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10395 } else { 10396 if (onSd) { 10397 // Install flag overrides everything. 10398 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10399 } 10400 // If current upgrade specifies particular preference 10401 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10402 // Application explicitly specified internal. 10403 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10404 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10405 // App explictly prefers external. Let policy decide 10406 } else { 10407 // Prefer previous location 10408 if (isExternal(pkg)) { 10409 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10410 } 10411 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10412 } 10413 } 10414 } else { 10415 // Invalid install. Return error code 10416 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10417 } 10418 } 10419 } 10420 // All the special cases have been taken care of. 10421 // Return result based on recommended install location. 10422 if (onSd) { 10423 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10424 } 10425 return pkgLite.recommendedInstallLocation; 10426 } 10427 10428 /* 10429 * Invoke remote method to get package information and install 10430 * location values. Override install location based on default 10431 * policy if needed and then create install arguments based 10432 * on the install location. 10433 */ 10434 public void handleStartCopy() throws RemoteException { 10435 int ret = PackageManager.INSTALL_SUCCEEDED; 10436 10437 // If we're already staged, we've firmly committed to an install location 10438 if (origin.staged) { 10439 if (origin.file != null) { 10440 installFlags |= PackageManager.INSTALL_INTERNAL; 10441 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10442 } else if (origin.cid != null) { 10443 installFlags |= PackageManager.INSTALL_EXTERNAL; 10444 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10445 } else { 10446 throw new IllegalStateException("Invalid stage location"); 10447 } 10448 } 10449 10450 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10451 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10452 10453 PackageInfoLite pkgLite = null; 10454 10455 if (onInt && onSd) { 10456 // Check if both bits are set. 10457 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10458 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10459 } else { 10460 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10461 packageAbiOverride); 10462 10463 /* 10464 * If we have too little free space, try to free cache 10465 * before giving up. 10466 */ 10467 if (!origin.staged && pkgLite.recommendedInstallLocation 10468 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10469 // TODO: focus freeing disk space on the target device 10470 final StorageManager storage = StorageManager.from(mContext); 10471 final long lowThreshold = storage.getStorageLowBytes( 10472 Environment.getDataDirectory()); 10473 10474 final long sizeBytes = mContainerService.calculateInstalledSize( 10475 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10476 10477 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10478 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10479 installFlags, packageAbiOverride); 10480 } 10481 10482 /* 10483 * The cache free must have deleted the file we 10484 * downloaded to install. 10485 * 10486 * TODO: fix the "freeCache" call to not delete 10487 * the file we care about. 10488 */ 10489 if (pkgLite.recommendedInstallLocation 10490 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10491 pkgLite.recommendedInstallLocation 10492 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10493 } 10494 } 10495 } 10496 10497 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10498 int loc = pkgLite.recommendedInstallLocation; 10499 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10500 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10501 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10502 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10503 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10504 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10505 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10506 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10507 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10508 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10509 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10510 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10511 } else { 10512 // Override with defaults if needed. 10513 loc = installLocationPolicy(pkgLite); 10514 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10515 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10516 } else if (!onSd && !onInt) { 10517 // Override install location with flags 10518 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10519 // Set the flag to install on external media. 10520 installFlags |= PackageManager.INSTALL_EXTERNAL; 10521 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10522 } else { 10523 // Make sure the flag for installing on external 10524 // media is unset 10525 installFlags |= PackageManager.INSTALL_INTERNAL; 10526 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10527 } 10528 } 10529 } 10530 } 10531 10532 final InstallArgs args = createInstallArgs(this); 10533 mArgs = args; 10534 10535 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10536 /* 10537 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10538 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10539 */ 10540 int userIdentifier = getUser().getIdentifier(); 10541 if (userIdentifier == UserHandle.USER_ALL 10542 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10543 userIdentifier = UserHandle.USER_OWNER; 10544 } 10545 10546 /* 10547 * Determine if we have any installed package verifiers. If we 10548 * do, then we'll defer to them to verify the packages. 10549 */ 10550 final int requiredUid = mRequiredVerifierPackage == null ? -1 10551 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10552 if (!origin.existing && requiredUid != -1 10553 && isVerificationEnabled(userIdentifier, installFlags)) { 10554 final Intent verification = new Intent( 10555 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10556 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10557 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10558 PACKAGE_MIME_TYPE); 10559 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10560 10561 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10562 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10563 0 /* TODO: Which userId? */); 10564 10565 if (DEBUG_VERIFY) { 10566 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10567 + verification.toString() + " with " + pkgLite.verifiers.length 10568 + " optional verifiers"); 10569 } 10570 10571 final int verificationId = mPendingVerificationToken++; 10572 10573 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10574 10575 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10576 installerPackageName); 10577 10578 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10579 installFlags); 10580 10581 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10582 pkgLite.packageName); 10583 10584 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10585 pkgLite.versionCode); 10586 10587 if (verificationParams != null) { 10588 if (verificationParams.getVerificationURI() != null) { 10589 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10590 verificationParams.getVerificationURI()); 10591 } 10592 if (verificationParams.getOriginatingURI() != null) { 10593 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10594 verificationParams.getOriginatingURI()); 10595 } 10596 if (verificationParams.getReferrer() != null) { 10597 verification.putExtra(Intent.EXTRA_REFERRER, 10598 verificationParams.getReferrer()); 10599 } 10600 if (verificationParams.getOriginatingUid() >= 0) { 10601 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10602 verificationParams.getOriginatingUid()); 10603 } 10604 if (verificationParams.getInstallerUid() >= 0) { 10605 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10606 verificationParams.getInstallerUid()); 10607 } 10608 } 10609 10610 final PackageVerificationState verificationState = new PackageVerificationState( 10611 requiredUid, args); 10612 10613 mPendingVerification.append(verificationId, verificationState); 10614 10615 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10616 receivers, verificationState); 10617 10618 /* 10619 * If any sufficient verifiers were listed in the package 10620 * manifest, attempt to ask them. 10621 */ 10622 if (sufficientVerifiers != null) { 10623 final int N = sufficientVerifiers.size(); 10624 if (N == 0) { 10625 Slog.i(TAG, "Additional verifiers required, but none installed."); 10626 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10627 } else { 10628 for (int i = 0; i < N; i++) { 10629 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10630 10631 final Intent sufficientIntent = new Intent(verification); 10632 sufficientIntent.setComponent(verifierComponent); 10633 10634 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10635 } 10636 } 10637 } 10638 10639 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10640 mRequiredVerifierPackage, receivers); 10641 if (ret == PackageManager.INSTALL_SUCCEEDED 10642 && mRequiredVerifierPackage != null) { 10643 /* 10644 * Send the intent to the required verification agent, 10645 * but only start the verification timeout after the 10646 * target BroadcastReceivers have run. 10647 */ 10648 verification.setComponent(requiredVerifierComponent); 10649 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10650 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10651 new BroadcastReceiver() { 10652 @Override 10653 public void onReceive(Context context, Intent intent) { 10654 final Message msg = mHandler 10655 .obtainMessage(CHECK_PENDING_VERIFICATION); 10656 msg.arg1 = verificationId; 10657 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10658 } 10659 }, null, 0, null, null); 10660 10661 /* 10662 * We don't want the copy to proceed until verification 10663 * succeeds, so null out this field. 10664 */ 10665 mArgs = null; 10666 } 10667 } else { 10668 /* 10669 * No package verification is enabled, so immediately start 10670 * the remote call to initiate copy using temporary file. 10671 */ 10672 ret = args.copyApk(mContainerService, true); 10673 } 10674 } 10675 10676 mRet = ret; 10677 } 10678 10679 @Override 10680 void handleReturnCode() { 10681 // If mArgs is null, then MCS couldn't be reached. When it 10682 // reconnects, it will try again to install. At that point, this 10683 // will succeed. 10684 if (mArgs != null) { 10685 processPendingInstall(mArgs, mRet); 10686 } 10687 } 10688 10689 @Override 10690 void handleServiceError() { 10691 mArgs = createInstallArgs(this); 10692 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10693 } 10694 10695 public boolean isForwardLocked() { 10696 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10697 } 10698 } 10699 10700 /** 10701 * Used during creation of InstallArgs 10702 * 10703 * @param installFlags package installation flags 10704 * @return true if should be installed on external storage 10705 */ 10706 private static boolean installOnExternalAsec(int installFlags) { 10707 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10708 return false; 10709 } 10710 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10711 return true; 10712 } 10713 return false; 10714 } 10715 10716 /** 10717 * Used during creation of InstallArgs 10718 * 10719 * @param installFlags package installation flags 10720 * @return true if should be installed as forward locked 10721 */ 10722 private static boolean installForwardLocked(int installFlags) { 10723 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10724 } 10725 10726 private InstallArgs createInstallArgs(InstallParams params) { 10727 if (params.move != null) { 10728 return new MoveInstallArgs(params); 10729 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10730 return new AsecInstallArgs(params); 10731 } else { 10732 return new FileInstallArgs(params); 10733 } 10734 } 10735 10736 /** 10737 * Create args that describe an existing installed package. Typically used 10738 * when cleaning up old installs, or used as a move source. 10739 */ 10740 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10741 String resourcePath, String[] instructionSets) { 10742 final boolean isInAsec; 10743 if (installOnExternalAsec(installFlags)) { 10744 /* Apps on SD card are always in ASEC containers. */ 10745 isInAsec = true; 10746 } else if (installForwardLocked(installFlags) 10747 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10748 /* 10749 * Forward-locked apps are only in ASEC containers if they're the 10750 * new style 10751 */ 10752 isInAsec = true; 10753 } else { 10754 isInAsec = false; 10755 } 10756 10757 if (isInAsec) { 10758 return new AsecInstallArgs(codePath, instructionSets, 10759 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10760 } else { 10761 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10762 } 10763 } 10764 10765 static abstract class InstallArgs { 10766 /** @see InstallParams#origin */ 10767 final OriginInfo origin; 10768 /** @see InstallParams#move */ 10769 final MoveInfo move; 10770 10771 final IPackageInstallObserver2 observer; 10772 // Always refers to PackageManager flags only 10773 final int installFlags; 10774 final String installerPackageName; 10775 final String volumeUuid; 10776 final ManifestDigest manifestDigest; 10777 final UserHandle user; 10778 final String abiOverride; 10779 10780 // The list of instruction sets supported by this app. This is currently 10781 // only used during the rmdex() phase to clean up resources. We can get rid of this 10782 // if we move dex files under the common app path. 10783 /* nullable */ String[] instructionSets; 10784 10785 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10786 int installFlags, String installerPackageName, String volumeUuid, 10787 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10788 String abiOverride) { 10789 this.origin = origin; 10790 this.move = move; 10791 this.installFlags = installFlags; 10792 this.observer = observer; 10793 this.installerPackageName = installerPackageName; 10794 this.volumeUuid = volumeUuid; 10795 this.manifestDigest = manifestDigest; 10796 this.user = user; 10797 this.instructionSets = instructionSets; 10798 this.abiOverride = abiOverride; 10799 } 10800 10801 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10802 abstract int doPreInstall(int status); 10803 10804 /** 10805 * Rename package into final resting place. All paths on the given 10806 * scanned package should be updated to reflect the rename. 10807 */ 10808 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10809 abstract int doPostInstall(int status, int uid); 10810 10811 /** @see PackageSettingBase#codePathString */ 10812 abstract String getCodePath(); 10813 /** @see PackageSettingBase#resourcePathString */ 10814 abstract String getResourcePath(); 10815 10816 // Need installer lock especially for dex file removal. 10817 abstract void cleanUpResourcesLI(); 10818 abstract boolean doPostDeleteLI(boolean delete); 10819 10820 /** 10821 * Called before the source arguments are copied. This is used mostly 10822 * for MoveParams when it needs to read the source file to put it in the 10823 * destination. 10824 */ 10825 int doPreCopy() { 10826 return PackageManager.INSTALL_SUCCEEDED; 10827 } 10828 10829 /** 10830 * Called after the source arguments are copied. This is used mostly for 10831 * MoveParams when it needs to read the source file to put it in the 10832 * destination. 10833 * 10834 * @return 10835 */ 10836 int doPostCopy(int uid) { 10837 return PackageManager.INSTALL_SUCCEEDED; 10838 } 10839 10840 protected boolean isFwdLocked() { 10841 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10842 } 10843 10844 protected boolean isExternalAsec() { 10845 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10846 } 10847 10848 UserHandle getUser() { 10849 return user; 10850 } 10851 } 10852 10853 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10854 if (!allCodePaths.isEmpty()) { 10855 if (instructionSets == null) { 10856 throw new IllegalStateException("instructionSet == null"); 10857 } 10858 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10859 for (String codePath : allCodePaths) { 10860 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10861 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10862 if (retCode < 0) { 10863 Slog.w(TAG, "Couldn't remove dex file for package: " 10864 + " at location " + codePath + ", retcode=" + retCode); 10865 // we don't consider this to be a failure of the core package deletion 10866 } 10867 } 10868 } 10869 } 10870 } 10871 10872 /** 10873 * Logic to handle installation of non-ASEC applications, including copying 10874 * and renaming logic. 10875 */ 10876 class FileInstallArgs extends InstallArgs { 10877 private File codeFile; 10878 private File resourceFile; 10879 10880 // Example topology: 10881 // /data/app/com.example/base.apk 10882 // /data/app/com.example/split_foo.apk 10883 // /data/app/com.example/lib/arm/libfoo.so 10884 // /data/app/com.example/lib/arm64/libfoo.so 10885 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10886 10887 /** New install */ 10888 FileInstallArgs(InstallParams params) { 10889 super(params.origin, params.move, params.observer, params.installFlags, 10890 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10891 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10892 if (isFwdLocked()) { 10893 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10894 } 10895 } 10896 10897 /** Existing install */ 10898 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10899 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10900 null); 10901 this.codeFile = (codePath != null) ? new File(codePath) : null; 10902 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10903 } 10904 10905 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10906 if (origin.staged) { 10907 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10908 codeFile = origin.file; 10909 resourceFile = origin.file; 10910 return PackageManager.INSTALL_SUCCEEDED; 10911 } 10912 10913 try { 10914 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10915 codeFile = tempDir; 10916 resourceFile = tempDir; 10917 } catch (IOException e) { 10918 Slog.w(TAG, "Failed to create copy file: " + e); 10919 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10920 } 10921 10922 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10923 @Override 10924 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10925 if (!FileUtils.isValidExtFilename(name)) { 10926 throw new IllegalArgumentException("Invalid filename: " + name); 10927 } 10928 try { 10929 final File file = new File(codeFile, name); 10930 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10931 O_RDWR | O_CREAT, 0644); 10932 Os.chmod(file.getAbsolutePath(), 0644); 10933 return new ParcelFileDescriptor(fd); 10934 } catch (ErrnoException e) { 10935 throw new RemoteException("Failed to open: " + e.getMessage()); 10936 } 10937 } 10938 }; 10939 10940 int ret = PackageManager.INSTALL_SUCCEEDED; 10941 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10942 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10943 Slog.e(TAG, "Failed to copy package"); 10944 return ret; 10945 } 10946 10947 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10948 NativeLibraryHelper.Handle handle = null; 10949 try { 10950 handle = NativeLibraryHelper.Handle.create(codeFile); 10951 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10952 abiOverride); 10953 } catch (IOException e) { 10954 Slog.e(TAG, "Copying native libraries failed", e); 10955 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10956 } finally { 10957 IoUtils.closeQuietly(handle); 10958 } 10959 10960 return ret; 10961 } 10962 10963 int doPreInstall(int status) { 10964 if (status != PackageManager.INSTALL_SUCCEEDED) { 10965 cleanUp(); 10966 } 10967 return status; 10968 } 10969 10970 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10971 if (status != PackageManager.INSTALL_SUCCEEDED) { 10972 cleanUp(); 10973 return false; 10974 } 10975 10976 final File targetDir = codeFile.getParentFile(); 10977 final File beforeCodeFile = codeFile; 10978 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10979 10980 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10981 try { 10982 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10983 } catch (ErrnoException e) { 10984 Slog.w(TAG, "Failed to rename", e); 10985 return false; 10986 } 10987 10988 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10989 Slog.w(TAG, "Failed to restorecon"); 10990 return false; 10991 } 10992 10993 // Reflect the rename internally 10994 codeFile = afterCodeFile; 10995 resourceFile = afterCodeFile; 10996 10997 // Reflect the rename in scanned details 10998 pkg.codePath = afterCodeFile.getAbsolutePath(); 10999 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11000 pkg.baseCodePath); 11001 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11002 pkg.splitCodePaths); 11003 11004 // Reflect the rename in app info 11005 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11006 pkg.applicationInfo.setCodePath(pkg.codePath); 11007 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11008 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11009 pkg.applicationInfo.setResourcePath(pkg.codePath); 11010 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11011 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11012 11013 return true; 11014 } 11015 11016 int doPostInstall(int status, int uid) { 11017 if (status != PackageManager.INSTALL_SUCCEEDED) { 11018 cleanUp(); 11019 } 11020 return status; 11021 } 11022 11023 @Override 11024 String getCodePath() { 11025 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11026 } 11027 11028 @Override 11029 String getResourcePath() { 11030 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11031 } 11032 11033 private boolean cleanUp() { 11034 if (codeFile == null || !codeFile.exists()) { 11035 return false; 11036 } 11037 11038 if (codeFile.isDirectory()) { 11039 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11040 } else { 11041 codeFile.delete(); 11042 } 11043 11044 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11045 resourceFile.delete(); 11046 } 11047 11048 return true; 11049 } 11050 11051 void cleanUpResourcesLI() { 11052 // Try enumerating all code paths before deleting 11053 List<String> allCodePaths = Collections.EMPTY_LIST; 11054 if (codeFile != null && codeFile.exists()) { 11055 try { 11056 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11057 allCodePaths = pkg.getAllCodePaths(); 11058 } catch (PackageParserException e) { 11059 // Ignored; we tried our best 11060 } 11061 } 11062 11063 cleanUp(); 11064 removeDexFiles(allCodePaths, instructionSets); 11065 } 11066 11067 boolean doPostDeleteLI(boolean delete) { 11068 // XXX err, shouldn't we respect the delete flag? 11069 cleanUpResourcesLI(); 11070 return true; 11071 } 11072 } 11073 11074 private boolean isAsecExternal(String cid) { 11075 final String asecPath = PackageHelper.getSdFilesystem(cid); 11076 return !asecPath.startsWith(mAsecInternalPath); 11077 } 11078 11079 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11080 PackageManagerException { 11081 if (copyRet < 0) { 11082 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11083 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11084 throw new PackageManagerException(copyRet, message); 11085 } 11086 } 11087 } 11088 11089 /** 11090 * Extract the MountService "container ID" from the full code path of an 11091 * .apk. 11092 */ 11093 static String cidFromCodePath(String fullCodePath) { 11094 int eidx = fullCodePath.lastIndexOf("/"); 11095 String subStr1 = fullCodePath.substring(0, eidx); 11096 int sidx = subStr1.lastIndexOf("/"); 11097 return subStr1.substring(sidx+1, eidx); 11098 } 11099 11100 /** 11101 * Logic to handle installation of ASEC applications, including copying and 11102 * renaming logic. 11103 */ 11104 class AsecInstallArgs extends InstallArgs { 11105 static final String RES_FILE_NAME = "pkg.apk"; 11106 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11107 11108 String cid; 11109 String packagePath; 11110 String resourcePath; 11111 11112 /** New install */ 11113 AsecInstallArgs(InstallParams params) { 11114 super(params.origin, params.move, params.observer, params.installFlags, 11115 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11116 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11117 } 11118 11119 /** Existing install */ 11120 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11121 boolean isExternal, boolean isForwardLocked) { 11122 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11123 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11124 instructionSets, null); 11125 // Hackily pretend we're still looking at a full code path 11126 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11127 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11128 } 11129 11130 // Extract cid from fullCodePath 11131 int eidx = fullCodePath.lastIndexOf("/"); 11132 String subStr1 = fullCodePath.substring(0, eidx); 11133 int sidx = subStr1.lastIndexOf("/"); 11134 cid = subStr1.substring(sidx+1, eidx); 11135 setMountPath(subStr1); 11136 } 11137 11138 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11139 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11140 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11141 instructionSets, null); 11142 this.cid = cid; 11143 setMountPath(PackageHelper.getSdDir(cid)); 11144 } 11145 11146 void createCopyFile() { 11147 cid = mInstallerService.allocateExternalStageCidLegacy(); 11148 } 11149 11150 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11151 if (origin.staged) { 11152 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11153 cid = origin.cid; 11154 setMountPath(PackageHelper.getSdDir(cid)); 11155 return PackageManager.INSTALL_SUCCEEDED; 11156 } 11157 11158 if (temp) { 11159 createCopyFile(); 11160 } else { 11161 /* 11162 * Pre-emptively destroy the container since it's destroyed if 11163 * copying fails due to it existing anyway. 11164 */ 11165 PackageHelper.destroySdDir(cid); 11166 } 11167 11168 final String newMountPath = imcs.copyPackageToContainer( 11169 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11170 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11171 11172 if (newMountPath != null) { 11173 setMountPath(newMountPath); 11174 return PackageManager.INSTALL_SUCCEEDED; 11175 } else { 11176 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11177 } 11178 } 11179 11180 @Override 11181 String getCodePath() { 11182 return packagePath; 11183 } 11184 11185 @Override 11186 String getResourcePath() { 11187 return resourcePath; 11188 } 11189 11190 int doPreInstall(int status) { 11191 if (status != PackageManager.INSTALL_SUCCEEDED) { 11192 // Destroy container 11193 PackageHelper.destroySdDir(cid); 11194 } else { 11195 boolean mounted = PackageHelper.isContainerMounted(cid); 11196 if (!mounted) { 11197 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11198 Process.SYSTEM_UID); 11199 if (newMountPath != null) { 11200 setMountPath(newMountPath); 11201 } else { 11202 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11203 } 11204 } 11205 } 11206 return status; 11207 } 11208 11209 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11210 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11211 String newMountPath = null; 11212 if (PackageHelper.isContainerMounted(cid)) { 11213 // Unmount the container 11214 if (!PackageHelper.unMountSdDir(cid)) { 11215 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11216 return false; 11217 } 11218 } 11219 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11220 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11221 " which might be stale. Will try to clean up."); 11222 // Clean up the stale container and proceed to recreate. 11223 if (!PackageHelper.destroySdDir(newCacheId)) { 11224 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11225 return false; 11226 } 11227 // Successfully cleaned up stale container. Try to rename again. 11228 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11229 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11230 + " inspite of cleaning it up."); 11231 return false; 11232 } 11233 } 11234 if (!PackageHelper.isContainerMounted(newCacheId)) { 11235 Slog.w(TAG, "Mounting container " + newCacheId); 11236 newMountPath = PackageHelper.mountSdDir(newCacheId, 11237 getEncryptKey(), Process.SYSTEM_UID); 11238 } else { 11239 newMountPath = PackageHelper.getSdDir(newCacheId); 11240 } 11241 if (newMountPath == null) { 11242 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11243 return false; 11244 } 11245 Log.i(TAG, "Succesfully renamed " + cid + 11246 " to " + newCacheId + 11247 " at new path: " + newMountPath); 11248 cid = newCacheId; 11249 11250 final File beforeCodeFile = new File(packagePath); 11251 setMountPath(newMountPath); 11252 final File afterCodeFile = new File(packagePath); 11253 11254 // Reflect the rename in scanned details 11255 pkg.codePath = afterCodeFile.getAbsolutePath(); 11256 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11257 pkg.baseCodePath); 11258 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11259 pkg.splitCodePaths); 11260 11261 // Reflect the rename in app info 11262 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11263 pkg.applicationInfo.setCodePath(pkg.codePath); 11264 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11265 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11266 pkg.applicationInfo.setResourcePath(pkg.codePath); 11267 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11268 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11269 11270 return true; 11271 } 11272 11273 private void setMountPath(String mountPath) { 11274 final File mountFile = new File(mountPath); 11275 11276 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11277 if (monolithicFile.exists()) { 11278 packagePath = monolithicFile.getAbsolutePath(); 11279 if (isFwdLocked()) { 11280 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11281 } else { 11282 resourcePath = packagePath; 11283 } 11284 } else { 11285 packagePath = mountFile.getAbsolutePath(); 11286 resourcePath = packagePath; 11287 } 11288 } 11289 11290 int doPostInstall(int status, int uid) { 11291 if (status != PackageManager.INSTALL_SUCCEEDED) { 11292 cleanUp(); 11293 } else { 11294 final int groupOwner; 11295 final String protectedFile; 11296 if (isFwdLocked()) { 11297 groupOwner = UserHandle.getSharedAppGid(uid); 11298 protectedFile = RES_FILE_NAME; 11299 } else { 11300 groupOwner = -1; 11301 protectedFile = null; 11302 } 11303 11304 if (uid < Process.FIRST_APPLICATION_UID 11305 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11306 Slog.e(TAG, "Failed to finalize " + cid); 11307 PackageHelper.destroySdDir(cid); 11308 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11309 } 11310 11311 boolean mounted = PackageHelper.isContainerMounted(cid); 11312 if (!mounted) { 11313 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11314 } 11315 } 11316 return status; 11317 } 11318 11319 private void cleanUp() { 11320 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11321 11322 // Destroy secure container 11323 PackageHelper.destroySdDir(cid); 11324 } 11325 11326 private List<String> getAllCodePaths() { 11327 final File codeFile = new File(getCodePath()); 11328 if (codeFile != null && codeFile.exists()) { 11329 try { 11330 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11331 return pkg.getAllCodePaths(); 11332 } catch (PackageParserException e) { 11333 // Ignored; we tried our best 11334 } 11335 } 11336 return Collections.EMPTY_LIST; 11337 } 11338 11339 void cleanUpResourcesLI() { 11340 // Enumerate all code paths before deleting 11341 cleanUpResourcesLI(getAllCodePaths()); 11342 } 11343 11344 private void cleanUpResourcesLI(List<String> allCodePaths) { 11345 cleanUp(); 11346 removeDexFiles(allCodePaths, instructionSets); 11347 } 11348 11349 String getPackageName() { 11350 return getAsecPackageName(cid); 11351 } 11352 11353 boolean doPostDeleteLI(boolean delete) { 11354 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11355 final List<String> allCodePaths = getAllCodePaths(); 11356 boolean mounted = PackageHelper.isContainerMounted(cid); 11357 if (mounted) { 11358 // Unmount first 11359 if (PackageHelper.unMountSdDir(cid)) { 11360 mounted = false; 11361 } 11362 } 11363 if (!mounted && delete) { 11364 cleanUpResourcesLI(allCodePaths); 11365 } 11366 return !mounted; 11367 } 11368 11369 @Override 11370 int doPreCopy() { 11371 if (isFwdLocked()) { 11372 if (!PackageHelper.fixSdPermissions(cid, 11373 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11374 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11375 } 11376 } 11377 11378 return PackageManager.INSTALL_SUCCEEDED; 11379 } 11380 11381 @Override 11382 int doPostCopy(int uid) { 11383 if (isFwdLocked()) { 11384 if (uid < Process.FIRST_APPLICATION_UID 11385 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11386 RES_FILE_NAME)) { 11387 Slog.e(TAG, "Failed to finalize " + cid); 11388 PackageHelper.destroySdDir(cid); 11389 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11390 } 11391 } 11392 11393 return PackageManager.INSTALL_SUCCEEDED; 11394 } 11395 } 11396 11397 /** 11398 * Logic to handle movement of existing installed applications. 11399 */ 11400 class MoveInstallArgs extends InstallArgs { 11401 private File codeFile; 11402 private File resourceFile; 11403 11404 /** New install */ 11405 MoveInstallArgs(InstallParams params) { 11406 super(params.origin, params.move, params.observer, params.installFlags, 11407 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11408 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11409 } 11410 11411 int copyApk(IMediaContainerService imcs, boolean temp) { 11412 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11413 + move.fromUuid + " to " + move.toUuid); 11414 synchronized (mInstaller) { 11415 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11416 move.dataAppName, move.appId, move.seinfo) != 0) { 11417 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11418 } 11419 } 11420 11421 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11422 resourceFile = codeFile; 11423 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11424 11425 return PackageManager.INSTALL_SUCCEEDED; 11426 } 11427 11428 int doPreInstall(int status) { 11429 if (status != PackageManager.INSTALL_SUCCEEDED) { 11430 cleanUp(move.toUuid); 11431 } 11432 return status; 11433 } 11434 11435 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11436 if (status != PackageManager.INSTALL_SUCCEEDED) { 11437 cleanUp(move.toUuid); 11438 return false; 11439 } 11440 11441 // Reflect the move in app info 11442 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11443 pkg.applicationInfo.setCodePath(pkg.codePath); 11444 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11445 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11446 pkg.applicationInfo.setResourcePath(pkg.codePath); 11447 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11448 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11449 11450 return true; 11451 } 11452 11453 int doPostInstall(int status, int uid) { 11454 if (status == PackageManager.INSTALL_SUCCEEDED) { 11455 cleanUp(move.fromUuid); 11456 } else { 11457 cleanUp(move.toUuid); 11458 } 11459 return status; 11460 } 11461 11462 @Override 11463 String getCodePath() { 11464 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11465 } 11466 11467 @Override 11468 String getResourcePath() { 11469 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11470 } 11471 11472 private boolean cleanUp(String volumeUuid) { 11473 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11474 move.dataAppName); 11475 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11476 synchronized (mInstallLock) { 11477 // Clean up both app data and code 11478 removeDataDirsLI(volumeUuid, move.packageName); 11479 if (codeFile.isDirectory()) { 11480 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11481 } else { 11482 codeFile.delete(); 11483 } 11484 } 11485 return true; 11486 } 11487 11488 void cleanUpResourcesLI() { 11489 throw new UnsupportedOperationException(); 11490 } 11491 11492 boolean doPostDeleteLI(boolean delete) { 11493 throw new UnsupportedOperationException(); 11494 } 11495 } 11496 11497 static String getAsecPackageName(String packageCid) { 11498 int idx = packageCid.lastIndexOf("-"); 11499 if (idx == -1) { 11500 return packageCid; 11501 } 11502 return packageCid.substring(0, idx); 11503 } 11504 11505 // Utility method used to create code paths based on package name and available index. 11506 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11507 String idxStr = ""; 11508 int idx = 1; 11509 // Fall back to default value of idx=1 if prefix is not 11510 // part of oldCodePath 11511 if (oldCodePath != null) { 11512 String subStr = oldCodePath; 11513 // Drop the suffix right away 11514 if (suffix != null && subStr.endsWith(suffix)) { 11515 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11516 } 11517 // If oldCodePath already contains prefix find out the 11518 // ending index to either increment or decrement. 11519 int sidx = subStr.lastIndexOf(prefix); 11520 if (sidx != -1) { 11521 subStr = subStr.substring(sidx + prefix.length()); 11522 if (subStr != null) { 11523 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11524 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11525 } 11526 try { 11527 idx = Integer.parseInt(subStr); 11528 if (idx <= 1) { 11529 idx++; 11530 } else { 11531 idx--; 11532 } 11533 } catch(NumberFormatException e) { 11534 } 11535 } 11536 } 11537 } 11538 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11539 return prefix + idxStr; 11540 } 11541 11542 private File getNextCodePath(File targetDir, String packageName) { 11543 int suffix = 1; 11544 File result; 11545 do { 11546 result = new File(targetDir, packageName + "-" + suffix); 11547 suffix++; 11548 } while (result.exists()); 11549 return result; 11550 } 11551 11552 // Utility method that returns the relative package path with respect 11553 // to the installation directory. Like say for /data/data/com.test-1.apk 11554 // string com.test-1 is returned. 11555 static String deriveCodePathName(String codePath) { 11556 if (codePath == null) { 11557 return null; 11558 } 11559 final File codeFile = new File(codePath); 11560 final String name = codeFile.getName(); 11561 if (codeFile.isDirectory()) { 11562 return name; 11563 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11564 final int lastDot = name.lastIndexOf('.'); 11565 return name.substring(0, lastDot); 11566 } else { 11567 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11568 return null; 11569 } 11570 } 11571 11572 class PackageInstalledInfo { 11573 String name; 11574 int uid; 11575 // The set of users that originally had this package installed. 11576 int[] origUsers; 11577 // The set of users that now have this package installed. 11578 int[] newUsers; 11579 PackageParser.Package pkg; 11580 int returnCode; 11581 String returnMsg; 11582 PackageRemovedInfo removedInfo; 11583 11584 public void setError(int code, String msg) { 11585 returnCode = code; 11586 returnMsg = msg; 11587 Slog.w(TAG, msg); 11588 } 11589 11590 public void setError(String msg, PackageParserException e) { 11591 returnCode = e.error; 11592 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11593 Slog.w(TAG, msg, e); 11594 } 11595 11596 public void setError(String msg, PackageManagerException e) { 11597 returnCode = e.error; 11598 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11599 Slog.w(TAG, msg, e); 11600 } 11601 11602 // In some error cases we want to convey more info back to the observer 11603 String origPackage; 11604 String origPermission; 11605 } 11606 11607 /* 11608 * Install a non-existing package. 11609 */ 11610 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11611 UserHandle user, String installerPackageName, String volumeUuid, 11612 PackageInstalledInfo res) { 11613 // Remember this for later, in case we need to rollback this install 11614 String pkgName = pkg.packageName; 11615 11616 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11617 final boolean dataDirExists = Environment 11618 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11619 synchronized(mPackages) { 11620 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11621 // A package with the same name is already installed, though 11622 // it has been renamed to an older name. The package we 11623 // are trying to install should be installed as an update to 11624 // the existing one, but that has not been requested, so bail. 11625 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11626 + " without first uninstalling package running as " 11627 + mSettings.mRenamedPackages.get(pkgName)); 11628 return; 11629 } 11630 if (mPackages.containsKey(pkgName)) { 11631 // Don't allow installation over an existing package with the same name. 11632 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11633 + " without first uninstalling."); 11634 return; 11635 } 11636 } 11637 11638 try { 11639 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11640 System.currentTimeMillis(), user); 11641 11642 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11643 // delete the partially installed application. the data directory will have to be 11644 // restored if it was already existing 11645 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11646 // remove package from internal structures. Note that we want deletePackageX to 11647 // delete the package data and cache directories that it created in 11648 // scanPackageLocked, unless those directories existed before we even tried to 11649 // install. 11650 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11651 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11652 res.removedInfo, true); 11653 } 11654 11655 } catch (PackageManagerException e) { 11656 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11657 } 11658 } 11659 11660 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11661 // Can't rotate keys during boot or if sharedUser. 11662 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11663 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11664 return false; 11665 } 11666 // app is using upgradeKeySets; make sure all are valid 11667 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11668 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11669 for (int i = 0; i < upgradeKeySets.length; i++) { 11670 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11671 Slog.wtf(TAG, "Package " 11672 + (oldPs.name != null ? oldPs.name : "<null>") 11673 + " contains upgrade-key-set reference to unknown key-set: " 11674 + upgradeKeySets[i] 11675 + " reverting to signatures check."); 11676 return false; 11677 } 11678 } 11679 return true; 11680 } 11681 11682 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11683 // Upgrade keysets are being used. Determine if new package has a superset of the 11684 // required keys. 11685 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11686 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11687 for (int i = 0; i < upgradeKeySets.length; i++) { 11688 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11689 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11690 return true; 11691 } 11692 } 11693 return false; 11694 } 11695 11696 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11697 UserHandle user, String installerPackageName, String volumeUuid, 11698 PackageInstalledInfo res) { 11699 final PackageParser.Package oldPackage; 11700 final String pkgName = pkg.packageName; 11701 final int[] allUsers; 11702 final boolean[] perUserInstalled; 11703 final boolean weFroze; 11704 11705 // First find the old package info and check signatures 11706 synchronized(mPackages) { 11707 oldPackage = mPackages.get(pkgName); 11708 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11709 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11710 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11711 if(!checkUpgradeKeySetLP(ps, pkg)) { 11712 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11713 "New package not signed by keys specified by upgrade-keysets: " 11714 + pkgName); 11715 return; 11716 } 11717 } else { 11718 // default to original signature matching 11719 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11720 != PackageManager.SIGNATURE_MATCH) { 11721 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11722 "New package has a different signature: " + pkgName); 11723 return; 11724 } 11725 } 11726 11727 // In case of rollback, remember per-user/profile install state 11728 allUsers = sUserManager.getUserIds(); 11729 perUserInstalled = new boolean[allUsers.length]; 11730 for (int i = 0; i < allUsers.length; i++) { 11731 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11732 } 11733 11734 // Mark the app as frozen to prevent launching during the upgrade 11735 // process, and then kill all running instances 11736 if (!ps.frozen) { 11737 ps.frozen = true; 11738 weFroze = true; 11739 } else { 11740 weFroze = false; 11741 } 11742 } 11743 11744 // Now that we're guarded by frozen state, kill app during upgrade 11745 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11746 11747 try { 11748 boolean sysPkg = (isSystemApp(oldPackage)); 11749 if (sysPkg) { 11750 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11751 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11752 } else { 11753 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11754 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11755 } 11756 } finally { 11757 // Regardless of success or failure of upgrade steps above, always 11758 // unfreeze the package if we froze it 11759 if (weFroze) { 11760 unfreezePackage(pkgName); 11761 } 11762 } 11763 } 11764 11765 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11766 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11767 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11768 String volumeUuid, PackageInstalledInfo res) { 11769 String pkgName = deletedPackage.packageName; 11770 boolean deletedPkg = true; 11771 boolean updatedSettings = false; 11772 11773 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11774 + deletedPackage); 11775 long origUpdateTime; 11776 if (pkg.mExtras != null) { 11777 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11778 } else { 11779 origUpdateTime = 0; 11780 } 11781 11782 // First delete the existing package while retaining the data directory 11783 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11784 res.removedInfo, true)) { 11785 // If the existing package wasn't successfully deleted 11786 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11787 deletedPkg = false; 11788 } else { 11789 // Successfully deleted the old package; proceed with replace. 11790 11791 // If deleted package lived in a container, give users a chance to 11792 // relinquish resources before killing. 11793 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11794 if (DEBUG_INSTALL) { 11795 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11796 } 11797 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11798 final ArrayList<String> pkgList = new ArrayList<String>(1); 11799 pkgList.add(deletedPackage.applicationInfo.packageName); 11800 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11801 } 11802 11803 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11804 try { 11805 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11806 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11807 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11808 perUserInstalled, res, user); 11809 updatedSettings = true; 11810 } catch (PackageManagerException e) { 11811 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11812 } 11813 } 11814 11815 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11816 // remove package from internal structures. Note that we want deletePackageX to 11817 // delete the package data and cache directories that it created in 11818 // scanPackageLocked, unless those directories existed before we even tried to 11819 // install. 11820 if(updatedSettings) { 11821 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11822 deletePackageLI( 11823 pkgName, null, true, allUsers, perUserInstalled, 11824 PackageManager.DELETE_KEEP_DATA, 11825 res.removedInfo, true); 11826 } 11827 // Since we failed to install the new package we need to restore the old 11828 // package that we deleted. 11829 if (deletedPkg) { 11830 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11831 File restoreFile = new File(deletedPackage.codePath); 11832 // Parse old package 11833 boolean oldExternal = isExternal(deletedPackage); 11834 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11835 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11836 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11837 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11838 try { 11839 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11840 } catch (PackageManagerException e) { 11841 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11842 + e.getMessage()); 11843 return; 11844 } 11845 // Restore of old package succeeded. Update permissions. 11846 // writer 11847 synchronized (mPackages) { 11848 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11849 UPDATE_PERMISSIONS_ALL); 11850 // can downgrade to reader 11851 mSettings.writeLPr(); 11852 } 11853 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11854 } 11855 } 11856 } 11857 11858 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11859 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11860 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11861 String volumeUuid, PackageInstalledInfo res) { 11862 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11863 + ", old=" + deletedPackage); 11864 boolean disabledSystem = false; 11865 boolean updatedSettings = false; 11866 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11867 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11868 != 0) { 11869 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11870 } 11871 String packageName = deletedPackage.packageName; 11872 if (packageName == null) { 11873 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11874 "Attempt to delete null packageName."); 11875 return; 11876 } 11877 PackageParser.Package oldPkg; 11878 PackageSetting oldPkgSetting; 11879 // reader 11880 synchronized (mPackages) { 11881 oldPkg = mPackages.get(packageName); 11882 oldPkgSetting = mSettings.mPackages.get(packageName); 11883 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11884 (oldPkgSetting == null)) { 11885 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11886 "Couldn't find package:" + packageName + " information"); 11887 return; 11888 } 11889 } 11890 11891 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11892 res.removedInfo.removedPackage = packageName; 11893 // Remove existing system package 11894 removePackageLI(oldPkgSetting, true); 11895 // writer 11896 synchronized (mPackages) { 11897 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11898 if (!disabledSystem && deletedPackage != null) { 11899 // We didn't need to disable the .apk as a current system package, 11900 // which means we are replacing another update that is already 11901 // installed. We need to make sure to delete the older one's .apk. 11902 res.removedInfo.args = createInstallArgsForExisting(0, 11903 deletedPackage.applicationInfo.getCodePath(), 11904 deletedPackage.applicationInfo.getResourcePath(), 11905 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11906 } else { 11907 res.removedInfo.args = null; 11908 } 11909 } 11910 11911 // Successfully disabled the old package. Now proceed with re-installation 11912 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11913 11914 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11915 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11916 11917 PackageParser.Package newPackage = null; 11918 try { 11919 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11920 if (newPackage.mExtras != null) { 11921 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11922 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11923 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11924 11925 // is the update attempting to change shared user? that isn't going to work... 11926 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11927 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11928 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11929 + " to " + newPkgSetting.sharedUser); 11930 updatedSettings = true; 11931 } 11932 } 11933 11934 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11935 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11936 perUserInstalled, res, user); 11937 updatedSettings = true; 11938 } 11939 11940 } catch (PackageManagerException e) { 11941 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11942 } 11943 11944 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11945 // Re installation failed. Restore old information 11946 // Remove new pkg information 11947 if (newPackage != null) { 11948 removeInstalledPackageLI(newPackage, true); 11949 } 11950 // Add back the old system package 11951 try { 11952 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11953 } catch (PackageManagerException e) { 11954 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11955 } 11956 // Restore the old system information in Settings 11957 synchronized (mPackages) { 11958 if (disabledSystem) { 11959 mSettings.enableSystemPackageLPw(packageName); 11960 } 11961 if (updatedSettings) { 11962 mSettings.setInstallerPackageName(packageName, 11963 oldPkgSetting.installerPackageName); 11964 } 11965 mSettings.writeLPr(); 11966 } 11967 } 11968 } 11969 11970 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11971 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11972 UserHandle user) { 11973 String pkgName = newPackage.packageName; 11974 synchronized (mPackages) { 11975 //write settings. the installStatus will be incomplete at this stage. 11976 //note that the new package setting would have already been 11977 //added to mPackages. It hasn't been persisted yet. 11978 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11979 mSettings.writeLPr(); 11980 } 11981 11982 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11983 11984 synchronized (mPackages) { 11985 updatePermissionsLPw(newPackage.packageName, newPackage, 11986 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11987 ? UPDATE_PERMISSIONS_ALL : 0)); 11988 // For system-bundled packages, we assume that installing an upgraded version 11989 // of the package implies that the user actually wants to run that new code, 11990 // so we enable the package. 11991 PackageSetting ps = mSettings.mPackages.get(pkgName); 11992 if (ps != null) { 11993 if (isSystemApp(newPackage)) { 11994 // NB: implicit assumption that system package upgrades apply to all users 11995 if (DEBUG_INSTALL) { 11996 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11997 } 11998 if (res.origUsers != null) { 11999 for (int userHandle : res.origUsers) { 12000 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12001 userHandle, installerPackageName); 12002 } 12003 } 12004 // Also convey the prior install/uninstall state 12005 if (allUsers != null && perUserInstalled != null) { 12006 for (int i = 0; i < allUsers.length; i++) { 12007 if (DEBUG_INSTALL) { 12008 Slog.d(TAG, " user " + allUsers[i] 12009 + " => " + perUserInstalled[i]); 12010 } 12011 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12012 } 12013 // these install state changes will be persisted in the 12014 // upcoming call to mSettings.writeLPr(). 12015 } 12016 } 12017 // It's implied that when a user requests installation, they want the app to be 12018 // installed and enabled. 12019 int userId = user.getIdentifier(); 12020 if (userId != UserHandle.USER_ALL) { 12021 ps.setInstalled(true, userId); 12022 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12023 } 12024 } 12025 res.name = pkgName; 12026 res.uid = newPackage.applicationInfo.uid; 12027 res.pkg = newPackage; 12028 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12029 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12030 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12031 //to update install status 12032 mSettings.writeLPr(); 12033 } 12034 } 12035 12036 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12037 final int installFlags = args.installFlags; 12038 final String installerPackageName = args.installerPackageName; 12039 final String volumeUuid = args.volumeUuid; 12040 final File tmpPackageFile = new File(args.getCodePath()); 12041 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12042 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12043 || (args.volumeUuid != null)); 12044 boolean replace = false; 12045 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12046 if (args.move != null) { 12047 // moving a complete application; perfom an initial scan on the new install location 12048 scanFlags |= SCAN_INITIAL; 12049 } 12050 // Result object to be returned 12051 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12052 12053 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12054 // Retrieve PackageSettings and parse package 12055 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12056 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12057 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12058 PackageParser pp = new PackageParser(); 12059 pp.setSeparateProcesses(mSeparateProcesses); 12060 pp.setDisplayMetrics(mMetrics); 12061 12062 final PackageParser.Package pkg; 12063 try { 12064 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12065 } catch (PackageParserException e) { 12066 res.setError("Failed parse during installPackageLI", e); 12067 return; 12068 } 12069 12070 // Mark that we have an install time CPU ABI override. 12071 pkg.cpuAbiOverride = args.abiOverride; 12072 12073 String pkgName = res.name = pkg.packageName; 12074 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12075 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12076 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12077 return; 12078 } 12079 } 12080 12081 try { 12082 pp.collectCertificates(pkg, parseFlags); 12083 pp.collectManifestDigest(pkg); 12084 } catch (PackageParserException e) { 12085 res.setError("Failed collect during installPackageLI", e); 12086 return; 12087 } 12088 12089 /* If the installer passed in a manifest digest, compare it now. */ 12090 if (args.manifestDigest != null) { 12091 if (DEBUG_INSTALL) { 12092 final String parsedManifest = pkg.manifestDigest == null ? "null" 12093 : pkg.manifestDigest.toString(); 12094 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12095 + parsedManifest); 12096 } 12097 12098 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12099 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12100 return; 12101 } 12102 } else if (DEBUG_INSTALL) { 12103 final String parsedManifest = pkg.manifestDigest == null 12104 ? "null" : pkg.manifestDigest.toString(); 12105 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12106 } 12107 12108 // Get rid of all references to package scan path via parser. 12109 pp = null; 12110 String oldCodePath = null; 12111 boolean systemApp = false; 12112 synchronized (mPackages) { 12113 // Check if installing already existing package 12114 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12115 String oldName = mSettings.mRenamedPackages.get(pkgName); 12116 if (pkg.mOriginalPackages != null 12117 && pkg.mOriginalPackages.contains(oldName) 12118 && mPackages.containsKey(oldName)) { 12119 // This package is derived from an original package, 12120 // and this device has been updating from that original 12121 // name. We must continue using the original name, so 12122 // rename the new package here. 12123 pkg.setPackageName(oldName); 12124 pkgName = pkg.packageName; 12125 replace = true; 12126 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12127 + oldName + " pkgName=" + pkgName); 12128 } else if (mPackages.containsKey(pkgName)) { 12129 // This package, under its official name, already exists 12130 // on the device; we should replace it. 12131 replace = true; 12132 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12133 } 12134 12135 // Prevent apps opting out from runtime permissions 12136 if (replace) { 12137 PackageParser.Package oldPackage = mPackages.get(pkgName); 12138 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12139 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12140 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12141 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12142 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12143 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12144 + " doesn't support runtime permissions but the old" 12145 + " target SDK " + oldTargetSdk + " does."); 12146 return; 12147 } 12148 } 12149 } 12150 12151 PackageSetting ps = mSettings.mPackages.get(pkgName); 12152 if (ps != null) { 12153 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12154 12155 // Quick sanity check that we're signed correctly if updating; 12156 // we'll check this again later when scanning, but we want to 12157 // bail early here before tripping over redefined permissions. 12158 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12159 if (!checkUpgradeKeySetLP(ps, pkg)) { 12160 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12161 + pkg.packageName + " upgrade keys do not match the " 12162 + "previously installed version"); 12163 return; 12164 } 12165 } else { 12166 try { 12167 verifySignaturesLP(ps, pkg); 12168 } catch (PackageManagerException e) { 12169 res.setError(e.error, e.getMessage()); 12170 return; 12171 } 12172 } 12173 12174 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12175 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12176 systemApp = (ps.pkg.applicationInfo.flags & 12177 ApplicationInfo.FLAG_SYSTEM) != 0; 12178 } 12179 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12180 } 12181 12182 // Check whether the newly-scanned package wants to define an already-defined perm 12183 int N = pkg.permissions.size(); 12184 for (int i = N-1; i >= 0; i--) { 12185 PackageParser.Permission perm = pkg.permissions.get(i); 12186 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12187 if (bp != null) { 12188 // If the defining package is signed with our cert, it's okay. This 12189 // also includes the "updating the same package" case, of course. 12190 // "updating same package" could also involve key-rotation. 12191 final boolean sigsOk; 12192 if (bp.sourcePackage.equals(pkg.packageName) 12193 && (bp.packageSetting instanceof PackageSetting) 12194 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12195 scanFlags))) { 12196 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12197 } else { 12198 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12199 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12200 } 12201 if (!sigsOk) { 12202 // If the owning package is the system itself, we log but allow 12203 // install to proceed; we fail the install on all other permission 12204 // redefinitions. 12205 if (!bp.sourcePackage.equals("android")) { 12206 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12207 + pkg.packageName + " attempting to redeclare permission " 12208 + perm.info.name + " already owned by " + bp.sourcePackage); 12209 res.origPermission = perm.info.name; 12210 res.origPackage = bp.sourcePackage; 12211 return; 12212 } else { 12213 Slog.w(TAG, "Package " + pkg.packageName 12214 + " attempting to redeclare system permission " 12215 + perm.info.name + "; ignoring new declaration"); 12216 pkg.permissions.remove(i); 12217 } 12218 } 12219 } 12220 } 12221 12222 } 12223 12224 if (systemApp && onExternal) { 12225 // Disable updates to system apps on sdcard 12226 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12227 "Cannot install updates to system apps on sdcard"); 12228 return; 12229 } 12230 12231 if (args.move != null) { 12232 // We did an in-place move, so dex is ready to roll 12233 scanFlags |= SCAN_NO_DEX; 12234 scanFlags |= SCAN_MOVE; 12235 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12236 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12237 scanFlags |= SCAN_NO_DEX; 12238 12239 try { 12240 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12241 true /* extract libs */); 12242 } catch (PackageManagerException pme) { 12243 Slog.e(TAG, "Error deriving application ABI", pme); 12244 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12245 return; 12246 } 12247 12248 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12249 int result = mPackageDexOptimizer 12250 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12251 false /* defer */, false /* inclDependencies */); 12252 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12253 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12254 return; 12255 } 12256 } 12257 12258 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12259 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12260 return; 12261 } 12262 12263 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12264 12265 if (replace) { 12266 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12267 installerPackageName, volumeUuid, res); 12268 } else { 12269 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12270 args.user, installerPackageName, volumeUuid, res); 12271 } 12272 synchronized (mPackages) { 12273 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12274 if (ps != null) { 12275 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12276 } 12277 } 12278 } 12279 12280 private void startIntentFilterVerifications(int userId, boolean replacing, 12281 PackageParser.Package pkg) { 12282 if (mIntentFilterVerifierComponent == null) { 12283 Slog.w(TAG, "No IntentFilter verification will not be done as " 12284 + "there is no IntentFilterVerifier available!"); 12285 return; 12286 } 12287 12288 final int verifierUid = getPackageUid( 12289 mIntentFilterVerifierComponent.getPackageName(), 12290 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12291 12292 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12293 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12294 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12295 mHandler.sendMessage(msg); 12296 } 12297 12298 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12299 PackageParser.Package pkg) { 12300 int size = pkg.activities.size(); 12301 if (size == 0) { 12302 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12303 "No activity, so no need to verify any IntentFilter!"); 12304 return; 12305 } 12306 12307 final boolean hasDomainURLs = hasDomainURLs(pkg); 12308 if (!hasDomainURLs) { 12309 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12310 "No domain URLs, so no need to verify any IntentFilter!"); 12311 return; 12312 } 12313 12314 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12315 + " if any IntentFilter from the " + size 12316 + " Activities needs verification ..."); 12317 12318 int count = 0; 12319 final String packageName = pkg.packageName; 12320 12321 synchronized (mPackages) { 12322 // If this is a new install and we see that we've already run verification for this 12323 // package, we have nothing to do: it means the state was restored from backup. 12324 if (!replacing) { 12325 IntentFilterVerificationInfo ivi = 12326 mSettings.getIntentFilterVerificationLPr(packageName); 12327 if (ivi != null) { 12328 if (DEBUG_DOMAIN_VERIFICATION) { 12329 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12330 + ivi.getStatusString()); 12331 } 12332 return; 12333 } 12334 } 12335 12336 // If any filters need to be verified, then all need to be. 12337 boolean needToVerify = false; 12338 for (PackageParser.Activity a : pkg.activities) { 12339 for (ActivityIntentInfo filter : a.intents) { 12340 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12341 if (DEBUG_DOMAIN_VERIFICATION) { 12342 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12343 } 12344 needToVerify = true; 12345 break; 12346 } 12347 } 12348 } 12349 12350 if (needToVerify) { 12351 final int verificationId = mIntentFilterVerificationToken++; 12352 for (PackageParser.Activity a : pkg.activities) { 12353 for (ActivityIntentInfo filter : a.intents) { 12354 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12355 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12356 "Verification needed for IntentFilter:" + filter.toString()); 12357 mIntentFilterVerifier.addOneIntentFilterVerification( 12358 verifierUid, userId, verificationId, filter, packageName); 12359 count++; 12360 } 12361 } 12362 } 12363 } 12364 } 12365 12366 if (count > 0) { 12367 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12368 + " IntentFilter verification" + (count > 1 ? "s" : "") 12369 + " for userId:" + userId); 12370 mIntentFilterVerifier.startVerifications(userId); 12371 } else { 12372 if (DEBUG_DOMAIN_VERIFICATION) { 12373 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12374 } 12375 } 12376 } 12377 12378 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12379 final ComponentName cn = filter.activity.getComponentName(); 12380 final String packageName = cn.getPackageName(); 12381 12382 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12383 packageName); 12384 if (ivi == null) { 12385 return true; 12386 } 12387 int status = ivi.getStatus(); 12388 switch (status) { 12389 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12390 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12391 return true; 12392 12393 default: 12394 // Nothing to do 12395 return false; 12396 } 12397 } 12398 12399 private static boolean isMultiArch(PackageSetting ps) { 12400 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12401 } 12402 12403 private static boolean isMultiArch(ApplicationInfo info) { 12404 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12405 } 12406 12407 private static boolean isExternal(PackageParser.Package pkg) { 12408 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12409 } 12410 12411 private static boolean isExternal(PackageSetting ps) { 12412 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12413 } 12414 12415 private static boolean isExternal(ApplicationInfo info) { 12416 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12417 } 12418 12419 private static boolean isSystemApp(PackageParser.Package pkg) { 12420 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12421 } 12422 12423 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12424 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12425 } 12426 12427 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12428 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12429 } 12430 12431 private static boolean isSystemApp(PackageSetting ps) { 12432 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12433 } 12434 12435 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12436 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12437 } 12438 12439 private int packageFlagsToInstallFlags(PackageSetting ps) { 12440 int installFlags = 0; 12441 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12442 // This existing package was an external ASEC install when we have 12443 // the external flag without a UUID 12444 installFlags |= PackageManager.INSTALL_EXTERNAL; 12445 } 12446 if (ps.isForwardLocked()) { 12447 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12448 } 12449 return installFlags; 12450 } 12451 12452 private void deleteTempPackageFiles() { 12453 final FilenameFilter filter = new FilenameFilter() { 12454 public boolean accept(File dir, String name) { 12455 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12456 } 12457 }; 12458 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12459 file.delete(); 12460 } 12461 } 12462 12463 @Override 12464 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12465 int flags) { 12466 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12467 flags); 12468 } 12469 12470 @Override 12471 public void deletePackage(final String packageName, 12472 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12473 mContext.enforceCallingOrSelfPermission( 12474 android.Manifest.permission.DELETE_PACKAGES, null); 12475 Preconditions.checkNotNull(packageName); 12476 Preconditions.checkNotNull(observer); 12477 final int uid = Binder.getCallingUid(); 12478 if (UserHandle.getUserId(uid) != userId) { 12479 mContext.enforceCallingPermission( 12480 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12481 "deletePackage for user " + userId); 12482 } 12483 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12484 try { 12485 observer.onPackageDeleted(packageName, 12486 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12487 } catch (RemoteException re) { 12488 } 12489 return; 12490 } 12491 12492 boolean uninstallBlocked = false; 12493 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12494 int[] users = sUserManager.getUserIds(); 12495 for (int i = 0; i < users.length; ++i) { 12496 if (getBlockUninstallForUser(packageName, users[i])) { 12497 uninstallBlocked = true; 12498 break; 12499 } 12500 } 12501 } else { 12502 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12503 } 12504 if (uninstallBlocked) { 12505 try { 12506 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12507 null); 12508 } catch (RemoteException re) { 12509 } 12510 return; 12511 } 12512 12513 if (DEBUG_REMOVE) { 12514 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12515 } 12516 // Queue up an async operation since the package deletion may take a little while. 12517 mHandler.post(new Runnable() { 12518 public void run() { 12519 mHandler.removeCallbacks(this); 12520 final int returnCode = deletePackageX(packageName, userId, flags); 12521 if (observer != null) { 12522 try { 12523 observer.onPackageDeleted(packageName, returnCode, null); 12524 } catch (RemoteException e) { 12525 Log.i(TAG, "Observer no longer exists."); 12526 } //end catch 12527 } //end if 12528 } //end run 12529 }); 12530 } 12531 12532 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12533 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12534 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12535 try { 12536 if (dpm != null) { 12537 if (dpm.isDeviceOwner(packageName)) { 12538 return true; 12539 } 12540 int[] users; 12541 if (userId == UserHandle.USER_ALL) { 12542 users = sUserManager.getUserIds(); 12543 } else { 12544 users = new int[]{userId}; 12545 } 12546 for (int i = 0; i < users.length; ++i) { 12547 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12548 return true; 12549 } 12550 } 12551 } 12552 } catch (RemoteException e) { 12553 } 12554 return false; 12555 } 12556 12557 /** 12558 * This method is an internal method that could be get invoked either 12559 * to delete an installed package or to clean up a failed installation. 12560 * After deleting an installed package, a broadcast is sent to notify any 12561 * listeners that the package has been installed. For cleaning up a failed 12562 * installation, the broadcast is not necessary since the package's 12563 * installation wouldn't have sent the initial broadcast either 12564 * The key steps in deleting a package are 12565 * deleting the package information in internal structures like mPackages, 12566 * deleting the packages base directories through installd 12567 * updating mSettings to reflect current status 12568 * persisting settings for later use 12569 * sending a broadcast if necessary 12570 */ 12571 private int deletePackageX(String packageName, int userId, int flags) { 12572 final PackageRemovedInfo info = new PackageRemovedInfo(); 12573 final boolean res; 12574 12575 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12576 ? UserHandle.ALL : new UserHandle(userId); 12577 12578 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12579 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12580 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12581 } 12582 12583 boolean removedForAllUsers = false; 12584 boolean systemUpdate = false; 12585 12586 // for the uninstall-updates case and restricted profiles, remember the per- 12587 // userhandle installed state 12588 int[] allUsers; 12589 boolean[] perUserInstalled; 12590 synchronized (mPackages) { 12591 PackageSetting ps = mSettings.mPackages.get(packageName); 12592 allUsers = sUserManager.getUserIds(); 12593 perUserInstalled = new boolean[allUsers.length]; 12594 for (int i = 0; i < allUsers.length; i++) { 12595 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12596 } 12597 } 12598 12599 synchronized (mInstallLock) { 12600 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12601 res = deletePackageLI(packageName, removeForUser, 12602 true, allUsers, perUserInstalled, 12603 flags | REMOVE_CHATTY, info, true); 12604 systemUpdate = info.isRemovedPackageSystemUpdate; 12605 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12606 removedForAllUsers = true; 12607 } 12608 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12609 + " removedForAllUsers=" + removedForAllUsers); 12610 } 12611 12612 if (res) { 12613 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12614 12615 // If the removed package was a system update, the old system package 12616 // was re-enabled; we need to broadcast this information 12617 if (systemUpdate) { 12618 Bundle extras = new Bundle(1); 12619 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12620 ? info.removedAppId : info.uid); 12621 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12622 12623 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12624 extras, null, null, null); 12625 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12626 extras, null, null, null); 12627 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12628 null, packageName, null, null); 12629 } 12630 } 12631 // Force a gc here. 12632 Runtime.getRuntime().gc(); 12633 // Delete the resources here after sending the broadcast to let 12634 // other processes clean up before deleting resources. 12635 if (info.args != null) { 12636 synchronized (mInstallLock) { 12637 info.args.doPostDeleteLI(true); 12638 } 12639 } 12640 12641 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12642 } 12643 12644 class PackageRemovedInfo { 12645 String removedPackage; 12646 int uid = -1; 12647 int removedAppId = -1; 12648 int[] removedUsers = null; 12649 boolean isRemovedPackageSystemUpdate = false; 12650 // Clean up resources deleted packages. 12651 InstallArgs args = null; 12652 12653 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12654 Bundle extras = new Bundle(1); 12655 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12656 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12657 if (replacing) { 12658 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12659 } 12660 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12661 if (removedPackage != null) { 12662 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12663 extras, null, null, removedUsers); 12664 if (fullRemove && !replacing) { 12665 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12666 extras, null, null, removedUsers); 12667 } 12668 } 12669 if (removedAppId >= 0) { 12670 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12671 removedUsers); 12672 } 12673 } 12674 } 12675 12676 /* 12677 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12678 * flag is not set, the data directory is removed as well. 12679 * make sure this flag is set for partially installed apps. If not its meaningless to 12680 * delete a partially installed application. 12681 */ 12682 private void removePackageDataLI(PackageSetting ps, 12683 int[] allUserHandles, boolean[] perUserInstalled, 12684 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12685 String packageName = ps.name; 12686 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12687 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12688 // Retrieve object to delete permissions for shared user later on 12689 final PackageSetting deletedPs; 12690 // reader 12691 synchronized (mPackages) { 12692 deletedPs = mSettings.mPackages.get(packageName); 12693 if (outInfo != null) { 12694 outInfo.removedPackage = packageName; 12695 outInfo.removedUsers = deletedPs != null 12696 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12697 : null; 12698 } 12699 } 12700 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12701 removeDataDirsLI(ps.volumeUuid, packageName); 12702 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12703 } 12704 // writer 12705 synchronized (mPackages) { 12706 if (deletedPs != null) { 12707 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12708 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12709 clearDefaultBrowserIfNeeded(packageName); 12710 if (outInfo != null) { 12711 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12712 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12713 } 12714 updatePermissionsLPw(deletedPs.name, null, 0); 12715 if (deletedPs.sharedUser != null) { 12716 // Remove permissions associated with package. Since runtime 12717 // permissions are per user we have to kill the removed package 12718 // or packages running under the shared user of the removed 12719 // package if revoking the permissions requested only by the removed 12720 // package is successful and this causes a change in gids. 12721 for (int userId : UserManagerService.getInstance().getUserIds()) { 12722 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12723 userId); 12724 if (userIdToKill == UserHandle.USER_ALL 12725 || userIdToKill >= UserHandle.USER_OWNER) { 12726 // If gids changed for this user, kill all affected packages. 12727 mHandler.post(new Runnable() { 12728 @Override 12729 public void run() { 12730 // This has to happen with no lock held. 12731 killSettingPackagesForUser(deletedPs, userIdToKill, 12732 KILL_APP_REASON_GIDS_CHANGED); 12733 } 12734 }); 12735 break; 12736 } 12737 } 12738 } 12739 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12740 } 12741 // make sure to preserve per-user disabled state if this removal was just 12742 // a downgrade of a system app to the factory package 12743 if (allUserHandles != null && perUserInstalled != null) { 12744 if (DEBUG_REMOVE) { 12745 Slog.d(TAG, "Propagating install state across downgrade"); 12746 } 12747 for (int i = 0; i < allUserHandles.length; i++) { 12748 if (DEBUG_REMOVE) { 12749 Slog.d(TAG, " user " + allUserHandles[i] 12750 + " => " + perUserInstalled[i]); 12751 } 12752 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12753 } 12754 } 12755 } 12756 // can downgrade to reader 12757 if (writeSettings) { 12758 // Save settings now 12759 mSettings.writeLPr(); 12760 } 12761 } 12762 if (outInfo != null) { 12763 // A user ID was deleted here. Go through all users and remove it 12764 // from KeyStore. 12765 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12766 } 12767 } 12768 12769 static boolean locationIsPrivileged(File path) { 12770 try { 12771 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12772 .getCanonicalPath(); 12773 return path.getCanonicalPath().startsWith(privilegedAppDir); 12774 } catch (IOException e) { 12775 Slog.e(TAG, "Unable to access code path " + path); 12776 } 12777 return false; 12778 } 12779 12780 /* 12781 * Tries to delete system package. 12782 */ 12783 private boolean deleteSystemPackageLI(PackageSetting newPs, 12784 int[] allUserHandles, boolean[] perUserInstalled, 12785 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12786 final boolean applyUserRestrictions 12787 = (allUserHandles != null) && (perUserInstalled != null); 12788 PackageSetting disabledPs = null; 12789 // Confirm if the system package has been updated 12790 // An updated system app can be deleted. This will also have to restore 12791 // the system pkg from system partition 12792 // reader 12793 synchronized (mPackages) { 12794 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12795 } 12796 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12797 + " disabledPs=" + disabledPs); 12798 if (disabledPs == null) { 12799 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12800 return false; 12801 } else if (DEBUG_REMOVE) { 12802 Slog.d(TAG, "Deleting system pkg from data partition"); 12803 } 12804 if (DEBUG_REMOVE) { 12805 if (applyUserRestrictions) { 12806 Slog.d(TAG, "Remembering install states:"); 12807 for (int i = 0; i < allUserHandles.length; i++) { 12808 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12809 } 12810 } 12811 } 12812 // Delete the updated package 12813 outInfo.isRemovedPackageSystemUpdate = true; 12814 if (disabledPs.versionCode < newPs.versionCode) { 12815 // Delete data for downgrades 12816 flags &= ~PackageManager.DELETE_KEEP_DATA; 12817 } else { 12818 // Preserve data by setting flag 12819 flags |= PackageManager.DELETE_KEEP_DATA; 12820 } 12821 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12822 allUserHandles, perUserInstalled, outInfo, writeSettings); 12823 if (!ret) { 12824 return false; 12825 } 12826 // writer 12827 synchronized (mPackages) { 12828 // Reinstate the old system package 12829 mSettings.enableSystemPackageLPw(newPs.name); 12830 // Remove any native libraries from the upgraded package. 12831 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12832 } 12833 // Install the system package 12834 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12835 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12836 if (locationIsPrivileged(disabledPs.codePath)) { 12837 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12838 } 12839 12840 final PackageParser.Package newPkg; 12841 try { 12842 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12843 } catch (PackageManagerException e) { 12844 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12845 return false; 12846 } 12847 12848 // writer 12849 synchronized (mPackages) { 12850 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12851 12852 // Propagate the permissions state as we do want to drop on the floor 12853 // runtime permissions. The update permissions method below will take 12854 // care of removing obsolete permissions and grant install permissions. 12855 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12856 updatePermissionsLPw(newPkg.packageName, newPkg, 12857 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12858 12859 if (applyUserRestrictions) { 12860 if (DEBUG_REMOVE) { 12861 Slog.d(TAG, "Propagating install state across reinstall"); 12862 } 12863 for (int i = 0; i < allUserHandles.length; i++) { 12864 if (DEBUG_REMOVE) { 12865 Slog.d(TAG, " user " + allUserHandles[i] 12866 + " => " + perUserInstalled[i]); 12867 } 12868 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12869 } 12870 // Regardless of writeSettings we need to ensure that this restriction 12871 // state propagation is persisted 12872 mSettings.writeAllUsersPackageRestrictionsLPr(); 12873 } 12874 // can downgrade to reader here 12875 if (writeSettings) { 12876 mSettings.writeLPr(); 12877 } 12878 } 12879 return true; 12880 } 12881 12882 private boolean deleteInstalledPackageLI(PackageSetting ps, 12883 boolean deleteCodeAndResources, int flags, 12884 int[] allUserHandles, boolean[] perUserInstalled, 12885 PackageRemovedInfo outInfo, boolean writeSettings) { 12886 if (outInfo != null) { 12887 outInfo.uid = ps.appId; 12888 } 12889 12890 // Delete package data from internal structures and also remove data if flag is set 12891 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12892 12893 // Delete application code and resources 12894 if (deleteCodeAndResources && (outInfo != null)) { 12895 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12896 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12897 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12898 } 12899 return true; 12900 } 12901 12902 @Override 12903 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12904 int userId) { 12905 mContext.enforceCallingOrSelfPermission( 12906 android.Manifest.permission.DELETE_PACKAGES, null); 12907 synchronized (mPackages) { 12908 PackageSetting ps = mSettings.mPackages.get(packageName); 12909 if (ps == null) { 12910 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12911 return false; 12912 } 12913 if (!ps.getInstalled(userId)) { 12914 // Can't block uninstall for an app that is not installed or enabled. 12915 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12916 return false; 12917 } 12918 ps.setBlockUninstall(blockUninstall, userId); 12919 mSettings.writePackageRestrictionsLPr(userId); 12920 } 12921 return true; 12922 } 12923 12924 @Override 12925 public boolean getBlockUninstallForUser(String packageName, int userId) { 12926 synchronized (mPackages) { 12927 PackageSetting ps = mSettings.mPackages.get(packageName); 12928 if (ps == null) { 12929 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12930 return false; 12931 } 12932 return ps.getBlockUninstall(userId); 12933 } 12934 } 12935 12936 /* 12937 * This method handles package deletion in general 12938 */ 12939 private boolean deletePackageLI(String packageName, UserHandle user, 12940 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12941 int flags, PackageRemovedInfo outInfo, 12942 boolean writeSettings) { 12943 if (packageName == null) { 12944 Slog.w(TAG, "Attempt to delete null packageName."); 12945 return false; 12946 } 12947 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12948 PackageSetting ps; 12949 boolean dataOnly = false; 12950 int removeUser = -1; 12951 int appId = -1; 12952 synchronized (mPackages) { 12953 ps = mSettings.mPackages.get(packageName); 12954 if (ps == null) { 12955 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12956 return false; 12957 } 12958 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12959 && user.getIdentifier() != UserHandle.USER_ALL) { 12960 // The caller is asking that the package only be deleted for a single 12961 // user. To do this, we just mark its uninstalled state and delete 12962 // its data. If this is a system app, we only allow this to happen if 12963 // they have set the special DELETE_SYSTEM_APP which requests different 12964 // semantics than normal for uninstalling system apps. 12965 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12966 ps.setUserState(user.getIdentifier(), 12967 COMPONENT_ENABLED_STATE_DEFAULT, 12968 false, //installed 12969 true, //stopped 12970 true, //notLaunched 12971 false, //hidden 12972 null, null, null, 12973 false, // blockUninstall 12974 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED, 0); 12975 if (!isSystemApp(ps)) { 12976 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12977 // Other user still have this package installed, so all 12978 // we need to do is clear this user's data and save that 12979 // it is uninstalled. 12980 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12981 removeUser = user.getIdentifier(); 12982 appId = ps.appId; 12983 scheduleWritePackageRestrictionsLocked(removeUser); 12984 } else { 12985 // We need to set it back to 'installed' so the uninstall 12986 // broadcasts will be sent correctly. 12987 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12988 ps.setInstalled(true, user.getIdentifier()); 12989 } 12990 } else { 12991 // This is a system app, so we assume that the 12992 // other users still have this package installed, so all 12993 // we need to do is clear this user's data and save that 12994 // it is uninstalled. 12995 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12996 removeUser = user.getIdentifier(); 12997 appId = ps.appId; 12998 scheduleWritePackageRestrictionsLocked(removeUser); 12999 } 13000 } 13001 } 13002 13003 if (removeUser >= 0) { 13004 // From above, we determined that we are deleting this only 13005 // for a single user. Continue the work here. 13006 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13007 if (outInfo != null) { 13008 outInfo.removedPackage = packageName; 13009 outInfo.removedAppId = appId; 13010 outInfo.removedUsers = new int[] {removeUser}; 13011 } 13012 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13013 removeKeystoreDataIfNeeded(removeUser, appId); 13014 schedulePackageCleaning(packageName, removeUser, false); 13015 synchronized (mPackages) { 13016 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13017 scheduleWritePackageRestrictionsLocked(removeUser); 13018 } 13019 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 13020 } 13021 return true; 13022 } 13023 13024 if (dataOnly) { 13025 // Delete application data first 13026 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13027 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13028 return true; 13029 } 13030 13031 boolean ret = false; 13032 if (isSystemApp(ps)) { 13033 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 13034 // When an updated system application is deleted we delete the existing resources as well and 13035 // fall back to existing code in system partition 13036 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13037 flags, outInfo, writeSettings); 13038 } else { 13039 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 13040 // Kill application pre-emptively especially for apps on sd. 13041 killApplication(packageName, ps.appId, "uninstall pkg"); 13042 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13043 allUserHandles, perUserInstalled, 13044 outInfo, writeSettings); 13045 } 13046 13047 return ret; 13048 } 13049 13050 private final class ClearStorageConnection implements ServiceConnection { 13051 IMediaContainerService mContainerService; 13052 13053 @Override 13054 public void onServiceConnected(ComponentName name, IBinder service) { 13055 synchronized (this) { 13056 mContainerService = IMediaContainerService.Stub.asInterface(service); 13057 notifyAll(); 13058 } 13059 } 13060 13061 @Override 13062 public void onServiceDisconnected(ComponentName name) { 13063 } 13064 } 13065 13066 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13067 final boolean mounted; 13068 if (Environment.isExternalStorageEmulated()) { 13069 mounted = true; 13070 } else { 13071 final String status = Environment.getExternalStorageState(); 13072 13073 mounted = status.equals(Environment.MEDIA_MOUNTED) 13074 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13075 } 13076 13077 if (!mounted) { 13078 return; 13079 } 13080 13081 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13082 int[] users; 13083 if (userId == UserHandle.USER_ALL) { 13084 users = sUserManager.getUserIds(); 13085 } else { 13086 users = new int[] { userId }; 13087 } 13088 final ClearStorageConnection conn = new ClearStorageConnection(); 13089 if (mContext.bindServiceAsUser( 13090 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13091 try { 13092 for (int curUser : users) { 13093 long timeout = SystemClock.uptimeMillis() + 5000; 13094 synchronized (conn) { 13095 long now = SystemClock.uptimeMillis(); 13096 while (conn.mContainerService == null && now < timeout) { 13097 try { 13098 conn.wait(timeout - now); 13099 } catch (InterruptedException e) { 13100 } 13101 } 13102 } 13103 if (conn.mContainerService == null) { 13104 return; 13105 } 13106 13107 final UserEnvironment userEnv = new UserEnvironment(curUser); 13108 clearDirectory(conn.mContainerService, 13109 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13110 if (allData) { 13111 clearDirectory(conn.mContainerService, 13112 userEnv.buildExternalStorageAppDataDirs(packageName)); 13113 clearDirectory(conn.mContainerService, 13114 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13115 } 13116 } 13117 } finally { 13118 mContext.unbindService(conn); 13119 } 13120 } 13121 } 13122 13123 @Override 13124 public void clearApplicationUserData(final String packageName, 13125 final IPackageDataObserver observer, final int userId) { 13126 mContext.enforceCallingOrSelfPermission( 13127 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13128 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13129 // Queue up an async operation since the package deletion may take a little while. 13130 mHandler.post(new Runnable() { 13131 public void run() { 13132 mHandler.removeCallbacks(this); 13133 final boolean succeeded; 13134 synchronized (mInstallLock) { 13135 succeeded = clearApplicationUserDataLI(packageName, userId); 13136 } 13137 clearExternalStorageDataSync(packageName, userId, true); 13138 if (succeeded) { 13139 // invoke DeviceStorageMonitor's update method to clear any notifications 13140 DeviceStorageMonitorInternal 13141 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13142 if (dsm != null) { 13143 dsm.checkMemory(); 13144 } 13145 } 13146 if(observer != null) { 13147 try { 13148 observer.onRemoveCompleted(packageName, succeeded); 13149 } catch (RemoteException e) { 13150 Log.i(TAG, "Observer no longer exists."); 13151 } 13152 } //end if observer 13153 } //end run 13154 }); 13155 } 13156 13157 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13158 if (packageName == null) { 13159 Slog.w(TAG, "Attempt to delete null packageName."); 13160 return false; 13161 } 13162 13163 // Try finding details about the requested package 13164 PackageParser.Package pkg; 13165 synchronized (mPackages) { 13166 pkg = mPackages.get(packageName); 13167 if (pkg == null) { 13168 final PackageSetting ps = mSettings.mPackages.get(packageName); 13169 if (ps != null) { 13170 pkg = ps.pkg; 13171 } 13172 } 13173 13174 if (pkg == null) { 13175 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13176 return false; 13177 } 13178 13179 PackageSetting ps = (PackageSetting) pkg.mExtras; 13180 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13181 } 13182 13183 // Always delete data directories for package, even if we found no other 13184 // record of app. This helps users recover from UID mismatches without 13185 // resorting to a full data wipe. 13186 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13187 if (retCode < 0) { 13188 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13189 return false; 13190 } 13191 13192 final int appId = pkg.applicationInfo.uid; 13193 removeKeystoreDataIfNeeded(userId, appId); 13194 13195 // Create a native library symlink only if we have native libraries 13196 // and if the native libraries are 32 bit libraries. We do not provide 13197 // this symlink for 64 bit libraries. 13198 if (pkg.applicationInfo.primaryCpuAbi != null && 13199 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13200 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13201 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13202 nativeLibPath, userId) < 0) { 13203 Slog.w(TAG, "Failed linking native library dir"); 13204 return false; 13205 } 13206 } 13207 13208 return true; 13209 } 13210 13211 /** 13212 * Reverts user permission state changes (permissions and flags). 13213 * 13214 * @param ps The package for which to reset. 13215 * @param userId The device user for which to do a reset. 13216 */ 13217 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13218 final PackageSetting ps, final int userId) { 13219 if (ps.pkg == null) { 13220 return; 13221 } 13222 13223 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13224 | FLAG_PERMISSION_USER_FIXED 13225 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13226 13227 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13228 | FLAG_PERMISSION_POLICY_FIXED; 13229 13230 boolean writeInstallPermissions = false; 13231 boolean writeRuntimePermissions = false; 13232 13233 final int permissionCount = ps.pkg.requestedPermissions.size(); 13234 for (int i = 0; i < permissionCount; i++) { 13235 String permission = ps.pkg.requestedPermissions.get(i); 13236 13237 BasePermission bp = mSettings.mPermissions.get(permission); 13238 if (bp == null) { 13239 continue; 13240 } 13241 13242 // If shared user we just reset the state to which only this app contributed. 13243 if (ps.sharedUser != null) { 13244 boolean used = false; 13245 final int packageCount = ps.sharedUser.packages.size(); 13246 for (int j = 0; j < packageCount; j++) { 13247 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13248 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13249 && pkg.pkg.requestedPermissions.contains(permission)) { 13250 used = true; 13251 break; 13252 } 13253 } 13254 if (used) { 13255 continue; 13256 } 13257 } 13258 13259 PermissionsState permissionsState = ps.getPermissionsState(); 13260 13261 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13262 13263 // Always clear the user settable flags. 13264 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13265 bp.name) != null; 13266 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13267 if (hasInstallState) { 13268 writeInstallPermissions = true; 13269 } else { 13270 writeRuntimePermissions = true; 13271 } 13272 } 13273 13274 // Below is only runtime permission handling. 13275 if (!bp.isRuntime()) { 13276 continue; 13277 } 13278 13279 // Never clobber system or policy. 13280 if ((oldFlags & policyOrSystemFlags) != 0) { 13281 continue; 13282 } 13283 13284 // If this permission was granted by default, make sure it is. 13285 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13286 if (permissionsState.grantRuntimePermission(bp, userId) 13287 != PERMISSION_OPERATION_FAILURE) { 13288 writeRuntimePermissions = true; 13289 } 13290 } else { 13291 // Otherwise, reset the permission. 13292 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13293 switch (revokeResult) { 13294 case PERMISSION_OPERATION_SUCCESS: { 13295 writeRuntimePermissions = true; 13296 } break; 13297 13298 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13299 writeRuntimePermissions = true; 13300 // If gids changed for this user, kill all affected packages. 13301 mHandler.post(new Runnable() { 13302 @Override 13303 public void run() { 13304 // This has to happen with no lock held. 13305 killSettingPackagesForUser(ps, userId, 13306 KILL_APP_REASON_GIDS_CHANGED); 13307 } 13308 }); 13309 } break; 13310 } 13311 } 13312 } 13313 13314 // Synchronously write as we are taking permissions away. 13315 if (writeRuntimePermissions) { 13316 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13317 } 13318 13319 // Synchronously write as we are taking permissions away. 13320 if (writeInstallPermissions) { 13321 mSettings.writeLPr(); 13322 } 13323 } 13324 13325 /** 13326 * Remove entries from the keystore daemon. Will only remove it if the 13327 * {@code appId} is valid. 13328 */ 13329 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13330 if (appId < 0) { 13331 return; 13332 } 13333 13334 final KeyStore keyStore = KeyStore.getInstance(); 13335 if (keyStore != null) { 13336 if (userId == UserHandle.USER_ALL) { 13337 for (final int individual : sUserManager.getUserIds()) { 13338 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13339 } 13340 } else { 13341 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13342 } 13343 } else { 13344 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13345 } 13346 } 13347 13348 @Override 13349 public void deleteApplicationCacheFiles(final String packageName, 13350 final IPackageDataObserver observer) { 13351 mContext.enforceCallingOrSelfPermission( 13352 android.Manifest.permission.DELETE_CACHE_FILES, null); 13353 // Queue up an async operation since the package deletion may take a little while. 13354 final int userId = UserHandle.getCallingUserId(); 13355 mHandler.post(new Runnable() { 13356 public void run() { 13357 mHandler.removeCallbacks(this); 13358 final boolean succeded; 13359 synchronized (mInstallLock) { 13360 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13361 } 13362 clearExternalStorageDataSync(packageName, userId, false); 13363 if (observer != null) { 13364 try { 13365 observer.onRemoveCompleted(packageName, succeded); 13366 } catch (RemoteException e) { 13367 Log.i(TAG, "Observer no longer exists."); 13368 } 13369 } //end if observer 13370 } //end run 13371 }); 13372 } 13373 13374 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13375 if (packageName == null) { 13376 Slog.w(TAG, "Attempt to delete null packageName."); 13377 return false; 13378 } 13379 PackageParser.Package p; 13380 synchronized (mPackages) { 13381 p = mPackages.get(packageName); 13382 } 13383 if (p == null) { 13384 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13385 return false; 13386 } 13387 final ApplicationInfo applicationInfo = p.applicationInfo; 13388 if (applicationInfo == null) { 13389 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13390 return false; 13391 } 13392 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13393 if (retCode < 0) { 13394 Slog.w(TAG, "Couldn't remove cache files for package: " 13395 + packageName + " u" + userId); 13396 return false; 13397 } 13398 return true; 13399 } 13400 13401 @Override 13402 public void getPackageSizeInfo(final String packageName, int userHandle, 13403 final IPackageStatsObserver observer) { 13404 mContext.enforceCallingOrSelfPermission( 13405 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13406 if (packageName == null) { 13407 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13408 } 13409 13410 PackageStats stats = new PackageStats(packageName, userHandle); 13411 13412 /* 13413 * Queue up an async operation since the package measurement may take a 13414 * little while. 13415 */ 13416 Message msg = mHandler.obtainMessage(INIT_COPY); 13417 msg.obj = new MeasureParams(stats, observer); 13418 mHandler.sendMessage(msg); 13419 } 13420 13421 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13422 PackageStats pStats) { 13423 if (packageName == null) { 13424 Slog.w(TAG, "Attempt to get size of null packageName."); 13425 return false; 13426 } 13427 PackageParser.Package p; 13428 boolean dataOnly = false; 13429 String libDirRoot = null; 13430 String asecPath = null; 13431 PackageSetting ps = null; 13432 synchronized (mPackages) { 13433 p = mPackages.get(packageName); 13434 ps = mSettings.mPackages.get(packageName); 13435 if(p == null) { 13436 dataOnly = true; 13437 if((ps == null) || (ps.pkg == null)) { 13438 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13439 return false; 13440 } 13441 p = ps.pkg; 13442 } 13443 if (ps != null) { 13444 libDirRoot = ps.legacyNativeLibraryPathString; 13445 } 13446 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13447 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13448 if (secureContainerId != null) { 13449 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13450 } 13451 } 13452 } 13453 String publicSrcDir = null; 13454 if(!dataOnly) { 13455 final ApplicationInfo applicationInfo = p.applicationInfo; 13456 if (applicationInfo == null) { 13457 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13458 return false; 13459 } 13460 if (p.isForwardLocked()) { 13461 publicSrcDir = applicationInfo.getBaseResourcePath(); 13462 } 13463 } 13464 // TODO: extend to measure size of split APKs 13465 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13466 // not just the first level. 13467 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13468 // just the primary. 13469 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13470 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13471 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13472 if (res < 0) { 13473 return false; 13474 } 13475 13476 // Fix-up for forward-locked applications in ASEC containers. 13477 if (!isExternal(p)) { 13478 pStats.codeSize += pStats.externalCodeSize; 13479 pStats.externalCodeSize = 0L; 13480 } 13481 13482 return true; 13483 } 13484 13485 13486 @Override 13487 public void addPackageToPreferred(String packageName) { 13488 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13489 } 13490 13491 @Override 13492 public void removePackageFromPreferred(String packageName) { 13493 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13494 } 13495 13496 @Override 13497 public List<PackageInfo> getPreferredPackages(int flags) { 13498 return new ArrayList<PackageInfo>(); 13499 } 13500 13501 private int getUidTargetSdkVersionLockedLPr(int uid) { 13502 Object obj = mSettings.getUserIdLPr(uid); 13503 if (obj instanceof SharedUserSetting) { 13504 final SharedUserSetting sus = (SharedUserSetting) obj; 13505 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13506 final Iterator<PackageSetting> it = sus.packages.iterator(); 13507 while (it.hasNext()) { 13508 final PackageSetting ps = it.next(); 13509 if (ps.pkg != null) { 13510 int v = ps.pkg.applicationInfo.targetSdkVersion; 13511 if (v < vers) vers = v; 13512 } 13513 } 13514 return vers; 13515 } else if (obj instanceof PackageSetting) { 13516 final PackageSetting ps = (PackageSetting) obj; 13517 if (ps.pkg != null) { 13518 return ps.pkg.applicationInfo.targetSdkVersion; 13519 } 13520 } 13521 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13522 } 13523 13524 @Override 13525 public void addPreferredActivity(IntentFilter filter, int match, 13526 ComponentName[] set, ComponentName activity, int userId) { 13527 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13528 "Adding preferred"); 13529 } 13530 13531 private void addPreferredActivityInternal(IntentFilter filter, int match, 13532 ComponentName[] set, ComponentName activity, boolean always, int userId, 13533 String opname) { 13534 // writer 13535 int callingUid = Binder.getCallingUid(); 13536 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13537 if (filter.countActions() == 0) { 13538 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13539 return; 13540 } 13541 synchronized (mPackages) { 13542 if (mContext.checkCallingOrSelfPermission( 13543 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13544 != PackageManager.PERMISSION_GRANTED) { 13545 if (getUidTargetSdkVersionLockedLPr(callingUid) 13546 < Build.VERSION_CODES.FROYO) { 13547 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13548 + callingUid); 13549 return; 13550 } 13551 mContext.enforceCallingOrSelfPermission( 13552 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13553 } 13554 13555 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13556 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13557 + userId + ":"); 13558 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13559 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13560 scheduleWritePackageRestrictionsLocked(userId); 13561 } 13562 } 13563 13564 @Override 13565 public void replacePreferredActivity(IntentFilter filter, int match, 13566 ComponentName[] set, ComponentName activity, int userId) { 13567 if (filter.countActions() != 1) { 13568 throw new IllegalArgumentException( 13569 "replacePreferredActivity expects filter to have only 1 action."); 13570 } 13571 if (filter.countDataAuthorities() != 0 13572 || filter.countDataPaths() != 0 13573 || filter.countDataSchemes() > 1 13574 || filter.countDataTypes() != 0) { 13575 throw new IllegalArgumentException( 13576 "replacePreferredActivity expects filter to have no data authorities, " + 13577 "paths, or types; and at most one scheme."); 13578 } 13579 13580 final int callingUid = Binder.getCallingUid(); 13581 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13582 synchronized (mPackages) { 13583 if (mContext.checkCallingOrSelfPermission( 13584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13585 != PackageManager.PERMISSION_GRANTED) { 13586 if (getUidTargetSdkVersionLockedLPr(callingUid) 13587 < Build.VERSION_CODES.FROYO) { 13588 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13589 + Binder.getCallingUid()); 13590 return; 13591 } 13592 mContext.enforceCallingOrSelfPermission( 13593 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13594 } 13595 13596 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13597 if (pir != null) { 13598 // Get all of the existing entries that exactly match this filter. 13599 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13600 if (existing != null && existing.size() == 1) { 13601 PreferredActivity cur = existing.get(0); 13602 if (DEBUG_PREFERRED) { 13603 Slog.i(TAG, "Checking replace of preferred:"); 13604 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13605 if (!cur.mPref.mAlways) { 13606 Slog.i(TAG, " -- CUR; not mAlways!"); 13607 } else { 13608 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13609 Slog.i(TAG, " -- CUR: mSet=" 13610 + Arrays.toString(cur.mPref.mSetComponents)); 13611 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13612 Slog.i(TAG, " -- NEW: mMatch=" 13613 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13614 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13615 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13616 } 13617 } 13618 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13619 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13620 && cur.mPref.sameSet(set)) { 13621 // Setting the preferred activity to what it happens to be already 13622 if (DEBUG_PREFERRED) { 13623 Slog.i(TAG, "Replacing with same preferred activity " 13624 + cur.mPref.mShortComponent + " for user " 13625 + userId + ":"); 13626 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13627 } 13628 return; 13629 } 13630 } 13631 13632 if (existing != null) { 13633 if (DEBUG_PREFERRED) { 13634 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13635 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13636 } 13637 for (int i = 0; i < existing.size(); i++) { 13638 PreferredActivity pa = existing.get(i); 13639 if (DEBUG_PREFERRED) { 13640 Slog.i(TAG, "Removing existing preferred activity " 13641 + pa.mPref.mComponent + ":"); 13642 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13643 } 13644 pir.removeFilter(pa); 13645 } 13646 } 13647 } 13648 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13649 "Replacing preferred"); 13650 } 13651 } 13652 13653 @Override 13654 public void clearPackagePreferredActivities(String packageName) { 13655 final int uid = Binder.getCallingUid(); 13656 // writer 13657 synchronized (mPackages) { 13658 PackageParser.Package pkg = mPackages.get(packageName); 13659 if (pkg == null || pkg.applicationInfo.uid != uid) { 13660 if (mContext.checkCallingOrSelfPermission( 13661 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13662 != PackageManager.PERMISSION_GRANTED) { 13663 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13664 < Build.VERSION_CODES.FROYO) { 13665 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13666 + Binder.getCallingUid()); 13667 return; 13668 } 13669 mContext.enforceCallingOrSelfPermission( 13670 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13671 } 13672 } 13673 13674 int user = UserHandle.getCallingUserId(); 13675 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13676 scheduleWritePackageRestrictionsLocked(user); 13677 } 13678 } 13679 } 13680 13681 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13682 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13683 ArrayList<PreferredActivity> removed = null; 13684 boolean changed = false; 13685 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13686 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13687 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13688 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13689 continue; 13690 } 13691 Iterator<PreferredActivity> it = pir.filterIterator(); 13692 while (it.hasNext()) { 13693 PreferredActivity pa = it.next(); 13694 // Mark entry for removal only if it matches the package name 13695 // and the entry is of type "always". 13696 if (packageName == null || 13697 (pa.mPref.mComponent.getPackageName().equals(packageName) 13698 && pa.mPref.mAlways)) { 13699 if (removed == null) { 13700 removed = new ArrayList<PreferredActivity>(); 13701 } 13702 removed.add(pa); 13703 } 13704 } 13705 if (removed != null) { 13706 for (int j=0; j<removed.size(); j++) { 13707 PreferredActivity pa = removed.get(j); 13708 pir.removeFilter(pa); 13709 } 13710 changed = true; 13711 } 13712 } 13713 return changed; 13714 } 13715 13716 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13717 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13718 if (userId == UserHandle.USER_ALL) { 13719 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13720 sUserManager.getUserIds())) { 13721 for (int oneUserId : sUserManager.getUserIds()) { 13722 scheduleWritePackageRestrictionsLocked(oneUserId); 13723 } 13724 } 13725 } else { 13726 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13727 scheduleWritePackageRestrictionsLocked(userId); 13728 } 13729 } 13730 } 13731 13732 13733 void clearDefaultBrowserIfNeeded(String packageName) { 13734 for (int oneUserId : sUserManager.getUserIds()) { 13735 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13736 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13737 if (packageName.equals(defaultBrowserPackageName)) { 13738 setDefaultBrowserPackageName(null, oneUserId); 13739 } 13740 } 13741 } 13742 13743 @Override 13744 public void resetPreferredActivities(int userId) { 13745 mContext.enforceCallingOrSelfPermission( 13746 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13747 // writer 13748 synchronized (mPackages) { 13749 clearPackagePreferredActivitiesLPw(null, userId); 13750 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13751 applyFactoryDefaultBrowserLPw(userId); 13752 primeDomainVerificationsLPw(userId); 13753 13754 scheduleWritePackageRestrictionsLocked(userId); 13755 } 13756 } 13757 13758 @Override 13759 public int getPreferredActivities(List<IntentFilter> outFilters, 13760 List<ComponentName> outActivities, String packageName) { 13761 13762 int num = 0; 13763 final int userId = UserHandle.getCallingUserId(); 13764 // reader 13765 synchronized (mPackages) { 13766 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13767 if (pir != null) { 13768 final Iterator<PreferredActivity> it = pir.filterIterator(); 13769 while (it.hasNext()) { 13770 final PreferredActivity pa = it.next(); 13771 if (packageName == null 13772 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13773 && pa.mPref.mAlways)) { 13774 if (outFilters != null) { 13775 outFilters.add(new IntentFilter(pa)); 13776 } 13777 if (outActivities != null) { 13778 outActivities.add(pa.mPref.mComponent); 13779 } 13780 } 13781 } 13782 } 13783 } 13784 13785 return num; 13786 } 13787 13788 @Override 13789 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13790 int userId) { 13791 int callingUid = Binder.getCallingUid(); 13792 if (callingUid != Process.SYSTEM_UID) { 13793 throw new SecurityException( 13794 "addPersistentPreferredActivity can only be run by the system"); 13795 } 13796 if (filter.countActions() == 0) { 13797 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13798 return; 13799 } 13800 synchronized (mPackages) { 13801 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13802 " :"); 13803 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13804 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13805 new PersistentPreferredActivity(filter, activity)); 13806 scheduleWritePackageRestrictionsLocked(userId); 13807 } 13808 } 13809 13810 @Override 13811 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13812 int callingUid = Binder.getCallingUid(); 13813 if (callingUid != Process.SYSTEM_UID) { 13814 throw new SecurityException( 13815 "clearPackagePersistentPreferredActivities can only be run by the system"); 13816 } 13817 ArrayList<PersistentPreferredActivity> removed = null; 13818 boolean changed = false; 13819 synchronized (mPackages) { 13820 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13821 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13822 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13823 .valueAt(i); 13824 if (userId != thisUserId) { 13825 continue; 13826 } 13827 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13828 while (it.hasNext()) { 13829 PersistentPreferredActivity ppa = it.next(); 13830 // Mark entry for removal only if it matches the package name. 13831 if (ppa.mComponent.getPackageName().equals(packageName)) { 13832 if (removed == null) { 13833 removed = new ArrayList<PersistentPreferredActivity>(); 13834 } 13835 removed.add(ppa); 13836 } 13837 } 13838 if (removed != null) { 13839 for (int j=0; j<removed.size(); j++) { 13840 PersistentPreferredActivity ppa = removed.get(j); 13841 ppir.removeFilter(ppa); 13842 } 13843 changed = true; 13844 } 13845 } 13846 13847 if (changed) { 13848 scheduleWritePackageRestrictionsLocked(userId); 13849 } 13850 } 13851 } 13852 13853 /** 13854 * Common machinery for picking apart a restored XML blob and passing 13855 * it to a caller-supplied functor to be applied to the running system. 13856 */ 13857 private void restoreFromXml(XmlPullParser parser, int userId, 13858 String expectedStartTag, BlobXmlRestorer functor) 13859 throws IOException, XmlPullParserException { 13860 int type; 13861 while ((type = parser.next()) != XmlPullParser.START_TAG 13862 && type != XmlPullParser.END_DOCUMENT) { 13863 } 13864 if (type != XmlPullParser.START_TAG) { 13865 // oops didn't find a start tag?! 13866 if (DEBUG_BACKUP) { 13867 Slog.e(TAG, "Didn't find start tag during restore"); 13868 } 13869 return; 13870 } 13871 13872 // this is supposed to be TAG_PREFERRED_BACKUP 13873 if (!expectedStartTag.equals(parser.getName())) { 13874 if (DEBUG_BACKUP) { 13875 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13876 } 13877 return; 13878 } 13879 13880 // skip interfering stuff, then we're aligned with the backing implementation 13881 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13882 functor.apply(parser, userId); 13883 } 13884 13885 private interface BlobXmlRestorer { 13886 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13887 } 13888 13889 /** 13890 * Non-Binder method, support for the backup/restore mechanism: write the 13891 * full set of preferred activities in its canonical XML format. Returns the 13892 * XML output as a byte array, or null if there is none. 13893 */ 13894 @Override 13895 public byte[] getPreferredActivityBackup(int userId) { 13896 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13897 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13898 } 13899 13900 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13901 try { 13902 final XmlSerializer serializer = new FastXmlSerializer(); 13903 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13904 serializer.startDocument(null, true); 13905 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13906 13907 synchronized (mPackages) { 13908 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13909 } 13910 13911 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13912 serializer.endDocument(); 13913 serializer.flush(); 13914 } catch (Exception e) { 13915 if (DEBUG_BACKUP) { 13916 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13917 } 13918 return null; 13919 } 13920 13921 return dataStream.toByteArray(); 13922 } 13923 13924 @Override 13925 public void restorePreferredActivities(byte[] backup, int userId) { 13926 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13927 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13928 } 13929 13930 try { 13931 final XmlPullParser parser = Xml.newPullParser(); 13932 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13933 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13934 new BlobXmlRestorer() { 13935 @Override 13936 public void apply(XmlPullParser parser, int userId) 13937 throws XmlPullParserException, IOException { 13938 synchronized (mPackages) { 13939 mSettings.readPreferredActivitiesLPw(parser, userId); 13940 } 13941 } 13942 } ); 13943 } catch (Exception e) { 13944 if (DEBUG_BACKUP) { 13945 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13946 } 13947 } 13948 } 13949 13950 /** 13951 * Non-Binder method, support for the backup/restore mechanism: write the 13952 * default browser (etc) settings in its canonical XML format. Returns the default 13953 * browser XML representation as a byte array, or null if there is none. 13954 */ 13955 @Override 13956 public byte[] getDefaultAppsBackup(int userId) { 13957 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13958 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13959 } 13960 13961 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13962 try { 13963 final XmlSerializer serializer = new FastXmlSerializer(); 13964 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13965 serializer.startDocument(null, true); 13966 serializer.startTag(null, TAG_DEFAULT_APPS); 13967 13968 synchronized (mPackages) { 13969 mSettings.writeDefaultAppsLPr(serializer, userId); 13970 } 13971 13972 serializer.endTag(null, TAG_DEFAULT_APPS); 13973 serializer.endDocument(); 13974 serializer.flush(); 13975 } catch (Exception e) { 13976 if (DEBUG_BACKUP) { 13977 Slog.e(TAG, "Unable to write default apps for backup", e); 13978 } 13979 return null; 13980 } 13981 13982 return dataStream.toByteArray(); 13983 } 13984 13985 @Override 13986 public void restoreDefaultApps(byte[] backup, int userId) { 13987 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13988 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13989 } 13990 13991 try { 13992 final XmlPullParser parser = Xml.newPullParser(); 13993 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13994 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13995 new BlobXmlRestorer() { 13996 @Override 13997 public void apply(XmlPullParser parser, int userId) 13998 throws XmlPullParserException, IOException { 13999 synchronized (mPackages) { 14000 mSettings.readDefaultAppsLPw(parser, userId); 14001 } 14002 } 14003 } ); 14004 } catch (Exception e) { 14005 if (DEBUG_BACKUP) { 14006 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14007 } 14008 } 14009 } 14010 14011 @Override 14012 public byte[] getIntentFilterVerificationBackup(int userId) { 14013 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14014 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14015 } 14016 14017 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14018 try { 14019 final XmlSerializer serializer = new FastXmlSerializer(); 14020 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14021 serializer.startDocument(null, true); 14022 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14023 14024 synchronized (mPackages) { 14025 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14026 } 14027 14028 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14029 serializer.endDocument(); 14030 serializer.flush(); 14031 } catch (Exception e) { 14032 if (DEBUG_BACKUP) { 14033 Slog.e(TAG, "Unable to write default apps for backup", e); 14034 } 14035 return null; 14036 } 14037 14038 return dataStream.toByteArray(); 14039 } 14040 14041 @Override 14042 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14043 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14044 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14045 } 14046 14047 try { 14048 final XmlPullParser parser = Xml.newPullParser(); 14049 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14050 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14051 new BlobXmlRestorer() { 14052 @Override 14053 public void apply(XmlPullParser parser, int userId) 14054 throws XmlPullParserException, IOException { 14055 synchronized (mPackages) { 14056 mSettings.readAllDomainVerificationsLPr(parser, userId); 14057 mSettings.writeLPr(); 14058 } 14059 } 14060 } ); 14061 } catch (Exception e) { 14062 if (DEBUG_BACKUP) { 14063 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14064 } 14065 } 14066 } 14067 14068 @Override 14069 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14070 int sourceUserId, int targetUserId, int flags) { 14071 mContext.enforceCallingOrSelfPermission( 14072 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14073 int callingUid = Binder.getCallingUid(); 14074 enforceOwnerRights(ownerPackage, callingUid); 14075 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14076 if (intentFilter.countActions() == 0) { 14077 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14078 return; 14079 } 14080 synchronized (mPackages) { 14081 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14082 ownerPackage, targetUserId, flags); 14083 CrossProfileIntentResolver resolver = 14084 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14085 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14086 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14087 if (existing != null) { 14088 int size = existing.size(); 14089 for (int i = 0; i < size; i++) { 14090 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14091 return; 14092 } 14093 } 14094 } 14095 resolver.addFilter(newFilter); 14096 scheduleWritePackageRestrictionsLocked(sourceUserId); 14097 } 14098 } 14099 14100 @Override 14101 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14102 mContext.enforceCallingOrSelfPermission( 14103 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14104 int callingUid = Binder.getCallingUid(); 14105 enforceOwnerRights(ownerPackage, callingUid); 14106 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14107 synchronized (mPackages) { 14108 CrossProfileIntentResolver resolver = 14109 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14110 ArraySet<CrossProfileIntentFilter> set = 14111 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14112 for (CrossProfileIntentFilter filter : set) { 14113 if (filter.getOwnerPackage().equals(ownerPackage)) { 14114 resolver.removeFilter(filter); 14115 } 14116 } 14117 scheduleWritePackageRestrictionsLocked(sourceUserId); 14118 } 14119 } 14120 14121 // Enforcing that callingUid is owning pkg on userId 14122 private void enforceOwnerRights(String pkg, int callingUid) { 14123 // The system owns everything. 14124 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14125 return; 14126 } 14127 int callingUserId = UserHandle.getUserId(callingUid); 14128 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14129 if (pi == null) { 14130 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14131 + callingUserId); 14132 } 14133 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14134 throw new SecurityException("Calling uid " + callingUid 14135 + " does not own package " + pkg); 14136 } 14137 } 14138 14139 @Override 14140 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14141 Intent intent = new Intent(Intent.ACTION_MAIN); 14142 intent.addCategory(Intent.CATEGORY_HOME); 14143 14144 final int callingUserId = UserHandle.getCallingUserId(); 14145 List<ResolveInfo> list = queryIntentActivities(intent, null, 14146 PackageManager.GET_META_DATA, callingUserId); 14147 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14148 true, false, false, callingUserId); 14149 14150 allHomeCandidates.clear(); 14151 if (list != null) { 14152 for (ResolveInfo ri : list) { 14153 allHomeCandidates.add(ri); 14154 } 14155 } 14156 return (preferred == null || preferred.activityInfo == null) 14157 ? null 14158 : new ComponentName(preferred.activityInfo.packageName, 14159 preferred.activityInfo.name); 14160 } 14161 14162 @Override 14163 public void setApplicationEnabledSetting(String appPackageName, 14164 int newState, int flags, int userId, String callingPackage) { 14165 if (!sUserManager.exists(userId)) return; 14166 if (callingPackage == null) { 14167 callingPackage = Integer.toString(Binder.getCallingUid()); 14168 } 14169 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14170 } 14171 14172 @Override 14173 public void setComponentEnabledSetting(ComponentName componentName, 14174 int newState, int flags, int userId) { 14175 if (!sUserManager.exists(userId)) return; 14176 setEnabledSetting(componentName.getPackageName(), 14177 componentName.getClassName(), newState, flags, userId, null); 14178 } 14179 14180 private void setEnabledSetting(final String packageName, String className, int newState, 14181 final int flags, int userId, String callingPackage) { 14182 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14183 || newState == COMPONENT_ENABLED_STATE_ENABLED 14184 || newState == COMPONENT_ENABLED_STATE_DISABLED 14185 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14186 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14187 throw new IllegalArgumentException("Invalid new component state: " 14188 + newState); 14189 } 14190 PackageSetting pkgSetting; 14191 final int uid = Binder.getCallingUid(); 14192 final int permission = mContext.checkCallingOrSelfPermission( 14193 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14194 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14195 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14196 boolean sendNow = false; 14197 boolean isApp = (className == null); 14198 String componentName = isApp ? packageName : className; 14199 int packageUid = -1; 14200 ArrayList<String> components; 14201 14202 // writer 14203 synchronized (mPackages) { 14204 pkgSetting = mSettings.mPackages.get(packageName); 14205 if (pkgSetting == null) { 14206 if (className == null) { 14207 throw new IllegalArgumentException( 14208 "Unknown package: " + packageName); 14209 } 14210 throw new IllegalArgumentException( 14211 "Unknown component: " + packageName 14212 + "/" + className); 14213 } 14214 // Allow root and verify that userId is not being specified by a different user 14215 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14216 throw new SecurityException( 14217 "Permission Denial: attempt to change component state from pid=" 14218 + Binder.getCallingPid() 14219 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14220 } 14221 if (className == null) { 14222 // We're dealing with an application/package level state change 14223 if (pkgSetting.getEnabled(userId) == newState) { 14224 // Nothing to do 14225 return; 14226 } 14227 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14228 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14229 // Don't care about who enables an app. 14230 callingPackage = null; 14231 } 14232 pkgSetting.setEnabled(newState, userId, callingPackage); 14233 // pkgSetting.pkg.mSetEnabled = newState; 14234 } else { 14235 // We're dealing with a component level state change 14236 // First, verify that this is a valid class name. 14237 PackageParser.Package pkg = pkgSetting.pkg; 14238 if (pkg == null || !pkg.hasComponentClassName(className)) { 14239 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14240 throw new IllegalArgumentException("Component class " + className 14241 + " does not exist in " + packageName); 14242 } else { 14243 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14244 + className + " does not exist in " + packageName); 14245 } 14246 } 14247 switch (newState) { 14248 case COMPONENT_ENABLED_STATE_ENABLED: 14249 if (!pkgSetting.enableComponentLPw(className, userId)) { 14250 return; 14251 } 14252 break; 14253 case COMPONENT_ENABLED_STATE_DISABLED: 14254 if (!pkgSetting.disableComponentLPw(className, userId)) { 14255 return; 14256 } 14257 break; 14258 case COMPONENT_ENABLED_STATE_DEFAULT: 14259 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14260 return; 14261 } 14262 break; 14263 default: 14264 Slog.e(TAG, "Invalid new component state: " + newState); 14265 return; 14266 } 14267 } 14268 scheduleWritePackageRestrictionsLocked(userId); 14269 components = mPendingBroadcasts.get(userId, packageName); 14270 final boolean newPackage = components == null; 14271 if (newPackage) { 14272 components = new ArrayList<String>(); 14273 } 14274 if (!components.contains(componentName)) { 14275 components.add(componentName); 14276 } 14277 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14278 sendNow = true; 14279 // Purge entry from pending broadcast list if another one exists already 14280 // since we are sending one right away. 14281 mPendingBroadcasts.remove(userId, packageName); 14282 } else { 14283 if (newPackage) { 14284 mPendingBroadcasts.put(userId, packageName, components); 14285 } 14286 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14287 // Schedule a message 14288 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14289 } 14290 } 14291 } 14292 14293 long callingId = Binder.clearCallingIdentity(); 14294 try { 14295 if (sendNow) { 14296 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14297 sendPackageChangedBroadcast(packageName, 14298 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14299 } 14300 } finally { 14301 Binder.restoreCallingIdentity(callingId); 14302 } 14303 } 14304 14305 private void sendPackageChangedBroadcast(String packageName, 14306 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14307 if (DEBUG_INSTALL) 14308 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14309 + componentNames); 14310 Bundle extras = new Bundle(4); 14311 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14312 String nameList[] = new String[componentNames.size()]; 14313 componentNames.toArray(nameList); 14314 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14315 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14316 extras.putInt(Intent.EXTRA_UID, packageUid); 14317 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14318 new int[] {UserHandle.getUserId(packageUid)}); 14319 } 14320 14321 @Override 14322 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14323 if (!sUserManager.exists(userId)) return; 14324 final int uid = Binder.getCallingUid(); 14325 final int permission = mContext.checkCallingOrSelfPermission( 14326 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14327 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14328 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14329 // writer 14330 synchronized (mPackages) { 14331 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14332 allowedByPermission, uid, userId)) { 14333 scheduleWritePackageRestrictionsLocked(userId); 14334 } 14335 } 14336 } 14337 14338 @Override 14339 public String getInstallerPackageName(String packageName) { 14340 // reader 14341 synchronized (mPackages) { 14342 return mSettings.getInstallerPackageNameLPr(packageName); 14343 } 14344 } 14345 14346 @Override 14347 public int getApplicationEnabledSetting(String packageName, int userId) { 14348 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14349 int uid = Binder.getCallingUid(); 14350 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14351 // reader 14352 synchronized (mPackages) { 14353 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14354 } 14355 } 14356 14357 @Override 14358 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14359 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14360 int uid = Binder.getCallingUid(); 14361 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14362 // reader 14363 synchronized (mPackages) { 14364 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14365 } 14366 } 14367 14368 @Override 14369 public void enterSafeMode() { 14370 enforceSystemOrRoot("Only the system can request entering safe mode"); 14371 14372 if (!mSystemReady) { 14373 mSafeMode = true; 14374 } 14375 } 14376 14377 @Override 14378 public void systemReady() { 14379 mSystemReady = true; 14380 14381 // Read the compatibilty setting when the system is ready. 14382 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14383 mContext.getContentResolver(), 14384 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14385 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14386 if (DEBUG_SETTINGS) { 14387 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14388 } 14389 14390 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14391 14392 synchronized (mPackages) { 14393 // Verify that all of the preferred activity components actually 14394 // exist. It is possible for applications to be updated and at 14395 // that point remove a previously declared activity component that 14396 // had been set as a preferred activity. We try to clean this up 14397 // the next time we encounter that preferred activity, but it is 14398 // possible for the user flow to never be able to return to that 14399 // situation so here we do a sanity check to make sure we haven't 14400 // left any junk around. 14401 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14402 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14403 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14404 removed.clear(); 14405 for (PreferredActivity pa : pir.filterSet()) { 14406 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14407 removed.add(pa); 14408 } 14409 } 14410 if (removed.size() > 0) { 14411 for (int r=0; r<removed.size(); r++) { 14412 PreferredActivity pa = removed.get(r); 14413 Slog.w(TAG, "Removing dangling preferred activity: " 14414 + pa.mPref.mComponent); 14415 pir.removeFilter(pa); 14416 } 14417 mSettings.writePackageRestrictionsLPr( 14418 mSettings.mPreferredActivities.keyAt(i)); 14419 } 14420 } 14421 14422 for (int userId : UserManagerService.getInstance().getUserIds()) { 14423 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14424 grantPermissionsUserIds = ArrayUtils.appendInt( 14425 grantPermissionsUserIds, userId); 14426 } 14427 } 14428 } 14429 sUserManager.systemReady(); 14430 14431 // If we upgraded grant all default permissions before kicking off. 14432 for (int userId : grantPermissionsUserIds) { 14433 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14434 } 14435 14436 // Kick off any messages waiting for system ready 14437 if (mPostSystemReadyMessages != null) { 14438 for (Message msg : mPostSystemReadyMessages) { 14439 msg.sendToTarget(); 14440 } 14441 mPostSystemReadyMessages = null; 14442 } 14443 14444 // Watch for external volumes that come and go over time 14445 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14446 storage.registerListener(mStorageListener); 14447 14448 mInstallerService.systemReady(); 14449 mPackageDexOptimizer.systemReady(); 14450 } 14451 14452 @Override 14453 public boolean isSafeMode() { 14454 return mSafeMode; 14455 } 14456 14457 @Override 14458 public boolean hasSystemUidErrors() { 14459 return mHasSystemUidErrors; 14460 } 14461 14462 static String arrayToString(int[] array) { 14463 StringBuffer buf = new StringBuffer(128); 14464 buf.append('['); 14465 if (array != null) { 14466 for (int i=0; i<array.length; i++) { 14467 if (i > 0) buf.append(", "); 14468 buf.append(array[i]); 14469 } 14470 } 14471 buf.append(']'); 14472 return buf.toString(); 14473 } 14474 14475 static class DumpState { 14476 public static final int DUMP_LIBS = 1 << 0; 14477 public static final int DUMP_FEATURES = 1 << 1; 14478 public static final int DUMP_RESOLVERS = 1 << 2; 14479 public static final int DUMP_PERMISSIONS = 1 << 3; 14480 public static final int DUMP_PACKAGES = 1 << 4; 14481 public static final int DUMP_SHARED_USERS = 1 << 5; 14482 public static final int DUMP_MESSAGES = 1 << 6; 14483 public static final int DUMP_PROVIDERS = 1 << 7; 14484 public static final int DUMP_VERIFIERS = 1 << 8; 14485 public static final int DUMP_PREFERRED = 1 << 9; 14486 public static final int DUMP_PREFERRED_XML = 1 << 10; 14487 public static final int DUMP_KEYSETS = 1 << 11; 14488 public static final int DUMP_VERSION = 1 << 12; 14489 public static final int DUMP_INSTALLS = 1 << 13; 14490 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14491 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14492 14493 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14494 14495 private int mTypes; 14496 14497 private int mOptions; 14498 14499 private boolean mTitlePrinted; 14500 14501 private SharedUserSetting mSharedUser; 14502 14503 public boolean isDumping(int type) { 14504 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14505 return true; 14506 } 14507 14508 return (mTypes & type) != 0; 14509 } 14510 14511 public void setDump(int type) { 14512 mTypes |= type; 14513 } 14514 14515 public boolean isOptionEnabled(int option) { 14516 return (mOptions & option) != 0; 14517 } 14518 14519 public void setOptionEnabled(int option) { 14520 mOptions |= option; 14521 } 14522 14523 public boolean onTitlePrinted() { 14524 final boolean printed = mTitlePrinted; 14525 mTitlePrinted = true; 14526 return printed; 14527 } 14528 14529 public boolean getTitlePrinted() { 14530 return mTitlePrinted; 14531 } 14532 14533 public void setTitlePrinted(boolean enabled) { 14534 mTitlePrinted = enabled; 14535 } 14536 14537 public SharedUserSetting getSharedUser() { 14538 return mSharedUser; 14539 } 14540 14541 public void setSharedUser(SharedUserSetting user) { 14542 mSharedUser = user; 14543 } 14544 } 14545 14546 @Override 14547 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14548 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14549 != PackageManager.PERMISSION_GRANTED) { 14550 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14551 + Binder.getCallingPid() 14552 + ", uid=" + Binder.getCallingUid() 14553 + " without permission " 14554 + android.Manifest.permission.DUMP); 14555 return; 14556 } 14557 14558 DumpState dumpState = new DumpState(); 14559 boolean fullPreferred = false; 14560 boolean checkin = false; 14561 14562 String packageName = null; 14563 ArraySet<String> permissionNames = null; 14564 14565 int opti = 0; 14566 while (opti < args.length) { 14567 String opt = args[opti]; 14568 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14569 break; 14570 } 14571 opti++; 14572 14573 if ("-a".equals(opt)) { 14574 // Right now we only know how to print all. 14575 } else if ("-h".equals(opt)) { 14576 pw.println("Package manager dump options:"); 14577 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14578 pw.println(" --checkin: dump for a checkin"); 14579 pw.println(" -f: print details of intent filters"); 14580 pw.println(" -h: print this help"); 14581 pw.println(" cmd may be one of:"); 14582 pw.println(" l[ibraries]: list known shared libraries"); 14583 pw.println(" f[ibraries]: list device features"); 14584 pw.println(" k[eysets]: print known keysets"); 14585 pw.println(" r[esolvers]: dump intent resolvers"); 14586 pw.println(" perm[issions]: dump permissions"); 14587 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14588 pw.println(" pref[erred]: print preferred package settings"); 14589 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14590 pw.println(" prov[iders]: dump content providers"); 14591 pw.println(" p[ackages]: dump installed packages"); 14592 pw.println(" s[hared-users]: dump shared user IDs"); 14593 pw.println(" m[essages]: print collected runtime messages"); 14594 pw.println(" v[erifiers]: print package verifier info"); 14595 pw.println(" version: print database version info"); 14596 pw.println(" write: write current settings now"); 14597 pw.println(" <package.name>: info about given package"); 14598 pw.println(" installs: details about install sessions"); 14599 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14600 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14601 return; 14602 } else if ("--checkin".equals(opt)) { 14603 checkin = true; 14604 } else if ("-f".equals(opt)) { 14605 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14606 } else { 14607 pw.println("Unknown argument: " + opt + "; use -h for help"); 14608 } 14609 } 14610 14611 // Is the caller requesting to dump a particular piece of data? 14612 if (opti < args.length) { 14613 String cmd = args[opti]; 14614 opti++; 14615 // Is this a package name? 14616 if ("android".equals(cmd) || cmd.contains(".")) { 14617 packageName = cmd; 14618 // When dumping a single package, we always dump all of its 14619 // filter information since the amount of data will be reasonable. 14620 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14621 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14622 dumpState.setDump(DumpState.DUMP_LIBS); 14623 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14624 dumpState.setDump(DumpState.DUMP_FEATURES); 14625 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14626 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14627 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14628 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14629 } else if ("permission".equals(cmd)) { 14630 if (opti >= args.length) { 14631 pw.println("Error: permission requires permission name"); 14632 return; 14633 } 14634 permissionNames = new ArraySet<>(); 14635 while (opti < args.length) { 14636 permissionNames.add(args[opti]); 14637 opti++; 14638 } 14639 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14640 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14641 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14642 dumpState.setDump(DumpState.DUMP_PREFERRED); 14643 } else if ("preferred-xml".equals(cmd)) { 14644 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14645 if (opti < args.length && "--full".equals(args[opti])) { 14646 fullPreferred = true; 14647 opti++; 14648 } 14649 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14650 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14651 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14652 dumpState.setDump(DumpState.DUMP_PACKAGES); 14653 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14654 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14655 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14656 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14657 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14658 dumpState.setDump(DumpState.DUMP_MESSAGES); 14659 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14660 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14661 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14662 || "intent-filter-verifiers".equals(cmd)) { 14663 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14664 } else if ("version".equals(cmd)) { 14665 dumpState.setDump(DumpState.DUMP_VERSION); 14666 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14667 dumpState.setDump(DumpState.DUMP_KEYSETS); 14668 } else if ("installs".equals(cmd)) { 14669 dumpState.setDump(DumpState.DUMP_INSTALLS); 14670 } else if ("write".equals(cmd)) { 14671 synchronized (mPackages) { 14672 mSettings.writeLPr(); 14673 pw.println("Settings written."); 14674 return; 14675 } 14676 } 14677 } 14678 14679 if (checkin) { 14680 pw.println("vers,1"); 14681 } 14682 14683 // reader 14684 synchronized (mPackages) { 14685 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14686 if (!checkin) { 14687 if (dumpState.onTitlePrinted()) 14688 pw.println(); 14689 pw.println("Database versions:"); 14690 pw.print(" SDK Version:"); 14691 pw.print(" internal="); 14692 pw.print(mSettings.mInternalSdkPlatform); 14693 pw.print(" external="); 14694 pw.println(mSettings.mExternalSdkPlatform); 14695 pw.print(" DB Version:"); 14696 pw.print(" internal="); 14697 pw.print(mSettings.mInternalDatabaseVersion); 14698 pw.print(" external="); 14699 pw.println(mSettings.mExternalDatabaseVersion); 14700 } 14701 } 14702 14703 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14704 if (!checkin) { 14705 if (dumpState.onTitlePrinted()) 14706 pw.println(); 14707 pw.println("Verifiers:"); 14708 pw.print(" Required: "); 14709 pw.print(mRequiredVerifierPackage); 14710 pw.print(" (uid="); 14711 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14712 pw.println(")"); 14713 } else if (mRequiredVerifierPackage != null) { 14714 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14715 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14716 } 14717 } 14718 14719 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14720 packageName == null) { 14721 if (mIntentFilterVerifierComponent != null) { 14722 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14723 if (!checkin) { 14724 if (dumpState.onTitlePrinted()) 14725 pw.println(); 14726 pw.println("Intent Filter Verifier:"); 14727 pw.print(" Using: "); 14728 pw.print(verifierPackageName); 14729 pw.print(" (uid="); 14730 pw.print(getPackageUid(verifierPackageName, 0)); 14731 pw.println(")"); 14732 } else if (verifierPackageName != null) { 14733 pw.print("ifv,"); pw.print(verifierPackageName); 14734 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14735 } 14736 } else { 14737 pw.println(); 14738 pw.println("No Intent Filter Verifier available!"); 14739 } 14740 } 14741 14742 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14743 boolean printedHeader = false; 14744 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14745 while (it.hasNext()) { 14746 String name = it.next(); 14747 SharedLibraryEntry ent = mSharedLibraries.get(name); 14748 if (!checkin) { 14749 if (!printedHeader) { 14750 if (dumpState.onTitlePrinted()) 14751 pw.println(); 14752 pw.println("Libraries:"); 14753 printedHeader = true; 14754 } 14755 pw.print(" "); 14756 } else { 14757 pw.print("lib,"); 14758 } 14759 pw.print(name); 14760 if (!checkin) { 14761 pw.print(" -> "); 14762 } 14763 if (ent.path != null) { 14764 if (!checkin) { 14765 pw.print("(jar) "); 14766 pw.print(ent.path); 14767 } else { 14768 pw.print(",jar,"); 14769 pw.print(ent.path); 14770 } 14771 } else { 14772 if (!checkin) { 14773 pw.print("(apk) "); 14774 pw.print(ent.apk); 14775 } else { 14776 pw.print(",apk,"); 14777 pw.print(ent.apk); 14778 } 14779 } 14780 pw.println(); 14781 } 14782 } 14783 14784 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14785 if (dumpState.onTitlePrinted()) 14786 pw.println(); 14787 if (!checkin) { 14788 pw.println("Features:"); 14789 } 14790 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14791 while (it.hasNext()) { 14792 String name = it.next(); 14793 if (!checkin) { 14794 pw.print(" "); 14795 } else { 14796 pw.print("feat,"); 14797 } 14798 pw.println(name); 14799 } 14800 } 14801 14802 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14803 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14804 : "Activity Resolver Table:", " ", packageName, 14805 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14806 dumpState.setTitlePrinted(true); 14807 } 14808 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14809 : "Receiver Resolver Table:", " ", packageName, 14810 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14811 dumpState.setTitlePrinted(true); 14812 } 14813 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14814 : "Service Resolver Table:", " ", packageName, 14815 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14816 dumpState.setTitlePrinted(true); 14817 } 14818 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14819 : "Provider Resolver Table:", " ", packageName, 14820 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14821 dumpState.setTitlePrinted(true); 14822 } 14823 } 14824 14825 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14826 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14827 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14828 int user = mSettings.mPreferredActivities.keyAt(i); 14829 if (pir.dump(pw, 14830 dumpState.getTitlePrinted() 14831 ? "\nPreferred Activities User " + user + ":" 14832 : "Preferred Activities User " + user + ":", " ", 14833 packageName, true, false)) { 14834 dumpState.setTitlePrinted(true); 14835 } 14836 } 14837 } 14838 14839 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14840 pw.flush(); 14841 FileOutputStream fout = new FileOutputStream(fd); 14842 BufferedOutputStream str = new BufferedOutputStream(fout); 14843 XmlSerializer serializer = new FastXmlSerializer(); 14844 try { 14845 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14846 serializer.startDocument(null, true); 14847 serializer.setFeature( 14848 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14849 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14850 serializer.endDocument(); 14851 serializer.flush(); 14852 } catch (IllegalArgumentException e) { 14853 pw.println("Failed writing: " + e); 14854 } catch (IllegalStateException e) { 14855 pw.println("Failed writing: " + e); 14856 } catch (IOException e) { 14857 pw.println("Failed writing: " + e); 14858 } 14859 } 14860 14861 if (!checkin 14862 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14863 && packageName == null) { 14864 pw.println(); 14865 int count = mSettings.mPackages.size(); 14866 if (count == 0) { 14867 pw.println("No applications!"); 14868 pw.println(); 14869 } else { 14870 final String prefix = " "; 14871 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14872 if (allPackageSettings.size() == 0) { 14873 pw.println("No domain preferred apps!"); 14874 pw.println(); 14875 } else { 14876 pw.println("App verification status:"); 14877 pw.println(); 14878 count = 0; 14879 for (PackageSetting ps : allPackageSettings) { 14880 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14881 if (ivi == null || ivi.getPackageName() == null) continue; 14882 pw.println(prefix + "Package: " + ivi.getPackageName()); 14883 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14884 pw.println(prefix + "Status: " + ivi.getStatusString()); 14885 pw.println(); 14886 count++; 14887 } 14888 if (count == 0) { 14889 pw.println(prefix + "No app verification established."); 14890 pw.println(); 14891 } 14892 for (int userId : sUserManager.getUserIds()) { 14893 pw.println("App linkages for user " + userId + ":"); 14894 pw.println(); 14895 count = 0; 14896 for (PackageSetting ps : allPackageSettings) { 14897 final long status = ps.getDomainVerificationStatusForUser(userId); 14898 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14899 continue; 14900 } 14901 pw.println(prefix + "Package: " + ps.name); 14902 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14903 String statusStr = IntentFilterVerificationInfo. 14904 getStatusStringFromValue(status); 14905 pw.println(prefix + "Status: " + statusStr); 14906 pw.println(); 14907 count++; 14908 } 14909 if (count == 0) { 14910 pw.println(prefix + "No configured app linkages."); 14911 pw.println(); 14912 } 14913 } 14914 } 14915 } 14916 } 14917 14918 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14919 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14920 if (packageName == null && permissionNames == null) { 14921 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14922 if (iperm == 0) { 14923 if (dumpState.onTitlePrinted()) 14924 pw.println(); 14925 pw.println("AppOp Permissions:"); 14926 } 14927 pw.print(" AppOp Permission "); 14928 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14929 pw.println(":"); 14930 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14931 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14932 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14933 } 14934 } 14935 } 14936 } 14937 14938 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14939 boolean printedSomething = false; 14940 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14941 if (packageName != null && !packageName.equals(p.info.packageName)) { 14942 continue; 14943 } 14944 if (!printedSomething) { 14945 if (dumpState.onTitlePrinted()) 14946 pw.println(); 14947 pw.println("Registered ContentProviders:"); 14948 printedSomething = true; 14949 } 14950 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14951 pw.print(" "); pw.println(p.toString()); 14952 } 14953 printedSomething = false; 14954 for (Map.Entry<String, PackageParser.Provider> entry : 14955 mProvidersByAuthority.entrySet()) { 14956 PackageParser.Provider p = entry.getValue(); 14957 if (packageName != null && !packageName.equals(p.info.packageName)) { 14958 continue; 14959 } 14960 if (!printedSomething) { 14961 if (dumpState.onTitlePrinted()) 14962 pw.println(); 14963 pw.println("ContentProvider Authorities:"); 14964 printedSomething = true; 14965 } 14966 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14967 pw.print(" "); pw.println(p.toString()); 14968 if (p.info != null && p.info.applicationInfo != null) { 14969 final String appInfo = p.info.applicationInfo.toString(); 14970 pw.print(" applicationInfo="); pw.println(appInfo); 14971 } 14972 } 14973 } 14974 14975 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14976 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14977 } 14978 14979 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14980 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14981 } 14982 14983 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14984 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14985 } 14986 14987 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14988 // XXX should handle packageName != null by dumping only install data that 14989 // the given package is involved with. 14990 if (dumpState.onTitlePrinted()) pw.println(); 14991 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14992 } 14993 14994 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14995 if (dumpState.onTitlePrinted()) pw.println(); 14996 mSettings.dumpReadMessagesLPr(pw, dumpState); 14997 14998 pw.println(); 14999 pw.println("Package warning messages:"); 15000 BufferedReader in = null; 15001 String line = null; 15002 try { 15003 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15004 while ((line = in.readLine()) != null) { 15005 if (line.contains("ignored: updated version")) continue; 15006 pw.println(line); 15007 } 15008 } catch (IOException ignored) { 15009 } finally { 15010 IoUtils.closeQuietly(in); 15011 } 15012 } 15013 15014 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15015 BufferedReader in = null; 15016 String line = null; 15017 try { 15018 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15019 while ((line = in.readLine()) != null) { 15020 if (line.contains("ignored: updated version")) continue; 15021 pw.print("msg,"); 15022 pw.println(line); 15023 } 15024 } catch (IOException ignored) { 15025 } finally { 15026 IoUtils.closeQuietly(in); 15027 } 15028 } 15029 } 15030 } 15031 15032 private String dumpDomainString(String packageName) { 15033 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 15034 List<IntentFilter> filters = getAllIntentFilters(packageName); 15035 15036 ArraySet<String> result = new ArraySet<>(); 15037 if (iviList.size() > 0) { 15038 for (IntentFilterVerificationInfo ivi : iviList) { 15039 for (String host : ivi.getDomains()) { 15040 result.add(host); 15041 } 15042 } 15043 } 15044 if (filters != null && filters.size() > 0) { 15045 for (IntentFilter filter : filters) { 15046 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 15047 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 15048 result.addAll(filter.getHostsList()); 15049 } 15050 } 15051 } 15052 15053 StringBuilder sb = new StringBuilder(result.size() * 16); 15054 for (String domain : result) { 15055 if (sb.length() > 0) sb.append(" "); 15056 sb.append(domain); 15057 } 15058 return sb.toString(); 15059 } 15060 15061 // ------- apps on sdcard specific code ------- 15062 static final boolean DEBUG_SD_INSTALL = false; 15063 15064 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15065 15066 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15067 15068 private boolean mMediaMounted = false; 15069 15070 static String getEncryptKey() { 15071 try { 15072 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15073 SD_ENCRYPTION_KEYSTORE_NAME); 15074 if (sdEncKey == null) { 15075 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15076 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15077 if (sdEncKey == null) { 15078 Slog.e(TAG, "Failed to create encryption keys"); 15079 return null; 15080 } 15081 } 15082 return sdEncKey; 15083 } catch (NoSuchAlgorithmException nsae) { 15084 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15085 return null; 15086 } catch (IOException ioe) { 15087 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15088 return null; 15089 } 15090 } 15091 15092 /* 15093 * Update media status on PackageManager. 15094 */ 15095 @Override 15096 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15097 int callingUid = Binder.getCallingUid(); 15098 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15099 throw new SecurityException("Media status can only be updated by the system"); 15100 } 15101 // reader; this apparently protects mMediaMounted, but should probably 15102 // be a different lock in that case. 15103 synchronized (mPackages) { 15104 Log.i(TAG, "Updating external media status from " 15105 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15106 + (mediaStatus ? "mounted" : "unmounted")); 15107 if (DEBUG_SD_INSTALL) 15108 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15109 + ", mMediaMounted=" + mMediaMounted); 15110 if (mediaStatus == mMediaMounted) { 15111 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15112 : 0, -1); 15113 mHandler.sendMessage(msg); 15114 return; 15115 } 15116 mMediaMounted = mediaStatus; 15117 } 15118 // Queue up an async operation since the package installation may take a 15119 // little while. 15120 mHandler.post(new Runnable() { 15121 public void run() { 15122 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15123 } 15124 }); 15125 } 15126 15127 /** 15128 * Called by MountService when the initial ASECs to scan are available. 15129 * Should block until all the ASEC containers are finished being scanned. 15130 */ 15131 public void scanAvailableAsecs() { 15132 updateExternalMediaStatusInner(true, false, false); 15133 if (mShouldRestoreconData) { 15134 SELinuxMMAC.setRestoreconDone(); 15135 mShouldRestoreconData = false; 15136 } 15137 } 15138 15139 /* 15140 * Collect information of applications on external media, map them against 15141 * existing containers and update information based on current mount status. 15142 * Please note that we always have to report status if reportStatus has been 15143 * set to true especially when unloading packages. 15144 */ 15145 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15146 boolean externalStorage) { 15147 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15148 int[] uidArr = EmptyArray.INT; 15149 15150 final String[] list = PackageHelper.getSecureContainerList(); 15151 if (ArrayUtils.isEmpty(list)) { 15152 Log.i(TAG, "No secure containers found"); 15153 } else { 15154 // Process list of secure containers and categorize them 15155 // as active or stale based on their package internal state. 15156 15157 // reader 15158 synchronized (mPackages) { 15159 for (String cid : list) { 15160 // Leave stages untouched for now; installer service owns them 15161 if (PackageInstallerService.isStageName(cid)) continue; 15162 15163 if (DEBUG_SD_INSTALL) 15164 Log.i(TAG, "Processing container " + cid); 15165 String pkgName = getAsecPackageName(cid); 15166 if (pkgName == null) { 15167 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15168 continue; 15169 } 15170 if (DEBUG_SD_INSTALL) 15171 Log.i(TAG, "Looking for pkg : " + pkgName); 15172 15173 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15174 if (ps == null) { 15175 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15176 continue; 15177 } 15178 15179 /* 15180 * Skip packages that are not external if we're unmounting 15181 * external storage. 15182 */ 15183 if (externalStorage && !isMounted && !isExternal(ps)) { 15184 continue; 15185 } 15186 15187 final AsecInstallArgs args = new AsecInstallArgs(cid, 15188 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15189 // The package status is changed only if the code path 15190 // matches between settings and the container id. 15191 if (ps.codePathString != null 15192 && ps.codePathString.startsWith(args.getCodePath())) { 15193 if (DEBUG_SD_INSTALL) { 15194 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15195 + " at code path: " + ps.codePathString); 15196 } 15197 15198 // We do have a valid package installed on sdcard 15199 processCids.put(args, ps.codePathString); 15200 final int uid = ps.appId; 15201 if (uid != -1) { 15202 uidArr = ArrayUtils.appendInt(uidArr, uid); 15203 } 15204 } else { 15205 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15206 + ps.codePathString); 15207 } 15208 } 15209 } 15210 15211 Arrays.sort(uidArr); 15212 } 15213 15214 // Process packages with valid entries. 15215 if (isMounted) { 15216 if (DEBUG_SD_INSTALL) 15217 Log.i(TAG, "Loading packages"); 15218 loadMediaPackages(processCids, uidArr); 15219 startCleaningPackages(); 15220 mInstallerService.onSecureContainersAvailable(); 15221 } else { 15222 if (DEBUG_SD_INSTALL) 15223 Log.i(TAG, "Unloading packages"); 15224 unloadMediaPackages(processCids, uidArr, reportStatus); 15225 } 15226 } 15227 15228 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15229 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15230 final int size = infos.size(); 15231 final String[] packageNames = new String[size]; 15232 final int[] packageUids = new int[size]; 15233 for (int i = 0; i < size; i++) { 15234 final ApplicationInfo info = infos.get(i); 15235 packageNames[i] = info.packageName; 15236 packageUids[i] = info.uid; 15237 } 15238 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15239 finishedReceiver); 15240 } 15241 15242 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15243 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15244 sendResourcesChangedBroadcast(mediaStatus, replacing, 15245 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15246 } 15247 15248 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15249 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15250 int size = pkgList.length; 15251 if (size > 0) { 15252 // Send broadcasts here 15253 Bundle extras = new Bundle(); 15254 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15255 if (uidArr != null) { 15256 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15257 } 15258 if (replacing) { 15259 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15260 } 15261 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15262 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15263 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15264 } 15265 } 15266 15267 /* 15268 * Look at potentially valid container ids from processCids If package 15269 * information doesn't match the one on record or package scanning fails, 15270 * the cid is added to list of removeCids. We currently don't delete stale 15271 * containers. 15272 */ 15273 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15274 ArrayList<String> pkgList = new ArrayList<String>(); 15275 Set<AsecInstallArgs> keys = processCids.keySet(); 15276 15277 for (AsecInstallArgs args : keys) { 15278 String codePath = processCids.get(args); 15279 if (DEBUG_SD_INSTALL) 15280 Log.i(TAG, "Loading container : " + args.cid); 15281 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15282 try { 15283 // Make sure there are no container errors first. 15284 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15285 Slog.e(TAG, "Failed to mount cid : " + args.cid 15286 + " when installing from sdcard"); 15287 continue; 15288 } 15289 // Check code path here. 15290 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15291 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15292 + " does not match one in settings " + codePath); 15293 continue; 15294 } 15295 // Parse package 15296 int parseFlags = mDefParseFlags; 15297 if (args.isExternalAsec()) { 15298 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15299 } 15300 if (args.isFwdLocked()) { 15301 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15302 } 15303 15304 synchronized (mInstallLock) { 15305 PackageParser.Package pkg = null; 15306 try { 15307 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15308 } catch (PackageManagerException e) { 15309 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15310 } 15311 // Scan the package 15312 if (pkg != null) { 15313 /* 15314 * TODO why is the lock being held? doPostInstall is 15315 * called in other places without the lock. This needs 15316 * to be straightened out. 15317 */ 15318 // writer 15319 synchronized (mPackages) { 15320 retCode = PackageManager.INSTALL_SUCCEEDED; 15321 pkgList.add(pkg.packageName); 15322 // Post process args 15323 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15324 pkg.applicationInfo.uid); 15325 } 15326 } else { 15327 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15328 } 15329 } 15330 15331 } finally { 15332 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15333 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15334 } 15335 } 15336 } 15337 // writer 15338 synchronized (mPackages) { 15339 // If the platform SDK has changed since the last time we booted, 15340 // we need to re-grant app permission to catch any new ones that 15341 // appear. This is really a hack, and means that apps can in some 15342 // cases get permissions that the user didn't initially explicitly 15343 // allow... it would be nice to have some better way to handle 15344 // this situation. 15345 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15346 if (regrantPermissions) 15347 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15348 + mSdkVersion + "; regranting permissions for external storage"); 15349 mSettings.mExternalSdkPlatform = mSdkVersion; 15350 15351 // Make sure group IDs have been assigned, and any permission 15352 // changes in other apps are accounted for 15353 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15354 | (regrantPermissions 15355 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15356 : 0)); 15357 15358 mSettings.updateExternalDatabaseVersion(); 15359 15360 // can downgrade to reader 15361 // Persist settings 15362 mSettings.writeLPr(); 15363 } 15364 // Send a broadcast to let everyone know we are done processing 15365 if (pkgList.size() > 0) { 15366 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15367 } 15368 } 15369 15370 /* 15371 * Utility method to unload a list of specified containers 15372 */ 15373 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15374 // Just unmount all valid containers. 15375 for (AsecInstallArgs arg : cidArgs) { 15376 synchronized (mInstallLock) { 15377 arg.doPostDeleteLI(false); 15378 } 15379 } 15380 } 15381 15382 /* 15383 * Unload packages mounted on external media. This involves deleting package 15384 * data from internal structures, sending broadcasts about diabled packages, 15385 * gc'ing to free up references, unmounting all secure containers 15386 * corresponding to packages on external media, and posting a 15387 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15388 * that we always have to post this message if status has been requested no 15389 * matter what. 15390 */ 15391 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15392 final boolean reportStatus) { 15393 if (DEBUG_SD_INSTALL) 15394 Log.i(TAG, "unloading media packages"); 15395 ArrayList<String> pkgList = new ArrayList<String>(); 15396 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15397 final Set<AsecInstallArgs> keys = processCids.keySet(); 15398 for (AsecInstallArgs args : keys) { 15399 String pkgName = args.getPackageName(); 15400 if (DEBUG_SD_INSTALL) 15401 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15402 // Delete package internally 15403 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15404 synchronized (mInstallLock) { 15405 boolean res = deletePackageLI(pkgName, null, false, null, null, 15406 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15407 if (res) { 15408 pkgList.add(pkgName); 15409 } else { 15410 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15411 failedList.add(args); 15412 } 15413 } 15414 } 15415 15416 // reader 15417 synchronized (mPackages) { 15418 // We didn't update the settings after removing each package; 15419 // write them now for all packages. 15420 mSettings.writeLPr(); 15421 } 15422 15423 // We have to absolutely send UPDATED_MEDIA_STATUS only 15424 // after confirming that all the receivers processed the ordered 15425 // broadcast when packages get disabled, force a gc to clean things up. 15426 // and unload all the containers. 15427 if (pkgList.size() > 0) { 15428 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15429 new IIntentReceiver.Stub() { 15430 public void performReceive(Intent intent, int resultCode, String data, 15431 Bundle extras, boolean ordered, boolean sticky, 15432 int sendingUser) throws RemoteException { 15433 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15434 reportStatus ? 1 : 0, 1, keys); 15435 mHandler.sendMessage(msg); 15436 } 15437 }); 15438 } else { 15439 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15440 keys); 15441 mHandler.sendMessage(msg); 15442 } 15443 } 15444 15445 private void loadPrivatePackages(VolumeInfo vol) { 15446 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15447 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15448 synchronized (mInstallLock) { 15449 synchronized (mPackages) { 15450 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15451 for (PackageSetting ps : packages) { 15452 final PackageParser.Package pkg; 15453 try { 15454 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15455 loaded.add(pkg.applicationInfo); 15456 } catch (PackageManagerException e) { 15457 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15458 } 15459 } 15460 15461 // TODO: regrant any permissions that changed based since original install 15462 15463 mSettings.writeLPr(); 15464 } 15465 } 15466 15467 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15468 sendResourcesChangedBroadcast(true, false, loaded, null); 15469 } 15470 15471 private void unloadPrivatePackages(VolumeInfo vol) { 15472 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15473 synchronized (mInstallLock) { 15474 synchronized (mPackages) { 15475 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15476 for (PackageSetting ps : packages) { 15477 if (ps.pkg == null) continue; 15478 15479 final ApplicationInfo info = ps.pkg.applicationInfo; 15480 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15481 if (deletePackageLI(ps.name, null, false, null, null, 15482 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15483 unloaded.add(info); 15484 } else { 15485 Slog.w(TAG, "Failed to unload " + ps.codePath); 15486 } 15487 } 15488 15489 mSettings.writeLPr(); 15490 } 15491 } 15492 15493 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15494 sendResourcesChangedBroadcast(false, false, unloaded, null); 15495 } 15496 15497 /** 15498 * Examine all users present on given mounted volume, and destroy data 15499 * belonging to users that are no longer valid, or whose user ID has been 15500 * recycled. 15501 */ 15502 private void reconcileUsers(String volumeUuid) { 15503 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15504 if (ArrayUtils.isEmpty(files)) { 15505 Slog.d(TAG, "No users found on " + volumeUuid); 15506 return; 15507 } 15508 15509 for (File file : files) { 15510 if (!file.isDirectory()) continue; 15511 15512 final int userId; 15513 final UserInfo info; 15514 try { 15515 userId = Integer.parseInt(file.getName()); 15516 info = sUserManager.getUserInfo(userId); 15517 } catch (NumberFormatException e) { 15518 Slog.w(TAG, "Invalid user directory " + file); 15519 continue; 15520 } 15521 15522 boolean destroyUser = false; 15523 if (info == null) { 15524 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15525 + " because no matching user was found"); 15526 destroyUser = true; 15527 } else { 15528 try { 15529 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15530 } catch (IOException e) { 15531 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15532 + " because we failed to enforce serial number: " + e); 15533 destroyUser = true; 15534 } 15535 } 15536 15537 if (destroyUser) { 15538 synchronized (mInstallLock) { 15539 mInstaller.removeUserDataDirs(volumeUuid, userId); 15540 } 15541 } 15542 } 15543 15544 final UserManager um = mContext.getSystemService(UserManager.class); 15545 for (UserInfo user : um.getUsers()) { 15546 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15547 if (userDir.exists()) continue; 15548 15549 try { 15550 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15551 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15552 } catch (IOException e) { 15553 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15554 } 15555 } 15556 } 15557 15558 /** 15559 * Examine all apps present on given mounted volume, and destroy apps that 15560 * aren't expected, either due to uninstallation or reinstallation on 15561 * another volume. 15562 */ 15563 private void reconcileApps(String volumeUuid) { 15564 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15565 if (ArrayUtils.isEmpty(files)) { 15566 Slog.d(TAG, "No apps found on " + volumeUuid); 15567 return; 15568 } 15569 15570 for (File file : files) { 15571 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15572 && !PackageInstallerService.isStageName(file.getName()); 15573 if (!isPackage) { 15574 // Ignore entries which are not packages 15575 continue; 15576 } 15577 15578 boolean destroyApp = false; 15579 String packageName = null; 15580 try { 15581 final PackageLite pkg = PackageParser.parsePackageLite(file, 15582 PackageParser.PARSE_MUST_BE_APK); 15583 packageName = pkg.packageName; 15584 15585 synchronized (mPackages) { 15586 final PackageSetting ps = mSettings.mPackages.get(packageName); 15587 if (ps == null) { 15588 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15589 + volumeUuid + " because we found no install record"); 15590 destroyApp = true; 15591 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15592 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15593 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15594 destroyApp = true; 15595 } 15596 } 15597 15598 } catch (PackageParserException e) { 15599 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15600 destroyApp = true; 15601 } 15602 15603 if (destroyApp) { 15604 synchronized (mInstallLock) { 15605 if (packageName != null) { 15606 removeDataDirsLI(volumeUuid, packageName); 15607 } 15608 if (file.isDirectory()) { 15609 mInstaller.rmPackageDir(file.getAbsolutePath()); 15610 } else { 15611 file.delete(); 15612 } 15613 } 15614 } 15615 } 15616 } 15617 15618 private void unfreezePackage(String packageName) { 15619 synchronized (mPackages) { 15620 final PackageSetting ps = mSettings.mPackages.get(packageName); 15621 if (ps != null) { 15622 ps.frozen = false; 15623 } 15624 } 15625 } 15626 15627 @Override 15628 public int movePackage(final String packageName, final String volumeUuid) { 15629 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15630 15631 final int moveId = mNextMoveId.getAndIncrement(); 15632 try { 15633 movePackageInternal(packageName, volumeUuid, moveId); 15634 } catch (PackageManagerException e) { 15635 Slog.w(TAG, "Failed to move " + packageName, e); 15636 mMoveCallbacks.notifyStatusChanged(moveId, 15637 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15638 } 15639 return moveId; 15640 } 15641 15642 private void movePackageInternal(final String packageName, final String volumeUuid, 15643 final int moveId) throws PackageManagerException { 15644 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15645 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15646 final PackageManager pm = mContext.getPackageManager(); 15647 15648 final boolean currentAsec; 15649 final String currentVolumeUuid; 15650 final File codeFile; 15651 final String installerPackageName; 15652 final String packageAbiOverride; 15653 final int appId; 15654 final String seinfo; 15655 final String label; 15656 15657 // reader 15658 synchronized (mPackages) { 15659 final PackageParser.Package pkg = mPackages.get(packageName); 15660 final PackageSetting ps = mSettings.mPackages.get(packageName); 15661 if (pkg == null || ps == null) { 15662 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15663 } 15664 15665 if (pkg.applicationInfo.isSystemApp()) { 15666 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15667 "Cannot move system application"); 15668 } 15669 15670 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15671 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15672 "Package already moved to " + volumeUuid); 15673 } 15674 15675 final File probe = new File(pkg.codePath); 15676 final File probeOat = new File(probe, "oat"); 15677 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15678 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15679 "Move only supported for modern cluster style installs"); 15680 } 15681 15682 if (ps.frozen) { 15683 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15684 "Failed to move already frozen package"); 15685 } 15686 ps.frozen = true; 15687 15688 currentAsec = pkg.applicationInfo.isForwardLocked() 15689 || pkg.applicationInfo.isExternalAsec(); 15690 currentVolumeUuid = ps.volumeUuid; 15691 codeFile = new File(pkg.codePath); 15692 installerPackageName = ps.installerPackageName; 15693 packageAbiOverride = ps.cpuAbiOverrideString; 15694 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15695 seinfo = pkg.applicationInfo.seinfo; 15696 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15697 } 15698 15699 // Now that we're guarded by frozen state, kill app during move 15700 killApplication(packageName, appId, "move pkg"); 15701 15702 final Bundle extras = new Bundle(); 15703 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15704 extras.putString(Intent.EXTRA_TITLE, label); 15705 mMoveCallbacks.notifyCreated(moveId, extras); 15706 15707 int installFlags; 15708 final boolean moveCompleteApp; 15709 final File measurePath; 15710 15711 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15712 installFlags = INSTALL_INTERNAL; 15713 moveCompleteApp = !currentAsec; 15714 measurePath = Environment.getDataAppDirectory(volumeUuid); 15715 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15716 installFlags = INSTALL_EXTERNAL; 15717 moveCompleteApp = false; 15718 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15719 } else { 15720 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15721 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15722 || !volume.isMountedWritable()) { 15723 unfreezePackage(packageName); 15724 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15725 "Move location not mounted private volume"); 15726 } 15727 15728 Preconditions.checkState(!currentAsec); 15729 15730 installFlags = INSTALL_INTERNAL; 15731 moveCompleteApp = true; 15732 measurePath = Environment.getDataAppDirectory(volumeUuid); 15733 } 15734 15735 final PackageStats stats = new PackageStats(null, -1); 15736 synchronized (mInstaller) { 15737 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15738 unfreezePackage(packageName); 15739 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15740 "Failed to measure package size"); 15741 } 15742 } 15743 15744 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15745 + stats.dataSize); 15746 15747 final long startFreeBytes = measurePath.getFreeSpace(); 15748 final long sizeBytes; 15749 if (moveCompleteApp) { 15750 sizeBytes = stats.codeSize + stats.dataSize; 15751 } else { 15752 sizeBytes = stats.codeSize; 15753 } 15754 15755 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15756 unfreezePackage(packageName); 15757 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15758 "Not enough free space to move"); 15759 } 15760 15761 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15762 15763 final CountDownLatch installedLatch = new CountDownLatch(1); 15764 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15765 @Override 15766 public void onUserActionRequired(Intent intent) throws RemoteException { 15767 throw new IllegalStateException(); 15768 } 15769 15770 @Override 15771 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15772 Bundle extras) throws RemoteException { 15773 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15774 + PackageManager.installStatusToString(returnCode, msg)); 15775 15776 installedLatch.countDown(); 15777 15778 // Regardless of success or failure of the move operation, 15779 // always unfreeze the package 15780 unfreezePackage(packageName); 15781 15782 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15783 switch (status) { 15784 case PackageInstaller.STATUS_SUCCESS: 15785 mMoveCallbacks.notifyStatusChanged(moveId, 15786 PackageManager.MOVE_SUCCEEDED); 15787 break; 15788 case PackageInstaller.STATUS_FAILURE_STORAGE: 15789 mMoveCallbacks.notifyStatusChanged(moveId, 15790 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15791 break; 15792 default: 15793 mMoveCallbacks.notifyStatusChanged(moveId, 15794 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15795 break; 15796 } 15797 } 15798 }; 15799 15800 final MoveInfo move; 15801 if (moveCompleteApp) { 15802 // Kick off a thread to report progress estimates 15803 new Thread() { 15804 @Override 15805 public void run() { 15806 while (true) { 15807 try { 15808 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15809 break; 15810 } 15811 } catch (InterruptedException ignored) { 15812 } 15813 15814 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15815 final int progress = 10 + (int) MathUtils.constrain( 15816 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15817 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15818 } 15819 } 15820 }.start(); 15821 15822 final String dataAppName = codeFile.getName(); 15823 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15824 dataAppName, appId, seinfo); 15825 } else { 15826 move = null; 15827 } 15828 15829 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15830 15831 final Message msg = mHandler.obtainMessage(INIT_COPY); 15832 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15833 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15834 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15835 mHandler.sendMessage(msg); 15836 } 15837 15838 @Override 15839 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15840 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15841 15842 final int realMoveId = mNextMoveId.getAndIncrement(); 15843 final Bundle extras = new Bundle(); 15844 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15845 mMoveCallbacks.notifyCreated(realMoveId, extras); 15846 15847 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15848 @Override 15849 public void onCreated(int moveId, Bundle extras) { 15850 // Ignored 15851 } 15852 15853 @Override 15854 public void onStatusChanged(int moveId, int status, long estMillis) { 15855 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15856 } 15857 }; 15858 15859 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15860 storage.setPrimaryStorageUuid(volumeUuid, callback); 15861 return realMoveId; 15862 } 15863 15864 @Override 15865 public int getMoveStatus(int moveId) { 15866 mContext.enforceCallingOrSelfPermission( 15867 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15868 return mMoveCallbacks.mLastStatus.get(moveId); 15869 } 15870 15871 @Override 15872 public void registerMoveCallback(IPackageMoveObserver callback) { 15873 mContext.enforceCallingOrSelfPermission( 15874 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15875 mMoveCallbacks.register(callback); 15876 } 15877 15878 @Override 15879 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15880 mContext.enforceCallingOrSelfPermission( 15881 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15882 mMoveCallbacks.unregister(callback); 15883 } 15884 15885 @Override 15886 public boolean setInstallLocation(int loc) { 15887 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15888 null); 15889 if (getInstallLocation() == loc) { 15890 return true; 15891 } 15892 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15893 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15894 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15895 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15896 return true; 15897 } 15898 return false; 15899 } 15900 15901 @Override 15902 public int getInstallLocation() { 15903 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15904 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15905 PackageHelper.APP_INSTALL_AUTO); 15906 } 15907 15908 /** Called by UserManagerService */ 15909 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15910 mDirtyUsers.remove(userHandle); 15911 mSettings.removeUserLPw(userHandle); 15912 mPendingBroadcasts.remove(userHandle); 15913 if (mInstaller != null) { 15914 // Technically, we shouldn't be doing this with the package lock 15915 // held. However, this is very rare, and there is already so much 15916 // other disk I/O going on, that we'll let it slide for now. 15917 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15918 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15919 final String volumeUuid = vol.getFsUuid(); 15920 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15921 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15922 } 15923 } 15924 mUserNeedsBadging.delete(userHandle); 15925 removeUnusedPackagesLILPw(userManager, userHandle); 15926 } 15927 15928 /** 15929 * We're removing userHandle and would like to remove any downloaded packages 15930 * that are no longer in use by any other user. 15931 * @param userHandle the user being removed 15932 */ 15933 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15934 final boolean DEBUG_CLEAN_APKS = false; 15935 int [] users = userManager.getUserIdsLPr(); 15936 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15937 while (psit.hasNext()) { 15938 PackageSetting ps = psit.next(); 15939 if (ps.pkg == null) { 15940 continue; 15941 } 15942 final String packageName = ps.pkg.packageName; 15943 // Skip over if system app 15944 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15945 continue; 15946 } 15947 if (DEBUG_CLEAN_APKS) { 15948 Slog.i(TAG, "Checking package " + packageName); 15949 } 15950 boolean keep = false; 15951 for (int i = 0; i < users.length; i++) { 15952 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15953 keep = true; 15954 if (DEBUG_CLEAN_APKS) { 15955 Slog.i(TAG, " Keeping package " + packageName + " for user " 15956 + users[i]); 15957 } 15958 break; 15959 } 15960 } 15961 if (!keep) { 15962 if (DEBUG_CLEAN_APKS) { 15963 Slog.i(TAG, " Removing package " + packageName); 15964 } 15965 mHandler.post(new Runnable() { 15966 public void run() { 15967 deletePackageX(packageName, userHandle, 0); 15968 } //end run 15969 }); 15970 } 15971 } 15972 } 15973 15974 /** Called by UserManagerService */ 15975 void createNewUserLILPw(int userHandle) { 15976 if (mInstaller != null) { 15977 mInstaller.createUserConfig(userHandle); 15978 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15979 applyFactoryDefaultBrowserLPw(userHandle); 15980 primeDomainVerificationsLPw(userHandle); 15981 } 15982 } 15983 15984 void newUserCreated(final int userHandle) { 15985 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15986 } 15987 15988 @Override 15989 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15990 mContext.enforceCallingOrSelfPermission( 15991 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15992 "Only package verification agents can read the verifier device identity"); 15993 15994 synchronized (mPackages) { 15995 return mSettings.getVerifierDeviceIdentityLPw(); 15996 } 15997 } 15998 15999 @Override 16000 public void setPermissionEnforced(String permission, boolean enforced) { 16001 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 16002 if (READ_EXTERNAL_STORAGE.equals(permission)) { 16003 synchronized (mPackages) { 16004 if (mSettings.mReadExternalStorageEnforced == null 16005 || mSettings.mReadExternalStorageEnforced != enforced) { 16006 mSettings.mReadExternalStorageEnforced = enforced; 16007 mSettings.writeLPr(); 16008 } 16009 } 16010 // kill any non-foreground processes so we restart them and 16011 // grant/revoke the GID. 16012 final IActivityManager am = ActivityManagerNative.getDefault(); 16013 if (am != null) { 16014 final long token = Binder.clearCallingIdentity(); 16015 try { 16016 am.killProcessesBelowForeground("setPermissionEnforcement"); 16017 } catch (RemoteException e) { 16018 } finally { 16019 Binder.restoreCallingIdentity(token); 16020 } 16021 } 16022 } else { 16023 throw new IllegalArgumentException("No selective enforcement for " + permission); 16024 } 16025 } 16026 16027 @Override 16028 @Deprecated 16029 public boolean isPermissionEnforced(String permission) { 16030 return true; 16031 } 16032 16033 @Override 16034 public boolean isStorageLow() { 16035 final long token = Binder.clearCallingIdentity(); 16036 try { 16037 final DeviceStorageMonitorInternal 16038 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 16039 if (dsm != null) { 16040 return dsm.isMemoryLow(); 16041 } else { 16042 return false; 16043 } 16044 } finally { 16045 Binder.restoreCallingIdentity(token); 16046 } 16047 } 16048 16049 @Override 16050 public IPackageInstaller getPackageInstaller() { 16051 return mInstallerService; 16052 } 16053 16054 private boolean userNeedsBadging(int userId) { 16055 int index = mUserNeedsBadging.indexOfKey(userId); 16056 if (index < 0) { 16057 final UserInfo userInfo; 16058 final long token = Binder.clearCallingIdentity(); 16059 try { 16060 userInfo = sUserManager.getUserInfo(userId); 16061 } finally { 16062 Binder.restoreCallingIdentity(token); 16063 } 16064 final boolean b; 16065 if (userInfo != null && userInfo.isManagedProfile()) { 16066 b = true; 16067 } else { 16068 b = false; 16069 } 16070 mUserNeedsBadging.put(userId, b); 16071 return b; 16072 } 16073 return mUserNeedsBadging.valueAt(index); 16074 } 16075 16076 @Override 16077 public KeySet getKeySetByAlias(String packageName, String alias) { 16078 if (packageName == null || alias == null) { 16079 return null; 16080 } 16081 synchronized(mPackages) { 16082 final PackageParser.Package pkg = mPackages.get(packageName); 16083 if (pkg == null) { 16084 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16085 throw new IllegalArgumentException("Unknown package: " + packageName); 16086 } 16087 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16088 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16089 } 16090 } 16091 16092 @Override 16093 public KeySet getSigningKeySet(String packageName) { 16094 if (packageName == null) { 16095 return null; 16096 } 16097 synchronized(mPackages) { 16098 final PackageParser.Package pkg = mPackages.get(packageName); 16099 if (pkg == null) { 16100 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16101 throw new IllegalArgumentException("Unknown package: " + packageName); 16102 } 16103 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16104 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16105 throw new SecurityException("May not access signing KeySet of other apps."); 16106 } 16107 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16108 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16109 } 16110 } 16111 16112 @Override 16113 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16114 if (packageName == null || ks == null) { 16115 return false; 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 IBinder ksh = ks.getToken(); 16124 if (ksh instanceof KeySetHandle) { 16125 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16126 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16127 } 16128 return false; 16129 } 16130 } 16131 16132 @Override 16133 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16134 if (packageName == null || ks == null) { 16135 return false; 16136 } 16137 synchronized(mPackages) { 16138 final PackageParser.Package pkg = mPackages.get(packageName); 16139 if (pkg == null) { 16140 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16141 throw new IllegalArgumentException("Unknown package: " + packageName); 16142 } 16143 IBinder ksh = ks.getToken(); 16144 if (ksh instanceof KeySetHandle) { 16145 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16146 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16147 } 16148 return false; 16149 } 16150 } 16151 16152 public void getUsageStatsIfNoPackageUsageInfo() { 16153 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16154 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16155 if (usm == null) { 16156 throw new IllegalStateException("UsageStatsManager must be initialized"); 16157 } 16158 long now = System.currentTimeMillis(); 16159 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16160 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16161 String packageName = entry.getKey(); 16162 PackageParser.Package pkg = mPackages.get(packageName); 16163 if (pkg == null) { 16164 continue; 16165 } 16166 UsageStats usage = entry.getValue(); 16167 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16168 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16169 } 16170 } 16171 } 16172 16173 /** 16174 * Check and throw if the given before/after packages would be considered a 16175 * downgrade. 16176 */ 16177 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16178 throws PackageManagerException { 16179 if (after.versionCode < before.mVersionCode) { 16180 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16181 "Update version code " + after.versionCode + " is older than current " 16182 + before.mVersionCode); 16183 } else if (after.versionCode == before.mVersionCode) { 16184 if (after.baseRevisionCode < before.baseRevisionCode) { 16185 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16186 "Update base revision code " + after.baseRevisionCode 16187 + " is older than current " + before.baseRevisionCode); 16188 } 16189 16190 if (!ArrayUtils.isEmpty(after.splitNames)) { 16191 for (int i = 0; i < after.splitNames.length; i++) { 16192 final String splitName = after.splitNames[i]; 16193 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16194 if (j != -1) { 16195 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16196 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16197 "Update split " + splitName + " revision code " 16198 + after.splitRevisionCodes[i] + " is older than current " 16199 + before.splitRevisionCodes[j]); 16200 } 16201 } 16202 } 16203 } 16204 } 16205 } 16206 16207 private static class MoveCallbacks extends Handler { 16208 private static final int MSG_CREATED = 1; 16209 private static final int MSG_STATUS_CHANGED = 2; 16210 16211 private final RemoteCallbackList<IPackageMoveObserver> 16212 mCallbacks = new RemoteCallbackList<>(); 16213 16214 private final SparseIntArray mLastStatus = new SparseIntArray(); 16215 16216 public MoveCallbacks(Looper looper) { 16217 super(looper); 16218 } 16219 16220 public void register(IPackageMoveObserver callback) { 16221 mCallbacks.register(callback); 16222 } 16223 16224 public void unregister(IPackageMoveObserver callback) { 16225 mCallbacks.unregister(callback); 16226 } 16227 16228 @Override 16229 public void handleMessage(Message msg) { 16230 final SomeArgs args = (SomeArgs) msg.obj; 16231 final int n = mCallbacks.beginBroadcast(); 16232 for (int i = 0; i < n; i++) { 16233 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16234 try { 16235 invokeCallback(callback, msg.what, args); 16236 } catch (RemoteException ignored) { 16237 } 16238 } 16239 mCallbacks.finishBroadcast(); 16240 args.recycle(); 16241 } 16242 16243 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16244 throws RemoteException { 16245 switch (what) { 16246 case MSG_CREATED: { 16247 callback.onCreated(args.argi1, (Bundle) args.arg2); 16248 break; 16249 } 16250 case MSG_STATUS_CHANGED: { 16251 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16252 break; 16253 } 16254 } 16255 } 16256 16257 private void notifyCreated(int moveId, Bundle extras) { 16258 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16259 16260 final SomeArgs args = SomeArgs.obtain(); 16261 args.argi1 = moveId; 16262 args.arg2 = extras; 16263 obtainMessage(MSG_CREATED, args).sendToTarget(); 16264 } 16265 16266 private void notifyStatusChanged(int moveId, int status) { 16267 notifyStatusChanged(moveId, status, -1); 16268 } 16269 16270 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16271 Slog.v(TAG, "Move " + moveId + " status " + status); 16272 16273 final SomeArgs args = SomeArgs.obtain(); 16274 args.argi1 = moveId; 16275 args.argi2 = status; 16276 args.arg3 = estMillis; 16277 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16278 16279 synchronized (mLastStatus) { 16280 mLastStatus.put(moveId, status); 16281 } 16282 } 16283 } 16284 16285 private final class OnPermissionChangeListeners extends Handler { 16286 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16287 16288 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16289 new RemoteCallbackList<>(); 16290 16291 public OnPermissionChangeListeners(Looper looper) { 16292 super(looper); 16293 } 16294 16295 @Override 16296 public void handleMessage(Message msg) { 16297 switch (msg.what) { 16298 case MSG_ON_PERMISSIONS_CHANGED: { 16299 final int uid = msg.arg1; 16300 handleOnPermissionsChanged(uid); 16301 } break; 16302 } 16303 } 16304 16305 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16306 mPermissionListeners.register(listener); 16307 16308 } 16309 16310 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16311 mPermissionListeners.unregister(listener); 16312 } 16313 16314 public void onPermissionsChanged(int uid) { 16315 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16316 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16317 } 16318 } 16319 16320 private void handleOnPermissionsChanged(int uid) { 16321 final int count = mPermissionListeners.beginBroadcast(); 16322 try { 16323 for (int i = 0; i < count; i++) { 16324 IOnPermissionsChangeListener callback = mPermissionListeners 16325 .getBroadcastItem(i); 16326 try { 16327 callback.onPermissionsChanged(uid); 16328 } catch (RemoteException e) { 16329 Log.e(TAG, "Permission listener is dead", e); 16330 } 16331 } 16332 } finally { 16333 mPermissionListeners.finishBroadcast(); 16334 } 16335 } 16336 } 16337 16338 private class PackageManagerInternalImpl extends PackageManagerInternal { 16339 @Override 16340 public void setLocationPackagesProvider(PackagesProvider provider) { 16341 synchronized (mPackages) { 16342 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16343 } 16344 } 16345 16346 @Override 16347 public void setImePackagesProvider(PackagesProvider provider) { 16348 synchronized (mPackages) { 16349 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16350 } 16351 } 16352 16353 @Override 16354 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16355 synchronized (mPackages) { 16356 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16357 } 16358 } 16359 16360 @Override 16361 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16362 synchronized (mPackages) { 16363 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16364 } 16365 } 16366 16367 @Override 16368 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16369 synchronized (mPackages) { 16370 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16371 } 16372 } 16373 16374 @Override 16375 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16376 synchronized (mPackages) { 16377 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16378 } 16379 } 16380 16381 @Override 16382 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16383 synchronized (mPackages) { 16384 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16385 packageName, userId); 16386 } 16387 } 16388 16389 @Override 16390 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16391 synchronized (mPackages) { 16392 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16393 packageName, userId); 16394 } 16395 } 16396 } 16397 16398 @Override 16399 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16400 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16401 synchronized (mPackages) { 16402 final long identity = Binder.clearCallingIdentity(); 16403 try { 16404 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16405 packageNames, userId); 16406 } finally { 16407 Binder.restoreCallingIdentity(identity); 16408 } 16409 } 16410 } 16411 16412 private static void enforceSystemOrPhoneCaller(String tag) { 16413 int callingUid = Binder.getCallingUid(); 16414 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16415 throw new SecurityException( 16416 "Cannot call " + tag + " from UID " + callingUid); 16417 } 16418 } 16419} 16420