PackageManagerService.java revision db3fe819902f2bea08746c3e3ea55a9a55e3bac5
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 47import static android.content.pm.PackageManager.INSTALL_INTERNAL; 48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 53import static android.content.pm.PackageManager.MATCH_ALL; 54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 58import static android.content.pm.PackageManager.PERMISSION_GRANTED; 59import static android.content.pm.PackageParser.isApkFile; 60import static android.os.Process.PACKAGE_INFO_GID; 61import static android.os.Process.SYSTEM_UID; 62import static android.system.OsConstants.O_CREAT; 63import static android.system.OsConstants.O_RDWR; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 68import static com.android.internal.util.ArrayUtils.appendInt; 69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 74 75import android.Manifest; 76import android.app.ActivityManager; 77import android.app.ActivityManagerNative; 78import android.app.AppGlobals; 79import android.app.IActivityManager; 80import android.app.admin.IDevicePolicyManager; 81import android.app.backup.IBackupManager; 82import android.app.usage.UsageStats; 83import android.app.usage.UsageStatsManager; 84import android.content.BroadcastReceiver; 85import android.content.ComponentName; 86import android.content.Context; 87import android.content.IIntentReceiver; 88import android.content.Intent; 89import android.content.IntentFilter; 90import android.content.IntentSender; 91import android.content.IntentSender.SendIntentException; 92import android.content.ServiceConnection; 93import android.content.pm.ActivityInfo; 94import android.content.pm.ApplicationInfo; 95import android.content.pm.FeatureInfo; 96import android.content.pm.IOnPermissionsChangeListener; 97import android.content.pm.IPackageDataObserver; 98import android.content.pm.IPackageDeleteObserver; 99import android.content.pm.IPackageDeleteObserver2; 100import android.content.pm.IPackageInstallObserver2; 101import android.content.pm.IPackageInstaller; 102import android.content.pm.IPackageManager; 103import android.content.pm.IPackageMoveObserver; 104import android.content.pm.IPackageStatsObserver; 105import android.content.pm.IPackagesProvider; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.IntentFilterVerificationInfo; 108import android.content.pm.KeySet; 109import android.content.pm.ManifestDigest; 110import android.content.pm.PackageCleanItem; 111import android.content.pm.PackageInfo; 112import android.content.pm.PackageInfoLite; 113import android.content.pm.PackageInstaller; 114import android.content.pm.PackageManager; 115import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 116import android.content.pm.PackageManagerInternal; 117import android.content.pm.PackageParser; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageStats; 122import android.content.pm.PackageUserState; 123import android.content.pm.ParceledListSlice; 124import android.content.pm.PermissionGroupInfo; 125import android.content.pm.PermissionInfo; 126import android.content.pm.ProviderInfo; 127import android.content.pm.ResolveInfo; 128import android.content.pm.ServiceInfo; 129import android.content.pm.Signature; 130import android.content.pm.UserInfo; 131import android.content.pm.VerificationParams; 132import android.content.pm.VerifierDeviceIdentity; 133import android.content.pm.VerifierInfo; 134import android.content.res.Resources; 135import android.hardware.display.DisplayManager; 136import android.net.Uri; 137import android.os.Binder; 138import android.os.Build; 139import android.os.Bundle; 140import android.os.Debug; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.FileUtils; 144import android.os.Handler; 145import android.os.IBinder; 146import android.os.Looper; 147import android.os.Message; 148import android.os.Parcel; 149import android.os.ParcelFileDescriptor; 150import android.os.Process; 151import android.os.RemoteCallbackList; 152import android.os.RemoteException; 153import android.os.SELinux; 154import android.os.ServiceManager; 155import android.os.SystemClock; 156import android.os.SystemProperties; 157import android.os.UserHandle; 158import android.os.UserManager; 159import android.os.storage.IMountService; 160import android.os.storage.StorageEventListener; 161import android.os.storage.StorageManager; 162import android.os.storage.VolumeInfo; 163import android.os.storage.VolumeRecord; 164import android.security.KeyStore; 165import android.security.SystemKeyStore; 166import android.system.ErrnoException; 167import android.system.Os; 168import android.system.StructStat; 169import android.text.TextUtils; 170import android.text.format.DateUtils; 171import android.util.ArrayMap; 172import android.util.ArraySet; 173import android.util.AtomicFile; 174import android.util.DisplayMetrics; 175import android.util.EventLog; 176import android.util.ExceptionUtils; 177import android.util.Log; 178import android.util.LogPrinter; 179import android.util.MathUtils; 180import android.util.PrintStreamPrinter; 181import android.util.Slog; 182import android.util.SparseArray; 183import android.util.SparseBooleanArray; 184import android.util.SparseIntArray; 185import android.util.Xml; 186import android.view.Display; 187 188import dalvik.system.DexFile; 189import dalvik.system.VMRuntime; 190 191import libcore.io.IoUtils; 192import libcore.util.EmptyArray; 193 194import com.android.internal.R; 195import com.android.internal.app.IMediaContainerService; 196import com.android.internal.app.ResolverActivity; 197import com.android.internal.content.NativeLibraryHelper; 198import com.android.internal.content.PackageHelper; 199import com.android.internal.os.IParcelFileDescriptorFactory; 200import com.android.internal.os.SomeArgs; 201import com.android.internal.os.Zygote; 202import com.android.internal.util.ArrayUtils; 203import com.android.internal.util.FastPrintWriter; 204import com.android.internal.util.FastXmlSerializer; 205import com.android.internal.util.IndentingPrintWriter; 206import com.android.internal.util.Preconditions; 207import com.android.server.EventLogTags; 208import com.android.server.FgThread; 209import com.android.server.IntentResolver; 210import com.android.server.LocalServices; 211import com.android.server.ServiceThread; 212import com.android.server.SystemConfig; 213import com.android.server.Watchdog; 214import com.android.server.pm.PermissionsState.PermissionState; 215import com.android.server.pm.Settings.DatabaseVersion; 216import com.android.server.storage.DeviceStorageMonitorInternal; 217 218import org.xmlpull.v1.XmlPullParser; 219import org.xmlpull.v1.XmlPullParserException; 220import org.xmlpull.v1.XmlSerializer; 221 222import java.io.BufferedInputStream; 223import java.io.BufferedOutputStream; 224import java.io.BufferedReader; 225import java.io.ByteArrayInputStream; 226import java.io.ByteArrayOutputStream; 227import java.io.File; 228import java.io.FileDescriptor; 229import java.io.FileNotFoundException; 230import java.io.FileOutputStream; 231import java.io.FileReader; 232import java.io.FilenameFilter; 233import java.io.IOException; 234import java.io.InputStream; 235import java.io.PrintWriter; 236import java.nio.charset.StandardCharsets; 237import java.security.NoSuchAlgorithmException; 238import java.security.PublicKey; 239import java.security.cert.CertificateEncodingException; 240import java.security.cert.CertificateException; 241import java.text.SimpleDateFormat; 242import java.util.ArrayList; 243import java.util.Arrays; 244import java.util.Collection; 245import java.util.Collections; 246import java.util.Comparator; 247import java.util.Date; 248import java.util.Iterator; 249import java.util.List; 250import java.util.Map; 251import java.util.Objects; 252import java.util.Set; 253import java.util.concurrent.CountDownLatch; 254import java.util.concurrent.TimeUnit; 255import java.util.concurrent.atomic.AtomicBoolean; 256import java.util.concurrent.atomic.AtomicInteger; 257import java.util.concurrent.atomic.AtomicLong; 258 259/** 260 * Keep track of all those .apks everywhere. 261 * 262 * This is very central to the platform's security; please run the unit 263 * tests whenever making modifications here: 264 * 265mmm frameworks/base/tests/AndroidTests 266adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 267adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 268 * 269 * {@hide} 270 */ 271public class PackageManagerService extends IPackageManager.Stub { 272 static final String TAG = "PackageManager"; 273 static final boolean DEBUG_SETTINGS = false; 274 static final boolean DEBUG_PREFERRED = false; 275 static final boolean DEBUG_UPGRADE = false; 276 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 277 private static final boolean DEBUG_BACKUP = true; 278 private static final boolean DEBUG_INSTALL = false; 279 private static final boolean DEBUG_REMOVE = false; 280 private static final boolean DEBUG_BROADCASTS = false; 281 private static final boolean DEBUG_SHOW_INFO = false; 282 private static final boolean DEBUG_PACKAGE_INFO = false; 283 private static final boolean DEBUG_INTENT_MATCHING = false; 284 private static final boolean DEBUG_PACKAGE_SCANNING = false; 285 private static final boolean DEBUG_VERIFY = false; 286 private static final boolean DEBUG_DEXOPT = false; 287 private static final boolean DEBUG_ABI_SELECTION = false; 288 289 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 290 291 private static final int RADIO_UID = Process.PHONE_UID; 292 private static final int LOG_UID = Process.LOG_UID; 293 private static final int NFC_UID = Process.NFC_UID; 294 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 295 private static final int SHELL_UID = Process.SHELL_UID; 296 297 // Cap the size of permission trees that 3rd party apps can define 298 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 299 300 // Suffix used during package installation when copying/moving 301 // package apks to install directory. 302 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 303 304 static final int SCAN_NO_DEX = 1<<1; 305 static final int SCAN_FORCE_DEX = 1<<2; 306 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 307 static final int SCAN_NEW_INSTALL = 1<<4; 308 static final int SCAN_NO_PATHS = 1<<5; 309 static final int SCAN_UPDATE_TIME = 1<<6; 310 static final int SCAN_DEFER_DEX = 1<<7; 311 static final int SCAN_BOOTING = 1<<8; 312 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 313 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 314 static final int SCAN_REQUIRE_KNOWN = 1<<12; 315 static final int SCAN_MOVE = 1<<13; 316 static final int SCAN_INITIAL = 1<<14; 317 318 static final int REMOVE_CHATTY = 1<<16; 319 320 private static final int[] EMPTY_INT_ARRAY = new int[0]; 321 322 /** 323 * Timeout (in milliseconds) after which the watchdog should declare that 324 * our handler thread is wedged. The usual default for such things is one 325 * minute but we sometimes do very lengthy I/O operations on this thread, 326 * such as installing multi-gigabyte applications, so ours needs to be longer. 327 */ 328 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 329 330 /** 331 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 332 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 333 * settings entry if available, otherwise we use the hardcoded default. If it's been 334 * more than this long since the last fstrim, we force one during the boot sequence. 335 * 336 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 337 * one gets run at the next available charging+idle time. This final mandatory 338 * no-fstrim check kicks in only of the other scheduling criteria is never met. 339 */ 340 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 341 342 /** 343 * Whether verification is enabled by default. 344 */ 345 private static final boolean DEFAULT_VERIFY_ENABLE = true; 346 347 /** 348 * The default maximum time to wait for the verification agent to return in 349 * milliseconds. 350 */ 351 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 352 353 /** 354 * The default response for package verification timeout. 355 * 356 * This can be either PackageManager.VERIFICATION_ALLOW or 357 * PackageManager.VERIFICATION_REJECT. 358 */ 359 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 360 361 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 362 363 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 364 DEFAULT_CONTAINER_PACKAGE, 365 "com.android.defcontainer.DefaultContainerService"); 366 367 private static final String KILL_APP_REASON_GIDS_CHANGED = 368 "permission grant or revoke changed gids"; 369 370 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 371 "permissions revoked"; 372 373 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 374 375 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 376 377 /** Permission grant: not grant the permission. */ 378 private static final int GRANT_DENIED = 1; 379 380 /** Permission grant: grant the permission as an install permission. */ 381 private static final int GRANT_INSTALL = 2; 382 383 /** Permission grant: grant the permission as an install permission for a legacy app. */ 384 private static final int GRANT_INSTALL_LEGACY = 3; 385 386 /** Permission grant: grant the permission as a runtime one. */ 387 private static final int GRANT_RUNTIME = 4; 388 389 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 390 private static final int GRANT_UPGRADE = 5; 391 392 final ServiceThread mHandlerThread; 393 394 final PackageHandler mHandler; 395 396 /** 397 * Messages for {@link #mHandler} that need to wait for system ready before 398 * being dispatched. 399 */ 400 private ArrayList<Message> mPostSystemReadyMessages; 401 402 final int mSdkVersion = Build.VERSION.SDK_INT; 403 404 final Context mContext; 405 final boolean mFactoryTest; 406 final boolean mOnlyCore; 407 final boolean mLazyDexOpt; 408 final long mDexOptLRUThresholdInMills; 409 final DisplayMetrics mMetrics; 410 final int mDefParseFlags; 411 final String[] mSeparateProcesses; 412 final boolean mIsUpgrade; 413 414 // This is where all application persistent data goes. 415 final File mAppDataDir; 416 417 // This is where all application persistent data goes for secondary users. 418 final File mUserAppDataDir; 419 420 /** The location for ASEC container files on internal storage. */ 421 final String mAsecInternalPath; 422 423 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 424 // LOCK HELD. Can be called with mInstallLock held. 425 final Installer mInstaller; 426 427 /** Directory where installed third-party apps stored */ 428 final File mAppInstallDir; 429 430 /** 431 * Directory to which applications installed internally have their 432 * 32 bit native libraries copied. 433 */ 434 private File mAppLib32InstallDir; 435 436 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 437 // apps. 438 final File mDrmAppPrivateInstallDir; 439 440 // ---------------------------------------------------------------- 441 442 // Lock for state used when installing and doing other long running 443 // operations. Methods that must be called with this lock held have 444 // the suffix "LI". 445 final Object mInstallLock = new Object(); 446 447 // ---------------------------------------------------------------- 448 449 // Keys are String (package name), values are Package. This also serves 450 // as the lock for the global state. Methods that must be called with 451 // this lock held have the prefix "LP". 452 final ArrayMap<String, PackageParser.Package> mPackages = 453 new ArrayMap<String, PackageParser.Package>(); 454 455 // Tracks available target package names -> overlay package paths. 456 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 457 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 458 459 final Settings mSettings; 460 boolean mRestoredSettings; 461 462 // System configuration read by SystemConfig. 463 final int[] mGlobalGids; 464 final SparseArray<ArraySet<String>> mSystemPermissions; 465 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 466 467 // If mac_permissions.xml was found for seinfo labeling. 468 boolean mFoundPolicyFile; 469 470 // If a recursive restorecon of /data/data/<pkg> is needed. 471 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 472 473 public static final class SharedLibraryEntry { 474 public final String path; 475 public final String apk; 476 477 SharedLibraryEntry(String _path, String _apk) { 478 path = _path; 479 apk = _apk; 480 } 481 } 482 483 // Currently known shared libraries. 484 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 485 new ArrayMap<String, SharedLibraryEntry>(); 486 487 // All available activities, for your resolving pleasure. 488 final ActivityIntentResolver mActivities = 489 new ActivityIntentResolver(); 490 491 // All available receivers, for your resolving pleasure. 492 final ActivityIntentResolver mReceivers = 493 new ActivityIntentResolver(); 494 495 // All available services, for your resolving pleasure. 496 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 497 498 // All available providers, for your resolving pleasure. 499 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 500 501 // Mapping from provider base names (first directory in content URI codePath) 502 // to the provider information. 503 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 504 new ArrayMap<String, PackageParser.Provider>(); 505 506 // Mapping from instrumentation class names to info about them. 507 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 508 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 509 510 // Mapping from permission names to info about them. 511 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 512 new ArrayMap<String, PackageParser.PermissionGroup>(); 513 514 // Packages whose data we have transfered into another package, thus 515 // should no longer exist. 516 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 517 518 // Broadcast actions that are only available to the system. 519 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 520 521 /** List of packages waiting for verification. */ 522 final SparseArray<PackageVerificationState> mPendingVerification 523 = new SparseArray<PackageVerificationState>(); 524 525 /** Set of packages associated with each app op permission. */ 526 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 527 528 final PackageInstallerService mInstallerService; 529 530 private final PackageDexOptimizer mPackageDexOptimizer; 531 532 private AtomicInteger mNextMoveId = new AtomicInteger(); 533 private final MoveCallbacks mMoveCallbacks; 534 535 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 536 537 // Cache of users who need badging. 538 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 539 540 /** Token for keys in mPendingVerification. */ 541 private int mPendingVerificationToken = 0; 542 543 volatile boolean mSystemReady; 544 volatile boolean mSafeMode; 545 volatile boolean mHasSystemUidErrors; 546 547 ApplicationInfo mAndroidApplication; 548 final ActivityInfo mResolveActivity = new ActivityInfo(); 549 final ResolveInfo mResolveInfo = new ResolveInfo(); 550 ComponentName mResolveComponentName; 551 PackageParser.Package mPlatformPackage; 552 ComponentName mCustomResolverComponentName; 553 554 boolean mResolverReplaced = false; 555 556 private final ComponentName mIntentFilterVerifierComponent; 557 private int mIntentFilterVerificationToken = 0; 558 559 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 560 = new SparseArray<IntentFilterVerificationState>(); 561 562 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 563 new DefaultPermissionGrantPolicy(this); 564 565 private static class IFVerificationParams { 566 PackageParser.Package pkg; 567 boolean replacing; 568 int userId; 569 int verifierUid; 570 571 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 572 int _userId, int _verifierUid) { 573 pkg = _pkg; 574 replacing = _replacing; 575 userId = _userId; 576 replacing = _replacing; 577 verifierUid = _verifierUid; 578 } 579 } 580 581 private interface IntentFilterVerifier<T extends IntentFilter> { 582 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 583 T filter, String packageName); 584 void startVerifications(int userId); 585 void receiveVerificationResponse(int verificationId); 586 } 587 588 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 589 private Context mContext; 590 private ComponentName mIntentFilterVerifierComponent; 591 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 592 593 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 594 mContext = context; 595 mIntentFilterVerifierComponent = verifierComponent; 596 } 597 598 private String getDefaultScheme() { 599 return IntentFilter.SCHEME_HTTPS; 600 } 601 602 @Override 603 public void startVerifications(int userId) { 604 // Launch verifications requests 605 int count = mCurrentIntentFilterVerifications.size(); 606 for (int n=0; n<count; n++) { 607 int verificationId = mCurrentIntentFilterVerifications.get(n); 608 final IntentFilterVerificationState ivs = 609 mIntentFilterVerificationStates.get(verificationId); 610 611 String packageName = ivs.getPackageName(); 612 613 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 614 final int filterCount = filters.size(); 615 ArraySet<String> domainsSet = new ArraySet<>(); 616 for (int m=0; m<filterCount; m++) { 617 PackageParser.ActivityIntentInfo filter = filters.get(m); 618 domainsSet.addAll(filter.getHostsList()); 619 } 620 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 621 synchronized (mPackages) { 622 if (mSettings.createIntentFilterVerificationIfNeededLPw( 623 packageName, domainsList) != null) { 624 scheduleWriteSettingsLocked(); 625 } 626 } 627 sendVerificationRequest(userId, verificationId, ivs); 628 } 629 mCurrentIntentFilterVerifications.clear(); 630 } 631 632 private void sendVerificationRequest(int userId, int verificationId, 633 IntentFilterVerificationState ivs) { 634 635 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 636 verificationIntent.putExtra( 637 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 638 verificationId); 639 verificationIntent.putExtra( 640 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 641 getDefaultScheme()); 642 verificationIntent.putExtra( 643 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 644 ivs.getHostsString()); 645 verificationIntent.putExtra( 646 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 647 ivs.getPackageName()); 648 verificationIntent.setComponent(mIntentFilterVerifierComponent); 649 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 650 651 UserHandle user = new UserHandle(userId); 652 mContext.sendBroadcastAsUser(verificationIntent, user); 653 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 654 "Sending IntentFilter verification broadcast"); 655 } 656 657 public void receiveVerificationResponse(int verificationId) { 658 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 659 660 final boolean verified = ivs.isVerified(); 661 662 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 663 final int count = filters.size(); 664 if (DEBUG_DOMAIN_VERIFICATION) { 665 Slog.i(TAG, "Received verification response " + verificationId 666 + " for " + count + " filters, verified=" + verified); 667 } 668 for (int n=0; n<count; n++) { 669 PackageParser.ActivityIntentInfo filter = filters.get(n); 670 filter.setVerified(verified); 671 672 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 673 + " verified with result:" + verified + " and hosts:" 674 + ivs.getHostsString()); 675 } 676 677 mIntentFilterVerificationStates.remove(verificationId); 678 679 final String packageName = ivs.getPackageName(); 680 IntentFilterVerificationInfo ivi = null; 681 682 synchronized (mPackages) { 683 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 684 } 685 if (ivi == null) { 686 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 687 + verificationId + " packageName:" + packageName); 688 return; 689 } 690 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 691 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 692 693 synchronized (mPackages) { 694 if (verified) { 695 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 696 } else { 697 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 698 } 699 scheduleWriteSettingsLocked(); 700 701 final int userId = ivs.getUserId(); 702 if (userId != UserHandle.USER_ALL) { 703 final int userStatus = 704 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 705 706 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 707 boolean needUpdate = false; 708 709 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 710 // already been set by the User thru the Disambiguation dialog 711 switch (userStatus) { 712 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 713 if (verified) { 714 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 715 } else { 716 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 717 } 718 needUpdate = true; 719 break; 720 721 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 722 if (verified) { 723 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 724 needUpdate = true; 725 } 726 break; 727 728 default: 729 // Nothing to do 730 } 731 732 if (needUpdate) { 733 mSettings.updateIntentFilterVerificationStatusLPw( 734 packageName, updatedStatus, userId); 735 scheduleWritePackageRestrictionsLocked(userId); 736 } 737 } 738 } 739 } 740 741 @Override 742 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 743 ActivityIntentInfo filter, String packageName) { 744 if (!hasValidDomains(filter)) { 745 return false; 746 } 747 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 748 if (ivs == null) { 749 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 750 packageName); 751 } 752 if (DEBUG_DOMAIN_VERIFICATION) { 753 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 754 } 755 ivs.addFilter(filter); 756 return true; 757 } 758 759 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 760 int userId, int verificationId, String packageName) { 761 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 762 verifierUid, userId, packageName); 763 ivs.setPendingState(); 764 synchronized (mPackages) { 765 mIntentFilterVerificationStates.append(verificationId, ivs); 766 mCurrentIntentFilterVerifications.add(verificationId); 767 } 768 return ivs; 769 } 770 } 771 772 private static boolean hasValidDomains(ActivityIntentInfo filter) { 773 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 774 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 775 if (!hasHTTPorHTTPS) { 776 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 777 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 778 return false; 779 } 780 return true; 781 } 782 783 private IntentFilterVerifier mIntentFilterVerifier; 784 785 // Set of pending broadcasts for aggregating enable/disable of components. 786 static class PendingPackageBroadcasts { 787 // for each user id, a map of <package name -> components within that package> 788 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 789 790 public PendingPackageBroadcasts() { 791 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 792 } 793 794 public ArrayList<String> get(int userId, String packageName) { 795 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 796 return packages.get(packageName); 797 } 798 799 public void put(int userId, String packageName, ArrayList<String> components) { 800 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 801 packages.put(packageName, components); 802 } 803 804 public void remove(int userId, String packageName) { 805 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 806 if (packages != null) { 807 packages.remove(packageName); 808 } 809 } 810 811 public void remove(int userId) { 812 mUidMap.remove(userId); 813 } 814 815 public int userIdCount() { 816 return mUidMap.size(); 817 } 818 819 public int userIdAt(int n) { 820 return mUidMap.keyAt(n); 821 } 822 823 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 824 return mUidMap.get(userId); 825 } 826 827 public int size() { 828 // total number of pending broadcast entries across all userIds 829 int num = 0; 830 for (int i = 0; i< mUidMap.size(); i++) { 831 num += mUidMap.valueAt(i).size(); 832 } 833 return num; 834 } 835 836 public void clear() { 837 mUidMap.clear(); 838 } 839 840 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 841 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 842 if (map == null) { 843 map = new ArrayMap<String, ArrayList<String>>(); 844 mUidMap.put(userId, map); 845 } 846 return map; 847 } 848 } 849 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 850 851 // Service Connection to remote media container service to copy 852 // package uri's from external media onto secure containers 853 // or internal storage. 854 private IMediaContainerService mContainerService = null; 855 856 static final int SEND_PENDING_BROADCAST = 1; 857 static final int MCS_BOUND = 3; 858 static final int END_COPY = 4; 859 static final int INIT_COPY = 5; 860 static final int MCS_UNBIND = 6; 861 static final int START_CLEANING_PACKAGE = 7; 862 static final int FIND_INSTALL_LOC = 8; 863 static final int POST_INSTALL = 9; 864 static final int MCS_RECONNECT = 10; 865 static final int MCS_GIVE_UP = 11; 866 static final int UPDATED_MEDIA_STATUS = 12; 867 static final int WRITE_SETTINGS = 13; 868 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 869 static final int PACKAGE_VERIFIED = 15; 870 static final int CHECK_PENDING_VERIFICATION = 16; 871 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 872 static final int INTENT_FILTER_VERIFIED = 18; 873 874 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 875 876 // Delay time in millisecs 877 static final int BROADCAST_DELAY = 10 * 1000; 878 879 static UserManagerService sUserManager; 880 881 // Stores a list of users whose package restrictions file needs to be updated 882 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 883 884 final private DefaultContainerConnection mDefContainerConn = 885 new DefaultContainerConnection(); 886 class DefaultContainerConnection implements ServiceConnection { 887 public void onServiceConnected(ComponentName name, IBinder service) { 888 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 889 IMediaContainerService imcs = 890 IMediaContainerService.Stub.asInterface(service); 891 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 892 } 893 894 public void onServiceDisconnected(ComponentName name) { 895 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 896 } 897 } 898 899 // Recordkeeping of restore-after-install operations that are currently in flight 900 // between the Package Manager and the Backup Manager 901 class PostInstallData { 902 public InstallArgs args; 903 public PackageInstalledInfo res; 904 905 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 906 args = _a; 907 res = _r; 908 } 909 } 910 911 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 912 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 913 914 // XML tags for backup/restore of various bits of state 915 private static final String TAG_PREFERRED_BACKUP = "pa"; 916 private static final String TAG_DEFAULT_APPS = "da"; 917 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 918 919 private final String mRequiredVerifierPackage; 920 921 private final PackageUsage mPackageUsage = new PackageUsage(); 922 923 private class PackageUsage { 924 private static final int WRITE_INTERVAL 925 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 926 927 private final Object mFileLock = new Object(); 928 private final AtomicLong mLastWritten = new AtomicLong(0); 929 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 930 931 private boolean mIsHistoricalPackageUsageAvailable = true; 932 933 boolean isHistoricalPackageUsageAvailable() { 934 return mIsHistoricalPackageUsageAvailable; 935 } 936 937 void write(boolean force) { 938 if (force) { 939 writeInternal(); 940 return; 941 } 942 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 943 && !DEBUG_DEXOPT) { 944 return; 945 } 946 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 947 new Thread("PackageUsage_DiskWriter") { 948 @Override 949 public void run() { 950 try { 951 writeInternal(); 952 } finally { 953 mBackgroundWriteRunning.set(false); 954 } 955 } 956 }.start(); 957 } 958 } 959 960 private void writeInternal() { 961 synchronized (mPackages) { 962 synchronized (mFileLock) { 963 AtomicFile file = getFile(); 964 FileOutputStream f = null; 965 try { 966 f = file.startWrite(); 967 BufferedOutputStream out = new BufferedOutputStream(f); 968 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 969 StringBuilder sb = new StringBuilder(); 970 for (PackageParser.Package pkg : mPackages.values()) { 971 if (pkg.mLastPackageUsageTimeInMills == 0) { 972 continue; 973 } 974 sb.setLength(0); 975 sb.append(pkg.packageName); 976 sb.append(' '); 977 sb.append((long)pkg.mLastPackageUsageTimeInMills); 978 sb.append('\n'); 979 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 980 } 981 out.flush(); 982 file.finishWrite(f); 983 } catch (IOException e) { 984 if (f != null) { 985 file.failWrite(f); 986 } 987 Log.e(TAG, "Failed to write package usage times", e); 988 } 989 } 990 } 991 mLastWritten.set(SystemClock.elapsedRealtime()); 992 } 993 994 void readLP() { 995 synchronized (mFileLock) { 996 AtomicFile file = getFile(); 997 BufferedInputStream in = null; 998 try { 999 in = new BufferedInputStream(file.openRead()); 1000 StringBuffer sb = new StringBuffer(); 1001 while (true) { 1002 String packageName = readToken(in, sb, ' '); 1003 if (packageName == null) { 1004 break; 1005 } 1006 String timeInMillisString = readToken(in, sb, '\n'); 1007 if (timeInMillisString == null) { 1008 throw new IOException("Failed to find last usage time for package " 1009 + packageName); 1010 } 1011 PackageParser.Package pkg = mPackages.get(packageName); 1012 if (pkg == null) { 1013 continue; 1014 } 1015 long timeInMillis; 1016 try { 1017 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1018 } catch (NumberFormatException e) { 1019 throw new IOException("Failed to parse " + timeInMillisString 1020 + " as a long.", e); 1021 } 1022 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1023 } 1024 } catch (FileNotFoundException expected) { 1025 mIsHistoricalPackageUsageAvailable = false; 1026 } catch (IOException e) { 1027 Log.w(TAG, "Failed to read package usage times", e); 1028 } finally { 1029 IoUtils.closeQuietly(in); 1030 } 1031 } 1032 mLastWritten.set(SystemClock.elapsedRealtime()); 1033 } 1034 1035 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1036 throws IOException { 1037 sb.setLength(0); 1038 while (true) { 1039 int ch = in.read(); 1040 if (ch == -1) { 1041 if (sb.length() == 0) { 1042 return null; 1043 } 1044 throw new IOException("Unexpected EOF"); 1045 } 1046 if (ch == endOfToken) { 1047 return sb.toString(); 1048 } 1049 sb.append((char)ch); 1050 } 1051 } 1052 1053 private AtomicFile getFile() { 1054 File dataDir = Environment.getDataDirectory(); 1055 File systemDir = new File(dataDir, "system"); 1056 File fname = new File(systemDir, "package-usage.list"); 1057 return new AtomicFile(fname); 1058 } 1059 } 1060 1061 class PackageHandler extends Handler { 1062 private boolean mBound = false; 1063 final ArrayList<HandlerParams> mPendingInstalls = 1064 new ArrayList<HandlerParams>(); 1065 1066 private boolean connectToService() { 1067 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1068 " DefaultContainerService"); 1069 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1070 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1071 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1072 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1073 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1074 mBound = true; 1075 return true; 1076 } 1077 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1078 return false; 1079 } 1080 1081 private void disconnectService() { 1082 mContainerService = null; 1083 mBound = false; 1084 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1085 mContext.unbindService(mDefContainerConn); 1086 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1087 } 1088 1089 PackageHandler(Looper looper) { 1090 super(looper); 1091 } 1092 1093 public void handleMessage(Message msg) { 1094 try { 1095 doHandleMessage(msg); 1096 } finally { 1097 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1098 } 1099 } 1100 1101 void doHandleMessage(Message msg) { 1102 switch (msg.what) { 1103 case INIT_COPY: { 1104 HandlerParams params = (HandlerParams) msg.obj; 1105 int idx = mPendingInstalls.size(); 1106 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1107 // If a bind was already initiated we dont really 1108 // need to do anything. The pending install 1109 // will be processed later on. 1110 if (!mBound) { 1111 // If this is the only one pending we might 1112 // have to bind to the service again. 1113 if (!connectToService()) { 1114 Slog.e(TAG, "Failed to bind to media container service"); 1115 params.serviceError(); 1116 return; 1117 } else { 1118 // Once we bind to the service, the first 1119 // pending request will be processed. 1120 mPendingInstalls.add(idx, params); 1121 } 1122 } else { 1123 mPendingInstalls.add(idx, params); 1124 // Already bound to the service. Just make 1125 // sure we trigger off processing the first request. 1126 if (idx == 0) { 1127 mHandler.sendEmptyMessage(MCS_BOUND); 1128 } 1129 } 1130 break; 1131 } 1132 case MCS_BOUND: { 1133 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1134 if (msg.obj != null) { 1135 mContainerService = (IMediaContainerService) msg.obj; 1136 } 1137 if (mContainerService == null) { 1138 if (!mBound) { 1139 // Something seriously wrong since we are not bound and we are not 1140 // waiting for connection. Bail out. 1141 Slog.e(TAG, "Cannot bind to media container service"); 1142 for (HandlerParams params : mPendingInstalls) { 1143 // Indicate service bind error 1144 params.serviceError(); 1145 } 1146 mPendingInstalls.clear(); 1147 } else { 1148 Slog.w(TAG, "Waiting to connect to media container service"); 1149 } 1150 } else if (mPendingInstalls.size() > 0) { 1151 HandlerParams params = mPendingInstalls.get(0); 1152 if (params != null) { 1153 if (params.startCopy()) { 1154 // We are done... look for more work or to 1155 // go idle. 1156 if (DEBUG_SD_INSTALL) Log.i(TAG, 1157 "Checking for more work or unbind..."); 1158 // Delete pending install 1159 if (mPendingInstalls.size() > 0) { 1160 mPendingInstalls.remove(0); 1161 } 1162 if (mPendingInstalls.size() == 0) { 1163 if (mBound) { 1164 if (DEBUG_SD_INSTALL) Log.i(TAG, 1165 "Posting delayed MCS_UNBIND"); 1166 removeMessages(MCS_UNBIND); 1167 Message ubmsg = obtainMessage(MCS_UNBIND); 1168 // Unbind after a little delay, to avoid 1169 // continual thrashing. 1170 sendMessageDelayed(ubmsg, 10000); 1171 } 1172 } else { 1173 // There are more pending requests in queue. 1174 // Just post MCS_BOUND message to trigger processing 1175 // of next pending install. 1176 if (DEBUG_SD_INSTALL) Log.i(TAG, 1177 "Posting MCS_BOUND for next work"); 1178 mHandler.sendEmptyMessage(MCS_BOUND); 1179 } 1180 } 1181 } 1182 } else { 1183 // Should never happen ideally. 1184 Slog.w(TAG, "Empty queue"); 1185 } 1186 break; 1187 } 1188 case MCS_RECONNECT: { 1189 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1190 if (mPendingInstalls.size() > 0) { 1191 if (mBound) { 1192 disconnectService(); 1193 } 1194 if (!connectToService()) { 1195 Slog.e(TAG, "Failed to bind to media container service"); 1196 for (HandlerParams params : mPendingInstalls) { 1197 // Indicate service bind error 1198 params.serviceError(); 1199 } 1200 mPendingInstalls.clear(); 1201 } 1202 } 1203 break; 1204 } 1205 case MCS_UNBIND: { 1206 // If there is no actual work left, then time to unbind. 1207 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1208 1209 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1210 if (mBound) { 1211 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1212 1213 disconnectService(); 1214 } 1215 } else if (mPendingInstalls.size() > 0) { 1216 // There are more pending requests in queue. 1217 // Just post MCS_BOUND message to trigger processing 1218 // of next pending install. 1219 mHandler.sendEmptyMessage(MCS_BOUND); 1220 } 1221 1222 break; 1223 } 1224 case MCS_GIVE_UP: { 1225 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1226 mPendingInstalls.remove(0); 1227 break; 1228 } 1229 case SEND_PENDING_BROADCAST: { 1230 String packages[]; 1231 ArrayList<String> components[]; 1232 int size = 0; 1233 int uids[]; 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1235 synchronized (mPackages) { 1236 if (mPendingBroadcasts == null) { 1237 return; 1238 } 1239 size = mPendingBroadcasts.size(); 1240 if (size <= 0) { 1241 // Nothing to be done. Just return 1242 return; 1243 } 1244 packages = new String[size]; 1245 components = new ArrayList[size]; 1246 uids = new int[size]; 1247 int i = 0; // filling out the above arrays 1248 1249 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1250 int packageUserId = mPendingBroadcasts.userIdAt(n); 1251 Iterator<Map.Entry<String, ArrayList<String>>> it 1252 = mPendingBroadcasts.packagesForUserId(packageUserId) 1253 .entrySet().iterator(); 1254 while (it.hasNext() && i < size) { 1255 Map.Entry<String, ArrayList<String>> ent = it.next(); 1256 packages[i] = ent.getKey(); 1257 components[i] = ent.getValue(); 1258 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1259 uids[i] = (ps != null) 1260 ? UserHandle.getUid(packageUserId, ps.appId) 1261 : -1; 1262 i++; 1263 } 1264 } 1265 size = i; 1266 mPendingBroadcasts.clear(); 1267 } 1268 // Send broadcasts 1269 for (int i = 0; i < size; i++) { 1270 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1271 } 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1273 break; 1274 } 1275 case START_CLEANING_PACKAGE: { 1276 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1277 final String packageName = (String)msg.obj; 1278 final int userId = msg.arg1; 1279 final boolean andCode = msg.arg2 != 0; 1280 synchronized (mPackages) { 1281 if (userId == UserHandle.USER_ALL) { 1282 int[] users = sUserManager.getUserIds(); 1283 for (int user : users) { 1284 mSettings.addPackageToCleanLPw( 1285 new PackageCleanItem(user, packageName, andCode)); 1286 } 1287 } else { 1288 mSettings.addPackageToCleanLPw( 1289 new PackageCleanItem(userId, packageName, andCode)); 1290 } 1291 } 1292 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1293 startCleaningPackages(); 1294 } break; 1295 case POST_INSTALL: { 1296 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1297 PostInstallData data = mRunningInstalls.get(msg.arg1); 1298 mRunningInstalls.delete(msg.arg1); 1299 boolean deleteOld = false; 1300 1301 if (data != null) { 1302 InstallArgs args = data.args; 1303 PackageInstalledInfo res = data.res; 1304 1305 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1306 res.removedInfo.sendBroadcast(false, true, false); 1307 Bundle extras = new Bundle(1); 1308 extras.putInt(Intent.EXTRA_UID, res.uid); 1309 1310 // Now that we successfully installed the package, grant runtime 1311 // permissions if requested before broadcasting the install. 1312 if ((args.installFlags 1313 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1314 grantRequestedRuntimePermissions(res.pkg, 1315 args.user.getIdentifier()); 1316 } 1317 1318 // Determine the set of users who are adding this 1319 // package for the first time vs. those who are seeing 1320 // an update. 1321 int[] firstUsers; 1322 int[] updateUsers = new int[0]; 1323 if (res.origUsers == null || res.origUsers.length == 0) { 1324 firstUsers = res.newUsers; 1325 } else { 1326 firstUsers = new int[0]; 1327 for (int i=0; i<res.newUsers.length; i++) { 1328 int user = res.newUsers[i]; 1329 boolean isNew = true; 1330 for (int j=0; j<res.origUsers.length; j++) { 1331 if (res.origUsers[j] == user) { 1332 isNew = false; 1333 break; 1334 } 1335 } 1336 if (isNew) { 1337 int[] newFirst = new int[firstUsers.length+1]; 1338 System.arraycopy(firstUsers, 0, newFirst, 0, 1339 firstUsers.length); 1340 newFirst[firstUsers.length] = user; 1341 firstUsers = newFirst; 1342 } else { 1343 int[] newUpdate = new int[updateUsers.length+1]; 1344 System.arraycopy(updateUsers, 0, newUpdate, 0, 1345 updateUsers.length); 1346 newUpdate[updateUsers.length] = user; 1347 updateUsers = newUpdate; 1348 } 1349 } 1350 } 1351 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1352 res.pkg.applicationInfo.packageName, 1353 extras, null, null, firstUsers); 1354 final boolean update = res.removedInfo.removedPackage != null; 1355 if (update) { 1356 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1357 } 1358 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1359 res.pkg.applicationInfo.packageName, 1360 extras, null, null, updateUsers); 1361 if (update) { 1362 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1363 res.pkg.applicationInfo.packageName, 1364 extras, null, null, updateUsers); 1365 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1366 null, null, 1367 res.pkg.applicationInfo.packageName, null, updateUsers); 1368 1369 // treat asec-hosted packages like removable media on upgrade 1370 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1371 if (DEBUG_INSTALL) { 1372 Slog.i(TAG, "upgrading pkg " + res.pkg 1373 + " is ASEC-hosted -> AVAILABLE"); 1374 } 1375 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1376 ArrayList<String> pkgList = new ArrayList<String>(1); 1377 pkgList.add(res.pkg.applicationInfo.packageName); 1378 sendResourcesChangedBroadcast(true, true, 1379 pkgList,uidArray, null); 1380 } 1381 } 1382 if (res.removedInfo.args != null) { 1383 // Remove the replaced package's older resources safely now 1384 deleteOld = true; 1385 } 1386 1387 // Log current value of "unknown sources" setting 1388 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1389 getUnknownSourcesSettings()); 1390 } 1391 // Force a gc to clear up things 1392 Runtime.getRuntime().gc(); 1393 // We delete after a gc for applications on sdcard. 1394 if (deleteOld) { 1395 synchronized (mInstallLock) { 1396 res.removedInfo.args.doPostDeleteLI(true); 1397 } 1398 } 1399 if (args.observer != null) { 1400 try { 1401 Bundle extras = extrasForInstallResult(res); 1402 args.observer.onPackageInstalled(res.name, res.returnCode, 1403 res.returnMsg, extras); 1404 } catch (RemoteException e) { 1405 Slog.i(TAG, "Observer no longer exists."); 1406 } 1407 } 1408 } else { 1409 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1410 } 1411 } break; 1412 case UPDATED_MEDIA_STATUS: { 1413 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1414 boolean reportStatus = msg.arg1 == 1; 1415 boolean doGc = msg.arg2 == 1; 1416 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1417 if (doGc) { 1418 // Force a gc to clear up stale containers. 1419 Runtime.getRuntime().gc(); 1420 } 1421 if (msg.obj != null) { 1422 @SuppressWarnings("unchecked") 1423 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1424 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1425 // Unload containers 1426 unloadAllContainers(args); 1427 } 1428 if (reportStatus) { 1429 try { 1430 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1431 PackageHelper.getMountService().finishMediaUpdate(); 1432 } catch (RemoteException e) { 1433 Log.e(TAG, "MountService not running?"); 1434 } 1435 } 1436 } break; 1437 case WRITE_SETTINGS: { 1438 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1439 synchronized (mPackages) { 1440 removeMessages(WRITE_SETTINGS); 1441 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1442 mSettings.writeLPr(); 1443 mDirtyUsers.clear(); 1444 } 1445 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1446 } break; 1447 case WRITE_PACKAGE_RESTRICTIONS: { 1448 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1449 synchronized (mPackages) { 1450 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1451 for (int userId : mDirtyUsers) { 1452 mSettings.writePackageRestrictionsLPr(userId); 1453 } 1454 mDirtyUsers.clear(); 1455 } 1456 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1457 } break; 1458 case CHECK_PENDING_VERIFICATION: { 1459 final int verificationId = msg.arg1; 1460 final PackageVerificationState state = mPendingVerification.get(verificationId); 1461 1462 if ((state != null) && !state.timeoutExtended()) { 1463 final InstallArgs args = state.getInstallArgs(); 1464 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1465 1466 Slog.i(TAG, "Verification timed out for " + originUri); 1467 mPendingVerification.remove(verificationId); 1468 1469 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1470 1471 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1472 Slog.i(TAG, "Continuing with installation of " + originUri); 1473 state.setVerifierResponse(Binder.getCallingUid(), 1474 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1475 broadcastPackageVerified(verificationId, originUri, 1476 PackageManager.VERIFICATION_ALLOW, 1477 state.getInstallArgs().getUser()); 1478 try { 1479 ret = args.copyApk(mContainerService, true); 1480 } catch (RemoteException e) { 1481 Slog.e(TAG, "Could not contact the ContainerService"); 1482 } 1483 } else { 1484 broadcastPackageVerified(verificationId, originUri, 1485 PackageManager.VERIFICATION_REJECT, 1486 state.getInstallArgs().getUser()); 1487 } 1488 1489 processPendingInstall(args, ret); 1490 mHandler.sendEmptyMessage(MCS_UNBIND); 1491 } 1492 break; 1493 } 1494 case PACKAGE_VERIFIED: { 1495 final int verificationId = msg.arg1; 1496 1497 final PackageVerificationState state = mPendingVerification.get(verificationId); 1498 if (state == null) { 1499 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1500 break; 1501 } 1502 1503 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1504 1505 state.setVerifierResponse(response.callerUid, response.code); 1506 1507 if (state.isVerificationComplete()) { 1508 mPendingVerification.remove(verificationId); 1509 1510 final InstallArgs args = state.getInstallArgs(); 1511 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1512 1513 int ret; 1514 if (state.isInstallAllowed()) { 1515 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1516 broadcastPackageVerified(verificationId, originUri, 1517 response.code, state.getInstallArgs().getUser()); 1518 try { 1519 ret = args.copyApk(mContainerService, true); 1520 } catch (RemoteException e) { 1521 Slog.e(TAG, "Could not contact the ContainerService"); 1522 } 1523 } else { 1524 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1525 } 1526 1527 processPendingInstall(args, ret); 1528 1529 mHandler.sendEmptyMessage(MCS_UNBIND); 1530 } 1531 1532 break; 1533 } 1534 case START_INTENT_FILTER_VERIFICATIONS: { 1535 IFVerificationParams params = (IFVerificationParams) msg.obj; 1536 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1537 params.replacing, params.pkg); 1538 break; 1539 } 1540 case INTENT_FILTER_VERIFIED: { 1541 final int verificationId = msg.arg1; 1542 1543 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1544 verificationId); 1545 if (state == null) { 1546 Slog.w(TAG, "Invalid IntentFilter verification token " 1547 + verificationId + " received"); 1548 break; 1549 } 1550 1551 final int userId = state.getUserId(); 1552 1553 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1554 "Processing IntentFilter verification with token:" 1555 + verificationId + " and userId:" + userId); 1556 1557 final IntentFilterVerificationResponse response = 1558 (IntentFilterVerificationResponse) msg.obj; 1559 1560 state.setVerifierResponse(response.callerUid, response.code); 1561 1562 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1563 "IntentFilter verification with token:" + verificationId 1564 + " and userId:" + userId 1565 + " is settings verifier response with response code:" 1566 + response.code); 1567 1568 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1569 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1570 + response.getFailedDomainsString()); 1571 } 1572 1573 if (state.isVerificationComplete()) { 1574 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1575 } else { 1576 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1577 "IntentFilter verification with token:" + verificationId 1578 + " was not said to be complete"); 1579 } 1580 1581 break; 1582 } 1583 } 1584 } 1585 } 1586 1587 private StorageEventListener mStorageListener = new StorageEventListener() { 1588 @Override 1589 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1590 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1591 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1592 // TODO: ensure that private directories exist for all active users 1593 // TODO: remove user data whose serial number doesn't match 1594 loadPrivatePackages(vol); 1595 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1596 unloadPrivatePackages(vol); 1597 } 1598 } 1599 1600 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1601 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1602 updateExternalMediaStatus(true, false); 1603 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1604 updateExternalMediaStatus(false, false); 1605 } 1606 } 1607 } 1608 1609 @Override 1610 public void onVolumeForgotten(String fsUuid) { 1611 // TODO: remove all packages hosted on this uuid 1612 } 1613 }; 1614 1615 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1616 if (userId >= UserHandle.USER_OWNER) { 1617 grantRequestedRuntimePermissionsForUser(pkg, userId); 1618 } else if (userId == UserHandle.USER_ALL) { 1619 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1620 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1621 } 1622 } 1623 1624 // We could have touched GID membership, so flush out packages.list 1625 synchronized (mPackages) { 1626 mSettings.writePackageListLPr(); 1627 } 1628 } 1629 1630 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1631 SettingBase sb = (SettingBase) pkg.mExtras; 1632 if (sb == null) { 1633 return; 1634 } 1635 1636 PermissionsState permissionsState = sb.getPermissionsState(); 1637 1638 for (String permission : pkg.requestedPermissions) { 1639 BasePermission bp = mSettings.mPermissions.get(permission); 1640 if (bp != null && bp.isRuntime()) { 1641 permissionsState.grantRuntimePermission(bp, userId); 1642 } 1643 } 1644 } 1645 1646 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1647 Bundle extras = null; 1648 switch (res.returnCode) { 1649 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1650 extras = new Bundle(); 1651 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1652 res.origPermission); 1653 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1654 res.origPackage); 1655 break; 1656 } 1657 case PackageManager.INSTALL_SUCCEEDED: { 1658 extras = new Bundle(); 1659 extras.putBoolean(Intent.EXTRA_REPLACING, 1660 res.removedInfo != null && res.removedInfo.removedPackage != null); 1661 break; 1662 } 1663 } 1664 return extras; 1665 } 1666 1667 void scheduleWriteSettingsLocked() { 1668 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1669 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1670 } 1671 } 1672 1673 void scheduleWritePackageRestrictionsLocked(int userId) { 1674 if (!sUserManager.exists(userId)) return; 1675 mDirtyUsers.add(userId); 1676 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1677 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1678 } 1679 } 1680 1681 public static PackageManagerService main(Context context, Installer installer, 1682 boolean factoryTest, boolean onlyCore) { 1683 PackageManagerService m = new PackageManagerService(context, installer, 1684 factoryTest, onlyCore); 1685 ServiceManager.addService("package", m); 1686 return m; 1687 } 1688 1689 static String[] splitString(String str, char sep) { 1690 int count = 1; 1691 int i = 0; 1692 while ((i=str.indexOf(sep, i)) >= 0) { 1693 count++; 1694 i++; 1695 } 1696 1697 String[] res = new String[count]; 1698 i=0; 1699 count = 0; 1700 int lastI=0; 1701 while ((i=str.indexOf(sep, i)) >= 0) { 1702 res[count] = str.substring(lastI, i); 1703 count++; 1704 i++; 1705 lastI = i; 1706 } 1707 res[count] = str.substring(lastI, str.length()); 1708 return res; 1709 } 1710 1711 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1712 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1713 Context.DISPLAY_SERVICE); 1714 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1715 } 1716 1717 public PackageManagerService(Context context, Installer installer, 1718 boolean factoryTest, boolean onlyCore) { 1719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1720 SystemClock.uptimeMillis()); 1721 1722 if (mSdkVersion <= 0) { 1723 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1724 } 1725 1726 mContext = context; 1727 mFactoryTest = factoryTest; 1728 mOnlyCore = onlyCore; 1729 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1730 mMetrics = new DisplayMetrics(); 1731 mSettings = new Settings(mPackages); 1732 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1733 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1734 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1735 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1736 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1737 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1738 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1739 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1740 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1741 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1742 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1743 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1744 1745 // TODO: add a property to control this? 1746 long dexOptLRUThresholdInMinutes; 1747 if (mLazyDexOpt) { 1748 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1749 } else { 1750 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1751 } 1752 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1753 1754 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1755 if (separateProcesses != null && separateProcesses.length() > 0) { 1756 if ("*".equals(separateProcesses)) { 1757 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1758 mSeparateProcesses = null; 1759 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1760 } else { 1761 mDefParseFlags = 0; 1762 mSeparateProcesses = separateProcesses.split(","); 1763 Slog.w(TAG, "Running with debug.separate_processes: " 1764 + separateProcesses); 1765 } 1766 } else { 1767 mDefParseFlags = 0; 1768 mSeparateProcesses = null; 1769 } 1770 1771 mInstaller = installer; 1772 mPackageDexOptimizer = new PackageDexOptimizer(this); 1773 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1774 1775 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1776 FgThread.get().getLooper()); 1777 1778 getDefaultDisplayMetrics(context, mMetrics); 1779 1780 SystemConfig systemConfig = SystemConfig.getInstance(); 1781 mGlobalGids = systemConfig.getGlobalGids(); 1782 mSystemPermissions = systemConfig.getSystemPermissions(); 1783 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1784 1785 synchronized (mInstallLock) { 1786 // writer 1787 synchronized (mPackages) { 1788 mHandlerThread = new ServiceThread(TAG, 1789 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1790 mHandlerThread.start(); 1791 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1792 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1793 1794 File dataDir = Environment.getDataDirectory(); 1795 mAppDataDir = new File(dataDir, "data"); 1796 mAppInstallDir = new File(dataDir, "app"); 1797 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1798 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1799 mUserAppDataDir = new File(dataDir, "user"); 1800 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1801 1802 sUserManager = new UserManagerService(context, this, 1803 mInstallLock, mPackages); 1804 1805 // Propagate permission configuration in to package manager. 1806 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1807 = systemConfig.getPermissions(); 1808 for (int i=0; i<permConfig.size(); i++) { 1809 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1810 BasePermission bp = mSettings.mPermissions.get(perm.name); 1811 if (bp == null) { 1812 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1813 mSettings.mPermissions.put(perm.name, bp); 1814 } 1815 if (perm.gids != null) { 1816 bp.setGids(perm.gids, perm.perUser); 1817 } 1818 } 1819 1820 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1821 for (int i=0; i<libConfig.size(); i++) { 1822 mSharedLibraries.put(libConfig.keyAt(i), 1823 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1824 } 1825 1826 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1827 1828 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1829 mSdkVersion, mOnlyCore); 1830 1831 String customResolverActivity = Resources.getSystem().getString( 1832 R.string.config_customResolverActivity); 1833 if (TextUtils.isEmpty(customResolverActivity)) { 1834 customResolverActivity = null; 1835 } else { 1836 mCustomResolverComponentName = ComponentName.unflattenFromString( 1837 customResolverActivity); 1838 } 1839 1840 long startTime = SystemClock.uptimeMillis(); 1841 1842 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1843 startTime); 1844 1845 // Set flag to monitor and not change apk file paths when 1846 // scanning install directories. 1847 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1848 1849 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1850 1851 /** 1852 * Add everything in the in the boot class path to the 1853 * list of process files because dexopt will have been run 1854 * if necessary during zygote startup. 1855 */ 1856 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1857 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1858 1859 if (bootClassPath != null) { 1860 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1861 for (String element : bootClassPathElements) { 1862 alreadyDexOpted.add(element); 1863 } 1864 } else { 1865 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1866 } 1867 1868 if (systemServerClassPath != null) { 1869 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1870 for (String element : systemServerClassPathElements) { 1871 alreadyDexOpted.add(element); 1872 } 1873 } else { 1874 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1875 } 1876 1877 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1878 final String[] dexCodeInstructionSets = 1879 getDexCodeInstructionSets( 1880 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1881 1882 /** 1883 * Ensure all external libraries have had dexopt run on them. 1884 */ 1885 if (mSharedLibraries.size() > 0) { 1886 // NOTE: For now, we're compiling these system "shared libraries" 1887 // (and framework jars) into all available architectures. It's possible 1888 // to compile them only when we come across an app that uses them (there's 1889 // already logic for that in scanPackageLI) but that adds some complexity. 1890 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1891 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1892 final String lib = libEntry.path; 1893 if (lib == null) { 1894 continue; 1895 } 1896 1897 try { 1898 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1899 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1900 alreadyDexOpted.add(lib); 1901 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1902 } 1903 } catch (FileNotFoundException e) { 1904 Slog.w(TAG, "Library not found: " + lib); 1905 } catch (IOException e) { 1906 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1907 + e.getMessage()); 1908 } 1909 } 1910 } 1911 } 1912 1913 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1914 1915 // Gross hack for now: we know this file doesn't contain any 1916 // code, so don't dexopt it to avoid the resulting log spew. 1917 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1918 1919 // Gross hack for now: we know this file is only part of 1920 // the boot class path for art, so don't dexopt it to 1921 // avoid the resulting log spew. 1922 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1923 1924 /** 1925 * There are a number of commands implemented in Java, which 1926 * we currently need to do the dexopt on so that they can be 1927 * run from a non-root shell. 1928 */ 1929 String[] frameworkFiles = frameworkDir.list(); 1930 if (frameworkFiles != null) { 1931 // TODO: We could compile these only for the most preferred ABI. We should 1932 // first double check that the dex files for these commands are not referenced 1933 // by other system apps. 1934 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1935 for (int i=0; i<frameworkFiles.length; i++) { 1936 File libPath = new File(frameworkDir, frameworkFiles[i]); 1937 String path = libPath.getPath(); 1938 // Skip the file if we already did it. 1939 if (alreadyDexOpted.contains(path)) { 1940 continue; 1941 } 1942 // Skip the file if it is not a type we want to dexopt. 1943 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1944 continue; 1945 } 1946 try { 1947 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1948 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1949 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1950 } 1951 } catch (FileNotFoundException e) { 1952 Slog.w(TAG, "Jar not found: " + path); 1953 } catch (IOException e) { 1954 Slog.w(TAG, "Exception reading jar: " + path, e); 1955 } 1956 } 1957 } 1958 } 1959 1960 // Collect vendor overlay packages. 1961 // (Do this before scanning any apps.) 1962 // For security and version matching reason, only consider 1963 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1964 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1965 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1966 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1967 1968 // Find base frameworks (resource packages without code). 1969 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1970 | PackageParser.PARSE_IS_SYSTEM_DIR 1971 | PackageParser.PARSE_IS_PRIVILEGED, 1972 scanFlags | SCAN_NO_DEX, 0); 1973 1974 // Collected privileged system packages. 1975 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1976 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1977 | PackageParser.PARSE_IS_SYSTEM_DIR 1978 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1979 1980 // Collect ordinary system packages. 1981 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1982 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1983 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1984 1985 // Collect all vendor packages. 1986 File vendorAppDir = new File("/vendor/app"); 1987 try { 1988 vendorAppDir = vendorAppDir.getCanonicalFile(); 1989 } catch (IOException e) { 1990 // failed to look up canonical path, continue with original one 1991 } 1992 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1993 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1994 1995 // Collect all OEM packages. 1996 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1997 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1998 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1999 2000 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2001 mInstaller.moveFiles(); 2002 2003 // Prune any system packages that no longer exist. 2004 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2005 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2006 if (!mOnlyCore) { 2007 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2008 while (psit.hasNext()) { 2009 PackageSetting ps = psit.next(); 2010 2011 /* 2012 * If this is not a system app, it can't be a 2013 * disable system app. 2014 */ 2015 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2016 continue; 2017 } 2018 2019 /* 2020 * If the package is scanned, it's not erased. 2021 */ 2022 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2023 if (scannedPkg != null) { 2024 /* 2025 * If the system app is both scanned and in the 2026 * disabled packages list, then it must have been 2027 * added via OTA. Remove it from the currently 2028 * scanned package so the previously user-installed 2029 * application can be scanned. 2030 */ 2031 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2032 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2033 + ps.name + "; removing system app. Last known codePath=" 2034 + ps.codePathString + ", installStatus=" + ps.installStatus 2035 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2036 + scannedPkg.mVersionCode); 2037 removePackageLI(ps, true); 2038 expectingBetter.put(ps.name, ps.codePath); 2039 } 2040 2041 continue; 2042 } 2043 2044 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2045 psit.remove(); 2046 logCriticalInfo(Log.WARN, "System package " + ps.name 2047 + " no longer exists; wiping its data"); 2048 removeDataDirsLI(null, ps.name); 2049 } else { 2050 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2051 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2052 possiblyDeletedUpdatedSystemApps.add(ps.name); 2053 } 2054 } 2055 } 2056 } 2057 2058 //look for any incomplete package installations 2059 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2060 //clean up list 2061 for(int i = 0; i < deletePkgsList.size(); i++) { 2062 //clean up here 2063 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2064 } 2065 //delete tmp files 2066 deleteTempPackageFiles(); 2067 2068 // Remove any shared userIDs that have no associated packages 2069 mSettings.pruneSharedUsersLPw(); 2070 2071 if (!mOnlyCore) { 2072 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2073 SystemClock.uptimeMillis()); 2074 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2075 2076 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2077 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2078 2079 /** 2080 * Remove disable package settings for any updated system 2081 * apps that were removed via an OTA. If they're not a 2082 * previously-updated app, remove them completely. 2083 * Otherwise, just revoke their system-level permissions. 2084 */ 2085 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2086 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2087 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2088 2089 String msg; 2090 if (deletedPkg == null) { 2091 msg = "Updated system package " + deletedAppName 2092 + " no longer exists; wiping its data"; 2093 removeDataDirsLI(null, deletedAppName); 2094 } else { 2095 msg = "Updated system app + " + deletedAppName 2096 + " no longer present; removing system privileges for " 2097 + deletedAppName; 2098 2099 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2100 2101 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2102 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2103 } 2104 logCriticalInfo(Log.WARN, msg); 2105 } 2106 2107 /** 2108 * Make sure all system apps that we expected to appear on 2109 * the userdata partition actually showed up. If they never 2110 * appeared, crawl back and revive the system version. 2111 */ 2112 for (int i = 0; i < expectingBetter.size(); i++) { 2113 final String packageName = expectingBetter.keyAt(i); 2114 if (!mPackages.containsKey(packageName)) { 2115 final File scanFile = expectingBetter.valueAt(i); 2116 2117 logCriticalInfo(Log.WARN, "Expected better " + packageName 2118 + " but never showed up; reverting to system"); 2119 2120 final int reparseFlags; 2121 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2122 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2123 | PackageParser.PARSE_IS_SYSTEM_DIR 2124 | PackageParser.PARSE_IS_PRIVILEGED; 2125 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2126 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2127 | PackageParser.PARSE_IS_SYSTEM_DIR; 2128 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2129 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2130 | PackageParser.PARSE_IS_SYSTEM_DIR; 2131 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2132 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2133 | PackageParser.PARSE_IS_SYSTEM_DIR; 2134 } else { 2135 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2136 continue; 2137 } 2138 2139 mSettings.enableSystemPackageLPw(packageName); 2140 2141 try { 2142 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2143 } catch (PackageManagerException e) { 2144 Slog.e(TAG, "Failed to parse original system package: " 2145 + e.getMessage()); 2146 } 2147 } 2148 } 2149 } 2150 2151 // Now that we know all of the shared libraries, update all clients to have 2152 // the correct library paths. 2153 updateAllSharedLibrariesLPw(); 2154 2155 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2156 // NOTE: We ignore potential failures here during a system scan (like 2157 // the rest of the commands above) because there's precious little we 2158 // can do about it. A settings error is reported, though. 2159 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2160 false /* force dexopt */, false /* defer dexopt */); 2161 } 2162 2163 // Now that we know all the packages we are keeping, 2164 // read and update their last usage times. 2165 mPackageUsage.readLP(); 2166 2167 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2168 SystemClock.uptimeMillis()); 2169 Slog.i(TAG, "Time to scan packages: " 2170 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2171 + " seconds"); 2172 2173 // If the platform SDK has changed since the last time we booted, 2174 // we need to re-grant app permission to catch any new ones that 2175 // appear. This is really a hack, and means that apps can in some 2176 // cases get permissions that the user didn't initially explicitly 2177 // allow... it would be nice to have some better way to handle 2178 // this situation. 2179 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2180 != mSdkVersion; 2181 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2182 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2183 + "; regranting permissions for internal storage"); 2184 mSettings.mInternalSdkPlatform = mSdkVersion; 2185 2186 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2187 | (regrantPermissions 2188 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2189 : 0)); 2190 2191 // If this is the first boot, and it is a normal boot, then 2192 // we need to initialize the default preferred apps. 2193 if (!mRestoredSettings && !onlyCore) { 2194 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2195 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2196 } 2197 2198 // If this is first boot after an OTA, and a normal boot, then 2199 // we need to clear code cache directories. 2200 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2201 if (mIsUpgrade && !onlyCore) { 2202 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2203 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2204 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2205 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2206 } 2207 mSettings.mFingerprint = Build.FINGERPRINT; 2208 } 2209 2210 primeDomainVerificationsLPw(); 2211 checkDefaultBrowser(); 2212 2213 // All the changes are done during package scanning. 2214 mSettings.updateInternalDatabaseVersion(); 2215 2216 // can downgrade to reader 2217 mSettings.writeLPr(); 2218 2219 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2220 SystemClock.uptimeMillis()); 2221 2222 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2223 2224 mInstallerService = new PackageInstallerService(context, this); 2225 2226 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2227 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2228 mIntentFilterVerifierComponent); 2229 2230 } // synchronized (mPackages) 2231 } // synchronized (mInstallLock) 2232 2233 // Now after opening every single application zip, make sure they 2234 // are all flushed. Not really needed, but keeps things nice and 2235 // tidy. 2236 Runtime.getRuntime().gc(); 2237 2238 // Expose private service for system components to use. 2239 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2240 } 2241 2242 @Override 2243 public boolean isFirstBoot() { 2244 return !mRestoredSettings; 2245 } 2246 2247 @Override 2248 public boolean isOnlyCoreApps() { 2249 return mOnlyCore; 2250 } 2251 2252 @Override 2253 public boolean isUpgrade() { 2254 return mIsUpgrade; 2255 } 2256 2257 private String getRequiredVerifierLPr() { 2258 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2259 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2260 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2261 2262 String requiredVerifier = null; 2263 2264 final int N = receivers.size(); 2265 for (int i = 0; i < N; i++) { 2266 final ResolveInfo info = receivers.get(i); 2267 2268 if (info.activityInfo == null) { 2269 continue; 2270 } 2271 2272 final String packageName = info.activityInfo.packageName; 2273 2274 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2275 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2276 continue; 2277 } 2278 2279 if (requiredVerifier != null) { 2280 throw new RuntimeException("There can be only one required verifier"); 2281 } 2282 2283 requiredVerifier = packageName; 2284 } 2285 2286 return requiredVerifier; 2287 } 2288 2289 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2290 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2291 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2292 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2293 2294 ComponentName verifierComponentName = null; 2295 2296 int priority = -1000; 2297 final int N = receivers.size(); 2298 for (int i = 0; i < N; i++) { 2299 final ResolveInfo info = receivers.get(i); 2300 2301 if (info.activityInfo == null) { 2302 continue; 2303 } 2304 2305 final String packageName = info.activityInfo.packageName; 2306 2307 final PackageSetting ps = mSettings.mPackages.get(packageName); 2308 if (ps == null) { 2309 continue; 2310 } 2311 2312 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2313 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2314 continue; 2315 } 2316 2317 // Select the IntentFilterVerifier with the highest priority 2318 if (priority < info.priority) { 2319 priority = info.priority; 2320 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2321 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2322 + verifierComponentName + " with priority: " + info.priority); 2323 } 2324 } 2325 2326 return verifierComponentName; 2327 } 2328 2329 private void primeDomainVerificationsLPw() { 2330 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2331 boolean updated = false; 2332 ArraySet<String> allHostsSet = new ArraySet<>(); 2333 for (PackageParser.Package pkg : mPackages.values()) { 2334 final String packageName = pkg.packageName; 2335 if (!hasDomainURLs(pkg)) { 2336 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2337 "package with no domain URLs: " + packageName); 2338 continue; 2339 } 2340 if (!pkg.isSystemApp()) { 2341 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2342 "No priming domain verifications for a non system package : " + 2343 packageName); 2344 continue; 2345 } 2346 for (PackageParser.Activity a : pkg.activities) { 2347 for (ActivityIntentInfo filter : a.intents) { 2348 if (hasValidDomains(filter)) { 2349 allHostsSet.addAll(filter.getHostsList()); 2350 } 2351 } 2352 } 2353 if (allHostsSet.size() == 0) { 2354 allHostsSet.add("*"); 2355 } 2356 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2357 IntentFilterVerificationInfo ivi = 2358 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2359 if (ivi != null) { 2360 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2361 "Priming domain verifications for package: " + packageName + 2362 " with hosts:" + ivi.getDomainsString()); 2363 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2364 updated = true; 2365 } 2366 else { 2367 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2368 "No priming domain verifications for package: " + packageName); 2369 } 2370 allHostsSet.clear(); 2371 } 2372 if (updated) { 2373 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2374 "Will need to write primed domain verifications"); 2375 } 2376 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2377 } 2378 2379 private void applyFactoryDefaultBrowserLPw(int userId) { 2380 // The default browser app's package name is stored in a string resource, 2381 // with a product-specific overlay used for vendor customization. 2382 String browserPkg = mContext.getResources().getString( 2383 com.android.internal.R.string.default_browser); 2384 if (browserPkg != null) { 2385 // non-empty string => required to be a known package 2386 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2387 if (ps == null) { 2388 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2389 browserPkg = null; 2390 } else { 2391 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2392 } 2393 } 2394 2395 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2396 // default. If there's more than one, just leave everything alone. 2397 if (browserPkg == null) { 2398 calculateDefaultBrowserLPw(userId); 2399 } 2400 } 2401 2402 private void calculateDefaultBrowserLPw(int userId) { 2403 List<String> allBrowsers = resolveAllBrowserApps(userId); 2404 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2405 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2406 } 2407 2408 private List<String> resolveAllBrowserApps(int userId) { 2409 // Match all generic http: browser apps 2410 Intent intent = new Intent(); 2411 intent.setAction(Intent.ACTION_VIEW); 2412 intent.addCategory(Intent.CATEGORY_BROWSABLE); 2413 intent.setData(Uri.parse("http:")); 2414 2415 // Resolve that intent and check that the handleAllWebDataURI boolean is set 2416 List<ResolveInfo> list = queryIntentActivities(intent, null, 0, userId); 2417 2418 final int count = list.size(); 2419 List<String> result = new ArrayList<String>(count); 2420 for (int i=0; i<count; i++) { 2421 ResolveInfo info = list.get(i); 2422 if (info.activityInfo == null 2423 || !info.handleAllWebDataURI 2424 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2425 || result.contains(info.activityInfo.packageName)) { 2426 continue; 2427 } 2428 result.add(info.activityInfo.packageName); 2429 } 2430 2431 return result; 2432 } 2433 2434 private void checkDefaultBrowser() { 2435 final int myUserId = UserHandle.myUserId(); 2436 final String packageName = getDefaultBrowserPackageName(myUserId); 2437 if (packageName != null) { 2438 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2439 if (info == null) { 2440 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2441 synchronized (mPackages) { 2442 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2443 } 2444 } 2445 } 2446 } 2447 2448 @Override 2449 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2450 throws RemoteException { 2451 try { 2452 return super.onTransact(code, data, reply, flags); 2453 } catch (RuntimeException e) { 2454 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2455 Slog.wtf(TAG, "Package Manager Crash", e); 2456 } 2457 throw e; 2458 } 2459 } 2460 2461 void cleanupInstallFailedPackage(PackageSetting ps) { 2462 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2463 2464 removeDataDirsLI(ps.volumeUuid, ps.name); 2465 if (ps.codePath != null) { 2466 if (ps.codePath.isDirectory()) { 2467 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2468 } else { 2469 ps.codePath.delete(); 2470 } 2471 } 2472 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2473 if (ps.resourcePath.isDirectory()) { 2474 FileUtils.deleteContents(ps.resourcePath); 2475 } 2476 ps.resourcePath.delete(); 2477 } 2478 mSettings.removePackageLPw(ps.name); 2479 } 2480 2481 static int[] appendInts(int[] cur, int[] add) { 2482 if (add == null) return cur; 2483 if (cur == null) return add; 2484 final int N = add.length; 2485 for (int i=0; i<N; i++) { 2486 cur = appendInt(cur, add[i]); 2487 } 2488 return cur; 2489 } 2490 2491 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2492 if (!sUserManager.exists(userId)) return null; 2493 final PackageSetting ps = (PackageSetting) p.mExtras; 2494 if (ps == null) { 2495 return null; 2496 } 2497 2498 final PermissionsState permissionsState = ps.getPermissionsState(); 2499 2500 final int[] gids = permissionsState.computeGids(userId); 2501 final Set<String> permissions = permissionsState.getPermissions(userId); 2502 final PackageUserState state = ps.readUserState(userId); 2503 2504 return PackageParser.generatePackageInfo(p, gids, flags, 2505 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2506 } 2507 2508 @Override 2509 public boolean isPackageFrozen(String packageName) { 2510 synchronized (mPackages) { 2511 final PackageSetting ps = mSettings.mPackages.get(packageName); 2512 if (ps != null) { 2513 return ps.frozen; 2514 } 2515 } 2516 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2517 return true; 2518 } 2519 2520 @Override 2521 public boolean isPackageAvailable(String packageName, int userId) { 2522 if (!sUserManager.exists(userId)) return false; 2523 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2524 synchronized (mPackages) { 2525 PackageParser.Package p = mPackages.get(packageName); 2526 if (p != null) { 2527 final PackageSetting ps = (PackageSetting) p.mExtras; 2528 if (ps != null) { 2529 final PackageUserState state = ps.readUserState(userId); 2530 if (state != null) { 2531 return PackageParser.isAvailable(state); 2532 } 2533 } 2534 } 2535 } 2536 return false; 2537 } 2538 2539 @Override 2540 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2541 if (!sUserManager.exists(userId)) return null; 2542 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2543 // reader 2544 synchronized (mPackages) { 2545 PackageParser.Package p = mPackages.get(packageName); 2546 if (DEBUG_PACKAGE_INFO) 2547 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2548 if (p != null) { 2549 return generatePackageInfo(p, flags, userId); 2550 } 2551 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2552 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2553 } 2554 } 2555 return null; 2556 } 2557 2558 @Override 2559 public String[] currentToCanonicalPackageNames(String[] names) { 2560 String[] out = new String[names.length]; 2561 // reader 2562 synchronized (mPackages) { 2563 for (int i=names.length-1; i>=0; i--) { 2564 PackageSetting ps = mSettings.mPackages.get(names[i]); 2565 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2566 } 2567 } 2568 return out; 2569 } 2570 2571 @Override 2572 public String[] canonicalToCurrentPackageNames(String[] names) { 2573 String[] out = new String[names.length]; 2574 // reader 2575 synchronized (mPackages) { 2576 for (int i=names.length-1; i>=0; i--) { 2577 String cur = mSettings.mRenamedPackages.get(names[i]); 2578 out[i] = cur != null ? cur : names[i]; 2579 } 2580 } 2581 return out; 2582 } 2583 2584 @Override 2585 public int getPackageUid(String packageName, int userId) { 2586 if (!sUserManager.exists(userId)) return -1; 2587 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2588 2589 // reader 2590 synchronized (mPackages) { 2591 PackageParser.Package p = mPackages.get(packageName); 2592 if(p != null) { 2593 return UserHandle.getUid(userId, p.applicationInfo.uid); 2594 } 2595 PackageSetting ps = mSettings.mPackages.get(packageName); 2596 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2597 return -1; 2598 } 2599 p = ps.pkg; 2600 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2601 } 2602 } 2603 2604 @Override 2605 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2606 if (!sUserManager.exists(userId)) { 2607 return null; 2608 } 2609 2610 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2611 "getPackageGids"); 2612 2613 // reader 2614 synchronized (mPackages) { 2615 PackageParser.Package p = mPackages.get(packageName); 2616 if (DEBUG_PACKAGE_INFO) { 2617 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2618 } 2619 if (p != null) { 2620 PackageSetting ps = (PackageSetting) p.mExtras; 2621 return ps.getPermissionsState().computeGids(userId); 2622 } 2623 } 2624 2625 return null; 2626 } 2627 2628 @Override 2629 public int getMountExternalMode(int uid) { 2630 if (Process.isIsolated(uid)) { 2631 return Zygote.MOUNT_EXTERNAL_NONE; 2632 } else { 2633 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2634 return Zygote.MOUNT_EXTERNAL_WRITE; 2635 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2636 return Zygote.MOUNT_EXTERNAL_READ; 2637 } else { 2638 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2639 } 2640 } 2641 } 2642 2643 static PermissionInfo generatePermissionInfo( 2644 BasePermission bp, int flags) { 2645 if (bp.perm != null) { 2646 return PackageParser.generatePermissionInfo(bp.perm, flags); 2647 } 2648 PermissionInfo pi = new PermissionInfo(); 2649 pi.name = bp.name; 2650 pi.packageName = bp.sourcePackage; 2651 pi.nonLocalizedLabel = bp.name; 2652 pi.protectionLevel = bp.protectionLevel; 2653 return pi; 2654 } 2655 2656 @Override 2657 public PermissionInfo getPermissionInfo(String name, int flags) { 2658 // reader 2659 synchronized (mPackages) { 2660 final BasePermission p = mSettings.mPermissions.get(name); 2661 if (p != null) { 2662 return generatePermissionInfo(p, flags); 2663 } 2664 return null; 2665 } 2666 } 2667 2668 @Override 2669 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2670 // reader 2671 synchronized (mPackages) { 2672 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2673 for (BasePermission p : mSettings.mPermissions.values()) { 2674 if (group == null) { 2675 if (p.perm == null || p.perm.info.group == null) { 2676 out.add(generatePermissionInfo(p, flags)); 2677 } 2678 } else { 2679 if (p.perm != null && group.equals(p.perm.info.group)) { 2680 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2681 } 2682 } 2683 } 2684 2685 if (out.size() > 0) { 2686 return out; 2687 } 2688 return mPermissionGroups.containsKey(group) ? out : null; 2689 } 2690 } 2691 2692 @Override 2693 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2694 // reader 2695 synchronized (mPackages) { 2696 return PackageParser.generatePermissionGroupInfo( 2697 mPermissionGroups.get(name), flags); 2698 } 2699 } 2700 2701 @Override 2702 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2703 // reader 2704 synchronized (mPackages) { 2705 final int N = mPermissionGroups.size(); 2706 ArrayList<PermissionGroupInfo> out 2707 = new ArrayList<PermissionGroupInfo>(N); 2708 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2709 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2710 } 2711 return out; 2712 } 2713 } 2714 2715 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2716 int userId) { 2717 if (!sUserManager.exists(userId)) return null; 2718 PackageSetting ps = mSettings.mPackages.get(packageName); 2719 if (ps != null) { 2720 if (ps.pkg == null) { 2721 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2722 flags, userId); 2723 if (pInfo != null) { 2724 return pInfo.applicationInfo; 2725 } 2726 return null; 2727 } 2728 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2729 ps.readUserState(userId), userId); 2730 } 2731 return null; 2732 } 2733 2734 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2735 int userId) { 2736 if (!sUserManager.exists(userId)) return null; 2737 PackageSetting ps = mSettings.mPackages.get(packageName); 2738 if (ps != null) { 2739 PackageParser.Package pkg = ps.pkg; 2740 if (pkg == null) { 2741 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2742 return null; 2743 } 2744 // Only data remains, so we aren't worried about code paths 2745 pkg = new PackageParser.Package(packageName); 2746 pkg.applicationInfo.packageName = packageName; 2747 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2748 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2749 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2750 packageName, userId).getAbsolutePath(); 2751 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2752 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2753 } 2754 return generatePackageInfo(pkg, flags, userId); 2755 } 2756 return null; 2757 } 2758 2759 @Override 2760 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2761 if (!sUserManager.exists(userId)) return null; 2762 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2763 // writer 2764 synchronized (mPackages) { 2765 PackageParser.Package p = mPackages.get(packageName); 2766 if (DEBUG_PACKAGE_INFO) Log.v( 2767 TAG, "getApplicationInfo " + packageName 2768 + ": " + p); 2769 if (p != null) { 2770 PackageSetting ps = mSettings.mPackages.get(packageName); 2771 if (ps == null) return null; 2772 // Note: isEnabledLP() does not apply here - always return info 2773 return PackageParser.generateApplicationInfo( 2774 p, flags, ps.readUserState(userId), userId); 2775 } 2776 if ("android".equals(packageName)||"system".equals(packageName)) { 2777 return mAndroidApplication; 2778 } 2779 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2780 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2781 } 2782 } 2783 return null; 2784 } 2785 2786 @Override 2787 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2788 final IPackageDataObserver observer) { 2789 mContext.enforceCallingOrSelfPermission( 2790 android.Manifest.permission.CLEAR_APP_CACHE, null); 2791 // Queue up an async operation since clearing cache may take a little while. 2792 mHandler.post(new Runnable() { 2793 public void run() { 2794 mHandler.removeCallbacks(this); 2795 int retCode = -1; 2796 synchronized (mInstallLock) { 2797 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2798 if (retCode < 0) { 2799 Slog.w(TAG, "Couldn't clear application caches"); 2800 } 2801 } 2802 if (observer != null) { 2803 try { 2804 observer.onRemoveCompleted(null, (retCode >= 0)); 2805 } catch (RemoteException e) { 2806 Slog.w(TAG, "RemoveException when invoking call back"); 2807 } 2808 } 2809 } 2810 }); 2811 } 2812 2813 @Override 2814 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2815 final IntentSender pi) { 2816 mContext.enforceCallingOrSelfPermission( 2817 android.Manifest.permission.CLEAR_APP_CACHE, null); 2818 // Queue up an async operation since clearing cache may take a little while. 2819 mHandler.post(new Runnable() { 2820 public void run() { 2821 mHandler.removeCallbacks(this); 2822 int retCode = -1; 2823 synchronized (mInstallLock) { 2824 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2825 if (retCode < 0) { 2826 Slog.w(TAG, "Couldn't clear application caches"); 2827 } 2828 } 2829 if(pi != null) { 2830 try { 2831 // Callback via pending intent 2832 int code = (retCode >= 0) ? 1 : 0; 2833 pi.sendIntent(null, code, null, 2834 null, null); 2835 } catch (SendIntentException e1) { 2836 Slog.i(TAG, "Failed to send pending intent"); 2837 } 2838 } 2839 } 2840 }); 2841 } 2842 2843 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2844 synchronized (mInstallLock) { 2845 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2846 throw new IOException("Failed to free enough space"); 2847 } 2848 } 2849 } 2850 2851 @Override 2852 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2853 if (!sUserManager.exists(userId)) return null; 2854 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2855 synchronized (mPackages) { 2856 PackageParser.Activity a = mActivities.mActivities.get(component); 2857 2858 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2859 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2860 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2861 if (ps == null) return null; 2862 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2863 userId); 2864 } 2865 if (mResolveComponentName.equals(component)) { 2866 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2867 new PackageUserState(), userId); 2868 } 2869 } 2870 return null; 2871 } 2872 2873 @Override 2874 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2875 String resolvedType) { 2876 synchronized (mPackages) { 2877 PackageParser.Activity a = mActivities.mActivities.get(component); 2878 if (a == null) { 2879 return false; 2880 } 2881 for (int i=0; i<a.intents.size(); i++) { 2882 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2883 intent.getData(), intent.getCategories(), TAG) >= 0) { 2884 return true; 2885 } 2886 } 2887 return false; 2888 } 2889 } 2890 2891 @Override 2892 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2893 if (!sUserManager.exists(userId)) return null; 2894 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2895 synchronized (mPackages) { 2896 PackageParser.Activity a = mReceivers.mActivities.get(component); 2897 if (DEBUG_PACKAGE_INFO) Log.v( 2898 TAG, "getReceiverInfo " + component + ": " + a); 2899 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2900 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2901 if (ps == null) return null; 2902 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2903 userId); 2904 } 2905 } 2906 return null; 2907 } 2908 2909 @Override 2910 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2911 if (!sUserManager.exists(userId)) return null; 2912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2913 synchronized (mPackages) { 2914 PackageParser.Service s = mServices.mServices.get(component); 2915 if (DEBUG_PACKAGE_INFO) Log.v( 2916 TAG, "getServiceInfo " + component + ": " + s); 2917 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2918 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2919 if (ps == null) return null; 2920 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2921 userId); 2922 } 2923 } 2924 return null; 2925 } 2926 2927 @Override 2928 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2929 if (!sUserManager.exists(userId)) return null; 2930 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2931 synchronized (mPackages) { 2932 PackageParser.Provider p = mProviders.mProviders.get(component); 2933 if (DEBUG_PACKAGE_INFO) Log.v( 2934 TAG, "getProviderInfo " + component + ": " + p); 2935 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2936 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2937 if (ps == null) return null; 2938 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2939 userId); 2940 } 2941 } 2942 return null; 2943 } 2944 2945 @Override 2946 public String[] getSystemSharedLibraryNames() { 2947 Set<String> libSet; 2948 synchronized (mPackages) { 2949 libSet = mSharedLibraries.keySet(); 2950 int size = libSet.size(); 2951 if (size > 0) { 2952 String[] libs = new String[size]; 2953 libSet.toArray(libs); 2954 return libs; 2955 } 2956 } 2957 return null; 2958 } 2959 2960 /** 2961 * @hide 2962 */ 2963 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2964 synchronized (mPackages) { 2965 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2966 if (lib != null && lib.apk != null) { 2967 return mPackages.get(lib.apk); 2968 } 2969 } 2970 return null; 2971 } 2972 2973 @Override 2974 public FeatureInfo[] getSystemAvailableFeatures() { 2975 Collection<FeatureInfo> featSet; 2976 synchronized (mPackages) { 2977 featSet = mAvailableFeatures.values(); 2978 int size = featSet.size(); 2979 if (size > 0) { 2980 FeatureInfo[] features = new FeatureInfo[size+1]; 2981 featSet.toArray(features); 2982 FeatureInfo fi = new FeatureInfo(); 2983 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2984 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2985 features[size] = fi; 2986 return features; 2987 } 2988 } 2989 return null; 2990 } 2991 2992 @Override 2993 public boolean hasSystemFeature(String name) { 2994 synchronized (mPackages) { 2995 return mAvailableFeatures.containsKey(name); 2996 } 2997 } 2998 2999 private void checkValidCaller(int uid, int userId) { 3000 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3001 return; 3002 3003 throw new SecurityException("Caller uid=" + uid 3004 + " is not privileged to communicate with user=" + userId); 3005 } 3006 3007 @Override 3008 public int checkPermission(String permName, String pkgName, int userId) { 3009 if (!sUserManager.exists(userId)) { 3010 return PackageManager.PERMISSION_DENIED; 3011 } 3012 3013 synchronized (mPackages) { 3014 final PackageParser.Package p = mPackages.get(pkgName); 3015 if (p != null && p.mExtras != null) { 3016 final PackageSetting ps = (PackageSetting) p.mExtras; 3017 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3018 return PackageManager.PERMISSION_GRANTED; 3019 } 3020 } 3021 } 3022 3023 return PackageManager.PERMISSION_DENIED; 3024 } 3025 3026 @Override 3027 public int checkUidPermission(String permName, int uid) { 3028 final int userId = UserHandle.getUserId(uid); 3029 3030 if (!sUserManager.exists(userId)) { 3031 return PackageManager.PERMISSION_DENIED; 3032 } 3033 3034 synchronized (mPackages) { 3035 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3036 if (obj != null) { 3037 final SettingBase ps = (SettingBase) obj; 3038 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3039 return PackageManager.PERMISSION_GRANTED; 3040 } 3041 } else { 3042 ArraySet<String> perms = mSystemPermissions.get(uid); 3043 if (perms != null && perms.contains(permName)) { 3044 return PackageManager.PERMISSION_GRANTED; 3045 } 3046 } 3047 } 3048 3049 return PackageManager.PERMISSION_DENIED; 3050 } 3051 3052 /** 3053 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3054 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3055 * @param checkShell TODO(yamasani): 3056 * @param message the message to log on security exception 3057 */ 3058 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3059 boolean checkShell, String message) { 3060 if (userId < 0) { 3061 throw new IllegalArgumentException("Invalid userId " + userId); 3062 } 3063 if (checkShell) { 3064 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3065 } 3066 if (userId == UserHandle.getUserId(callingUid)) return; 3067 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3068 if (requireFullPermission) { 3069 mContext.enforceCallingOrSelfPermission( 3070 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3071 } else { 3072 try { 3073 mContext.enforceCallingOrSelfPermission( 3074 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3075 } catch (SecurityException se) { 3076 mContext.enforceCallingOrSelfPermission( 3077 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3078 } 3079 } 3080 } 3081 } 3082 3083 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3084 if (callingUid == Process.SHELL_UID) { 3085 if (userHandle >= 0 3086 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3087 throw new SecurityException("Shell does not have permission to access user " 3088 + userHandle); 3089 } else if (userHandle < 0) { 3090 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3091 + Debug.getCallers(3)); 3092 } 3093 } 3094 } 3095 3096 private BasePermission findPermissionTreeLP(String permName) { 3097 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3098 if (permName.startsWith(bp.name) && 3099 permName.length() > bp.name.length() && 3100 permName.charAt(bp.name.length()) == '.') { 3101 return bp; 3102 } 3103 } 3104 return null; 3105 } 3106 3107 private BasePermission checkPermissionTreeLP(String permName) { 3108 if (permName != null) { 3109 BasePermission bp = findPermissionTreeLP(permName); 3110 if (bp != null) { 3111 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3112 return bp; 3113 } 3114 throw new SecurityException("Calling uid " 3115 + Binder.getCallingUid() 3116 + " is not allowed to add to permission tree " 3117 + bp.name + " owned by uid " + bp.uid); 3118 } 3119 } 3120 throw new SecurityException("No permission tree found for " + permName); 3121 } 3122 3123 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3124 if (s1 == null) { 3125 return s2 == null; 3126 } 3127 if (s2 == null) { 3128 return false; 3129 } 3130 if (s1.getClass() != s2.getClass()) { 3131 return false; 3132 } 3133 return s1.equals(s2); 3134 } 3135 3136 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3137 if (pi1.icon != pi2.icon) return false; 3138 if (pi1.logo != pi2.logo) return false; 3139 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3140 if (!compareStrings(pi1.name, pi2.name)) return false; 3141 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3142 // We'll take care of setting this one. 3143 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3144 // These are not currently stored in settings. 3145 //if (!compareStrings(pi1.group, pi2.group)) return false; 3146 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3147 //if (pi1.labelRes != pi2.labelRes) return false; 3148 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3149 return true; 3150 } 3151 3152 int permissionInfoFootprint(PermissionInfo info) { 3153 int size = info.name.length(); 3154 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3155 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3156 return size; 3157 } 3158 3159 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3160 int size = 0; 3161 for (BasePermission perm : mSettings.mPermissions.values()) { 3162 if (perm.uid == tree.uid) { 3163 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3164 } 3165 } 3166 return size; 3167 } 3168 3169 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3170 // We calculate the max size of permissions defined by this uid and throw 3171 // if that plus the size of 'info' would exceed our stated maximum. 3172 if (tree.uid != Process.SYSTEM_UID) { 3173 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3174 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3175 throw new SecurityException("Permission tree size cap exceeded"); 3176 } 3177 } 3178 } 3179 3180 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3181 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3182 throw new SecurityException("Label must be specified in permission"); 3183 } 3184 BasePermission tree = checkPermissionTreeLP(info.name); 3185 BasePermission bp = mSettings.mPermissions.get(info.name); 3186 boolean added = bp == null; 3187 boolean changed = true; 3188 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3189 if (added) { 3190 enforcePermissionCapLocked(info, tree); 3191 bp = new BasePermission(info.name, tree.sourcePackage, 3192 BasePermission.TYPE_DYNAMIC); 3193 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3194 throw new SecurityException( 3195 "Not allowed to modify non-dynamic permission " 3196 + info.name); 3197 } else { 3198 if (bp.protectionLevel == fixedLevel 3199 && bp.perm.owner.equals(tree.perm.owner) 3200 && bp.uid == tree.uid 3201 && comparePermissionInfos(bp.perm.info, info)) { 3202 changed = false; 3203 } 3204 } 3205 bp.protectionLevel = fixedLevel; 3206 info = new PermissionInfo(info); 3207 info.protectionLevel = fixedLevel; 3208 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3209 bp.perm.info.packageName = tree.perm.info.packageName; 3210 bp.uid = tree.uid; 3211 if (added) { 3212 mSettings.mPermissions.put(info.name, bp); 3213 } 3214 if (changed) { 3215 if (!async) { 3216 mSettings.writeLPr(); 3217 } else { 3218 scheduleWriteSettingsLocked(); 3219 } 3220 } 3221 return added; 3222 } 3223 3224 @Override 3225 public boolean addPermission(PermissionInfo info) { 3226 synchronized (mPackages) { 3227 return addPermissionLocked(info, false); 3228 } 3229 } 3230 3231 @Override 3232 public boolean addPermissionAsync(PermissionInfo info) { 3233 synchronized (mPackages) { 3234 return addPermissionLocked(info, true); 3235 } 3236 } 3237 3238 @Override 3239 public void removePermission(String name) { 3240 synchronized (mPackages) { 3241 checkPermissionTreeLP(name); 3242 BasePermission bp = mSettings.mPermissions.get(name); 3243 if (bp != null) { 3244 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3245 throw new SecurityException( 3246 "Not allowed to modify non-dynamic permission " 3247 + name); 3248 } 3249 mSettings.mPermissions.remove(name); 3250 mSettings.writeLPr(); 3251 } 3252 } 3253 } 3254 3255 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3256 BasePermission bp) { 3257 int index = pkg.requestedPermissions.indexOf(bp.name); 3258 if (index == -1) { 3259 throw new SecurityException("Package " + pkg.packageName 3260 + " has not requested permission " + bp.name); 3261 } 3262 if (!bp.isRuntime()) { 3263 throw new SecurityException("Permission " + bp.name 3264 + " is not a changeable permission type"); 3265 } 3266 } 3267 3268 @Override 3269 public void grantRuntimePermission(String packageName, String name, final int userId) { 3270 if (!sUserManager.exists(userId)) { 3271 Log.e(TAG, "No such user:" + userId); 3272 return; 3273 } 3274 3275 mContext.enforceCallingOrSelfPermission( 3276 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3277 "grantRuntimePermission"); 3278 3279 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3280 "grantRuntimePermission"); 3281 3282 final int uid; 3283 final SettingBase sb; 3284 3285 synchronized (mPackages) { 3286 final PackageParser.Package pkg = mPackages.get(packageName); 3287 if (pkg == null) { 3288 throw new IllegalArgumentException("Unknown package: " + packageName); 3289 } 3290 3291 final BasePermission bp = mSettings.mPermissions.get(name); 3292 if (bp == null) { 3293 throw new IllegalArgumentException("Unknown permission: " + name); 3294 } 3295 3296 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3297 3298 uid = pkg.applicationInfo.uid; 3299 sb = (SettingBase) pkg.mExtras; 3300 if (sb == null) { 3301 throw new IllegalArgumentException("Unknown package: " + packageName); 3302 } 3303 3304 final PermissionsState permissionsState = sb.getPermissionsState(); 3305 3306 final int flags = permissionsState.getPermissionFlags(name, userId); 3307 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3308 throw new SecurityException("Cannot grant system fixed permission: " 3309 + name + " for package: " + packageName); 3310 } 3311 3312 final int result = permissionsState.grantRuntimePermission(bp, userId); 3313 switch (result) { 3314 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3315 return; 3316 } 3317 3318 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3319 mHandler.post(new Runnable() { 3320 @Override 3321 public void run() { 3322 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3323 } 3324 }); 3325 } break; 3326 } 3327 3328 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3329 3330 // Not critical if that is lost - app has to request again. 3331 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3332 } 3333 3334 if (READ_EXTERNAL_STORAGE.equals(name) 3335 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3336 final long token = Binder.clearCallingIdentity(); 3337 try { 3338 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3339 storage.remountUid(uid); 3340 } finally { 3341 Binder.restoreCallingIdentity(token); 3342 } 3343 } 3344 } 3345 3346 @Override 3347 public void revokeRuntimePermission(String packageName, String name, int userId) { 3348 if (!sUserManager.exists(userId)) { 3349 Log.e(TAG, "No such user:" + userId); 3350 return; 3351 } 3352 3353 mContext.enforceCallingOrSelfPermission( 3354 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3355 "revokeRuntimePermission"); 3356 3357 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3358 "revokeRuntimePermission"); 3359 3360 final SettingBase sb; 3361 3362 synchronized (mPackages) { 3363 final PackageParser.Package pkg = mPackages.get(packageName); 3364 if (pkg == null) { 3365 throw new IllegalArgumentException("Unknown package: " + packageName); 3366 } 3367 3368 final BasePermission bp = mSettings.mPermissions.get(name); 3369 if (bp == null) { 3370 throw new IllegalArgumentException("Unknown permission: " + name); 3371 } 3372 3373 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3374 3375 sb = (SettingBase) pkg.mExtras; 3376 if (sb == null) { 3377 throw new IllegalArgumentException("Unknown package: " + packageName); 3378 } 3379 3380 final PermissionsState permissionsState = sb.getPermissionsState(); 3381 3382 final int flags = permissionsState.getPermissionFlags(name, userId); 3383 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3384 throw new SecurityException("Cannot revoke system fixed permission: " 3385 + name + " for package: " + packageName); 3386 } 3387 3388 if (permissionsState.revokeRuntimePermission(bp, userId) == 3389 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3390 return; 3391 } 3392 3393 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3394 3395 // Critical, after this call app should never have the permission. 3396 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3397 } 3398 3399 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3400 } 3401 3402 @Override 3403 public int getPermissionFlags(String name, String packageName, int userId) { 3404 if (!sUserManager.exists(userId)) { 3405 return 0; 3406 } 3407 3408 mContext.enforceCallingOrSelfPermission( 3409 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3410 "getPermissionFlags"); 3411 3412 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3413 "getPermissionFlags"); 3414 3415 synchronized (mPackages) { 3416 final PackageParser.Package pkg = mPackages.get(packageName); 3417 if (pkg == null) { 3418 throw new IllegalArgumentException("Unknown package: " + packageName); 3419 } 3420 3421 final BasePermission bp = mSettings.mPermissions.get(name); 3422 if (bp == null) { 3423 throw new IllegalArgumentException("Unknown permission: " + name); 3424 } 3425 3426 SettingBase sb = (SettingBase) pkg.mExtras; 3427 if (sb == null) { 3428 throw new IllegalArgumentException("Unknown package: " + packageName); 3429 } 3430 3431 PermissionsState permissionsState = sb.getPermissionsState(); 3432 return permissionsState.getPermissionFlags(name, userId); 3433 } 3434 } 3435 3436 @Override 3437 public void updatePermissionFlags(String name, String packageName, int flagMask, 3438 int flagValues, int userId) { 3439 if (!sUserManager.exists(userId)) { 3440 return; 3441 } 3442 3443 mContext.enforceCallingOrSelfPermission( 3444 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3445 "updatePermissionFlags"); 3446 3447 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3448 "updatePermissionFlags"); 3449 3450 // Only the system can change system fixed flags. 3451 if (getCallingUid() != Process.SYSTEM_UID) { 3452 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3453 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3454 } 3455 3456 synchronized (mPackages) { 3457 final PackageParser.Package pkg = mPackages.get(packageName); 3458 if (pkg == null) { 3459 throw new IllegalArgumentException("Unknown package: " + packageName); 3460 } 3461 3462 final BasePermission bp = mSettings.mPermissions.get(name); 3463 if (bp == null) { 3464 throw new IllegalArgumentException("Unknown permission: " + name); 3465 } 3466 3467 SettingBase sb = (SettingBase) pkg.mExtras; 3468 if (sb == null) { 3469 throw new IllegalArgumentException("Unknown package: " + packageName); 3470 } 3471 3472 PermissionsState permissionsState = sb.getPermissionsState(); 3473 3474 // Only the package manager can change flags for system component permissions. 3475 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3476 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3477 return; 3478 } 3479 3480 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3481 3482 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3483 // Install and runtime permissions are stored in different places, 3484 // so figure out what permission changed and persist the change. 3485 if (permissionsState.getInstallPermissionState(name) != null) { 3486 scheduleWriteSettingsLocked(); 3487 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3488 || hadState) { 3489 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3490 } 3491 } 3492 } 3493 } 3494 3495 /** 3496 * Update the permission flags for all packages and runtime permissions of a user in order 3497 * to allow device or profile owner to remove POLICY_FIXED. 3498 */ 3499 @Override 3500 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3501 if (!sUserManager.exists(userId)) { 3502 return; 3503 } 3504 3505 mContext.enforceCallingOrSelfPermission( 3506 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3507 "updatePermissionFlagsForAllApps"); 3508 3509 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3510 "updatePermissionFlagsForAllApps"); 3511 3512 // Only the system can change system fixed flags. 3513 if (getCallingUid() != Process.SYSTEM_UID) { 3514 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3515 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3516 } 3517 3518 synchronized (mPackages) { 3519 boolean changed = false; 3520 final int packageCount = mPackages.size(); 3521 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3522 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3523 SettingBase sb = (SettingBase) pkg.mExtras; 3524 if (sb == null) { 3525 continue; 3526 } 3527 PermissionsState permissionsState = sb.getPermissionsState(); 3528 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3529 userId, flagMask, flagValues); 3530 } 3531 if (changed) { 3532 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3533 } 3534 } 3535 } 3536 3537 @Override 3538 public boolean shouldShowRequestPermissionRationale(String permissionName, 3539 String packageName, int userId) { 3540 if (UserHandle.getCallingUserId() != userId) { 3541 mContext.enforceCallingPermission( 3542 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3543 "canShowRequestPermissionRationale for user " + userId); 3544 } 3545 3546 final int uid = getPackageUid(packageName, userId); 3547 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3548 return false; 3549 } 3550 3551 if (checkPermission(permissionName, packageName, userId) 3552 == PackageManager.PERMISSION_GRANTED) { 3553 return false; 3554 } 3555 3556 final int flags; 3557 3558 final long identity = Binder.clearCallingIdentity(); 3559 try { 3560 flags = getPermissionFlags(permissionName, 3561 packageName, userId); 3562 } finally { 3563 Binder.restoreCallingIdentity(identity); 3564 } 3565 3566 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3567 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3568 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3569 3570 if ((flags & fixedFlags) != 0) { 3571 return false; 3572 } 3573 3574 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3575 } 3576 3577 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3578 BasePermission bp = mSettings.mPermissions.get(permission); 3579 if (bp == null) { 3580 throw new SecurityException("Missing " + permission + " permission"); 3581 } 3582 3583 SettingBase sb = (SettingBase) pkg.mExtras; 3584 PermissionsState permissionsState = sb.getPermissionsState(); 3585 3586 if (permissionsState.grantInstallPermission(bp) != 3587 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3588 scheduleWriteSettingsLocked(); 3589 } 3590 } 3591 3592 @Override 3593 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3594 mContext.enforceCallingOrSelfPermission( 3595 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3596 "addOnPermissionsChangeListener"); 3597 3598 synchronized (mPackages) { 3599 mOnPermissionChangeListeners.addListenerLocked(listener); 3600 } 3601 } 3602 3603 @Override 3604 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3605 synchronized (mPackages) { 3606 mOnPermissionChangeListeners.removeListenerLocked(listener); 3607 } 3608 } 3609 3610 @Override 3611 public boolean isProtectedBroadcast(String actionName) { 3612 synchronized (mPackages) { 3613 return mProtectedBroadcasts.contains(actionName); 3614 } 3615 } 3616 3617 @Override 3618 public int checkSignatures(String pkg1, String pkg2) { 3619 synchronized (mPackages) { 3620 final PackageParser.Package p1 = mPackages.get(pkg1); 3621 final PackageParser.Package p2 = mPackages.get(pkg2); 3622 if (p1 == null || p1.mExtras == null 3623 || p2 == null || p2.mExtras == null) { 3624 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3625 } 3626 return compareSignatures(p1.mSignatures, p2.mSignatures); 3627 } 3628 } 3629 3630 @Override 3631 public int checkUidSignatures(int uid1, int uid2) { 3632 // Map to base uids. 3633 uid1 = UserHandle.getAppId(uid1); 3634 uid2 = UserHandle.getAppId(uid2); 3635 // reader 3636 synchronized (mPackages) { 3637 Signature[] s1; 3638 Signature[] s2; 3639 Object obj = mSettings.getUserIdLPr(uid1); 3640 if (obj != null) { 3641 if (obj instanceof SharedUserSetting) { 3642 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3643 } else if (obj instanceof PackageSetting) { 3644 s1 = ((PackageSetting)obj).signatures.mSignatures; 3645 } else { 3646 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3647 } 3648 } else { 3649 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3650 } 3651 obj = mSettings.getUserIdLPr(uid2); 3652 if (obj != null) { 3653 if (obj instanceof SharedUserSetting) { 3654 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3655 } else if (obj instanceof PackageSetting) { 3656 s2 = ((PackageSetting)obj).signatures.mSignatures; 3657 } else { 3658 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3659 } 3660 } else { 3661 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3662 } 3663 return compareSignatures(s1, s2); 3664 } 3665 } 3666 3667 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3668 final long identity = Binder.clearCallingIdentity(); 3669 try { 3670 if (sb instanceof SharedUserSetting) { 3671 SharedUserSetting sus = (SharedUserSetting) sb; 3672 final int packageCount = sus.packages.size(); 3673 for (int i = 0; i < packageCount; i++) { 3674 PackageSetting susPs = sus.packages.valueAt(i); 3675 if (userId == UserHandle.USER_ALL) { 3676 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3677 } else { 3678 final int uid = UserHandle.getUid(userId, susPs.appId); 3679 killUid(uid, reason); 3680 } 3681 } 3682 } else if (sb instanceof PackageSetting) { 3683 PackageSetting ps = (PackageSetting) sb; 3684 if (userId == UserHandle.USER_ALL) { 3685 killApplication(ps.pkg.packageName, ps.appId, reason); 3686 } else { 3687 final int uid = UserHandle.getUid(userId, ps.appId); 3688 killUid(uid, reason); 3689 } 3690 } 3691 } finally { 3692 Binder.restoreCallingIdentity(identity); 3693 } 3694 } 3695 3696 private static void killUid(int uid, String reason) { 3697 IActivityManager am = ActivityManagerNative.getDefault(); 3698 if (am != null) { 3699 try { 3700 am.killUid(uid, reason); 3701 } catch (RemoteException e) { 3702 /* ignore - same process */ 3703 } 3704 } 3705 } 3706 3707 /** 3708 * Compares two sets of signatures. Returns: 3709 * <br /> 3710 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3711 * <br /> 3712 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3713 * <br /> 3714 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3715 * <br /> 3716 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3717 * <br /> 3718 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3719 */ 3720 static int compareSignatures(Signature[] s1, Signature[] s2) { 3721 if (s1 == null) { 3722 return s2 == null 3723 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3724 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3725 } 3726 3727 if (s2 == null) { 3728 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3729 } 3730 3731 if (s1.length != s2.length) { 3732 return PackageManager.SIGNATURE_NO_MATCH; 3733 } 3734 3735 // Since both signature sets are of size 1, we can compare without HashSets. 3736 if (s1.length == 1) { 3737 return s1[0].equals(s2[0]) ? 3738 PackageManager.SIGNATURE_MATCH : 3739 PackageManager.SIGNATURE_NO_MATCH; 3740 } 3741 3742 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3743 for (Signature sig : s1) { 3744 set1.add(sig); 3745 } 3746 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3747 for (Signature sig : s2) { 3748 set2.add(sig); 3749 } 3750 // Make sure s2 contains all signatures in s1. 3751 if (set1.equals(set2)) { 3752 return PackageManager.SIGNATURE_MATCH; 3753 } 3754 return PackageManager.SIGNATURE_NO_MATCH; 3755 } 3756 3757 /** 3758 * If the database version for this type of package (internal storage or 3759 * external storage) is less than the version where package signatures 3760 * were updated, return true. 3761 */ 3762 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3763 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3764 DatabaseVersion.SIGNATURE_END_ENTITY)) 3765 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3766 DatabaseVersion.SIGNATURE_END_ENTITY)); 3767 } 3768 3769 /** 3770 * Used for backward compatibility to make sure any packages with 3771 * certificate chains get upgraded to the new style. {@code existingSigs} 3772 * will be in the old format (since they were stored on disk from before the 3773 * system upgrade) and {@code scannedSigs} will be in the newer format. 3774 */ 3775 private int compareSignaturesCompat(PackageSignatures existingSigs, 3776 PackageParser.Package scannedPkg) { 3777 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3778 return PackageManager.SIGNATURE_NO_MATCH; 3779 } 3780 3781 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3782 for (Signature sig : existingSigs.mSignatures) { 3783 existingSet.add(sig); 3784 } 3785 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3786 for (Signature sig : scannedPkg.mSignatures) { 3787 try { 3788 Signature[] chainSignatures = sig.getChainSignatures(); 3789 for (Signature chainSig : chainSignatures) { 3790 scannedCompatSet.add(chainSig); 3791 } 3792 } catch (CertificateEncodingException e) { 3793 scannedCompatSet.add(sig); 3794 } 3795 } 3796 /* 3797 * Make sure the expanded scanned set contains all signatures in the 3798 * existing one. 3799 */ 3800 if (scannedCompatSet.equals(existingSet)) { 3801 // Migrate the old signatures to the new scheme. 3802 existingSigs.assignSignatures(scannedPkg.mSignatures); 3803 // The new KeySets will be re-added later in the scanning process. 3804 synchronized (mPackages) { 3805 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3806 } 3807 return PackageManager.SIGNATURE_MATCH; 3808 } 3809 return PackageManager.SIGNATURE_NO_MATCH; 3810 } 3811 3812 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3813 if (isExternal(scannedPkg)) { 3814 return mSettings.isExternalDatabaseVersionOlderThan( 3815 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3816 } else { 3817 return mSettings.isInternalDatabaseVersionOlderThan( 3818 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3819 } 3820 } 3821 3822 private int compareSignaturesRecover(PackageSignatures existingSigs, 3823 PackageParser.Package scannedPkg) { 3824 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3825 return PackageManager.SIGNATURE_NO_MATCH; 3826 } 3827 3828 String msg = null; 3829 try { 3830 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3831 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3832 + scannedPkg.packageName); 3833 return PackageManager.SIGNATURE_MATCH; 3834 } 3835 } catch (CertificateException e) { 3836 msg = e.getMessage(); 3837 } 3838 3839 logCriticalInfo(Log.INFO, 3840 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3841 return PackageManager.SIGNATURE_NO_MATCH; 3842 } 3843 3844 @Override 3845 public String[] getPackagesForUid(int uid) { 3846 uid = UserHandle.getAppId(uid); 3847 // reader 3848 synchronized (mPackages) { 3849 Object obj = mSettings.getUserIdLPr(uid); 3850 if (obj instanceof SharedUserSetting) { 3851 final SharedUserSetting sus = (SharedUserSetting) obj; 3852 final int N = sus.packages.size(); 3853 final String[] res = new String[N]; 3854 final Iterator<PackageSetting> it = sus.packages.iterator(); 3855 int i = 0; 3856 while (it.hasNext()) { 3857 res[i++] = it.next().name; 3858 } 3859 return res; 3860 } else if (obj instanceof PackageSetting) { 3861 final PackageSetting ps = (PackageSetting) obj; 3862 return new String[] { ps.name }; 3863 } 3864 } 3865 return null; 3866 } 3867 3868 @Override 3869 public String getNameForUid(int uid) { 3870 // reader 3871 synchronized (mPackages) { 3872 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3873 if (obj instanceof SharedUserSetting) { 3874 final SharedUserSetting sus = (SharedUserSetting) obj; 3875 return sus.name + ":" + sus.userId; 3876 } else if (obj instanceof PackageSetting) { 3877 final PackageSetting ps = (PackageSetting) obj; 3878 return ps.name; 3879 } 3880 } 3881 return null; 3882 } 3883 3884 @Override 3885 public int getUidForSharedUser(String sharedUserName) { 3886 if(sharedUserName == null) { 3887 return -1; 3888 } 3889 // reader 3890 synchronized (mPackages) { 3891 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3892 if (suid == null) { 3893 return -1; 3894 } 3895 return suid.userId; 3896 } 3897 } 3898 3899 @Override 3900 public int getFlagsForUid(int uid) { 3901 synchronized (mPackages) { 3902 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3903 if (obj instanceof SharedUserSetting) { 3904 final SharedUserSetting sus = (SharedUserSetting) obj; 3905 return sus.pkgFlags; 3906 } else if (obj instanceof PackageSetting) { 3907 final PackageSetting ps = (PackageSetting) obj; 3908 return ps.pkgFlags; 3909 } 3910 } 3911 return 0; 3912 } 3913 3914 @Override 3915 public int getPrivateFlagsForUid(int uid) { 3916 synchronized (mPackages) { 3917 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3918 if (obj instanceof SharedUserSetting) { 3919 final SharedUserSetting sus = (SharedUserSetting) obj; 3920 return sus.pkgPrivateFlags; 3921 } else if (obj instanceof PackageSetting) { 3922 final PackageSetting ps = (PackageSetting) obj; 3923 return ps.pkgPrivateFlags; 3924 } 3925 } 3926 return 0; 3927 } 3928 3929 @Override 3930 public boolean isUidPrivileged(int uid) { 3931 uid = UserHandle.getAppId(uid); 3932 // reader 3933 synchronized (mPackages) { 3934 Object obj = mSettings.getUserIdLPr(uid); 3935 if (obj instanceof SharedUserSetting) { 3936 final SharedUserSetting sus = (SharedUserSetting) obj; 3937 final Iterator<PackageSetting> it = sus.packages.iterator(); 3938 while (it.hasNext()) { 3939 if (it.next().isPrivileged()) { 3940 return true; 3941 } 3942 } 3943 } else if (obj instanceof PackageSetting) { 3944 final PackageSetting ps = (PackageSetting) obj; 3945 return ps.isPrivileged(); 3946 } 3947 } 3948 return false; 3949 } 3950 3951 @Override 3952 public String[] getAppOpPermissionPackages(String permissionName) { 3953 synchronized (mPackages) { 3954 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3955 if (pkgs == null) { 3956 return null; 3957 } 3958 return pkgs.toArray(new String[pkgs.size()]); 3959 } 3960 } 3961 3962 @Override 3963 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3964 int flags, int userId) { 3965 if (!sUserManager.exists(userId)) return null; 3966 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3967 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3968 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3969 } 3970 3971 @Override 3972 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3973 IntentFilter filter, int match, ComponentName activity) { 3974 final int userId = UserHandle.getCallingUserId(); 3975 if (DEBUG_PREFERRED) { 3976 Log.v(TAG, "setLastChosenActivity intent=" + intent 3977 + " resolvedType=" + resolvedType 3978 + " flags=" + flags 3979 + " filter=" + filter 3980 + " match=" + match 3981 + " activity=" + activity); 3982 filter.dump(new PrintStreamPrinter(System.out), " "); 3983 } 3984 intent.setComponent(null); 3985 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3986 // Find any earlier preferred or last chosen entries and nuke them 3987 findPreferredActivity(intent, resolvedType, 3988 flags, query, 0, false, true, false, userId); 3989 // Add the new activity as the last chosen for this filter 3990 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3991 "Setting last chosen"); 3992 } 3993 3994 @Override 3995 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3996 final int userId = UserHandle.getCallingUserId(); 3997 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3998 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3999 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4000 false, false, false, userId); 4001 } 4002 4003 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4004 int flags, List<ResolveInfo> query, int userId) { 4005 if (query != null) { 4006 final int N = query.size(); 4007 if (N == 1) { 4008 return query.get(0); 4009 } else if (N > 1) { 4010 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4011 // If there is more than one activity with the same priority, 4012 // then let the user decide between them. 4013 ResolveInfo r0 = query.get(0); 4014 ResolveInfo r1 = query.get(1); 4015 if (DEBUG_INTENT_MATCHING || debug) { 4016 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4017 + r1.activityInfo.name + "=" + r1.priority); 4018 } 4019 // If the first activity has a higher priority, or a different 4020 // default, then it is always desireable to pick it. 4021 if (r0.priority != r1.priority 4022 || r0.preferredOrder != r1.preferredOrder 4023 || r0.isDefault != r1.isDefault) { 4024 return query.get(0); 4025 } 4026 // If we have saved a preference for a preferred activity for 4027 // this Intent, use that. 4028 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4029 flags, query, r0.priority, true, false, debug, userId); 4030 if (ri != null) { 4031 return ri; 4032 } 4033 if (userId != 0) { 4034 ri = new ResolveInfo(mResolveInfo); 4035 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4036 ri.activityInfo.applicationInfo = new ApplicationInfo( 4037 ri.activityInfo.applicationInfo); 4038 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4039 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4040 return ri; 4041 } 4042 return mResolveInfo; 4043 } 4044 } 4045 return null; 4046 } 4047 4048 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4049 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4050 final int N = query.size(); 4051 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4052 .get(userId); 4053 // Get the list of persistent preferred activities that handle the intent 4054 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4055 List<PersistentPreferredActivity> pprefs = ppir != null 4056 ? ppir.queryIntent(intent, resolvedType, 4057 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4058 : null; 4059 if (pprefs != null && pprefs.size() > 0) { 4060 final int M = pprefs.size(); 4061 for (int i=0; i<M; i++) { 4062 final PersistentPreferredActivity ppa = pprefs.get(i); 4063 if (DEBUG_PREFERRED || debug) { 4064 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4065 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4066 + "\n component=" + ppa.mComponent); 4067 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4068 } 4069 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4070 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4071 if (DEBUG_PREFERRED || debug) { 4072 Slog.v(TAG, "Found persistent preferred activity:"); 4073 if (ai != null) { 4074 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4075 } else { 4076 Slog.v(TAG, " null"); 4077 } 4078 } 4079 if (ai == null) { 4080 // This previously registered persistent preferred activity 4081 // component is no longer known. Ignore it and do NOT remove it. 4082 continue; 4083 } 4084 for (int j=0; j<N; j++) { 4085 final ResolveInfo ri = query.get(j); 4086 if (!ri.activityInfo.applicationInfo.packageName 4087 .equals(ai.applicationInfo.packageName)) { 4088 continue; 4089 } 4090 if (!ri.activityInfo.name.equals(ai.name)) { 4091 continue; 4092 } 4093 // Found a persistent preference that can handle the intent. 4094 if (DEBUG_PREFERRED || debug) { 4095 Slog.v(TAG, "Returning persistent preferred activity: " + 4096 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4097 } 4098 return ri; 4099 } 4100 } 4101 } 4102 return null; 4103 } 4104 4105 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4106 List<ResolveInfo> query, int priority, boolean always, 4107 boolean removeMatches, boolean debug, int userId) { 4108 if (!sUserManager.exists(userId)) return null; 4109 // writer 4110 synchronized (mPackages) { 4111 if (intent.getSelector() != null) { 4112 intent = intent.getSelector(); 4113 } 4114 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4115 4116 // Try to find a matching persistent preferred activity. 4117 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4118 debug, userId); 4119 4120 // If a persistent preferred activity matched, use it. 4121 if (pri != null) { 4122 return pri; 4123 } 4124 4125 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4126 // Get the list of preferred activities that handle the intent 4127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4128 List<PreferredActivity> prefs = pir != null 4129 ? pir.queryIntent(intent, resolvedType, 4130 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4131 : null; 4132 if (prefs != null && prefs.size() > 0) { 4133 boolean changed = false; 4134 try { 4135 // First figure out how good the original match set is. 4136 // We will only allow preferred activities that came 4137 // from the same match quality. 4138 int match = 0; 4139 4140 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4141 4142 final int N = query.size(); 4143 for (int j=0; j<N; j++) { 4144 final ResolveInfo ri = query.get(j); 4145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4146 + ": 0x" + Integer.toHexString(match)); 4147 if (ri.match > match) { 4148 match = ri.match; 4149 } 4150 } 4151 4152 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4153 + Integer.toHexString(match)); 4154 4155 match &= IntentFilter.MATCH_CATEGORY_MASK; 4156 final int M = prefs.size(); 4157 for (int i=0; i<M; i++) { 4158 final PreferredActivity pa = prefs.get(i); 4159 if (DEBUG_PREFERRED || debug) { 4160 Slog.v(TAG, "Checking PreferredActivity ds=" 4161 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4162 + "\n component=" + pa.mPref.mComponent); 4163 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4164 } 4165 if (pa.mPref.mMatch != match) { 4166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4167 + Integer.toHexString(pa.mPref.mMatch)); 4168 continue; 4169 } 4170 // If it's not an "always" type preferred activity and that's what we're 4171 // looking for, skip it. 4172 if (always && !pa.mPref.mAlways) { 4173 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4174 continue; 4175 } 4176 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4177 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4178 if (DEBUG_PREFERRED || debug) { 4179 Slog.v(TAG, "Found preferred activity:"); 4180 if (ai != null) { 4181 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4182 } else { 4183 Slog.v(TAG, " null"); 4184 } 4185 } 4186 if (ai == null) { 4187 // This previously registered preferred activity 4188 // component is no longer known. Most likely an update 4189 // to the app was installed and in the new version this 4190 // component no longer exists. Clean it up by removing 4191 // it from the preferred activities list, and skip it. 4192 Slog.w(TAG, "Removing dangling preferred activity: " 4193 + pa.mPref.mComponent); 4194 pir.removeFilter(pa); 4195 changed = true; 4196 continue; 4197 } 4198 for (int j=0; j<N; j++) { 4199 final ResolveInfo ri = query.get(j); 4200 if (!ri.activityInfo.applicationInfo.packageName 4201 .equals(ai.applicationInfo.packageName)) { 4202 continue; 4203 } 4204 if (!ri.activityInfo.name.equals(ai.name)) { 4205 continue; 4206 } 4207 4208 if (removeMatches) { 4209 pir.removeFilter(pa); 4210 changed = true; 4211 if (DEBUG_PREFERRED) { 4212 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4213 } 4214 break; 4215 } 4216 4217 // Okay we found a previously set preferred or last chosen app. 4218 // If the result set is different from when this 4219 // was created, we need to clear it and re-ask the 4220 // user their preference, if we're looking for an "always" type entry. 4221 if (always && !pa.mPref.sameSet(query)) { 4222 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4223 + intent + " type " + resolvedType); 4224 if (DEBUG_PREFERRED) { 4225 Slog.v(TAG, "Removing preferred activity since set changed " 4226 + pa.mPref.mComponent); 4227 } 4228 pir.removeFilter(pa); 4229 // Re-add the filter as a "last chosen" entry (!always) 4230 PreferredActivity lastChosen = new PreferredActivity( 4231 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4232 pir.addFilter(lastChosen); 4233 changed = true; 4234 return null; 4235 } 4236 4237 // Yay! Either the set matched or we're looking for the last chosen 4238 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4239 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4240 return ri; 4241 } 4242 } 4243 } finally { 4244 if (changed) { 4245 if (DEBUG_PREFERRED) { 4246 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4247 } 4248 scheduleWritePackageRestrictionsLocked(userId); 4249 } 4250 } 4251 } 4252 } 4253 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4254 return null; 4255 } 4256 4257 /* 4258 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4259 */ 4260 @Override 4261 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4262 int targetUserId) { 4263 mContext.enforceCallingOrSelfPermission( 4264 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4265 List<CrossProfileIntentFilter> matches = 4266 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4267 if (matches != null) { 4268 int size = matches.size(); 4269 for (int i = 0; i < size; i++) { 4270 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4271 } 4272 } 4273 if (hasWebURI(intent)) { 4274 // cross-profile app linking works only towards the parent. 4275 final UserInfo parent = getProfileParent(sourceUserId); 4276 synchronized(mPackages) { 4277 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4278 parent.id) != null; 4279 } 4280 } 4281 return false; 4282 } 4283 4284 private UserInfo getProfileParent(int userId) { 4285 final long identity = Binder.clearCallingIdentity(); 4286 try { 4287 return sUserManager.getProfileParent(userId); 4288 } finally { 4289 Binder.restoreCallingIdentity(identity); 4290 } 4291 } 4292 4293 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4294 String resolvedType, int userId) { 4295 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4296 if (resolver != null) { 4297 return resolver.queryIntent(intent, resolvedType, false, userId); 4298 } 4299 return null; 4300 } 4301 4302 @Override 4303 public List<ResolveInfo> queryIntentActivities(Intent intent, 4304 String resolvedType, int flags, int userId) { 4305 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4306 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4307 ComponentName comp = intent.getComponent(); 4308 if (comp == null) { 4309 if (intent.getSelector() != null) { 4310 intent = intent.getSelector(); 4311 comp = intent.getComponent(); 4312 } 4313 } 4314 4315 if (comp != null) { 4316 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4317 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4318 if (ai != null) { 4319 final ResolveInfo ri = new ResolveInfo(); 4320 ri.activityInfo = ai; 4321 list.add(ri); 4322 } 4323 return list; 4324 } 4325 4326 // reader 4327 synchronized (mPackages) { 4328 final String pkgName = intent.getPackage(); 4329 if (pkgName == null) { 4330 List<CrossProfileIntentFilter> matchingFilters = 4331 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4332 // Check for results that need to skip the current profile. 4333 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4334 resolvedType, flags, userId); 4335 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4336 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4337 result.add(xpResolveInfo); 4338 return filterIfNotPrimaryUser(result, userId); 4339 } 4340 4341 // Check for results in the current profile. 4342 List<ResolveInfo> result = mActivities.queryIntent( 4343 intent, resolvedType, flags, userId); 4344 4345 // Check for cross profile results. 4346 xpResolveInfo = queryCrossProfileIntents( 4347 matchingFilters, intent, resolvedType, flags, userId); 4348 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4349 result.add(xpResolveInfo); 4350 Collections.sort(result, mResolvePrioritySorter); 4351 } 4352 result = filterIfNotPrimaryUser(result, userId); 4353 if (hasWebURI(intent)) { 4354 CrossProfileDomainInfo xpDomainInfo = null; 4355 final UserInfo parent = getProfileParent(userId); 4356 if (parent != null) { 4357 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4358 flags, userId, parent.id); 4359 } 4360 if (xpDomainInfo != null) { 4361 if (xpResolveInfo != null) { 4362 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4363 // in the result. 4364 result.remove(xpResolveInfo); 4365 } 4366 if (result.size() == 0) { 4367 result.add(xpDomainInfo.resolveInfo); 4368 return result; 4369 } 4370 } else if (result.size() <= 1) { 4371 return result; 4372 } 4373 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4374 xpDomainInfo); 4375 Collections.sort(result, mResolvePrioritySorter); 4376 } 4377 return result; 4378 } 4379 final PackageParser.Package pkg = mPackages.get(pkgName); 4380 if (pkg != null) { 4381 return filterIfNotPrimaryUser( 4382 mActivities.queryIntentForPackage( 4383 intent, resolvedType, flags, pkg.activities, userId), 4384 userId); 4385 } 4386 return new ArrayList<ResolveInfo>(); 4387 } 4388 } 4389 4390 private static class CrossProfileDomainInfo { 4391 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4392 ResolveInfo resolveInfo; 4393 /* Best domain verification status of the activities found in the other profile */ 4394 int bestDomainVerificationStatus; 4395 } 4396 4397 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4398 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4399 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING, 4400 sourceUserId)) { 4401 return null; 4402 } 4403 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4404 resolvedType, flags, parentUserId); 4405 4406 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4407 return null; 4408 } 4409 CrossProfileDomainInfo result = null; 4410 int size = resultTargetUser.size(); 4411 for (int i = 0; i < size; i++) { 4412 ResolveInfo riTargetUser = resultTargetUser.get(i); 4413 // Intent filter verification is only for filters that specify a host. So don't return 4414 // those that handle all web uris. 4415 if (riTargetUser.handleAllWebDataURI) { 4416 continue; 4417 } 4418 String packageName = riTargetUser.activityInfo.packageName; 4419 PackageSetting ps = mSettings.mPackages.get(packageName); 4420 if (ps == null) { 4421 continue; 4422 } 4423 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4424 if (result == null) { 4425 result = new CrossProfileDomainInfo(); 4426 result.resolveInfo = 4427 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4428 result.bestDomainVerificationStatus = status; 4429 } else { 4430 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4431 result.bestDomainVerificationStatus); 4432 } 4433 } 4434 return result; 4435 } 4436 4437 /** 4438 * Verification statuses are ordered from the worse to the best, except for 4439 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4440 */ 4441 private int bestDomainVerificationStatus(int status1, int status2) { 4442 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4443 return status2; 4444 } 4445 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4446 return status1; 4447 } 4448 return (int) MathUtils.max(status1, status2); 4449 } 4450 4451 private boolean isUserEnabled(int userId) { 4452 long callingId = Binder.clearCallingIdentity(); 4453 try { 4454 UserInfo userInfo = sUserManager.getUserInfo(userId); 4455 return userInfo != null && userInfo.isEnabled(); 4456 } finally { 4457 Binder.restoreCallingIdentity(callingId); 4458 } 4459 } 4460 4461 /** 4462 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4463 * 4464 * @return filtered list 4465 */ 4466 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4467 if (userId == UserHandle.USER_OWNER) { 4468 return resolveInfos; 4469 } 4470 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4471 ResolveInfo info = resolveInfos.get(i); 4472 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4473 resolveInfos.remove(i); 4474 } 4475 } 4476 return resolveInfos; 4477 } 4478 4479 private static boolean hasWebURI(Intent intent) { 4480 if (intent.getData() == null) { 4481 return false; 4482 } 4483 final String scheme = intent.getScheme(); 4484 if (TextUtils.isEmpty(scheme)) { 4485 return false; 4486 } 4487 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4488 } 4489 4490 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4491 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4492 if (DEBUG_PREFERRED) { 4493 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4494 candidates.size()); 4495 } 4496 4497 final int userId = UserHandle.getCallingUserId(); 4498 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4499 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4500 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4501 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4502 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4503 4504 synchronized (mPackages) { 4505 final int count = candidates.size(); 4506 // First, try to use the domain preferred app. Partition the candidates into four lists: 4507 // one for the final results, one for the "do not use ever", one for "undefined status" 4508 // and finally one for "Browser App type". 4509 for (int n=0; n<count; n++) { 4510 ResolveInfo info = candidates.get(n); 4511 String packageName = info.activityInfo.packageName; 4512 PackageSetting ps = mSettings.mPackages.get(packageName); 4513 if (ps != null) { 4514 // Add to the special match all list (Browser use case) 4515 if (info.handleAllWebDataURI) { 4516 matchAllList.add(info); 4517 continue; 4518 } 4519 // Try to get the status from User settings first 4520 int status = getDomainVerificationStatusLPr(ps, userId); 4521 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4522 alwaysList.add(info); 4523 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4524 neverList.add(info); 4525 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4526 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4527 undefinedList.add(info); 4528 } 4529 } 4530 } 4531 // First try to add the "always" resolution for the current user if there is any 4532 if (alwaysList.size() > 0) { 4533 result.addAll(alwaysList); 4534 // if there is an "always" for the parent user, add it. 4535 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4536 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4537 result.add(xpDomainInfo.resolveInfo); 4538 } else { 4539 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4540 result.addAll(undefinedList); 4541 if (xpDomainInfo != null && ( 4542 xpDomainInfo.bestDomainVerificationStatus 4543 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4544 || xpDomainInfo.bestDomainVerificationStatus 4545 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4546 result.add(xpDomainInfo.resolveInfo); 4547 } 4548 // Also add Browsers (all of them or only the default one) 4549 if ((flags & MATCH_ALL) != 0) { 4550 result.addAll(matchAllList); 4551 } else { 4552 // Try to add the Default Browser if we can 4553 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4554 UserHandle.myUserId()); 4555 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4556 boolean defaultBrowserFound = false; 4557 final int browserCount = matchAllList.size(); 4558 for (int n=0; n<browserCount; n++) { 4559 ResolveInfo browser = matchAllList.get(n); 4560 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4561 result.add(browser); 4562 defaultBrowserFound = true; 4563 break; 4564 } 4565 } 4566 if (!defaultBrowserFound) { 4567 result.addAll(matchAllList); 4568 } 4569 } else { 4570 result.addAll(matchAllList); 4571 } 4572 } 4573 4574 // If there is nothing selected, add all candidates and remove the ones that the User 4575 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4576 if (result.size() == 0) { 4577 result.addAll(candidates); 4578 result.removeAll(neverList); 4579 } 4580 } 4581 } 4582 if (DEBUG_PREFERRED) { 4583 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4584 result.size()); 4585 } 4586 return result; 4587 } 4588 4589 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4590 int status = ps.getDomainVerificationStatusForUser(userId); 4591 // if none available, get the master status 4592 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4593 if (ps.getIntentFilterVerificationInfo() != null) { 4594 status = ps.getIntentFilterVerificationInfo().getStatus(); 4595 } 4596 } 4597 return status; 4598 } 4599 4600 private ResolveInfo querySkipCurrentProfileIntents( 4601 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4602 int flags, int sourceUserId) { 4603 if (matchingFilters != null) { 4604 int size = matchingFilters.size(); 4605 for (int i = 0; i < size; i ++) { 4606 CrossProfileIntentFilter filter = matchingFilters.get(i); 4607 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4608 // Checking if there are activities in the target user that can handle the 4609 // intent. 4610 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4611 flags, sourceUserId); 4612 if (resolveInfo != null) { 4613 return resolveInfo; 4614 } 4615 } 4616 } 4617 } 4618 return null; 4619 } 4620 4621 // Return matching ResolveInfo if any for skip current profile intent filters. 4622 private ResolveInfo queryCrossProfileIntents( 4623 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4624 int flags, int sourceUserId) { 4625 if (matchingFilters != null) { 4626 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4627 // match the same intent. For performance reasons, it is better not to 4628 // run queryIntent twice for the same userId 4629 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4630 int size = matchingFilters.size(); 4631 for (int i = 0; i < size; i++) { 4632 CrossProfileIntentFilter filter = matchingFilters.get(i); 4633 int targetUserId = filter.getTargetUserId(); 4634 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4635 && !alreadyTriedUserIds.get(targetUserId)) { 4636 // Checking if there are activities in the target user that can handle the 4637 // intent. 4638 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4639 flags, sourceUserId); 4640 if (resolveInfo != null) return resolveInfo; 4641 alreadyTriedUserIds.put(targetUserId, true); 4642 } 4643 } 4644 } 4645 return null; 4646 } 4647 4648 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4649 String resolvedType, int flags, int sourceUserId) { 4650 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4651 resolvedType, flags, filter.getTargetUserId()); 4652 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4653 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4654 } 4655 return null; 4656 } 4657 4658 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4659 int sourceUserId, int targetUserId) { 4660 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4661 String className; 4662 if (targetUserId == UserHandle.USER_OWNER) { 4663 className = FORWARD_INTENT_TO_USER_OWNER; 4664 } else { 4665 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4666 } 4667 ComponentName forwardingActivityComponentName = new ComponentName( 4668 mAndroidApplication.packageName, className); 4669 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4670 sourceUserId); 4671 if (targetUserId == UserHandle.USER_OWNER) { 4672 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4673 forwardingResolveInfo.noResourceId = true; 4674 } 4675 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4676 forwardingResolveInfo.priority = 0; 4677 forwardingResolveInfo.preferredOrder = 0; 4678 forwardingResolveInfo.match = 0; 4679 forwardingResolveInfo.isDefault = true; 4680 forwardingResolveInfo.filter = filter; 4681 forwardingResolveInfo.targetUserId = targetUserId; 4682 return forwardingResolveInfo; 4683 } 4684 4685 @Override 4686 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4687 Intent[] specifics, String[] specificTypes, Intent intent, 4688 String resolvedType, int flags, int userId) { 4689 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4690 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4691 false, "query intent activity options"); 4692 final String resultsAction = intent.getAction(); 4693 4694 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4695 | PackageManager.GET_RESOLVED_FILTER, userId); 4696 4697 if (DEBUG_INTENT_MATCHING) { 4698 Log.v(TAG, "Query " + intent + ": " + results); 4699 } 4700 4701 int specificsPos = 0; 4702 int N; 4703 4704 // todo: note that the algorithm used here is O(N^2). This 4705 // isn't a problem in our current environment, but if we start running 4706 // into situations where we have more than 5 or 10 matches then this 4707 // should probably be changed to something smarter... 4708 4709 // First we go through and resolve each of the specific items 4710 // that were supplied, taking care of removing any corresponding 4711 // duplicate items in the generic resolve list. 4712 if (specifics != null) { 4713 for (int i=0; i<specifics.length; i++) { 4714 final Intent sintent = specifics[i]; 4715 if (sintent == null) { 4716 continue; 4717 } 4718 4719 if (DEBUG_INTENT_MATCHING) { 4720 Log.v(TAG, "Specific #" + i + ": " + sintent); 4721 } 4722 4723 String action = sintent.getAction(); 4724 if (resultsAction != null && resultsAction.equals(action)) { 4725 // If this action was explicitly requested, then don't 4726 // remove things that have it. 4727 action = null; 4728 } 4729 4730 ResolveInfo ri = null; 4731 ActivityInfo ai = null; 4732 4733 ComponentName comp = sintent.getComponent(); 4734 if (comp == null) { 4735 ri = resolveIntent( 4736 sintent, 4737 specificTypes != null ? specificTypes[i] : null, 4738 flags, userId); 4739 if (ri == null) { 4740 continue; 4741 } 4742 if (ri == mResolveInfo) { 4743 // ACK! Must do something better with this. 4744 } 4745 ai = ri.activityInfo; 4746 comp = new ComponentName(ai.applicationInfo.packageName, 4747 ai.name); 4748 } else { 4749 ai = getActivityInfo(comp, flags, userId); 4750 if (ai == null) { 4751 continue; 4752 } 4753 } 4754 4755 // Look for any generic query activities that are duplicates 4756 // of this specific one, and remove them from the results. 4757 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4758 N = results.size(); 4759 int j; 4760 for (j=specificsPos; j<N; j++) { 4761 ResolveInfo sri = results.get(j); 4762 if ((sri.activityInfo.name.equals(comp.getClassName()) 4763 && sri.activityInfo.applicationInfo.packageName.equals( 4764 comp.getPackageName())) 4765 || (action != null && sri.filter.matchAction(action))) { 4766 results.remove(j); 4767 if (DEBUG_INTENT_MATCHING) Log.v( 4768 TAG, "Removing duplicate item from " + j 4769 + " due to specific " + specificsPos); 4770 if (ri == null) { 4771 ri = sri; 4772 } 4773 j--; 4774 N--; 4775 } 4776 } 4777 4778 // Add this specific item to its proper place. 4779 if (ri == null) { 4780 ri = new ResolveInfo(); 4781 ri.activityInfo = ai; 4782 } 4783 results.add(specificsPos, ri); 4784 ri.specificIndex = i; 4785 specificsPos++; 4786 } 4787 } 4788 4789 // Now we go through the remaining generic results and remove any 4790 // duplicate actions that are found here. 4791 N = results.size(); 4792 for (int i=specificsPos; i<N-1; i++) { 4793 final ResolveInfo rii = results.get(i); 4794 if (rii.filter == null) { 4795 continue; 4796 } 4797 4798 // Iterate over all of the actions of this result's intent 4799 // filter... typically this should be just one. 4800 final Iterator<String> it = rii.filter.actionsIterator(); 4801 if (it == null) { 4802 continue; 4803 } 4804 while (it.hasNext()) { 4805 final String action = it.next(); 4806 if (resultsAction != null && resultsAction.equals(action)) { 4807 // If this action was explicitly requested, then don't 4808 // remove things that have it. 4809 continue; 4810 } 4811 for (int j=i+1; j<N; j++) { 4812 final ResolveInfo rij = results.get(j); 4813 if (rij.filter != null && rij.filter.hasAction(action)) { 4814 results.remove(j); 4815 if (DEBUG_INTENT_MATCHING) Log.v( 4816 TAG, "Removing duplicate item from " + j 4817 + " due to action " + action + " at " + i); 4818 j--; 4819 N--; 4820 } 4821 } 4822 } 4823 4824 // If the caller didn't request filter information, drop it now 4825 // so we don't have to marshall/unmarshall it. 4826 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4827 rii.filter = null; 4828 } 4829 } 4830 4831 // Filter out the caller activity if so requested. 4832 if (caller != null) { 4833 N = results.size(); 4834 for (int i=0; i<N; i++) { 4835 ActivityInfo ainfo = results.get(i).activityInfo; 4836 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4837 && caller.getClassName().equals(ainfo.name)) { 4838 results.remove(i); 4839 break; 4840 } 4841 } 4842 } 4843 4844 // If the caller didn't request filter information, 4845 // drop them now so we don't have to 4846 // marshall/unmarshall it. 4847 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4848 N = results.size(); 4849 for (int i=0; i<N; i++) { 4850 results.get(i).filter = null; 4851 } 4852 } 4853 4854 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4855 return results; 4856 } 4857 4858 @Override 4859 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4860 int userId) { 4861 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4862 ComponentName comp = intent.getComponent(); 4863 if (comp == null) { 4864 if (intent.getSelector() != null) { 4865 intent = intent.getSelector(); 4866 comp = intent.getComponent(); 4867 } 4868 } 4869 if (comp != null) { 4870 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4871 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4872 if (ai != null) { 4873 ResolveInfo ri = new ResolveInfo(); 4874 ri.activityInfo = ai; 4875 list.add(ri); 4876 } 4877 return list; 4878 } 4879 4880 // reader 4881 synchronized (mPackages) { 4882 String pkgName = intent.getPackage(); 4883 if (pkgName == null) { 4884 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4885 } 4886 final PackageParser.Package pkg = mPackages.get(pkgName); 4887 if (pkg != null) { 4888 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4889 userId); 4890 } 4891 return null; 4892 } 4893 } 4894 4895 @Override 4896 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4897 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4898 if (!sUserManager.exists(userId)) return null; 4899 if (query != null) { 4900 if (query.size() >= 1) { 4901 // If there is more than one service with the same priority, 4902 // just arbitrarily pick the first one. 4903 return query.get(0); 4904 } 4905 } 4906 return null; 4907 } 4908 4909 @Override 4910 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4911 int userId) { 4912 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4913 ComponentName comp = intent.getComponent(); 4914 if (comp == null) { 4915 if (intent.getSelector() != null) { 4916 intent = intent.getSelector(); 4917 comp = intent.getComponent(); 4918 } 4919 } 4920 if (comp != null) { 4921 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4922 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4923 if (si != null) { 4924 final ResolveInfo ri = new ResolveInfo(); 4925 ri.serviceInfo = si; 4926 list.add(ri); 4927 } 4928 return list; 4929 } 4930 4931 // reader 4932 synchronized (mPackages) { 4933 String pkgName = intent.getPackage(); 4934 if (pkgName == null) { 4935 return mServices.queryIntent(intent, resolvedType, flags, userId); 4936 } 4937 final PackageParser.Package pkg = mPackages.get(pkgName); 4938 if (pkg != null) { 4939 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4940 userId); 4941 } 4942 return null; 4943 } 4944 } 4945 4946 @Override 4947 public List<ResolveInfo> queryIntentContentProviders( 4948 Intent intent, String resolvedType, int flags, int userId) { 4949 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4950 ComponentName comp = intent.getComponent(); 4951 if (comp == null) { 4952 if (intent.getSelector() != null) { 4953 intent = intent.getSelector(); 4954 comp = intent.getComponent(); 4955 } 4956 } 4957 if (comp != null) { 4958 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4959 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4960 if (pi != null) { 4961 final ResolveInfo ri = new ResolveInfo(); 4962 ri.providerInfo = pi; 4963 list.add(ri); 4964 } 4965 return list; 4966 } 4967 4968 // reader 4969 synchronized (mPackages) { 4970 String pkgName = intent.getPackage(); 4971 if (pkgName == null) { 4972 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4973 } 4974 final PackageParser.Package pkg = mPackages.get(pkgName); 4975 if (pkg != null) { 4976 return mProviders.queryIntentForPackage( 4977 intent, resolvedType, flags, pkg.providers, userId); 4978 } 4979 return null; 4980 } 4981 } 4982 4983 @Override 4984 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4985 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4986 4987 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4988 4989 // writer 4990 synchronized (mPackages) { 4991 ArrayList<PackageInfo> list; 4992 if (listUninstalled) { 4993 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4994 for (PackageSetting ps : mSettings.mPackages.values()) { 4995 PackageInfo pi; 4996 if (ps.pkg != null) { 4997 pi = generatePackageInfo(ps.pkg, flags, userId); 4998 } else { 4999 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5000 } 5001 if (pi != null) { 5002 list.add(pi); 5003 } 5004 } 5005 } else { 5006 list = new ArrayList<PackageInfo>(mPackages.size()); 5007 for (PackageParser.Package p : mPackages.values()) { 5008 PackageInfo pi = generatePackageInfo(p, flags, userId); 5009 if (pi != null) { 5010 list.add(pi); 5011 } 5012 } 5013 } 5014 5015 return new ParceledListSlice<PackageInfo>(list); 5016 } 5017 } 5018 5019 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5020 String[] permissions, boolean[] tmp, int flags, int userId) { 5021 int numMatch = 0; 5022 final PermissionsState permissionsState = ps.getPermissionsState(); 5023 for (int i=0; i<permissions.length; i++) { 5024 final String permission = permissions[i]; 5025 if (permissionsState.hasPermission(permission, userId)) { 5026 tmp[i] = true; 5027 numMatch++; 5028 } else { 5029 tmp[i] = false; 5030 } 5031 } 5032 if (numMatch == 0) { 5033 return; 5034 } 5035 PackageInfo pi; 5036 if (ps.pkg != null) { 5037 pi = generatePackageInfo(ps.pkg, flags, userId); 5038 } else { 5039 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5040 } 5041 // The above might return null in cases of uninstalled apps or install-state 5042 // skew across users/profiles. 5043 if (pi != null) { 5044 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5045 if (numMatch == permissions.length) { 5046 pi.requestedPermissions = permissions; 5047 } else { 5048 pi.requestedPermissions = new String[numMatch]; 5049 numMatch = 0; 5050 for (int i=0; i<permissions.length; i++) { 5051 if (tmp[i]) { 5052 pi.requestedPermissions[numMatch] = permissions[i]; 5053 numMatch++; 5054 } 5055 } 5056 } 5057 } 5058 list.add(pi); 5059 } 5060 } 5061 5062 @Override 5063 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5064 String[] permissions, int flags, int userId) { 5065 if (!sUserManager.exists(userId)) return null; 5066 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5067 5068 // writer 5069 synchronized (mPackages) { 5070 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5071 boolean[] tmpBools = new boolean[permissions.length]; 5072 if (listUninstalled) { 5073 for (PackageSetting ps : mSettings.mPackages.values()) { 5074 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5075 } 5076 } else { 5077 for (PackageParser.Package pkg : mPackages.values()) { 5078 PackageSetting ps = (PackageSetting)pkg.mExtras; 5079 if (ps != null) { 5080 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5081 userId); 5082 } 5083 } 5084 } 5085 5086 return new ParceledListSlice<PackageInfo>(list); 5087 } 5088 } 5089 5090 @Override 5091 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5092 if (!sUserManager.exists(userId)) return null; 5093 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5094 5095 // writer 5096 synchronized (mPackages) { 5097 ArrayList<ApplicationInfo> list; 5098 if (listUninstalled) { 5099 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5100 for (PackageSetting ps : mSettings.mPackages.values()) { 5101 ApplicationInfo ai; 5102 if (ps.pkg != null) { 5103 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5104 ps.readUserState(userId), userId); 5105 } else { 5106 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5107 } 5108 if (ai != null) { 5109 list.add(ai); 5110 } 5111 } 5112 } else { 5113 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5114 for (PackageParser.Package p : mPackages.values()) { 5115 if (p.mExtras != null) { 5116 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5117 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5118 if (ai != null) { 5119 list.add(ai); 5120 } 5121 } 5122 } 5123 } 5124 5125 return new ParceledListSlice<ApplicationInfo>(list); 5126 } 5127 } 5128 5129 public List<ApplicationInfo> getPersistentApplications(int flags) { 5130 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5131 5132 // reader 5133 synchronized (mPackages) { 5134 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5135 final int userId = UserHandle.getCallingUserId(); 5136 while (i.hasNext()) { 5137 final PackageParser.Package p = i.next(); 5138 if (p.applicationInfo != null 5139 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5140 && (!mSafeMode || isSystemApp(p))) { 5141 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5142 if (ps != null) { 5143 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5144 ps.readUserState(userId), userId); 5145 if (ai != null) { 5146 finalList.add(ai); 5147 } 5148 } 5149 } 5150 } 5151 } 5152 5153 return finalList; 5154 } 5155 5156 @Override 5157 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5158 if (!sUserManager.exists(userId)) return null; 5159 // reader 5160 synchronized (mPackages) { 5161 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5162 PackageSetting ps = provider != null 5163 ? mSettings.mPackages.get(provider.owner.packageName) 5164 : null; 5165 return ps != null 5166 && mSettings.isEnabledLPr(provider.info, flags, userId) 5167 && (!mSafeMode || (provider.info.applicationInfo.flags 5168 &ApplicationInfo.FLAG_SYSTEM) != 0) 5169 ? PackageParser.generateProviderInfo(provider, flags, 5170 ps.readUserState(userId), userId) 5171 : null; 5172 } 5173 } 5174 5175 /** 5176 * @deprecated 5177 */ 5178 @Deprecated 5179 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5180 // reader 5181 synchronized (mPackages) { 5182 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5183 .entrySet().iterator(); 5184 final int userId = UserHandle.getCallingUserId(); 5185 while (i.hasNext()) { 5186 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5187 PackageParser.Provider p = entry.getValue(); 5188 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5189 5190 if (ps != null && p.syncable 5191 && (!mSafeMode || (p.info.applicationInfo.flags 5192 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5193 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5194 ps.readUserState(userId), userId); 5195 if (info != null) { 5196 outNames.add(entry.getKey()); 5197 outInfo.add(info); 5198 } 5199 } 5200 } 5201 } 5202 } 5203 5204 @Override 5205 public List<ProviderInfo> queryContentProviders(String processName, 5206 int uid, int flags) { 5207 ArrayList<ProviderInfo> finalList = null; 5208 // reader 5209 synchronized (mPackages) { 5210 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5211 final int userId = processName != null ? 5212 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5213 while (i.hasNext()) { 5214 final PackageParser.Provider p = i.next(); 5215 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5216 if (ps != null && p.info.authority != null 5217 && (processName == null 5218 || (p.info.processName.equals(processName) 5219 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5220 && mSettings.isEnabledLPr(p.info, flags, userId) 5221 && (!mSafeMode 5222 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5223 if (finalList == null) { 5224 finalList = new ArrayList<ProviderInfo>(3); 5225 } 5226 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5227 ps.readUserState(userId), userId); 5228 if (info != null) { 5229 finalList.add(info); 5230 } 5231 } 5232 } 5233 } 5234 5235 if (finalList != null) { 5236 Collections.sort(finalList, mProviderInitOrderSorter); 5237 } 5238 5239 return finalList; 5240 } 5241 5242 @Override 5243 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5244 int flags) { 5245 // reader 5246 synchronized (mPackages) { 5247 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5248 return PackageParser.generateInstrumentationInfo(i, flags); 5249 } 5250 } 5251 5252 @Override 5253 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5254 int flags) { 5255 ArrayList<InstrumentationInfo> finalList = 5256 new ArrayList<InstrumentationInfo>(); 5257 5258 // reader 5259 synchronized (mPackages) { 5260 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5261 while (i.hasNext()) { 5262 final PackageParser.Instrumentation p = i.next(); 5263 if (targetPackage == null 5264 || targetPackage.equals(p.info.targetPackage)) { 5265 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5266 flags); 5267 if (ii != null) { 5268 finalList.add(ii); 5269 } 5270 } 5271 } 5272 } 5273 5274 return finalList; 5275 } 5276 5277 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5278 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5279 if (overlays == null) { 5280 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5281 return; 5282 } 5283 for (PackageParser.Package opkg : overlays.values()) { 5284 // Not much to do if idmap fails: we already logged the error 5285 // and we certainly don't want to abort installation of pkg simply 5286 // because an overlay didn't fit properly. For these reasons, 5287 // ignore the return value of createIdmapForPackagePairLI. 5288 createIdmapForPackagePairLI(pkg, opkg); 5289 } 5290 } 5291 5292 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5293 PackageParser.Package opkg) { 5294 if (!opkg.mTrustedOverlay) { 5295 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5296 opkg.baseCodePath + ": overlay not trusted"); 5297 return false; 5298 } 5299 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5300 if (overlaySet == null) { 5301 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5302 opkg.baseCodePath + " but target package has no known overlays"); 5303 return false; 5304 } 5305 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5306 // TODO: generate idmap for split APKs 5307 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5308 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5309 + opkg.baseCodePath); 5310 return false; 5311 } 5312 PackageParser.Package[] overlayArray = 5313 overlaySet.values().toArray(new PackageParser.Package[0]); 5314 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5315 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5316 return p1.mOverlayPriority - p2.mOverlayPriority; 5317 } 5318 }; 5319 Arrays.sort(overlayArray, cmp); 5320 5321 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5322 int i = 0; 5323 for (PackageParser.Package p : overlayArray) { 5324 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5325 } 5326 return true; 5327 } 5328 5329 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5330 final File[] files = dir.listFiles(); 5331 if (ArrayUtils.isEmpty(files)) { 5332 Log.d(TAG, "No files in app dir " + dir); 5333 return; 5334 } 5335 5336 if (DEBUG_PACKAGE_SCANNING) { 5337 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5338 + " flags=0x" + Integer.toHexString(parseFlags)); 5339 } 5340 5341 for (File file : files) { 5342 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5343 && !PackageInstallerService.isStageName(file.getName()); 5344 if (!isPackage) { 5345 // Ignore entries which are not packages 5346 continue; 5347 } 5348 try { 5349 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5350 scanFlags, currentTime, null); 5351 } catch (PackageManagerException e) { 5352 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5353 5354 // Delete invalid userdata apps 5355 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5356 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5357 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5358 if (file.isDirectory()) { 5359 mInstaller.rmPackageDir(file.getAbsolutePath()); 5360 } else { 5361 file.delete(); 5362 } 5363 } 5364 } 5365 } 5366 } 5367 5368 private static File getSettingsProblemFile() { 5369 File dataDir = Environment.getDataDirectory(); 5370 File systemDir = new File(dataDir, "system"); 5371 File fname = new File(systemDir, "uiderrors.txt"); 5372 return fname; 5373 } 5374 5375 static void reportSettingsProblem(int priority, String msg) { 5376 logCriticalInfo(priority, msg); 5377 } 5378 5379 static void logCriticalInfo(int priority, String msg) { 5380 Slog.println(priority, TAG, msg); 5381 EventLogTags.writePmCriticalInfo(msg); 5382 try { 5383 File fname = getSettingsProblemFile(); 5384 FileOutputStream out = new FileOutputStream(fname, true); 5385 PrintWriter pw = new FastPrintWriter(out); 5386 SimpleDateFormat formatter = new SimpleDateFormat(); 5387 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5388 pw.println(dateString + ": " + msg); 5389 pw.close(); 5390 FileUtils.setPermissions( 5391 fname.toString(), 5392 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5393 -1, -1); 5394 } catch (java.io.IOException e) { 5395 } 5396 } 5397 5398 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5399 PackageParser.Package pkg, File srcFile, int parseFlags) 5400 throws PackageManagerException { 5401 if (ps != null 5402 && ps.codePath.equals(srcFile) 5403 && ps.timeStamp == srcFile.lastModified() 5404 && !isCompatSignatureUpdateNeeded(pkg) 5405 && !isRecoverSignatureUpdateNeeded(pkg)) { 5406 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5407 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5408 ArraySet<PublicKey> signingKs; 5409 synchronized (mPackages) { 5410 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5411 } 5412 if (ps.signatures.mSignatures != null 5413 && ps.signatures.mSignatures.length != 0 5414 && signingKs != null) { 5415 // Optimization: reuse the existing cached certificates 5416 // if the package appears to be unchanged. 5417 pkg.mSignatures = ps.signatures.mSignatures; 5418 pkg.mSigningKeys = signingKs; 5419 return; 5420 } 5421 5422 Slog.w(TAG, "PackageSetting for " + ps.name 5423 + " is missing signatures. Collecting certs again to recover them."); 5424 } else { 5425 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5426 } 5427 5428 try { 5429 pp.collectCertificates(pkg, parseFlags); 5430 pp.collectManifestDigest(pkg); 5431 } catch (PackageParserException e) { 5432 throw PackageManagerException.from(e); 5433 } 5434 } 5435 5436 /* 5437 * Scan a package and return the newly parsed package. 5438 * Returns null in case of errors and the error code is stored in mLastScanError 5439 */ 5440 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5441 long currentTime, UserHandle user) throws PackageManagerException { 5442 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5443 parseFlags |= mDefParseFlags; 5444 PackageParser pp = new PackageParser(); 5445 pp.setSeparateProcesses(mSeparateProcesses); 5446 pp.setOnlyCoreApps(mOnlyCore); 5447 pp.setDisplayMetrics(mMetrics); 5448 5449 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5450 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5451 } 5452 5453 final PackageParser.Package pkg; 5454 try { 5455 pkg = pp.parsePackage(scanFile, parseFlags); 5456 } catch (PackageParserException e) { 5457 throw PackageManagerException.from(e); 5458 } 5459 5460 PackageSetting ps = null; 5461 PackageSetting updatedPkg; 5462 // reader 5463 synchronized (mPackages) { 5464 // Look to see if we already know about this package. 5465 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5466 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5467 // This package has been renamed to its original name. Let's 5468 // use that. 5469 ps = mSettings.peekPackageLPr(oldName); 5470 } 5471 // If there was no original package, see one for the real package name. 5472 if (ps == null) { 5473 ps = mSettings.peekPackageLPr(pkg.packageName); 5474 } 5475 // Check to see if this package could be hiding/updating a system 5476 // package. Must look for it either under the original or real 5477 // package name depending on our state. 5478 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5479 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5480 } 5481 boolean updatedPkgBetter = false; 5482 // First check if this is a system package that may involve an update 5483 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5484 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5485 // it needs to drop FLAG_PRIVILEGED. 5486 if (locationIsPrivileged(scanFile)) { 5487 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5488 } else { 5489 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5490 } 5491 5492 if (ps != null && !ps.codePath.equals(scanFile)) { 5493 // The path has changed from what was last scanned... check the 5494 // version of the new path against what we have stored to determine 5495 // what to do. 5496 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5497 if (pkg.mVersionCode <= ps.versionCode) { 5498 // The system package has been updated and the code path does not match 5499 // Ignore entry. Skip it. 5500 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5501 + " ignored: updated version " + ps.versionCode 5502 + " better than this " + pkg.mVersionCode); 5503 if (!updatedPkg.codePath.equals(scanFile)) { 5504 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5505 + ps.name + " changing from " + updatedPkg.codePathString 5506 + " to " + scanFile); 5507 updatedPkg.codePath = scanFile; 5508 updatedPkg.codePathString = scanFile.toString(); 5509 updatedPkg.resourcePath = scanFile; 5510 updatedPkg.resourcePathString = scanFile.toString(); 5511 } 5512 updatedPkg.pkg = pkg; 5513 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5514 } else { 5515 // The current app on the system partition is better than 5516 // what we have updated to on the data partition; switch 5517 // back to the system partition version. 5518 // At this point, its safely assumed that package installation for 5519 // apps in system partition will go through. If not there won't be a working 5520 // version of the app 5521 // writer 5522 synchronized (mPackages) { 5523 // Just remove the loaded entries from package lists. 5524 mPackages.remove(ps.name); 5525 } 5526 5527 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5528 + " reverting from " + ps.codePathString 5529 + ": new version " + pkg.mVersionCode 5530 + " better than installed " + ps.versionCode); 5531 5532 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5533 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5534 synchronized (mInstallLock) { 5535 args.cleanUpResourcesLI(); 5536 } 5537 synchronized (mPackages) { 5538 mSettings.enableSystemPackageLPw(ps.name); 5539 } 5540 updatedPkgBetter = true; 5541 } 5542 } 5543 } 5544 5545 if (updatedPkg != null) { 5546 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5547 // initially 5548 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5549 5550 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5551 // flag set initially 5552 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5553 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5554 } 5555 } 5556 5557 // Verify certificates against what was last scanned 5558 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5559 5560 /* 5561 * A new system app appeared, but we already had a non-system one of the 5562 * same name installed earlier. 5563 */ 5564 boolean shouldHideSystemApp = false; 5565 if (updatedPkg == null && ps != null 5566 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5567 /* 5568 * Check to make sure the signatures match first. If they don't, 5569 * wipe the installed application and its data. 5570 */ 5571 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5572 != PackageManager.SIGNATURE_MATCH) { 5573 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5574 + " signatures don't match existing userdata copy; removing"); 5575 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5576 ps = null; 5577 } else { 5578 /* 5579 * If the newly-added system app is an older version than the 5580 * already installed version, hide it. It will be scanned later 5581 * and re-added like an update. 5582 */ 5583 if (pkg.mVersionCode <= ps.versionCode) { 5584 shouldHideSystemApp = true; 5585 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5586 + " but new version " + pkg.mVersionCode + " better than installed " 5587 + ps.versionCode + "; hiding system"); 5588 } else { 5589 /* 5590 * The newly found system app is a newer version that the 5591 * one previously installed. Simply remove the 5592 * already-installed application and replace it with our own 5593 * while keeping the application data. 5594 */ 5595 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5596 + " reverting from " + ps.codePathString + ": new version " 5597 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5598 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5599 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5600 synchronized (mInstallLock) { 5601 args.cleanUpResourcesLI(); 5602 } 5603 } 5604 } 5605 } 5606 5607 // The apk is forward locked (not public) if its code and resources 5608 // are kept in different files. (except for app in either system or 5609 // vendor path). 5610 // TODO grab this value from PackageSettings 5611 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5612 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5613 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5614 } 5615 } 5616 5617 // TODO: extend to support forward-locked splits 5618 String resourcePath = null; 5619 String baseResourcePath = null; 5620 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5621 if (ps != null && ps.resourcePathString != null) { 5622 resourcePath = ps.resourcePathString; 5623 baseResourcePath = ps.resourcePathString; 5624 } else { 5625 // Should not happen at all. Just log an error. 5626 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5627 } 5628 } else { 5629 resourcePath = pkg.codePath; 5630 baseResourcePath = pkg.baseCodePath; 5631 } 5632 5633 // Set application objects path explicitly. 5634 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5635 pkg.applicationInfo.setCodePath(pkg.codePath); 5636 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5637 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5638 pkg.applicationInfo.setResourcePath(resourcePath); 5639 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5640 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5641 5642 // Note that we invoke the following method only if we are about to unpack an application 5643 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5644 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5645 5646 /* 5647 * If the system app should be overridden by a previously installed 5648 * data, hide the system app now and let the /data/app scan pick it up 5649 * again. 5650 */ 5651 if (shouldHideSystemApp) { 5652 synchronized (mPackages) { 5653 /* 5654 * We have to grant systems permissions before we hide, because 5655 * grantPermissions will assume the package update is trying to 5656 * expand its permissions. 5657 */ 5658 grantPermissionsLPw(pkg, true, pkg.packageName); 5659 mSettings.disableSystemPackageLPw(pkg.packageName); 5660 } 5661 } 5662 5663 return scannedPkg; 5664 } 5665 5666 private static String fixProcessName(String defProcessName, 5667 String processName, int uid) { 5668 if (processName == null) { 5669 return defProcessName; 5670 } 5671 return processName; 5672 } 5673 5674 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5675 throws PackageManagerException { 5676 if (pkgSetting.signatures.mSignatures != null) { 5677 // Already existing package. Make sure signatures match 5678 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5679 == PackageManager.SIGNATURE_MATCH; 5680 if (!match) { 5681 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5682 == PackageManager.SIGNATURE_MATCH; 5683 } 5684 if (!match) { 5685 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5686 == PackageManager.SIGNATURE_MATCH; 5687 } 5688 if (!match) { 5689 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5690 + pkg.packageName + " signatures do not match the " 5691 + "previously installed version; ignoring!"); 5692 } 5693 } 5694 5695 // Check for shared user signatures 5696 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5697 // Already existing package. Make sure signatures match 5698 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5699 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5700 if (!match) { 5701 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5702 == PackageManager.SIGNATURE_MATCH; 5703 } 5704 if (!match) { 5705 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5706 == PackageManager.SIGNATURE_MATCH; 5707 } 5708 if (!match) { 5709 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5710 "Package " + pkg.packageName 5711 + " has no signatures that match those in shared user " 5712 + pkgSetting.sharedUser.name + "; ignoring!"); 5713 } 5714 } 5715 } 5716 5717 /** 5718 * Enforces that only the system UID or root's UID can call a method exposed 5719 * via Binder. 5720 * 5721 * @param message used as message if SecurityException is thrown 5722 * @throws SecurityException if the caller is not system or root 5723 */ 5724 private static final void enforceSystemOrRoot(String message) { 5725 final int uid = Binder.getCallingUid(); 5726 if (uid != Process.SYSTEM_UID && uid != 0) { 5727 throw new SecurityException(message); 5728 } 5729 } 5730 5731 @Override 5732 public void performBootDexOpt() { 5733 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5734 5735 // Before everything else, see whether we need to fstrim. 5736 try { 5737 IMountService ms = PackageHelper.getMountService(); 5738 if (ms != null) { 5739 final boolean isUpgrade = isUpgrade(); 5740 boolean doTrim = isUpgrade; 5741 if (doTrim) { 5742 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5743 } else { 5744 final long interval = android.provider.Settings.Global.getLong( 5745 mContext.getContentResolver(), 5746 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5747 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5748 if (interval > 0) { 5749 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5750 if (timeSinceLast > interval) { 5751 doTrim = true; 5752 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5753 + "; running immediately"); 5754 } 5755 } 5756 } 5757 if (doTrim) { 5758 if (!isFirstBoot()) { 5759 try { 5760 ActivityManagerNative.getDefault().showBootMessage( 5761 mContext.getResources().getString( 5762 R.string.android_upgrading_fstrim), true); 5763 } catch (RemoteException e) { 5764 } 5765 } 5766 ms.runMaintenance(); 5767 } 5768 } else { 5769 Slog.e(TAG, "Mount service unavailable!"); 5770 } 5771 } catch (RemoteException e) { 5772 // Can't happen; MountService is local 5773 } 5774 5775 final ArraySet<PackageParser.Package> pkgs; 5776 synchronized (mPackages) { 5777 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5778 } 5779 5780 if (pkgs != null) { 5781 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5782 // in case the device runs out of space. 5783 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5784 // Give priority to core apps. 5785 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5786 PackageParser.Package pkg = it.next(); 5787 if (pkg.coreApp) { 5788 if (DEBUG_DEXOPT) { 5789 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5790 } 5791 sortedPkgs.add(pkg); 5792 it.remove(); 5793 } 5794 } 5795 // Give priority to system apps that listen for pre boot complete. 5796 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5797 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5798 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5799 PackageParser.Package pkg = it.next(); 5800 if (pkgNames.contains(pkg.packageName)) { 5801 if (DEBUG_DEXOPT) { 5802 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5803 } 5804 sortedPkgs.add(pkg); 5805 it.remove(); 5806 } 5807 } 5808 // Give priority to system apps. 5809 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5810 PackageParser.Package pkg = it.next(); 5811 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5812 if (DEBUG_DEXOPT) { 5813 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5814 } 5815 sortedPkgs.add(pkg); 5816 it.remove(); 5817 } 5818 } 5819 // Give priority to updated system apps. 5820 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5821 PackageParser.Package pkg = it.next(); 5822 if (pkg.isUpdatedSystemApp()) { 5823 if (DEBUG_DEXOPT) { 5824 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5825 } 5826 sortedPkgs.add(pkg); 5827 it.remove(); 5828 } 5829 } 5830 // Give priority to apps that listen for boot complete. 5831 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5832 pkgNames = getPackageNamesForIntent(intent); 5833 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5834 PackageParser.Package pkg = it.next(); 5835 if (pkgNames.contains(pkg.packageName)) { 5836 if (DEBUG_DEXOPT) { 5837 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5838 } 5839 sortedPkgs.add(pkg); 5840 it.remove(); 5841 } 5842 } 5843 // Filter out packages that aren't recently used. 5844 filterRecentlyUsedApps(pkgs); 5845 // Add all remaining apps. 5846 for (PackageParser.Package pkg : pkgs) { 5847 if (DEBUG_DEXOPT) { 5848 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5849 } 5850 sortedPkgs.add(pkg); 5851 } 5852 5853 // If we want to be lazy, filter everything that wasn't recently used. 5854 if (mLazyDexOpt) { 5855 filterRecentlyUsedApps(sortedPkgs); 5856 } 5857 5858 int i = 0; 5859 int total = sortedPkgs.size(); 5860 File dataDir = Environment.getDataDirectory(); 5861 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5862 if (lowThreshold == 0) { 5863 throw new IllegalStateException("Invalid low memory threshold"); 5864 } 5865 for (PackageParser.Package pkg : sortedPkgs) { 5866 long usableSpace = dataDir.getUsableSpace(); 5867 if (usableSpace < lowThreshold) { 5868 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5869 break; 5870 } 5871 performBootDexOpt(pkg, ++i, total); 5872 } 5873 } 5874 } 5875 5876 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5877 // Filter out packages that aren't recently used. 5878 // 5879 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5880 // should do a full dexopt. 5881 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5882 int total = pkgs.size(); 5883 int skipped = 0; 5884 long now = System.currentTimeMillis(); 5885 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5886 PackageParser.Package pkg = i.next(); 5887 long then = pkg.mLastPackageUsageTimeInMills; 5888 if (then + mDexOptLRUThresholdInMills < now) { 5889 if (DEBUG_DEXOPT) { 5890 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5891 ((then == 0) ? "never" : new Date(then))); 5892 } 5893 i.remove(); 5894 skipped++; 5895 } 5896 } 5897 if (DEBUG_DEXOPT) { 5898 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5899 } 5900 } 5901 } 5902 5903 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5904 List<ResolveInfo> ris = null; 5905 try { 5906 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5907 intent, null, 0, UserHandle.USER_OWNER); 5908 } catch (RemoteException e) { 5909 } 5910 ArraySet<String> pkgNames = new ArraySet<String>(); 5911 if (ris != null) { 5912 for (ResolveInfo ri : ris) { 5913 pkgNames.add(ri.activityInfo.packageName); 5914 } 5915 } 5916 return pkgNames; 5917 } 5918 5919 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5920 if (DEBUG_DEXOPT) { 5921 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5922 } 5923 if (!isFirstBoot()) { 5924 try { 5925 ActivityManagerNative.getDefault().showBootMessage( 5926 mContext.getResources().getString(R.string.android_upgrading_apk, 5927 curr, total), true); 5928 } catch (RemoteException e) { 5929 } 5930 } 5931 PackageParser.Package p = pkg; 5932 synchronized (mInstallLock) { 5933 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5934 false /* force dex */, false /* defer */, true /* include dependencies */); 5935 } 5936 } 5937 5938 @Override 5939 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5940 return performDexOpt(packageName, instructionSet, false); 5941 } 5942 5943 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5944 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5945 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5946 if (!dexopt && !updateUsage) { 5947 // We aren't going to dexopt or update usage, so bail early. 5948 return false; 5949 } 5950 PackageParser.Package p; 5951 final String targetInstructionSet; 5952 synchronized (mPackages) { 5953 p = mPackages.get(packageName); 5954 if (p == null) { 5955 return false; 5956 } 5957 if (updateUsage) { 5958 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5959 } 5960 mPackageUsage.write(false); 5961 if (!dexopt) { 5962 // We aren't going to dexopt, so bail early. 5963 return false; 5964 } 5965 5966 targetInstructionSet = instructionSet != null ? instructionSet : 5967 getPrimaryInstructionSet(p.applicationInfo); 5968 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5969 return false; 5970 } 5971 } 5972 5973 synchronized (mInstallLock) { 5974 final String[] instructionSets = new String[] { targetInstructionSet }; 5975 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5976 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5977 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5978 } 5979 } 5980 5981 public ArraySet<String> getPackagesThatNeedDexOpt() { 5982 ArraySet<String> pkgs = null; 5983 synchronized (mPackages) { 5984 for (PackageParser.Package p : mPackages.values()) { 5985 if (DEBUG_DEXOPT) { 5986 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5987 } 5988 if (!p.mDexOptPerformed.isEmpty()) { 5989 continue; 5990 } 5991 if (pkgs == null) { 5992 pkgs = new ArraySet<String>(); 5993 } 5994 pkgs.add(p.packageName); 5995 } 5996 } 5997 return pkgs; 5998 } 5999 6000 public void shutdown() { 6001 mPackageUsage.write(true); 6002 } 6003 6004 @Override 6005 public void forceDexOpt(String packageName) { 6006 enforceSystemOrRoot("forceDexOpt"); 6007 6008 PackageParser.Package pkg; 6009 synchronized (mPackages) { 6010 pkg = mPackages.get(packageName); 6011 if (pkg == null) { 6012 throw new IllegalArgumentException("Missing package: " + packageName); 6013 } 6014 } 6015 6016 synchronized (mInstallLock) { 6017 final String[] instructionSets = new String[] { 6018 getPrimaryInstructionSet(pkg.applicationInfo) }; 6019 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6020 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6021 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6022 throw new IllegalStateException("Failed to dexopt: " + res); 6023 } 6024 } 6025 } 6026 6027 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6028 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6029 Slog.w(TAG, "Unable to update from " + oldPkg.name 6030 + " to " + newPkg.packageName 6031 + ": old package not in system partition"); 6032 return false; 6033 } else if (mPackages.get(oldPkg.name) != null) { 6034 Slog.w(TAG, "Unable to update from " + oldPkg.name 6035 + " to " + newPkg.packageName 6036 + ": old package still exists"); 6037 return false; 6038 } 6039 return true; 6040 } 6041 6042 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6043 int[] users = sUserManager.getUserIds(); 6044 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6045 if (res < 0) { 6046 return res; 6047 } 6048 for (int user : users) { 6049 if (user != 0) { 6050 res = mInstaller.createUserData(volumeUuid, packageName, 6051 UserHandle.getUid(user, uid), user, seinfo); 6052 if (res < 0) { 6053 return res; 6054 } 6055 } 6056 } 6057 return res; 6058 } 6059 6060 private int removeDataDirsLI(String volumeUuid, String packageName) { 6061 int[] users = sUserManager.getUserIds(); 6062 int res = 0; 6063 for (int user : users) { 6064 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6065 if (resInner < 0) { 6066 res = resInner; 6067 } 6068 } 6069 6070 return res; 6071 } 6072 6073 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6074 int[] users = sUserManager.getUserIds(); 6075 int res = 0; 6076 for (int user : users) { 6077 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6078 if (resInner < 0) { 6079 res = resInner; 6080 } 6081 } 6082 return res; 6083 } 6084 6085 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6086 PackageParser.Package changingLib) { 6087 if (file.path != null) { 6088 usesLibraryFiles.add(file.path); 6089 return; 6090 } 6091 PackageParser.Package p = mPackages.get(file.apk); 6092 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6093 // If we are doing this while in the middle of updating a library apk, 6094 // then we need to make sure to use that new apk for determining the 6095 // dependencies here. (We haven't yet finished committing the new apk 6096 // to the package manager state.) 6097 if (p == null || p.packageName.equals(changingLib.packageName)) { 6098 p = changingLib; 6099 } 6100 } 6101 if (p != null) { 6102 usesLibraryFiles.addAll(p.getAllCodePaths()); 6103 } 6104 } 6105 6106 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6107 PackageParser.Package changingLib) throws PackageManagerException { 6108 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6109 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6110 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6111 for (int i=0; i<N; i++) { 6112 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6113 if (file == null) { 6114 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6115 "Package " + pkg.packageName + " requires unavailable shared library " 6116 + pkg.usesLibraries.get(i) + "; failing!"); 6117 } 6118 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6119 } 6120 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6121 for (int i=0; i<N; i++) { 6122 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6123 if (file == null) { 6124 Slog.w(TAG, "Package " + pkg.packageName 6125 + " desires unavailable shared library " 6126 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6127 } else { 6128 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6129 } 6130 } 6131 N = usesLibraryFiles.size(); 6132 if (N > 0) { 6133 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6134 } else { 6135 pkg.usesLibraryFiles = null; 6136 } 6137 } 6138 } 6139 6140 private static boolean hasString(List<String> list, List<String> which) { 6141 if (list == null) { 6142 return false; 6143 } 6144 for (int i=list.size()-1; i>=0; i--) { 6145 for (int j=which.size()-1; j>=0; j--) { 6146 if (which.get(j).equals(list.get(i))) { 6147 return true; 6148 } 6149 } 6150 } 6151 return false; 6152 } 6153 6154 private void updateAllSharedLibrariesLPw() { 6155 for (PackageParser.Package pkg : mPackages.values()) { 6156 try { 6157 updateSharedLibrariesLPw(pkg, null); 6158 } catch (PackageManagerException e) { 6159 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6160 } 6161 } 6162 } 6163 6164 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6165 PackageParser.Package changingPkg) { 6166 ArrayList<PackageParser.Package> res = null; 6167 for (PackageParser.Package pkg : mPackages.values()) { 6168 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6169 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6170 if (res == null) { 6171 res = new ArrayList<PackageParser.Package>(); 6172 } 6173 res.add(pkg); 6174 try { 6175 updateSharedLibrariesLPw(pkg, changingPkg); 6176 } catch (PackageManagerException e) { 6177 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6178 } 6179 } 6180 } 6181 return res; 6182 } 6183 6184 /** 6185 * Derive the value of the {@code cpuAbiOverride} based on the provided 6186 * value and an optional stored value from the package settings. 6187 */ 6188 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6189 String cpuAbiOverride = null; 6190 6191 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6192 cpuAbiOverride = null; 6193 } else if (abiOverride != null) { 6194 cpuAbiOverride = abiOverride; 6195 } else if (settings != null) { 6196 cpuAbiOverride = settings.cpuAbiOverrideString; 6197 } 6198 6199 return cpuAbiOverride; 6200 } 6201 6202 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6203 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6204 boolean success = false; 6205 try { 6206 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6207 currentTime, user); 6208 success = true; 6209 return res; 6210 } finally { 6211 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6212 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6213 } 6214 } 6215 } 6216 6217 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6218 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6219 final File scanFile = new File(pkg.codePath); 6220 if (pkg.applicationInfo.getCodePath() == null || 6221 pkg.applicationInfo.getResourcePath() == null) { 6222 // Bail out. The resource and code paths haven't been set. 6223 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6224 "Code and resource paths haven't been set correctly"); 6225 } 6226 6227 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6228 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6229 } else { 6230 // Only allow system apps to be flagged as core apps. 6231 pkg.coreApp = false; 6232 } 6233 6234 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6235 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6236 } 6237 6238 if (mCustomResolverComponentName != null && 6239 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6240 setUpCustomResolverActivity(pkg); 6241 } 6242 6243 if (pkg.packageName.equals("android")) { 6244 synchronized (mPackages) { 6245 if (mAndroidApplication != null) { 6246 Slog.w(TAG, "*************************************************"); 6247 Slog.w(TAG, "Core android package being redefined. Skipping."); 6248 Slog.w(TAG, " file=" + scanFile); 6249 Slog.w(TAG, "*************************************************"); 6250 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6251 "Core android package being redefined. Skipping."); 6252 } 6253 6254 // Set up information for our fall-back user intent resolution activity. 6255 mPlatformPackage = pkg; 6256 pkg.mVersionCode = mSdkVersion; 6257 mAndroidApplication = pkg.applicationInfo; 6258 6259 if (!mResolverReplaced) { 6260 mResolveActivity.applicationInfo = mAndroidApplication; 6261 mResolveActivity.name = ResolverActivity.class.getName(); 6262 mResolveActivity.packageName = mAndroidApplication.packageName; 6263 mResolveActivity.processName = "system:ui"; 6264 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6265 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6266 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6267 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6268 mResolveActivity.exported = true; 6269 mResolveActivity.enabled = true; 6270 mResolveInfo.activityInfo = mResolveActivity; 6271 mResolveInfo.priority = 0; 6272 mResolveInfo.preferredOrder = 0; 6273 mResolveInfo.match = 0; 6274 mResolveComponentName = new ComponentName( 6275 mAndroidApplication.packageName, mResolveActivity.name); 6276 } 6277 } 6278 } 6279 6280 if (DEBUG_PACKAGE_SCANNING) { 6281 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6282 Log.d(TAG, "Scanning package " + pkg.packageName); 6283 } 6284 6285 if (mPackages.containsKey(pkg.packageName) 6286 || mSharedLibraries.containsKey(pkg.packageName)) { 6287 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6288 "Application package " + pkg.packageName 6289 + " already installed. Skipping duplicate."); 6290 } 6291 6292 // If we're only installing presumed-existing packages, require that the 6293 // scanned APK is both already known and at the path previously established 6294 // for it. Previously unknown packages we pick up normally, but if we have an 6295 // a priori expectation about this package's install presence, enforce it. 6296 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6297 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6298 if (known != null) { 6299 if (DEBUG_PACKAGE_SCANNING) { 6300 Log.d(TAG, "Examining " + pkg.codePath 6301 + " and requiring known paths " + known.codePathString 6302 + " & " + known.resourcePathString); 6303 } 6304 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6305 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6306 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6307 "Application package " + pkg.packageName 6308 + " found at " + pkg.applicationInfo.getCodePath() 6309 + " but expected at " + known.codePathString + "; ignoring."); 6310 } 6311 } 6312 } 6313 6314 // Initialize package source and resource directories 6315 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6316 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6317 6318 SharedUserSetting suid = null; 6319 PackageSetting pkgSetting = null; 6320 6321 if (!isSystemApp(pkg)) { 6322 // Only system apps can use these features. 6323 pkg.mOriginalPackages = null; 6324 pkg.mRealPackage = null; 6325 pkg.mAdoptPermissions = null; 6326 } 6327 6328 // writer 6329 synchronized (mPackages) { 6330 if (pkg.mSharedUserId != null) { 6331 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6332 if (suid == null) { 6333 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6334 "Creating application package " + pkg.packageName 6335 + " for shared user failed"); 6336 } 6337 if (DEBUG_PACKAGE_SCANNING) { 6338 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6339 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6340 + "): packages=" + suid.packages); 6341 } 6342 } 6343 6344 // Check if we are renaming from an original package name. 6345 PackageSetting origPackage = null; 6346 String realName = null; 6347 if (pkg.mOriginalPackages != null) { 6348 // This package may need to be renamed to a previously 6349 // installed name. Let's check on that... 6350 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6351 if (pkg.mOriginalPackages.contains(renamed)) { 6352 // This package had originally been installed as the 6353 // original name, and we have already taken care of 6354 // transitioning to the new one. Just update the new 6355 // one to continue using the old name. 6356 realName = pkg.mRealPackage; 6357 if (!pkg.packageName.equals(renamed)) { 6358 // Callers into this function may have already taken 6359 // care of renaming the package; only do it here if 6360 // it is not already done. 6361 pkg.setPackageName(renamed); 6362 } 6363 6364 } else { 6365 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6366 if ((origPackage = mSettings.peekPackageLPr( 6367 pkg.mOriginalPackages.get(i))) != null) { 6368 // We do have the package already installed under its 6369 // original name... should we use it? 6370 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6371 // New package is not compatible with original. 6372 origPackage = null; 6373 continue; 6374 } else if (origPackage.sharedUser != null) { 6375 // Make sure uid is compatible between packages. 6376 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6377 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6378 + " to " + pkg.packageName + ": old uid " 6379 + origPackage.sharedUser.name 6380 + " differs from " + pkg.mSharedUserId); 6381 origPackage = null; 6382 continue; 6383 } 6384 } else { 6385 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6386 + pkg.packageName + " to old name " + origPackage.name); 6387 } 6388 break; 6389 } 6390 } 6391 } 6392 } 6393 6394 if (mTransferedPackages.contains(pkg.packageName)) { 6395 Slog.w(TAG, "Package " + pkg.packageName 6396 + " was transferred to another, but its .apk remains"); 6397 } 6398 6399 // Just create the setting, don't add it yet. For already existing packages 6400 // the PkgSetting exists already and doesn't have to be created. 6401 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6402 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6403 pkg.applicationInfo.primaryCpuAbi, 6404 pkg.applicationInfo.secondaryCpuAbi, 6405 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6406 user, false); 6407 if (pkgSetting == null) { 6408 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6409 "Creating application package " + pkg.packageName + " failed"); 6410 } 6411 6412 if (pkgSetting.origPackage != null) { 6413 // If we are first transitioning from an original package, 6414 // fix up the new package's name now. We need to do this after 6415 // looking up the package under its new name, so getPackageLP 6416 // can take care of fiddling things correctly. 6417 pkg.setPackageName(origPackage.name); 6418 6419 // File a report about this. 6420 String msg = "New package " + pkgSetting.realName 6421 + " renamed to replace old package " + pkgSetting.name; 6422 reportSettingsProblem(Log.WARN, msg); 6423 6424 // Make a note of it. 6425 mTransferedPackages.add(origPackage.name); 6426 6427 // No longer need to retain this. 6428 pkgSetting.origPackage = null; 6429 } 6430 6431 if (realName != null) { 6432 // Make a note of it. 6433 mTransferedPackages.add(pkg.packageName); 6434 } 6435 6436 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6437 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6438 } 6439 6440 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6441 // Check all shared libraries and map to their actual file path. 6442 // We only do this here for apps not on a system dir, because those 6443 // are the only ones that can fail an install due to this. We 6444 // will take care of the system apps by updating all of their 6445 // library paths after the scan is done. 6446 updateSharedLibrariesLPw(pkg, null); 6447 } 6448 6449 if (mFoundPolicyFile) { 6450 SELinuxMMAC.assignSeinfoValue(pkg); 6451 } 6452 6453 pkg.applicationInfo.uid = pkgSetting.appId; 6454 pkg.mExtras = pkgSetting; 6455 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6456 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6457 // We just determined the app is signed correctly, so bring 6458 // over the latest parsed certs. 6459 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6460 } else { 6461 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6462 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6463 "Package " + pkg.packageName + " upgrade keys do not match the " 6464 + "previously installed version"); 6465 } else { 6466 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6467 String msg = "System package " + pkg.packageName 6468 + " signature changed; retaining data."; 6469 reportSettingsProblem(Log.WARN, msg); 6470 } 6471 } 6472 } else { 6473 try { 6474 verifySignaturesLP(pkgSetting, pkg); 6475 // We just determined the app is signed correctly, so bring 6476 // over the latest parsed certs. 6477 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6478 } catch (PackageManagerException e) { 6479 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6480 throw e; 6481 } 6482 // The signature has changed, but this package is in the system 6483 // image... let's recover! 6484 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6485 // However... if this package is part of a shared user, but it 6486 // doesn't match the signature of the shared user, let's fail. 6487 // What this means is that you can't change the signatures 6488 // associated with an overall shared user, which doesn't seem all 6489 // that unreasonable. 6490 if (pkgSetting.sharedUser != null) { 6491 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6492 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6493 throw new PackageManagerException( 6494 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6495 "Signature mismatch for shared user : " 6496 + pkgSetting.sharedUser); 6497 } 6498 } 6499 // File a report about this. 6500 String msg = "System package " + pkg.packageName 6501 + " signature changed; retaining data."; 6502 reportSettingsProblem(Log.WARN, msg); 6503 } 6504 } 6505 // Verify that this new package doesn't have any content providers 6506 // that conflict with existing packages. Only do this if the 6507 // package isn't already installed, since we don't want to break 6508 // things that are installed. 6509 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6510 final int N = pkg.providers.size(); 6511 int i; 6512 for (i=0; i<N; i++) { 6513 PackageParser.Provider p = pkg.providers.get(i); 6514 if (p.info.authority != null) { 6515 String names[] = p.info.authority.split(";"); 6516 for (int j = 0; j < names.length; j++) { 6517 if (mProvidersByAuthority.containsKey(names[j])) { 6518 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6519 final String otherPackageName = 6520 ((other != null && other.getComponentName() != null) ? 6521 other.getComponentName().getPackageName() : "?"); 6522 throw new PackageManagerException( 6523 INSTALL_FAILED_CONFLICTING_PROVIDER, 6524 "Can't install because provider name " + names[j] 6525 + " (in package " + pkg.applicationInfo.packageName 6526 + ") is already used by " + otherPackageName); 6527 } 6528 } 6529 } 6530 } 6531 } 6532 6533 if (pkg.mAdoptPermissions != null) { 6534 // This package wants to adopt ownership of permissions from 6535 // another package. 6536 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6537 final String origName = pkg.mAdoptPermissions.get(i); 6538 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6539 if (orig != null) { 6540 if (verifyPackageUpdateLPr(orig, pkg)) { 6541 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6542 + pkg.packageName); 6543 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6544 } 6545 } 6546 } 6547 } 6548 } 6549 6550 final String pkgName = pkg.packageName; 6551 6552 final long scanFileTime = scanFile.lastModified(); 6553 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6554 pkg.applicationInfo.processName = fixProcessName( 6555 pkg.applicationInfo.packageName, 6556 pkg.applicationInfo.processName, 6557 pkg.applicationInfo.uid); 6558 6559 File dataPath; 6560 if (mPlatformPackage == pkg) { 6561 // The system package is special. 6562 dataPath = new File(Environment.getDataDirectory(), "system"); 6563 6564 pkg.applicationInfo.dataDir = dataPath.getPath(); 6565 6566 } else { 6567 // This is a normal package, need to make its data directory. 6568 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6569 UserHandle.USER_OWNER); 6570 6571 boolean uidError = false; 6572 if (dataPath.exists()) { 6573 int currentUid = 0; 6574 try { 6575 StructStat stat = Os.stat(dataPath.getPath()); 6576 currentUid = stat.st_uid; 6577 } catch (ErrnoException e) { 6578 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6579 } 6580 6581 // If we have mismatched owners for the data path, we have a problem. 6582 if (currentUid != pkg.applicationInfo.uid) { 6583 boolean recovered = false; 6584 if (currentUid == 0) { 6585 // The directory somehow became owned by root. Wow. 6586 // This is probably because the system was stopped while 6587 // installd was in the middle of messing with its libs 6588 // directory. Ask installd to fix that. 6589 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6590 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6591 if (ret >= 0) { 6592 recovered = true; 6593 String msg = "Package " + pkg.packageName 6594 + " unexpectedly changed to uid 0; recovered to " + 6595 + pkg.applicationInfo.uid; 6596 reportSettingsProblem(Log.WARN, msg); 6597 } 6598 } 6599 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6600 || (scanFlags&SCAN_BOOTING) != 0)) { 6601 // If this is a system app, we can at least delete its 6602 // current data so the application will still work. 6603 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6604 if (ret >= 0) { 6605 // TODO: Kill the processes first 6606 // Old data gone! 6607 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6608 ? "System package " : "Third party package "; 6609 String msg = prefix + pkg.packageName 6610 + " has changed from uid: " 6611 + currentUid + " to " 6612 + pkg.applicationInfo.uid + "; old data erased"; 6613 reportSettingsProblem(Log.WARN, msg); 6614 recovered = true; 6615 6616 // And now re-install the app. 6617 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6618 pkg.applicationInfo.seinfo); 6619 if (ret == -1) { 6620 // Ack should not happen! 6621 msg = prefix + pkg.packageName 6622 + " could not have data directory re-created after delete."; 6623 reportSettingsProblem(Log.WARN, msg); 6624 throw new PackageManagerException( 6625 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6626 } 6627 } 6628 if (!recovered) { 6629 mHasSystemUidErrors = true; 6630 } 6631 } else if (!recovered) { 6632 // If we allow this install to proceed, we will be broken. 6633 // Abort, abort! 6634 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6635 "scanPackageLI"); 6636 } 6637 if (!recovered) { 6638 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6639 + pkg.applicationInfo.uid + "/fs_" 6640 + currentUid; 6641 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6642 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6643 String msg = "Package " + pkg.packageName 6644 + " has mismatched uid: " 6645 + currentUid + " on disk, " 6646 + pkg.applicationInfo.uid + " in settings"; 6647 // writer 6648 synchronized (mPackages) { 6649 mSettings.mReadMessages.append(msg); 6650 mSettings.mReadMessages.append('\n'); 6651 uidError = true; 6652 if (!pkgSetting.uidError) { 6653 reportSettingsProblem(Log.ERROR, msg); 6654 } 6655 } 6656 } 6657 } 6658 pkg.applicationInfo.dataDir = dataPath.getPath(); 6659 if (mShouldRestoreconData) { 6660 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6661 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6662 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6663 } 6664 } else { 6665 if (DEBUG_PACKAGE_SCANNING) { 6666 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6667 Log.v(TAG, "Want this data dir: " + dataPath); 6668 } 6669 //invoke installer to do the actual installation 6670 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6671 pkg.applicationInfo.seinfo); 6672 if (ret < 0) { 6673 // Error from installer 6674 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6675 "Unable to create data dirs [errorCode=" + ret + "]"); 6676 } 6677 6678 if (dataPath.exists()) { 6679 pkg.applicationInfo.dataDir = dataPath.getPath(); 6680 } else { 6681 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6682 pkg.applicationInfo.dataDir = null; 6683 } 6684 } 6685 6686 pkgSetting.uidError = uidError; 6687 } 6688 6689 final String path = scanFile.getPath(); 6690 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6691 6692 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6693 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6694 6695 // Some system apps still use directory structure for native libraries 6696 // in which case we might end up not detecting abi solely based on apk 6697 // structure. Try to detect abi based on directory structure. 6698 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6699 pkg.applicationInfo.primaryCpuAbi == null) { 6700 setBundledAppAbisAndRoots(pkg, pkgSetting); 6701 setNativeLibraryPaths(pkg); 6702 } 6703 6704 } else { 6705 if ((scanFlags & SCAN_MOVE) != 0) { 6706 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6707 // but we already have this packages package info in the PackageSetting. We just 6708 // use that and derive the native library path based on the new codepath. 6709 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6710 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6711 } 6712 6713 // Set native library paths again. For moves, the path will be updated based on the 6714 // ABIs we've determined above. For non-moves, the path will be updated based on the 6715 // ABIs we determined during compilation, but the path will depend on the final 6716 // package path (after the rename away from the stage path). 6717 setNativeLibraryPaths(pkg); 6718 } 6719 6720 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6721 final int[] userIds = sUserManager.getUserIds(); 6722 synchronized (mInstallLock) { 6723 // Create a native library symlink only if we have native libraries 6724 // and if the native libraries are 32 bit libraries. We do not provide 6725 // this symlink for 64 bit libraries. 6726 if (pkg.applicationInfo.primaryCpuAbi != null && 6727 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6728 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6729 for (int userId : userIds) { 6730 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6731 nativeLibPath, userId) < 0) { 6732 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6733 "Failed linking native library dir (user=" + userId + ")"); 6734 } 6735 } 6736 } 6737 } 6738 6739 // This is a special case for the "system" package, where the ABI is 6740 // dictated by the zygote configuration (and init.rc). We should keep track 6741 // of this ABI so that we can deal with "normal" applications that run under 6742 // the same UID correctly. 6743 if (mPlatformPackage == pkg) { 6744 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6745 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6746 } 6747 6748 // If there's a mismatch between the abi-override in the package setting 6749 // and the abiOverride specified for the install. Warn about this because we 6750 // would've already compiled the app without taking the package setting into 6751 // account. 6752 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6753 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6754 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6755 " for package: " + pkg.packageName); 6756 } 6757 } 6758 6759 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6760 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6761 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6762 6763 // Copy the derived override back to the parsed package, so that we can 6764 // update the package settings accordingly. 6765 pkg.cpuAbiOverride = cpuAbiOverride; 6766 6767 if (DEBUG_ABI_SELECTION) { 6768 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6769 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6770 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6771 } 6772 6773 // Push the derived path down into PackageSettings so we know what to 6774 // clean up at uninstall time. 6775 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6776 6777 if (DEBUG_ABI_SELECTION) { 6778 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6779 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6780 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6781 } 6782 6783 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6784 // We don't do this here during boot because we can do it all 6785 // at once after scanning all existing packages. 6786 // 6787 // We also do this *before* we perform dexopt on this package, so that 6788 // we can avoid redundant dexopts, and also to make sure we've got the 6789 // code and package path correct. 6790 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6791 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6792 } 6793 6794 if ((scanFlags & SCAN_NO_DEX) == 0) { 6795 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6796 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6797 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6798 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6799 } 6800 } 6801 if (mFactoryTest && pkg.requestedPermissions.contains( 6802 android.Manifest.permission.FACTORY_TEST)) { 6803 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6804 } 6805 6806 ArrayList<PackageParser.Package> clientLibPkgs = null; 6807 6808 // writer 6809 synchronized (mPackages) { 6810 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6811 // Only system apps can add new shared libraries. 6812 if (pkg.libraryNames != null) { 6813 for (int i=0; i<pkg.libraryNames.size(); i++) { 6814 String name = pkg.libraryNames.get(i); 6815 boolean allowed = false; 6816 if (pkg.isUpdatedSystemApp()) { 6817 // New library entries can only be added through the 6818 // system image. This is important to get rid of a lot 6819 // of nasty edge cases: for example if we allowed a non- 6820 // system update of the app to add a library, then uninstalling 6821 // the update would make the library go away, and assumptions 6822 // we made such as through app install filtering would now 6823 // have allowed apps on the device which aren't compatible 6824 // with it. Better to just have the restriction here, be 6825 // conservative, and create many fewer cases that can negatively 6826 // impact the user experience. 6827 final PackageSetting sysPs = mSettings 6828 .getDisabledSystemPkgLPr(pkg.packageName); 6829 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6830 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6831 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6832 allowed = true; 6833 allowed = true; 6834 break; 6835 } 6836 } 6837 } 6838 } else { 6839 allowed = true; 6840 } 6841 if (allowed) { 6842 if (!mSharedLibraries.containsKey(name)) { 6843 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6844 } else if (!name.equals(pkg.packageName)) { 6845 Slog.w(TAG, "Package " + pkg.packageName + " library " 6846 + name + " already exists; skipping"); 6847 } 6848 } else { 6849 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6850 + name + " that is not declared on system image; skipping"); 6851 } 6852 } 6853 if ((scanFlags&SCAN_BOOTING) == 0) { 6854 // If we are not booting, we need to update any applications 6855 // that are clients of our shared library. If we are booting, 6856 // this will all be done once the scan is complete. 6857 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6858 } 6859 } 6860 } 6861 } 6862 6863 // We also need to dexopt any apps that are dependent on this library. Note that 6864 // if these fail, we should abort the install since installing the library will 6865 // result in some apps being broken. 6866 if (clientLibPkgs != null) { 6867 if ((scanFlags & SCAN_NO_DEX) == 0) { 6868 for (int i = 0; i < clientLibPkgs.size(); i++) { 6869 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6870 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6871 null /* instruction sets */, forceDex, 6872 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6873 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6874 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6875 "scanPackageLI failed to dexopt clientLibPkgs"); 6876 } 6877 } 6878 } 6879 } 6880 6881 // Also need to kill any apps that are dependent on the library. 6882 if (clientLibPkgs != null) { 6883 for (int i=0; i<clientLibPkgs.size(); i++) { 6884 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6885 killApplication(clientPkg.applicationInfo.packageName, 6886 clientPkg.applicationInfo.uid, "update lib"); 6887 } 6888 } 6889 6890 // Make sure we're not adding any bogus keyset info 6891 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6892 ksms.assertScannedPackageValid(pkg); 6893 6894 // writer 6895 synchronized (mPackages) { 6896 // We don't expect installation to fail beyond this point 6897 6898 // Add the new setting to mSettings 6899 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6900 // Add the new setting to mPackages 6901 mPackages.put(pkg.applicationInfo.packageName, pkg); 6902 // Make sure we don't accidentally delete its data. 6903 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6904 while (iter.hasNext()) { 6905 PackageCleanItem item = iter.next(); 6906 if (pkgName.equals(item.packageName)) { 6907 iter.remove(); 6908 } 6909 } 6910 6911 // Take care of first install / last update times. 6912 if (currentTime != 0) { 6913 if (pkgSetting.firstInstallTime == 0) { 6914 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6915 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6916 pkgSetting.lastUpdateTime = currentTime; 6917 } 6918 } else if (pkgSetting.firstInstallTime == 0) { 6919 // We need *something*. Take time time stamp of the file. 6920 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6921 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6922 if (scanFileTime != pkgSetting.timeStamp) { 6923 // A package on the system image has changed; consider this 6924 // to be an update. 6925 pkgSetting.lastUpdateTime = scanFileTime; 6926 } 6927 } 6928 6929 // Add the package's KeySets to the global KeySetManagerService 6930 ksms.addScannedPackageLPw(pkg); 6931 6932 int N = pkg.providers.size(); 6933 StringBuilder r = null; 6934 int i; 6935 for (i=0; i<N; i++) { 6936 PackageParser.Provider p = pkg.providers.get(i); 6937 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6938 p.info.processName, pkg.applicationInfo.uid); 6939 mProviders.addProvider(p); 6940 p.syncable = p.info.isSyncable; 6941 if (p.info.authority != null) { 6942 String names[] = p.info.authority.split(";"); 6943 p.info.authority = null; 6944 for (int j = 0; j < names.length; j++) { 6945 if (j == 1 && p.syncable) { 6946 // We only want the first authority for a provider to possibly be 6947 // syncable, so if we already added this provider using a different 6948 // authority clear the syncable flag. We copy the provider before 6949 // changing it because the mProviders object contains a reference 6950 // to a provider that we don't want to change. 6951 // Only do this for the second authority since the resulting provider 6952 // object can be the same for all future authorities for this provider. 6953 p = new PackageParser.Provider(p); 6954 p.syncable = false; 6955 } 6956 if (!mProvidersByAuthority.containsKey(names[j])) { 6957 mProvidersByAuthority.put(names[j], p); 6958 if (p.info.authority == null) { 6959 p.info.authority = names[j]; 6960 } else { 6961 p.info.authority = p.info.authority + ";" + names[j]; 6962 } 6963 if (DEBUG_PACKAGE_SCANNING) { 6964 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6965 Log.d(TAG, "Registered content provider: " + names[j] 6966 + ", className = " + p.info.name + ", isSyncable = " 6967 + p.info.isSyncable); 6968 } 6969 } else { 6970 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6971 Slog.w(TAG, "Skipping provider name " + names[j] + 6972 " (in package " + pkg.applicationInfo.packageName + 6973 "): name already used by " 6974 + ((other != null && other.getComponentName() != null) 6975 ? other.getComponentName().getPackageName() : "?")); 6976 } 6977 } 6978 } 6979 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6980 if (r == null) { 6981 r = new StringBuilder(256); 6982 } else { 6983 r.append(' '); 6984 } 6985 r.append(p.info.name); 6986 } 6987 } 6988 if (r != null) { 6989 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6990 } 6991 6992 N = pkg.services.size(); 6993 r = null; 6994 for (i=0; i<N; i++) { 6995 PackageParser.Service s = pkg.services.get(i); 6996 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6997 s.info.processName, pkg.applicationInfo.uid); 6998 mServices.addService(s); 6999 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7000 if (r == null) { 7001 r = new StringBuilder(256); 7002 } else { 7003 r.append(' '); 7004 } 7005 r.append(s.info.name); 7006 } 7007 } 7008 if (r != null) { 7009 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7010 } 7011 7012 N = pkg.receivers.size(); 7013 r = null; 7014 for (i=0; i<N; i++) { 7015 PackageParser.Activity a = pkg.receivers.get(i); 7016 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7017 a.info.processName, pkg.applicationInfo.uid); 7018 mReceivers.addActivity(a, "receiver"); 7019 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7020 if (r == null) { 7021 r = new StringBuilder(256); 7022 } else { 7023 r.append(' '); 7024 } 7025 r.append(a.info.name); 7026 } 7027 } 7028 if (r != null) { 7029 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7030 } 7031 7032 N = pkg.activities.size(); 7033 r = null; 7034 for (i=0; i<N; i++) { 7035 PackageParser.Activity a = pkg.activities.get(i); 7036 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7037 a.info.processName, pkg.applicationInfo.uid); 7038 mActivities.addActivity(a, "activity"); 7039 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7040 if (r == null) { 7041 r = new StringBuilder(256); 7042 } else { 7043 r.append(' '); 7044 } 7045 r.append(a.info.name); 7046 } 7047 } 7048 if (r != null) { 7049 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7050 } 7051 7052 N = pkg.permissionGroups.size(); 7053 r = null; 7054 for (i=0; i<N; i++) { 7055 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7056 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7057 if (cur == null) { 7058 mPermissionGroups.put(pg.info.name, pg); 7059 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7060 if (r == null) { 7061 r = new StringBuilder(256); 7062 } else { 7063 r.append(' '); 7064 } 7065 r.append(pg.info.name); 7066 } 7067 } else { 7068 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7069 + pg.info.packageName + " ignored: original from " 7070 + cur.info.packageName); 7071 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7072 if (r == null) { 7073 r = new StringBuilder(256); 7074 } else { 7075 r.append(' '); 7076 } 7077 r.append("DUP:"); 7078 r.append(pg.info.name); 7079 } 7080 } 7081 } 7082 if (r != null) { 7083 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7084 } 7085 7086 N = pkg.permissions.size(); 7087 r = null; 7088 for (i=0; i<N; i++) { 7089 PackageParser.Permission p = pkg.permissions.get(i); 7090 7091 // Now that permission groups have a special meaning, we ignore permission 7092 // groups for legacy apps to prevent unexpected behavior. In particular, 7093 // permissions for one app being granted to someone just becuase they happen 7094 // to be in a group defined by another app (before this had no implications). 7095 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7096 p.group = mPermissionGroups.get(p.info.group); 7097 // Warn for a permission in an unknown group. 7098 if (p.info.group != null && p.group == null) { 7099 Slog.w(TAG, "Permission " + p.info.name + " from package " 7100 + p.info.packageName + " in an unknown group " + p.info.group); 7101 } 7102 } 7103 7104 ArrayMap<String, BasePermission> permissionMap = 7105 p.tree ? mSettings.mPermissionTrees 7106 : mSettings.mPermissions; 7107 BasePermission bp = permissionMap.get(p.info.name); 7108 7109 // Allow system apps to redefine non-system permissions 7110 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7111 final boolean currentOwnerIsSystem = (bp.perm != null 7112 && isSystemApp(bp.perm.owner)); 7113 if (isSystemApp(p.owner)) { 7114 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7115 // It's a built-in permission and no owner, take ownership now 7116 bp.packageSetting = pkgSetting; 7117 bp.perm = p; 7118 bp.uid = pkg.applicationInfo.uid; 7119 bp.sourcePackage = p.info.packageName; 7120 } else if (!currentOwnerIsSystem) { 7121 String msg = "New decl " + p.owner + " of permission " 7122 + p.info.name + " is system; overriding " + bp.sourcePackage; 7123 reportSettingsProblem(Log.WARN, msg); 7124 bp = null; 7125 } 7126 } 7127 } 7128 7129 if (bp == null) { 7130 bp = new BasePermission(p.info.name, p.info.packageName, 7131 BasePermission.TYPE_NORMAL); 7132 permissionMap.put(p.info.name, bp); 7133 } 7134 7135 if (bp.perm == null) { 7136 if (bp.sourcePackage == null 7137 || bp.sourcePackage.equals(p.info.packageName)) { 7138 BasePermission tree = findPermissionTreeLP(p.info.name); 7139 if (tree == null 7140 || tree.sourcePackage.equals(p.info.packageName)) { 7141 bp.packageSetting = pkgSetting; 7142 bp.perm = p; 7143 bp.uid = pkg.applicationInfo.uid; 7144 bp.sourcePackage = p.info.packageName; 7145 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7146 if (r == null) { 7147 r = new StringBuilder(256); 7148 } else { 7149 r.append(' '); 7150 } 7151 r.append(p.info.name); 7152 } 7153 } else { 7154 Slog.w(TAG, "Permission " + p.info.name + " from package " 7155 + p.info.packageName + " ignored: base tree " 7156 + tree.name + " is from package " 7157 + tree.sourcePackage); 7158 } 7159 } else { 7160 Slog.w(TAG, "Permission " + p.info.name + " from package " 7161 + p.info.packageName + " ignored: original from " 7162 + bp.sourcePackage); 7163 } 7164 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7165 if (r == null) { 7166 r = new StringBuilder(256); 7167 } else { 7168 r.append(' '); 7169 } 7170 r.append("DUP:"); 7171 r.append(p.info.name); 7172 } 7173 if (bp.perm == p) { 7174 bp.protectionLevel = p.info.protectionLevel; 7175 } 7176 } 7177 7178 if (r != null) { 7179 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7180 } 7181 7182 N = pkg.instrumentation.size(); 7183 r = null; 7184 for (i=0; i<N; i++) { 7185 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7186 a.info.packageName = pkg.applicationInfo.packageName; 7187 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7188 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7189 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7190 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7191 a.info.dataDir = pkg.applicationInfo.dataDir; 7192 7193 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7194 // need other information about the application, like the ABI and what not ? 7195 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7196 mInstrumentation.put(a.getComponentName(), a); 7197 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7198 if (r == null) { 7199 r = new StringBuilder(256); 7200 } else { 7201 r.append(' '); 7202 } 7203 r.append(a.info.name); 7204 } 7205 } 7206 if (r != null) { 7207 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7208 } 7209 7210 if (pkg.protectedBroadcasts != null) { 7211 N = pkg.protectedBroadcasts.size(); 7212 for (i=0; i<N; i++) { 7213 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7214 } 7215 } 7216 7217 pkgSetting.setTimeStamp(scanFileTime); 7218 7219 // Create idmap files for pairs of (packages, overlay packages). 7220 // Note: "android", ie framework-res.apk, is handled by native layers. 7221 if (pkg.mOverlayTarget != null) { 7222 // This is an overlay package. 7223 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7224 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7225 mOverlays.put(pkg.mOverlayTarget, 7226 new ArrayMap<String, PackageParser.Package>()); 7227 } 7228 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7229 map.put(pkg.packageName, pkg); 7230 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7231 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7232 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7233 "scanPackageLI failed to createIdmap"); 7234 } 7235 } 7236 } else if (mOverlays.containsKey(pkg.packageName) && 7237 !pkg.packageName.equals("android")) { 7238 // This is a regular package, with one or more known overlay packages. 7239 createIdmapsForPackageLI(pkg); 7240 } 7241 } 7242 7243 return pkg; 7244 } 7245 7246 /** 7247 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7248 * is derived purely on the basis of the contents of {@code scanFile} and 7249 * {@code cpuAbiOverride}. 7250 * 7251 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7252 */ 7253 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7254 String cpuAbiOverride, boolean extractLibs) 7255 throws PackageManagerException { 7256 // TODO: We can probably be smarter about this stuff. For installed apps, 7257 // we can calculate this information at install time once and for all. For 7258 // system apps, we can probably assume that this information doesn't change 7259 // after the first boot scan. As things stand, we do lots of unnecessary work. 7260 7261 // Give ourselves some initial paths; we'll come back for another 7262 // pass once we've determined ABI below. 7263 setNativeLibraryPaths(pkg); 7264 7265 // We would never need to extract libs for forward-locked and external packages, 7266 // since the container service will do it for us. We shouldn't attempt to 7267 // extract libs from system app when it was not updated. 7268 if (pkg.isForwardLocked() || isExternal(pkg) || 7269 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7270 extractLibs = false; 7271 } 7272 7273 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7274 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7275 7276 NativeLibraryHelper.Handle handle = null; 7277 try { 7278 handle = NativeLibraryHelper.Handle.create(scanFile); 7279 // TODO(multiArch): This can be null for apps that didn't go through the 7280 // usual installation process. We can calculate it again, like we 7281 // do during install time. 7282 // 7283 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7284 // unnecessary. 7285 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7286 7287 // Null out the abis so that they can be recalculated. 7288 pkg.applicationInfo.primaryCpuAbi = null; 7289 pkg.applicationInfo.secondaryCpuAbi = null; 7290 if (isMultiArch(pkg.applicationInfo)) { 7291 // Warn if we've set an abiOverride for multi-lib packages.. 7292 // By definition, we need to copy both 32 and 64 bit libraries for 7293 // such packages. 7294 if (pkg.cpuAbiOverride != null 7295 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7296 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7297 } 7298 7299 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7300 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7301 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7302 if (extractLibs) { 7303 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7304 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7305 useIsaSpecificSubdirs); 7306 } else { 7307 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7308 } 7309 } 7310 7311 maybeThrowExceptionForMultiArchCopy( 7312 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7313 7314 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7315 if (extractLibs) { 7316 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7317 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7318 useIsaSpecificSubdirs); 7319 } else { 7320 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7321 } 7322 } 7323 7324 maybeThrowExceptionForMultiArchCopy( 7325 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7326 7327 if (abi64 >= 0) { 7328 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7329 } 7330 7331 if (abi32 >= 0) { 7332 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7333 if (abi64 >= 0) { 7334 pkg.applicationInfo.secondaryCpuAbi = abi; 7335 } else { 7336 pkg.applicationInfo.primaryCpuAbi = abi; 7337 } 7338 } 7339 } else { 7340 String[] abiList = (cpuAbiOverride != null) ? 7341 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7342 7343 // Enable gross and lame hacks for apps that are built with old 7344 // SDK tools. We must scan their APKs for renderscript bitcode and 7345 // not launch them if it's present. Don't bother checking on devices 7346 // that don't have 64 bit support. 7347 boolean needsRenderScriptOverride = false; 7348 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7349 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7350 abiList = Build.SUPPORTED_32_BIT_ABIS; 7351 needsRenderScriptOverride = true; 7352 } 7353 7354 final int copyRet; 7355 if (extractLibs) { 7356 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7357 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7358 } else { 7359 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7360 } 7361 7362 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7363 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7364 "Error unpackaging native libs for app, errorCode=" + copyRet); 7365 } 7366 7367 if (copyRet >= 0) { 7368 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7369 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7370 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7371 } else if (needsRenderScriptOverride) { 7372 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7373 } 7374 } 7375 } catch (IOException ioe) { 7376 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7377 } finally { 7378 IoUtils.closeQuietly(handle); 7379 } 7380 7381 // Now that we've calculated the ABIs and determined if it's an internal app, 7382 // we will go ahead and populate the nativeLibraryPath. 7383 setNativeLibraryPaths(pkg); 7384 } 7385 7386 /** 7387 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7388 * i.e, so that all packages can be run inside a single process if required. 7389 * 7390 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7391 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7392 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7393 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7394 * updating a package that belongs to a shared user. 7395 * 7396 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7397 * adds unnecessary complexity. 7398 */ 7399 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7400 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7401 String requiredInstructionSet = null; 7402 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7403 requiredInstructionSet = VMRuntime.getInstructionSet( 7404 scannedPackage.applicationInfo.primaryCpuAbi); 7405 } 7406 7407 PackageSetting requirer = null; 7408 for (PackageSetting ps : packagesForUser) { 7409 // If packagesForUser contains scannedPackage, we skip it. This will happen 7410 // when scannedPackage is an update of an existing package. Without this check, 7411 // we will never be able to change the ABI of any package belonging to a shared 7412 // user, even if it's compatible with other packages. 7413 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7414 if (ps.primaryCpuAbiString == null) { 7415 continue; 7416 } 7417 7418 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7419 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7420 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7421 // this but there's not much we can do. 7422 String errorMessage = "Instruction set mismatch, " 7423 + ((requirer == null) ? "[caller]" : requirer) 7424 + " requires " + requiredInstructionSet + " whereas " + ps 7425 + " requires " + instructionSet; 7426 Slog.w(TAG, errorMessage); 7427 } 7428 7429 if (requiredInstructionSet == null) { 7430 requiredInstructionSet = instructionSet; 7431 requirer = ps; 7432 } 7433 } 7434 } 7435 7436 if (requiredInstructionSet != null) { 7437 String adjustedAbi; 7438 if (requirer != null) { 7439 // requirer != null implies that either scannedPackage was null or that scannedPackage 7440 // did not require an ABI, in which case we have to adjust scannedPackage to match 7441 // the ABI of the set (which is the same as requirer's ABI) 7442 adjustedAbi = requirer.primaryCpuAbiString; 7443 if (scannedPackage != null) { 7444 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7445 } 7446 } else { 7447 // requirer == null implies that we're updating all ABIs in the set to 7448 // match scannedPackage. 7449 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7450 } 7451 7452 for (PackageSetting ps : packagesForUser) { 7453 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7454 if (ps.primaryCpuAbiString != null) { 7455 continue; 7456 } 7457 7458 ps.primaryCpuAbiString = adjustedAbi; 7459 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7460 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7461 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7462 7463 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7464 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7465 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7466 ps.primaryCpuAbiString = null; 7467 ps.pkg.applicationInfo.primaryCpuAbi = null; 7468 return; 7469 } else { 7470 mInstaller.rmdex(ps.codePathString, 7471 getDexCodeInstructionSet(getPreferredInstructionSet())); 7472 } 7473 } 7474 } 7475 } 7476 } 7477 } 7478 7479 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7480 synchronized (mPackages) { 7481 mResolverReplaced = true; 7482 // Set up information for custom user intent resolution activity. 7483 mResolveActivity.applicationInfo = pkg.applicationInfo; 7484 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7485 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7486 mResolveActivity.processName = pkg.applicationInfo.packageName; 7487 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7488 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7489 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7490 mResolveActivity.theme = 0; 7491 mResolveActivity.exported = true; 7492 mResolveActivity.enabled = true; 7493 mResolveInfo.activityInfo = mResolveActivity; 7494 mResolveInfo.priority = 0; 7495 mResolveInfo.preferredOrder = 0; 7496 mResolveInfo.match = 0; 7497 mResolveComponentName = mCustomResolverComponentName; 7498 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7499 mResolveComponentName); 7500 } 7501 } 7502 7503 private static String calculateBundledApkRoot(final String codePathString) { 7504 final File codePath = new File(codePathString); 7505 final File codeRoot; 7506 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7507 codeRoot = Environment.getRootDirectory(); 7508 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7509 codeRoot = Environment.getOemDirectory(); 7510 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7511 codeRoot = Environment.getVendorDirectory(); 7512 } else { 7513 // Unrecognized code path; take its top real segment as the apk root: 7514 // e.g. /something/app/blah.apk => /something 7515 try { 7516 File f = codePath.getCanonicalFile(); 7517 File parent = f.getParentFile(); // non-null because codePath is a file 7518 File tmp; 7519 while ((tmp = parent.getParentFile()) != null) { 7520 f = parent; 7521 parent = tmp; 7522 } 7523 codeRoot = f; 7524 Slog.w(TAG, "Unrecognized code path " 7525 + codePath + " - using " + codeRoot); 7526 } catch (IOException e) { 7527 // Can't canonicalize the code path -- shenanigans? 7528 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7529 return Environment.getRootDirectory().getPath(); 7530 } 7531 } 7532 return codeRoot.getPath(); 7533 } 7534 7535 /** 7536 * Derive and set the location of native libraries for the given package, 7537 * which varies depending on where and how the package was installed. 7538 */ 7539 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7540 final ApplicationInfo info = pkg.applicationInfo; 7541 final String codePath = pkg.codePath; 7542 final File codeFile = new File(codePath); 7543 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7544 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7545 7546 info.nativeLibraryRootDir = null; 7547 info.nativeLibraryRootRequiresIsa = false; 7548 info.nativeLibraryDir = null; 7549 info.secondaryNativeLibraryDir = null; 7550 7551 if (isApkFile(codeFile)) { 7552 // Monolithic install 7553 if (bundledApp) { 7554 // If "/system/lib64/apkname" exists, assume that is the per-package 7555 // native library directory to use; otherwise use "/system/lib/apkname". 7556 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7557 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7558 getPrimaryInstructionSet(info)); 7559 7560 // This is a bundled system app so choose the path based on the ABI. 7561 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7562 // is just the default path. 7563 final String apkName = deriveCodePathName(codePath); 7564 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7565 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7566 apkName).getAbsolutePath(); 7567 7568 if (info.secondaryCpuAbi != null) { 7569 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7570 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7571 secondaryLibDir, apkName).getAbsolutePath(); 7572 } 7573 } else if (asecApp) { 7574 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7575 .getAbsolutePath(); 7576 } else { 7577 final String apkName = deriveCodePathName(codePath); 7578 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7579 .getAbsolutePath(); 7580 } 7581 7582 info.nativeLibraryRootRequiresIsa = false; 7583 info.nativeLibraryDir = info.nativeLibraryRootDir; 7584 } else { 7585 // Cluster install 7586 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7587 info.nativeLibraryRootRequiresIsa = true; 7588 7589 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7590 getPrimaryInstructionSet(info)).getAbsolutePath(); 7591 7592 if (info.secondaryCpuAbi != null) { 7593 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7594 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7595 } 7596 } 7597 } 7598 7599 /** 7600 * Calculate the abis and roots for a bundled app. These can uniquely 7601 * be determined from the contents of the system partition, i.e whether 7602 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7603 * of this information, and instead assume that the system was built 7604 * sensibly. 7605 */ 7606 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7607 PackageSetting pkgSetting) { 7608 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7609 7610 // If "/system/lib64/apkname" exists, assume that is the per-package 7611 // native library directory to use; otherwise use "/system/lib/apkname". 7612 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7613 setBundledAppAbi(pkg, apkRoot, apkName); 7614 // pkgSetting might be null during rescan following uninstall of updates 7615 // to a bundled app, so accommodate that possibility. The settings in 7616 // that case will be established later from the parsed package. 7617 // 7618 // If the settings aren't null, sync them up with what we've just derived. 7619 // note that apkRoot isn't stored in the package settings. 7620 if (pkgSetting != null) { 7621 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7622 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7623 } 7624 } 7625 7626 /** 7627 * Deduces the ABI of a bundled app and sets the relevant fields on the 7628 * parsed pkg object. 7629 * 7630 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7631 * under which system libraries are installed. 7632 * @param apkName the name of the installed package. 7633 */ 7634 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7635 final File codeFile = new File(pkg.codePath); 7636 7637 final boolean has64BitLibs; 7638 final boolean has32BitLibs; 7639 if (isApkFile(codeFile)) { 7640 // Monolithic install 7641 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7642 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7643 } else { 7644 // Cluster install 7645 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7646 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7647 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7648 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7649 has64BitLibs = (new File(rootDir, isa)).exists(); 7650 } else { 7651 has64BitLibs = false; 7652 } 7653 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7654 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7655 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7656 has32BitLibs = (new File(rootDir, isa)).exists(); 7657 } else { 7658 has32BitLibs = false; 7659 } 7660 } 7661 7662 if (has64BitLibs && !has32BitLibs) { 7663 // The package has 64 bit libs, but not 32 bit libs. Its primary 7664 // ABI should be 64 bit. We can safely assume here that the bundled 7665 // native libraries correspond to the most preferred ABI in the list. 7666 7667 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7668 pkg.applicationInfo.secondaryCpuAbi = null; 7669 } else if (has32BitLibs && !has64BitLibs) { 7670 // The package has 32 bit libs but not 64 bit libs. Its primary 7671 // ABI should be 32 bit. 7672 7673 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7674 pkg.applicationInfo.secondaryCpuAbi = null; 7675 } else if (has32BitLibs && has64BitLibs) { 7676 // The application has both 64 and 32 bit bundled libraries. We check 7677 // here that the app declares multiArch support, and warn if it doesn't. 7678 // 7679 // We will be lenient here and record both ABIs. The primary will be the 7680 // ABI that's higher on the list, i.e, a device that's configured to prefer 7681 // 64 bit apps will see a 64 bit primary ABI, 7682 7683 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7684 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7685 } 7686 7687 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7688 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7689 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7690 } else { 7691 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7692 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7693 } 7694 } else { 7695 pkg.applicationInfo.primaryCpuAbi = null; 7696 pkg.applicationInfo.secondaryCpuAbi = null; 7697 } 7698 } 7699 7700 private void killApplication(String pkgName, int appId, String reason) { 7701 // Request the ActivityManager to kill the process(only for existing packages) 7702 // so that we do not end up in a confused state while the user is still using the older 7703 // version of the application while the new one gets installed. 7704 IActivityManager am = ActivityManagerNative.getDefault(); 7705 if (am != null) { 7706 try { 7707 am.killApplicationWithAppId(pkgName, appId, reason); 7708 } catch (RemoteException e) { 7709 } 7710 } 7711 } 7712 7713 void removePackageLI(PackageSetting ps, boolean chatty) { 7714 if (DEBUG_INSTALL) { 7715 if (chatty) 7716 Log.d(TAG, "Removing package " + ps.name); 7717 } 7718 7719 // writer 7720 synchronized (mPackages) { 7721 mPackages.remove(ps.name); 7722 final PackageParser.Package pkg = ps.pkg; 7723 if (pkg != null) { 7724 cleanPackageDataStructuresLILPw(pkg, chatty); 7725 } 7726 } 7727 } 7728 7729 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7730 if (DEBUG_INSTALL) { 7731 if (chatty) 7732 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7733 } 7734 7735 // writer 7736 synchronized (mPackages) { 7737 mPackages.remove(pkg.applicationInfo.packageName); 7738 cleanPackageDataStructuresLILPw(pkg, chatty); 7739 } 7740 } 7741 7742 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7743 int N = pkg.providers.size(); 7744 StringBuilder r = null; 7745 int i; 7746 for (i=0; i<N; i++) { 7747 PackageParser.Provider p = pkg.providers.get(i); 7748 mProviders.removeProvider(p); 7749 if (p.info.authority == null) { 7750 7751 /* There was another ContentProvider with this authority when 7752 * this app was installed so this authority is null, 7753 * Ignore it as we don't have to unregister the provider. 7754 */ 7755 continue; 7756 } 7757 String names[] = p.info.authority.split(";"); 7758 for (int j = 0; j < names.length; j++) { 7759 if (mProvidersByAuthority.get(names[j]) == p) { 7760 mProvidersByAuthority.remove(names[j]); 7761 if (DEBUG_REMOVE) { 7762 if (chatty) 7763 Log.d(TAG, "Unregistered content provider: " + names[j] 7764 + ", className = " + p.info.name + ", isSyncable = " 7765 + p.info.isSyncable); 7766 } 7767 } 7768 } 7769 if (DEBUG_REMOVE && chatty) { 7770 if (r == null) { 7771 r = new StringBuilder(256); 7772 } else { 7773 r.append(' '); 7774 } 7775 r.append(p.info.name); 7776 } 7777 } 7778 if (r != null) { 7779 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7780 } 7781 7782 N = pkg.services.size(); 7783 r = null; 7784 for (i=0; i<N; i++) { 7785 PackageParser.Service s = pkg.services.get(i); 7786 mServices.removeService(s); 7787 if (chatty) { 7788 if (r == null) { 7789 r = new StringBuilder(256); 7790 } else { 7791 r.append(' '); 7792 } 7793 r.append(s.info.name); 7794 } 7795 } 7796 if (r != null) { 7797 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7798 } 7799 7800 N = pkg.receivers.size(); 7801 r = null; 7802 for (i=0; i<N; i++) { 7803 PackageParser.Activity a = pkg.receivers.get(i); 7804 mReceivers.removeActivity(a, "receiver"); 7805 if (DEBUG_REMOVE && chatty) { 7806 if (r == null) { 7807 r = new StringBuilder(256); 7808 } else { 7809 r.append(' '); 7810 } 7811 r.append(a.info.name); 7812 } 7813 } 7814 if (r != null) { 7815 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7816 } 7817 7818 N = pkg.activities.size(); 7819 r = null; 7820 for (i=0; i<N; i++) { 7821 PackageParser.Activity a = pkg.activities.get(i); 7822 mActivities.removeActivity(a, "activity"); 7823 if (DEBUG_REMOVE && chatty) { 7824 if (r == null) { 7825 r = new StringBuilder(256); 7826 } else { 7827 r.append(' '); 7828 } 7829 r.append(a.info.name); 7830 } 7831 } 7832 if (r != null) { 7833 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7834 } 7835 7836 N = pkg.permissions.size(); 7837 r = null; 7838 for (i=0; i<N; i++) { 7839 PackageParser.Permission p = pkg.permissions.get(i); 7840 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7841 if (bp == null) { 7842 bp = mSettings.mPermissionTrees.get(p.info.name); 7843 } 7844 if (bp != null && bp.perm == p) { 7845 bp.perm = null; 7846 if (DEBUG_REMOVE && chatty) { 7847 if (r == null) { 7848 r = new StringBuilder(256); 7849 } else { 7850 r.append(' '); 7851 } 7852 r.append(p.info.name); 7853 } 7854 } 7855 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7856 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7857 if (appOpPerms != null) { 7858 appOpPerms.remove(pkg.packageName); 7859 } 7860 } 7861 } 7862 if (r != null) { 7863 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7864 } 7865 7866 N = pkg.requestedPermissions.size(); 7867 r = null; 7868 for (i=0; i<N; i++) { 7869 String perm = pkg.requestedPermissions.get(i); 7870 BasePermission bp = mSettings.mPermissions.get(perm); 7871 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7872 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7873 if (appOpPerms != null) { 7874 appOpPerms.remove(pkg.packageName); 7875 if (appOpPerms.isEmpty()) { 7876 mAppOpPermissionPackages.remove(perm); 7877 } 7878 } 7879 } 7880 } 7881 if (r != null) { 7882 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7883 } 7884 7885 N = pkg.instrumentation.size(); 7886 r = null; 7887 for (i=0; i<N; i++) { 7888 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7889 mInstrumentation.remove(a.getComponentName()); 7890 if (DEBUG_REMOVE && chatty) { 7891 if (r == null) { 7892 r = new StringBuilder(256); 7893 } else { 7894 r.append(' '); 7895 } 7896 r.append(a.info.name); 7897 } 7898 } 7899 if (r != null) { 7900 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7901 } 7902 7903 r = null; 7904 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7905 // Only system apps can hold shared libraries. 7906 if (pkg.libraryNames != null) { 7907 for (i=0; i<pkg.libraryNames.size(); i++) { 7908 String name = pkg.libraryNames.get(i); 7909 SharedLibraryEntry cur = mSharedLibraries.get(name); 7910 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7911 mSharedLibraries.remove(name); 7912 if (DEBUG_REMOVE && chatty) { 7913 if (r == null) { 7914 r = new StringBuilder(256); 7915 } else { 7916 r.append(' '); 7917 } 7918 r.append(name); 7919 } 7920 } 7921 } 7922 } 7923 } 7924 if (r != null) { 7925 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7926 } 7927 } 7928 7929 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7930 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7931 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7932 return true; 7933 } 7934 } 7935 return false; 7936 } 7937 7938 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7939 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7940 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7941 7942 private void updatePermissionsLPw(String changingPkg, 7943 PackageParser.Package pkgInfo, int flags) { 7944 // Make sure there are no dangling permission trees. 7945 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7946 while (it.hasNext()) { 7947 final BasePermission bp = it.next(); 7948 if (bp.packageSetting == null) { 7949 // We may not yet have parsed the package, so just see if 7950 // we still know about its settings. 7951 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7952 } 7953 if (bp.packageSetting == null) { 7954 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7955 + " from package " + bp.sourcePackage); 7956 it.remove(); 7957 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7958 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7959 Slog.i(TAG, "Removing old permission tree: " + bp.name 7960 + " from package " + bp.sourcePackage); 7961 flags |= UPDATE_PERMISSIONS_ALL; 7962 it.remove(); 7963 } 7964 } 7965 } 7966 7967 // Make sure all dynamic permissions have been assigned to a package, 7968 // and make sure there are no dangling permissions. 7969 it = mSettings.mPermissions.values().iterator(); 7970 while (it.hasNext()) { 7971 final BasePermission bp = it.next(); 7972 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7973 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7974 + bp.name + " pkg=" + bp.sourcePackage 7975 + " info=" + bp.pendingInfo); 7976 if (bp.packageSetting == null && bp.pendingInfo != null) { 7977 final BasePermission tree = findPermissionTreeLP(bp.name); 7978 if (tree != null && tree.perm != null) { 7979 bp.packageSetting = tree.packageSetting; 7980 bp.perm = new PackageParser.Permission(tree.perm.owner, 7981 new PermissionInfo(bp.pendingInfo)); 7982 bp.perm.info.packageName = tree.perm.info.packageName; 7983 bp.perm.info.name = bp.name; 7984 bp.uid = tree.uid; 7985 } 7986 } 7987 } 7988 if (bp.packageSetting == null) { 7989 // We may not yet have parsed the package, so just see if 7990 // we still know about its settings. 7991 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7992 } 7993 if (bp.packageSetting == null) { 7994 Slog.w(TAG, "Removing dangling permission: " + bp.name 7995 + " from package " + bp.sourcePackage); 7996 it.remove(); 7997 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7998 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7999 Slog.i(TAG, "Removing old permission: " + bp.name 8000 + " from package " + bp.sourcePackage); 8001 flags |= UPDATE_PERMISSIONS_ALL; 8002 it.remove(); 8003 } 8004 } 8005 } 8006 8007 // Now update the permissions for all packages, in particular 8008 // replace the granted permissions of the system packages. 8009 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8010 for (PackageParser.Package pkg : mPackages.values()) { 8011 if (pkg != pkgInfo) { 8012 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8013 changingPkg); 8014 } 8015 } 8016 } 8017 8018 if (pkgInfo != null) { 8019 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8020 } 8021 } 8022 8023 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8024 String packageOfInterest) { 8025 // IMPORTANT: There are two types of permissions: install and runtime. 8026 // Install time permissions are granted when the app is installed to 8027 // all device users and users added in the future. Runtime permissions 8028 // are granted at runtime explicitly to specific users. Normal and signature 8029 // protected permissions are install time permissions. Dangerous permissions 8030 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8031 // otherwise they are runtime permissions. This function does not manage 8032 // runtime permissions except for the case an app targeting Lollipop MR1 8033 // being upgraded to target a newer SDK, in which case dangerous permissions 8034 // are transformed from install time to runtime ones. 8035 8036 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8037 if (ps == null) { 8038 return; 8039 } 8040 8041 PermissionsState permissionsState = ps.getPermissionsState(); 8042 PermissionsState origPermissions = permissionsState; 8043 8044 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8045 8046 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8047 8048 boolean changedInstallPermission = false; 8049 8050 if (replace) { 8051 ps.installPermissionsFixed = false; 8052 if (!ps.isSharedUser()) { 8053 origPermissions = new PermissionsState(permissionsState); 8054 permissionsState.reset(); 8055 } 8056 } 8057 8058 permissionsState.setGlobalGids(mGlobalGids); 8059 8060 final int N = pkg.requestedPermissions.size(); 8061 for (int i=0; i<N; i++) { 8062 final String name = pkg.requestedPermissions.get(i); 8063 final BasePermission bp = mSettings.mPermissions.get(name); 8064 8065 if (DEBUG_INSTALL) { 8066 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8067 } 8068 8069 if (bp == null || bp.packageSetting == null) { 8070 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8071 Slog.w(TAG, "Unknown permission " + name 8072 + " in package " + pkg.packageName); 8073 } 8074 continue; 8075 } 8076 8077 final String perm = bp.name; 8078 boolean allowedSig = false; 8079 int grant = GRANT_DENIED; 8080 8081 // Keep track of app op permissions. 8082 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8083 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8084 if (pkgs == null) { 8085 pkgs = new ArraySet<>(); 8086 mAppOpPermissionPackages.put(bp.name, pkgs); 8087 } 8088 pkgs.add(pkg.packageName); 8089 } 8090 8091 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8092 switch (level) { 8093 case PermissionInfo.PROTECTION_NORMAL: { 8094 // For all apps normal permissions are install time ones. 8095 grant = GRANT_INSTALL; 8096 } break; 8097 8098 case PermissionInfo.PROTECTION_DANGEROUS: { 8099 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8100 // For legacy apps dangerous permissions are install time ones. 8101 grant = GRANT_INSTALL_LEGACY; 8102 } else if (origPermissions.hasInstallPermission(bp.name)) { 8103 // For legacy apps that became modern, install becomes runtime. 8104 grant = GRANT_UPGRADE; 8105 } else { 8106 // For modern apps keep runtime permissions unchanged. 8107 grant = GRANT_RUNTIME; 8108 } 8109 } break; 8110 8111 case PermissionInfo.PROTECTION_SIGNATURE: { 8112 // For all apps signature permissions are install time ones. 8113 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8114 if (allowedSig) { 8115 grant = GRANT_INSTALL; 8116 } 8117 } break; 8118 } 8119 8120 if (DEBUG_INSTALL) { 8121 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8122 } 8123 8124 if (grant != GRANT_DENIED) { 8125 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8126 // If this is an existing, non-system package, then 8127 // we can't add any new permissions to it. 8128 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8129 // Except... if this is a permission that was added 8130 // to the platform (note: need to only do this when 8131 // updating the platform). 8132 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8133 grant = GRANT_DENIED; 8134 } 8135 } 8136 } 8137 8138 switch (grant) { 8139 case GRANT_INSTALL: { 8140 // Revoke this as runtime permission to handle the case of 8141 // a runtime permission being downgraded to an install one. 8142 for (int userId : UserManagerService.getInstance().getUserIds()) { 8143 if (origPermissions.getRuntimePermissionState( 8144 bp.name, userId) != null) { 8145 // Revoke the runtime permission and clear the flags. 8146 origPermissions.revokeRuntimePermission(bp, userId); 8147 origPermissions.updatePermissionFlags(bp, userId, 8148 PackageManager.MASK_PERMISSION_FLAGS, 0); 8149 // If we revoked a permission permission, we have to write. 8150 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8151 changedRuntimePermissionUserIds, userId); 8152 } 8153 } 8154 // Grant an install permission. 8155 if (permissionsState.grantInstallPermission(bp) != 8156 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8157 changedInstallPermission = true; 8158 } 8159 } break; 8160 8161 case GRANT_INSTALL_LEGACY: { 8162 // Grant an install permission. 8163 if (permissionsState.grantInstallPermission(bp) != 8164 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8165 changedInstallPermission = true; 8166 } 8167 } break; 8168 8169 case GRANT_RUNTIME: { 8170 // Grant previously granted runtime permissions. 8171 for (int userId : UserManagerService.getInstance().getUserIds()) { 8172 PermissionState permissionState = origPermissions 8173 .getRuntimePermissionState(bp.name, userId); 8174 final int flags = permissionState != null 8175 ? permissionState.getFlags() : 0; 8176 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8177 if (permissionsState.grantRuntimePermission(bp, userId) == 8178 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8179 // If we cannot put the permission as it was, we have to write. 8180 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8181 changedRuntimePermissionUserIds, userId); 8182 } 8183 } 8184 // Propagate the permission flags. 8185 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8186 } 8187 } break; 8188 8189 case GRANT_UPGRADE: { 8190 // Grant runtime permissions for a previously held install permission. 8191 PermissionState permissionState = origPermissions 8192 .getInstallPermissionState(bp.name); 8193 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8194 8195 if (origPermissions.revokeInstallPermission(bp) 8196 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8197 // We will be transferring the permission flags, so clear them. 8198 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8199 PackageManager.MASK_PERMISSION_FLAGS, 0); 8200 changedInstallPermission = true; 8201 } 8202 8203 // If the permission is not to be promoted to runtime we ignore it and 8204 // also its other flags as they are not applicable to install permissions. 8205 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8206 for (int userId : currentUserIds) { 8207 if (permissionsState.grantRuntimePermission(bp, userId) != 8208 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8209 // Transfer the permission flags. 8210 permissionsState.updatePermissionFlags(bp, userId, 8211 flags, flags); 8212 // If we granted the permission, we have to write. 8213 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8214 changedRuntimePermissionUserIds, userId); 8215 } 8216 } 8217 } 8218 } break; 8219 8220 default: { 8221 if (packageOfInterest == null 8222 || packageOfInterest.equals(pkg.packageName)) { 8223 Slog.w(TAG, "Not granting permission " + perm 8224 + " to package " + pkg.packageName 8225 + " because it was previously installed without"); 8226 } 8227 } break; 8228 } 8229 } else { 8230 if (permissionsState.revokeInstallPermission(bp) != 8231 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8232 // Also drop the permission flags. 8233 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8234 PackageManager.MASK_PERMISSION_FLAGS, 0); 8235 changedInstallPermission = true; 8236 Slog.i(TAG, "Un-granting permission " + perm 8237 + " from package " + pkg.packageName 8238 + " (protectionLevel=" + bp.protectionLevel 8239 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8240 + ")"); 8241 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8242 // Don't print warning for app op permissions, since it is fine for them 8243 // not to be granted, there is a UI for the user to decide. 8244 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8245 Slog.w(TAG, "Not granting permission " + perm 8246 + " to package " + pkg.packageName 8247 + " (protectionLevel=" + bp.protectionLevel 8248 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8249 + ")"); 8250 } 8251 } 8252 } 8253 } 8254 8255 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8256 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8257 // This is the first that we have heard about this package, so the 8258 // permissions we have now selected are fixed until explicitly 8259 // changed. 8260 ps.installPermissionsFixed = true; 8261 } 8262 8263 // Persist the runtime permissions state for users with changes. 8264 for (int userId : changedRuntimePermissionUserIds) { 8265 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8266 } 8267 } 8268 8269 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8270 boolean allowed = false; 8271 final int NP = PackageParser.NEW_PERMISSIONS.length; 8272 for (int ip=0; ip<NP; ip++) { 8273 final PackageParser.NewPermissionInfo npi 8274 = PackageParser.NEW_PERMISSIONS[ip]; 8275 if (npi.name.equals(perm) 8276 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8277 allowed = true; 8278 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8279 + pkg.packageName); 8280 break; 8281 } 8282 } 8283 return allowed; 8284 } 8285 8286 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8287 BasePermission bp, PermissionsState origPermissions) { 8288 boolean allowed; 8289 allowed = (compareSignatures( 8290 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8291 == PackageManager.SIGNATURE_MATCH) 8292 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8293 == PackageManager.SIGNATURE_MATCH); 8294 if (!allowed && (bp.protectionLevel 8295 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8296 if (isSystemApp(pkg)) { 8297 // For updated system applications, a system permission 8298 // is granted only if it had been defined by the original application. 8299 if (pkg.isUpdatedSystemApp()) { 8300 final PackageSetting sysPs = mSettings 8301 .getDisabledSystemPkgLPr(pkg.packageName); 8302 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8303 // If the original was granted this permission, we take 8304 // that grant decision as read and propagate it to the 8305 // update. 8306 if (sysPs.isPrivileged()) { 8307 allowed = true; 8308 } 8309 } else { 8310 // The system apk may have been updated with an older 8311 // version of the one on the data partition, but which 8312 // granted a new system permission that it didn't have 8313 // before. In this case we do want to allow the app to 8314 // now get the new permission if the ancestral apk is 8315 // privileged to get it. 8316 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8317 for (int j=0; 8318 j<sysPs.pkg.requestedPermissions.size(); j++) { 8319 if (perm.equals( 8320 sysPs.pkg.requestedPermissions.get(j))) { 8321 allowed = true; 8322 break; 8323 } 8324 } 8325 } 8326 } 8327 } else { 8328 allowed = isPrivilegedApp(pkg); 8329 } 8330 } 8331 } 8332 if (!allowed && (bp.protectionLevel 8333 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8334 // For development permissions, a development permission 8335 // is granted only if it was already granted. 8336 allowed = origPermissions.hasInstallPermission(perm); 8337 } 8338 return allowed; 8339 } 8340 8341 final class ActivityIntentResolver 8342 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8343 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8344 boolean defaultOnly, int userId) { 8345 if (!sUserManager.exists(userId)) return null; 8346 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8347 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8348 } 8349 8350 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8351 int userId) { 8352 if (!sUserManager.exists(userId)) return null; 8353 mFlags = flags; 8354 return super.queryIntent(intent, resolvedType, 8355 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8356 } 8357 8358 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8359 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8360 if (!sUserManager.exists(userId)) return null; 8361 if (packageActivities == null) { 8362 return null; 8363 } 8364 mFlags = flags; 8365 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8366 final int N = packageActivities.size(); 8367 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8368 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8369 8370 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8371 for (int i = 0; i < N; ++i) { 8372 intentFilters = packageActivities.get(i).intents; 8373 if (intentFilters != null && intentFilters.size() > 0) { 8374 PackageParser.ActivityIntentInfo[] array = 8375 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8376 intentFilters.toArray(array); 8377 listCut.add(array); 8378 } 8379 } 8380 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8381 } 8382 8383 public final void addActivity(PackageParser.Activity a, String type) { 8384 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8385 mActivities.put(a.getComponentName(), a); 8386 if (DEBUG_SHOW_INFO) 8387 Log.v( 8388 TAG, " " + type + " " + 8389 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8390 if (DEBUG_SHOW_INFO) 8391 Log.v(TAG, " Class=" + a.info.name); 8392 final int NI = a.intents.size(); 8393 for (int j=0; j<NI; j++) { 8394 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8395 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8396 intent.setPriority(0); 8397 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8398 + a.className + " with priority > 0, forcing to 0"); 8399 } 8400 if (DEBUG_SHOW_INFO) { 8401 Log.v(TAG, " IntentFilter:"); 8402 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8403 } 8404 if (!intent.debugCheck()) { 8405 Log.w(TAG, "==> For Activity " + a.info.name); 8406 } 8407 addFilter(intent); 8408 } 8409 } 8410 8411 public final void removeActivity(PackageParser.Activity a, String type) { 8412 mActivities.remove(a.getComponentName()); 8413 if (DEBUG_SHOW_INFO) { 8414 Log.v(TAG, " " + type + " " 8415 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8416 : a.info.name) + ":"); 8417 Log.v(TAG, " Class=" + a.info.name); 8418 } 8419 final int NI = a.intents.size(); 8420 for (int j=0; j<NI; j++) { 8421 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8422 if (DEBUG_SHOW_INFO) { 8423 Log.v(TAG, " IntentFilter:"); 8424 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8425 } 8426 removeFilter(intent); 8427 } 8428 } 8429 8430 @Override 8431 protected boolean allowFilterResult( 8432 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8433 ActivityInfo filterAi = filter.activity.info; 8434 for (int i=dest.size()-1; i>=0; i--) { 8435 ActivityInfo destAi = dest.get(i).activityInfo; 8436 if (destAi.name == filterAi.name 8437 && destAi.packageName == filterAi.packageName) { 8438 return false; 8439 } 8440 } 8441 return true; 8442 } 8443 8444 @Override 8445 protected ActivityIntentInfo[] newArray(int size) { 8446 return new ActivityIntentInfo[size]; 8447 } 8448 8449 @Override 8450 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8451 if (!sUserManager.exists(userId)) return true; 8452 PackageParser.Package p = filter.activity.owner; 8453 if (p != null) { 8454 PackageSetting ps = (PackageSetting)p.mExtras; 8455 if (ps != null) { 8456 // System apps are never considered stopped for purposes of 8457 // filtering, because there may be no way for the user to 8458 // actually re-launch them. 8459 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8460 && ps.getStopped(userId); 8461 } 8462 } 8463 return false; 8464 } 8465 8466 @Override 8467 protected boolean isPackageForFilter(String packageName, 8468 PackageParser.ActivityIntentInfo info) { 8469 return packageName.equals(info.activity.owner.packageName); 8470 } 8471 8472 @Override 8473 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8474 int match, int userId) { 8475 if (!sUserManager.exists(userId)) return null; 8476 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8477 return null; 8478 } 8479 final PackageParser.Activity activity = info.activity; 8480 if (mSafeMode && (activity.info.applicationInfo.flags 8481 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8482 return null; 8483 } 8484 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8485 if (ps == null) { 8486 return null; 8487 } 8488 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8489 ps.readUserState(userId), userId); 8490 if (ai == null) { 8491 return null; 8492 } 8493 final ResolveInfo res = new ResolveInfo(); 8494 res.activityInfo = ai; 8495 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8496 res.filter = info; 8497 } 8498 if (info != null) { 8499 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8500 } 8501 res.priority = info.getPriority(); 8502 res.preferredOrder = activity.owner.mPreferredOrder; 8503 //System.out.println("Result: " + res.activityInfo.className + 8504 // " = " + res.priority); 8505 res.match = match; 8506 res.isDefault = info.hasDefault; 8507 res.labelRes = info.labelRes; 8508 res.nonLocalizedLabel = info.nonLocalizedLabel; 8509 if (userNeedsBadging(userId)) { 8510 res.noResourceId = true; 8511 } else { 8512 res.icon = info.icon; 8513 } 8514 res.iconResourceId = info.icon; 8515 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8516 return res; 8517 } 8518 8519 @Override 8520 protected void sortResults(List<ResolveInfo> results) { 8521 Collections.sort(results, mResolvePrioritySorter); 8522 } 8523 8524 @Override 8525 protected void dumpFilter(PrintWriter out, String prefix, 8526 PackageParser.ActivityIntentInfo filter) { 8527 out.print(prefix); out.print( 8528 Integer.toHexString(System.identityHashCode(filter.activity))); 8529 out.print(' '); 8530 filter.activity.printComponentShortName(out); 8531 out.print(" filter "); 8532 out.println(Integer.toHexString(System.identityHashCode(filter))); 8533 } 8534 8535 @Override 8536 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8537 return filter.activity; 8538 } 8539 8540 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8541 PackageParser.Activity activity = (PackageParser.Activity)label; 8542 out.print(prefix); out.print( 8543 Integer.toHexString(System.identityHashCode(activity))); 8544 out.print(' '); 8545 activity.printComponentShortName(out); 8546 if (count > 1) { 8547 out.print(" ("); out.print(count); out.print(" filters)"); 8548 } 8549 out.println(); 8550 } 8551 8552// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8553// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8554// final List<ResolveInfo> retList = Lists.newArrayList(); 8555// while (i.hasNext()) { 8556// final ResolveInfo resolveInfo = i.next(); 8557// if (isEnabledLP(resolveInfo.activityInfo)) { 8558// retList.add(resolveInfo); 8559// } 8560// } 8561// return retList; 8562// } 8563 8564 // Keys are String (activity class name), values are Activity. 8565 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8566 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8567 private int mFlags; 8568 } 8569 8570 private final class ServiceIntentResolver 8571 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8572 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8573 boolean defaultOnly, int userId) { 8574 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8575 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8576 } 8577 8578 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8579 int userId) { 8580 if (!sUserManager.exists(userId)) return null; 8581 mFlags = flags; 8582 return super.queryIntent(intent, resolvedType, 8583 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8584 } 8585 8586 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8587 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8588 if (!sUserManager.exists(userId)) return null; 8589 if (packageServices == null) { 8590 return null; 8591 } 8592 mFlags = flags; 8593 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8594 final int N = packageServices.size(); 8595 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8596 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8597 8598 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8599 for (int i = 0; i < N; ++i) { 8600 intentFilters = packageServices.get(i).intents; 8601 if (intentFilters != null && intentFilters.size() > 0) { 8602 PackageParser.ServiceIntentInfo[] array = 8603 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8604 intentFilters.toArray(array); 8605 listCut.add(array); 8606 } 8607 } 8608 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8609 } 8610 8611 public final void addService(PackageParser.Service s) { 8612 mServices.put(s.getComponentName(), s); 8613 if (DEBUG_SHOW_INFO) { 8614 Log.v(TAG, " " 8615 + (s.info.nonLocalizedLabel != null 8616 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8617 Log.v(TAG, " Class=" + s.info.name); 8618 } 8619 final int NI = s.intents.size(); 8620 int j; 8621 for (j=0; j<NI; j++) { 8622 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8623 if (DEBUG_SHOW_INFO) { 8624 Log.v(TAG, " IntentFilter:"); 8625 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8626 } 8627 if (!intent.debugCheck()) { 8628 Log.w(TAG, "==> For Service " + s.info.name); 8629 } 8630 addFilter(intent); 8631 } 8632 } 8633 8634 public final void removeService(PackageParser.Service s) { 8635 mServices.remove(s.getComponentName()); 8636 if (DEBUG_SHOW_INFO) { 8637 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8638 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8639 Log.v(TAG, " Class=" + s.info.name); 8640 } 8641 final int NI = s.intents.size(); 8642 int j; 8643 for (j=0; j<NI; j++) { 8644 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8645 if (DEBUG_SHOW_INFO) { 8646 Log.v(TAG, " IntentFilter:"); 8647 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8648 } 8649 removeFilter(intent); 8650 } 8651 } 8652 8653 @Override 8654 protected boolean allowFilterResult( 8655 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8656 ServiceInfo filterSi = filter.service.info; 8657 for (int i=dest.size()-1; i>=0; i--) { 8658 ServiceInfo destAi = dest.get(i).serviceInfo; 8659 if (destAi.name == filterSi.name 8660 && destAi.packageName == filterSi.packageName) { 8661 return false; 8662 } 8663 } 8664 return true; 8665 } 8666 8667 @Override 8668 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8669 return new PackageParser.ServiceIntentInfo[size]; 8670 } 8671 8672 @Override 8673 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8674 if (!sUserManager.exists(userId)) return true; 8675 PackageParser.Package p = filter.service.owner; 8676 if (p != null) { 8677 PackageSetting ps = (PackageSetting)p.mExtras; 8678 if (ps != null) { 8679 // System apps are never considered stopped for purposes of 8680 // filtering, because there may be no way for the user to 8681 // actually re-launch them. 8682 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8683 && ps.getStopped(userId); 8684 } 8685 } 8686 return false; 8687 } 8688 8689 @Override 8690 protected boolean isPackageForFilter(String packageName, 8691 PackageParser.ServiceIntentInfo info) { 8692 return packageName.equals(info.service.owner.packageName); 8693 } 8694 8695 @Override 8696 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8697 int match, int userId) { 8698 if (!sUserManager.exists(userId)) return null; 8699 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8700 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8701 return null; 8702 } 8703 final PackageParser.Service service = info.service; 8704 if (mSafeMode && (service.info.applicationInfo.flags 8705 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8706 return null; 8707 } 8708 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8709 if (ps == null) { 8710 return null; 8711 } 8712 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8713 ps.readUserState(userId), userId); 8714 if (si == null) { 8715 return null; 8716 } 8717 final ResolveInfo res = new ResolveInfo(); 8718 res.serviceInfo = si; 8719 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8720 res.filter = filter; 8721 } 8722 res.priority = info.getPriority(); 8723 res.preferredOrder = service.owner.mPreferredOrder; 8724 res.match = match; 8725 res.isDefault = info.hasDefault; 8726 res.labelRes = info.labelRes; 8727 res.nonLocalizedLabel = info.nonLocalizedLabel; 8728 res.icon = info.icon; 8729 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8730 return res; 8731 } 8732 8733 @Override 8734 protected void sortResults(List<ResolveInfo> results) { 8735 Collections.sort(results, mResolvePrioritySorter); 8736 } 8737 8738 @Override 8739 protected void dumpFilter(PrintWriter out, String prefix, 8740 PackageParser.ServiceIntentInfo filter) { 8741 out.print(prefix); out.print( 8742 Integer.toHexString(System.identityHashCode(filter.service))); 8743 out.print(' '); 8744 filter.service.printComponentShortName(out); 8745 out.print(" filter "); 8746 out.println(Integer.toHexString(System.identityHashCode(filter))); 8747 } 8748 8749 @Override 8750 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8751 return filter.service; 8752 } 8753 8754 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8755 PackageParser.Service service = (PackageParser.Service)label; 8756 out.print(prefix); out.print( 8757 Integer.toHexString(System.identityHashCode(service))); 8758 out.print(' '); 8759 service.printComponentShortName(out); 8760 if (count > 1) { 8761 out.print(" ("); out.print(count); out.print(" filters)"); 8762 } 8763 out.println(); 8764 } 8765 8766// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8767// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8768// final List<ResolveInfo> retList = Lists.newArrayList(); 8769// while (i.hasNext()) { 8770// final ResolveInfo resolveInfo = (ResolveInfo) i; 8771// if (isEnabledLP(resolveInfo.serviceInfo)) { 8772// retList.add(resolveInfo); 8773// } 8774// } 8775// return retList; 8776// } 8777 8778 // Keys are String (activity class name), values are Activity. 8779 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8780 = new ArrayMap<ComponentName, PackageParser.Service>(); 8781 private int mFlags; 8782 }; 8783 8784 private final class ProviderIntentResolver 8785 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8786 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8787 boolean defaultOnly, int userId) { 8788 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8789 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8790 } 8791 8792 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8793 int userId) { 8794 if (!sUserManager.exists(userId)) 8795 return null; 8796 mFlags = flags; 8797 return super.queryIntent(intent, resolvedType, 8798 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8799 } 8800 8801 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8802 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8803 if (!sUserManager.exists(userId)) 8804 return null; 8805 if (packageProviders == null) { 8806 return null; 8807 } 8808 mFlags = flags; 8809 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8810 final int N = packageProviders.size(); 8811 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8812 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8813 8814 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8815 for (int i = 0; i < N; ++i) { 8816 intentFilters = packageProviders.get(i).intents; 8817 if (intentFilters != null && intentFilters.size() > 0) { 8818 PackageParser.ProviderIntentInfo[] array = 8819 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8820 intentFilters.toArray(array); 8821 listCut.add(array); 8822 } 8823 } 8824 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8825 } 8826 8827 public final void addProvider(PackageParser.Provider p) { 8828 if (mProviders.containsKey(p.getComponentName())) { 8829 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8830 return; 8831 } 8832 8833 mProviders.put(p.getComponentName(), p); 8834 if (DEBUG_SHOW_INFO) { 8835 Log.v(TAG, " " 8836 + (p.info.nonLocalizedLabel != null 8837 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8838 Log.v(TAG, " Class=" + p.info.name); 8839 } 8840 final int NI = p.intents.size(); 8841 int j; 8842 for (j = 0; j < NI; j++) { 8843 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8844 if (DEBUG_SHOW_INFO) { 8845 Log.v(TAG, " IntentFilter:"); 8846 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8847 } 8848 if (!intent.debugCheck()) { 8849 Log.w(TAG, "==> For Provider " + p.info.name); 8850 } 8851 addFilter(intent); 8852 } 8853 } 8854 8855 public final void removeProvider(PackageParser.Provider p) { 8856 mProviders.remove(p.getComponentName()); 8857 if (DEBUG_SHOW_INFO) { 8858 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8859 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8860 Log.v(TAG, " Class=" + p.info.name); 8861 } 8862 final int NI = p.intents.size(); 8863 int j; 8864 for (j = 0; j < NI; j++) { 8865 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8866 if (DEBUG_SHOW_INFO) { 8867 Log.v(TAG, " IntentFilter:"); 8868 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8869 } 8870 removeFilter(intent); 8871 } 8872 } 8873 8874 @Override 8875 protected boolean allowFilterResult( 8876 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8877 ProviderInfo filterPi = filter.provider.info; 8878 for (int i = dest.size() - 1; i >= 0; i--) { 8879 ProviderInfo destPi = dest.get(i).providerInfo; 8880 if (destPi.name == filterPi.name 8881 && destPi.packageName == filterPi.packageName) { 8882 return false; 8883 } 8884 } 8885 return true; 8886 } 8887 8888 @Override 8889 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8890 return new PackageParser.ProviderIntentInfo[size]; 8891 } 8892 8893 @Override 8894 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8895 if (!sUserManager.exists(userId)) 8896 return true; 8897 PackageParser.Package p = filter.provider.owner; 8898 if (p != null) { 8899 PackageSetting ps = (PackageSetting) p.mExtras; 8900 if (ps != null) { 8901 // System apps are never considered stopped for purposes of 8902 // filtering, because there may be no way for the user to 8903 // actually re-launch them. 8904 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8905 && ps.getStopped(userId); 8906 } 8907 } 8908 return false; 8909 } 8910 8911 @Override 8912 protected boolean isPackageForFilter(String packageName, 8913 PackageParser.ProviderIntentInfo info) { 8914 return packageName.equals(info.provider.owner.packageName); 8915 } 8916 8917 @Override 8918 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8919 int match, int userId) { 8920 if (!sUserManager.exists(userId)) 8921 return null; 8922 final PackageParser.ProviderIntentInfo info = filter; 8923 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8924 return null; 8925 } 8926 final PackageParser.Provider provider = info.provider; 8927 if (mSafeMode && (provider.info.applicationInfo.flags 8928 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8929 return null; 8930 } 8931 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8932 if (ps == null) { 8933 return null; 8934 } 8935 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8936 ps.readUserState(userId), userId); 8937 if (pi == null) { 8938 return null; 8939 } 8940 final ResolveInfo res = new ResolveInfo(); 8941 res.providerInfo = pi; 8942 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8943 res.filter = filter; 8944 } 8945 res.priority = info.getPriority(); 8946 res.preferredOrder = provider.owner.mPreferredOrder; 8947 res.match = match; 8948 res.isDefault = info.hasDefault; 8949 res.labelRes = info.labelRes; 8950 res.nonLocalizedLabel = info.nonLocalizedLabel; 8951 res.icon = info.icon; 8952 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8953 return res; 8954 } 8955 8956 @Override 8957 protected void sortResults(List<ResolveInfo> results) { 8958 Collections.sort(results, mResolvePrioritySorter); 8959 } 8960 8961 @Override 8962 protected void dumpFilter(PrintWriter out, String prefix, 8963 PackageParser.ProviderIntentInfo filter) { 8964 out.print(prefix); 8965 out.print( 8966 Integer.toHexString(System.identityHashCode(filter.provider))); 8967 out.print(' '); 8968 filter.provider.printComponentShortName(out); 8969 out.print(" filter "); 8970 out.println(Integer.toHexString(System.identityHashCode(filter))); 8971 } 8972 8973 @Override 8974 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8975 return filter.provider; 8976 } 8977 8978 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8979 PackageParser.Provider provider = (PackageParser.Provider)label; 8980 out.print(prefix); out.print( 8981 Integer.toHexString(System.identityHashCode(provider))); 8982 out.print(' '); 8983 provider.printComponentShortName(out); 8984 if (count > 1) { 8985 out.print(" ("); out.print(count); out.print(" filters)"); 8986 } 8987 out.println(); 8988 } 8989 8990 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8991 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8992 private int mFlags; 8993 }; 8994 8995 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8996 new Comparator<ResolveInfo>() { 8997 public int compare(ResolveInfo r1, ResolveInfo r2) { 8998 int v1 = r1.priority; 8999 int v2 = r2.priority; 9000 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9001 if (v1 != v2) { 9002 return (v1 > v2) ? -1 : 1; 9003 } 9004 v1 = r1.preferredOrder; 9005 v2 = r2.preferredOrder; 9006 if (v1 != v2) { 9007 return (v1 > v2) ? -1 : 1; 9008 } 9009 if (r1.isDefault != r2.isDefault) { 9010 return r1.isDefault ? -1 : 1; 9011 } 9012 v1 = r1.match; 9013 v2 = r2.match; 9014 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9015 if (v1 != v2) { 9016 return (v1 > v2) ? -1 : 1; 9017 } 9018 if (r1.system != r2.system) { 9019 return r1.system ? -1 : 1; 9020 } 9021 return 0; 9022 } 9023 }; 9024 9025 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9026 new Comparator<ProviderInfo>() { 9027 public int compare(ProviderInfo p1, ProviderInfo p2) { 9028 final int v1 = p1.initOrder; 9029 final int v2 = p2.initOrder; 9030 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9031 } 9032 }; 9033 9034 final void sendPackageBroadcast(final String action, final String pkg, 9035 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9036 final int[] userIds) { 9037 mHandler.post(new Runnable() { 9038 @Override 9039 public void run() { 9040 try { 9041 final IActivityManager am = ActivityManagerNative.getDefault(); 9042 if (am == null) return; 9043 final int[] resolvedUserIds; 9044 if (userIds == null) { 9045 resolvedUserIds = am.getRunningUserIds(); 9046 } else { 9047 resolvedUserIds = userIds; 9048 } 9049 for (int id : resolvedUserIds) { 9050 final Intent intent = new Intent(action, 9051 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9052 if (extras != null) { 9053 intent.putExtras(extras); 9054 } 9055 if (targetPkg != null) { 9056 intent.setPackage(targetPkg); 9057 } 9058 // Modify the UID when posting to other users 9059 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9060 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9061 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9062 intent.putExtra(Intent.EXTRA_UID, uid); 9063 } 9064 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9065 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9066 if (DEBUG_BROADCASTS) { 9067 RuntimeException here = new RuntimeException("here"); 9068 here.fillInStackTrace(); 9069 Slog.d(TAG, "Sending to user " + id + ": " 9070 + intent.toShortString(false, true, false, false) 9071 + " " + intent.getExtras(), here); 9072 } 9073 am.broadcastIntent(null, intent, null, finishedReceiver, 9074 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9075 null, finishedReceiver != null, false, id); 9076 } 9077 } catch (RemoteException ex) { 9078 } 9079 } 9080 }); 9081 } 9082 9083 /** 9084 * Check if the external storage media is available. This is true if there 9085 * is a mounted external storage medium or if the external storage is 9086 * emulated. 9087 */ 9088 private boolean isExternalMediaAvailable() { 9089 return mMediaMounted || Environment.isExternalStorageEmulated(); 9090 } 9091 9092 @Override 9093 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9094 // writer 9095 synchronized (mPackages) { 9096 if (!isExternalMediaAvailable()) { 9097 // If the external storage is no longer mounted at this point, 9098 // the caller may not have been able to delete all of this 9099 // packages files and can not delete any more. Bail. 9100 return null; 9101 } 9102 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9103 if (lastPackage != null) { 9104 pkgs.remove(lastPackage); 9105 } 9106 if (pkgs.size() > 0) { 9107 return pkgs.get(0); 9108 } 9109 } 9110 return null; 9111 } 9112 9113 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9114 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9115 userId, andCode ? 1 : 0, packageName); 9116 if (mSystemReady) { 9117 msg.sendToTarget(); 9118 } else { 9119 if (mPostSystemReadyMessages == null) { 9120 mPostSystemReadyMessages = new ArrayList<>(); 9121 } 9122 mPostSystemReadyMessages.add(msg); 9123 } 9124 } 9125 9126 void startCleaningPackages() { 9127 // reader 9128 synchronized (mPackages) { 9129 if (!isExternalMediaAvailable()) { 9130 return; 9131 } 9132 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9133 return; 9134 } 9135 } 9136 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9137 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9138 IActivityManager am = ActivityManagerNative.getDefault(); 9139 if (am != null) { 9140 try { 9141 am.startService(null, intent, null, UserHandle.USER_OWNER); 9142 } catch (RemoteException e) { 9143 } 9144 } 9145 } 9146 9147 @Override 9148 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9149 int installFlags, String installerPackageName, VerificationParams verificationParams, 9150 String packageAbiOverride) { 9151 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9152 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9153 } 9154 9155 @Override 9156 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9157 int installFlags, String installerPackageName, VerificationParams verificationParams, 9158 String packageAbiOverride, int userId) { 9159 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9160 9161 final int callingUid = Binder.getCallingUid(); 9162 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9163 9164 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9165 try { 9166 if (observer != null) { 9167 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9168 } 9169 } catch (RemoteException re) { 9170 } 9171 return; 9172 } 9173 9174 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9175 installFlags |= PackageManager.INSTALL_FROM_ADB; 9176 9177 } else { 9178 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9179 // about installerPackageName. 9180 9181 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9182 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9183 } 9184 9185 UserHandle user; 9186 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9187 user = UserHandle.ALL; 9188 } else { 9189 user = new UserHandle(userId); 9190 } 9191 9192 // Only system components can circumvent runtime permissions when installing. 9193 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9194 && mContext.checkCallingOrSelfPermission(Manifest.permission 9195 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9196 throw new SecurityException("You need the " 9197 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9198 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9199 } 9200 9201 verificationParams.setInstallerUid(callingUid); 9202 9203 final File originFile = new File(originPath); 9204 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9205 9206 final Message msg = mHandler.obtainMessage(INIT_COPY); 9207 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9208 null, verificationParams, user, packageAbiOverride); 9209 mHandler.sendMessage(msg); 9210 } 9211 9212 void installStage(String packageName, File stagedDir, String stagedCid, 9213 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9214 String installerPackageName, int installerUid, UserHandle user) { 9215 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9216 params.referrerUri, installerUid, null); 9217 verifParams.setInstallerUid(installerUid); 9218 9219 final OriginInfo origin; 9220 if (stagedDir != null) { 9221 origin = OriginInfo.fromStagedFile(stagedDir); 9222 } else { 9223 origin = OriginInfo.fromStagedContainer(stagedCid); 9224 } 9225 9226 final Message msg = mHandler.obtainMessage(INIT_COPY); 9227 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9228 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9229 mHandler.sendMessage(msg); 9230 } 9231 9232 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9233 Bundle extras = new Bundle(1); 9234 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9235 9236 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9237 packageName, extras, null, null, new int[] {userId}); 9238 try { 9239 IActivityManager am = ActivityManagerNative.getDefault(); 9240 final boolean isSystem = 9241 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9242 if (isSystem && am.isUserRunning(userId, false)) { 9243 // The just-installed/enabled app is bundled on the system, so presumed 9244 // to be able to run automatically without needing an explicit launch. 9245 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9246 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9247 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9248 .setPackage(packageName); 9249 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9250 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9251 } 9252 } catch (RemoteException e) { 9253 // shouldn't happen 9254 Slog.w(TAG, "Unable to bootstrap installed package", e); 9255 } 9256 } 9257 9258 @Override 9259 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9260 int userId) { 9261 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9262 PackageSetting pkgSetting; 9263 final int uid = Binder.getCallingUid(); 9264 enforceCrossUserPermission(uid, userId, true, true, 9265 "setApplicationHiddenSetting for user " + userId); 9266 9267 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9268 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9269 return false; 9270 } 9271 9272 long callingId = Binder.clearCallingIdentity(); 9273 try { 9274 boolean sendAdded = false; 9275 boolean sendRemoved = false; 9276 // writer 9277 synchronized (mPackages) { 9278 pkgSetting = mSettings.mPackages.get(packageName); 9279 if (pkgSetting == null) { 9280 return false; 9281 } 9282 if (pkgSetting.getHidden(userId) != hidden) { 9283 pkgSetting.setHidden(hidden, userId); 9284 mSettings.writePackageRestrictionsLPr(userId); 9285 if (hidden) { 9286 sendRemoved = true; 9287 } else { 9288 sendAdded = true; 9289 } 9290 } 9291 } 9292 if (sendAdded) { 9293 sendPackageAddedForUser(packageName, pkgSetting, userId); 9294 return true; 9295 } 9296 if (sendRemoved) { 9297 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9298 "hiding pkg"); 9299 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9300 } 9301 } finally { 9302 Binder.restoreCallingIdentity(callingId); 9303 } 9304 return false; 9305 } 9306 9307 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9308 int userId) { 9309 final PackageRemovedInfo info = new PackageRemovedInfo(); 9310 info.removedPackage = packageName; 9311 info.removedUsers = new int[] {userId}; 9312 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9313 info.sendBroadcast(false, false, false); 9314 } 9315 9316 /** 9317 * Returns true if application is not found or there was an error. Otherwise it returns 9318 * the hidden state of the package for the given user. 9319 */ 9320 @Override 9321 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9322 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9323 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9324 false, "getApplicationHidden for user " + userId); 9325 PackageSetting pkgSetting; 9326 long callingId = Binder.clearCallingIdentity(); 9327 try { 9328 // writer 9329 synchronized (mPackages) { 9330 pkgSetting = mSettings.mPackages.get(packageName); 9331 if (pkgSetting == null) { 9332 return true; 9333 } 9334 return pkgSetting.getHidden(userId); 9335 } 9336 } finally { 9337 Binder.restoreCallingIdentity(callingId); 9338 } 9339 } 9340 9341 /** 9342 * @hide 9343 */ 9344 @Override 9345 public int installExistingPackageAsUser(String packageName, int userId) { 9346 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9347 null); 9348 PackageSetting pkgSetting; 9349 final int uid = Binder.getCallingUid(); 9350 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9351 + userId); 9352 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9353 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9354 } 9355 9356 long callingId = Binder.clearCallingIdentity(); 9357 try { 9358 boolean sendAdded = false; 9359 9360 // writer 9361 synchronized (mPackages) { 9362 pkgSetting = mSettings.mPackages.get(packageName); 9363 if (pkgSetting == null) { 9364 return PackageManager.INSTALL_FAILED_INVALID_URI; 9365 } 9366 if (!pkgSetting.getInstalled(userId)) { 9367 pkgSetting.setInstalled(true, userId); 9368 pkgSetting.setHidden(false, userId); 9369 mSettings.writePackageRestrictionsLPr(userId); 9370 sendAdded = true; 9371 } 9372 } 9373 9374 if (sendAdded) { 9375 sendPackageAddedForUser(packageName, pkgSetting, userId); 9376 } 9377 } finally { 9378 Binder.restoreCallingIdentity(callingId); 9379 } 9380 9381 return PackageManager.INSTALL_SUCCEEDED; 9382 } 9383 9384 boolean isUserRestricted(int userId, String restrictionKey) { 9385 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9386 if (restrictions.getBoolean(restrictionKey, false)) { 9387 Log.w(TAG, "User is restricted: " + restrictionKey); 9388 return true; 9389 } 9390 return false; 9391 } 9392 9393 @Override 9394 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9395 mContext.enforceCallingOrSelfPermission( 9396 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9397 "Only package verification agents can verify applications"); 9398 9399 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9400 final PackageVerificationResponse response = new PackageVerificationResponse( 9401 verificationCode, Binder.getCallingUid()); 9402 msg.arg1 = id; 9403 msg.obj = response; 9404 mHandler.sendMessage(msg); 9405 } 9406 9407 @Override 9408 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9409 long millisecondsToDelay) { 9410 mContext.enforceCallingOrSelfPermission( 9411 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9412 "Only package verification agents can extend verification timeouts"); 9413 9414 final PackageVerificationState state = mPendingVerification.get(id); 9415 final PackageVerificationResponse response = new PackageVerificationResponse( 9416 verificationCodeAtTimeout, Binder.getCallingUid()); 9417 9418 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9419 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9420 } 9421 if (millisecondsToDelay < 0) { 9422 millisecondsToDelay = 0; 9423 } 9424 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9425 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9426 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9427 } 9428 9429 if ((state != null) && !state.timeoutExtended()) { 9430 state.extendTimeout(); 9431 9432 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9433 msg.arg1 = id; 9434 msg.obj = response; 9435 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9436 } 9437 } 9438 9439 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9440 int verificationCode, UserHandle user) { 9441 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9442 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9443 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9444 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9445 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9446 9447 mContext.sendBroadcastAsUser(intent, user, 9448 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9449 } 9450 9451 private ComponentName matchComponentForVerifier(String packageName, 9452 List<ResolveInfo> receivers) { 9453 ActivityInfo targetReceiver = null; 9454 9455 final int NR = receivers.size(); 9456 for (int i = 0; i < NR; i++) { 9457 final ResolveInfo info = receivers.get(i); 9458 if (info.activityInfo == null) { 9459 continue; 9460 } 9461 9462 if (packageName.equals(info.activityInfo.packageName)) { 9463 targetReceiver = info.activityInfo; 9464 break; 9465 } 9466 } 9467 9468 if (targetReceiver == null) { 9469 return null; 9470 } 9471 9472 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9473 } 9474 9475 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9476 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9477 if (pkgInfo.verifiers.length == 0) { 9478 return null; 9479 } 9480 9481 final int N = pkgInfo.verifiers.length; 9482 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9483 for (int i = 0; i < N; i++) { 9484 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9485 9486 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9487 receivers); 9488 if (comp == null) { 9489 continue; 9490 } 9491 9492 final int verifierUid = getUidForVerifier(verifierInfo); 9493 if (verifierUid == -1) { 9494 continue; 9495 } 9496 9497 if (DEBUG_VERIFY) { 9498 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9499 + " with the correct signature"); 9500 } 9501 sufficientVerifiers.add(comp); 9502 verificationState.addSufficientVerifier(verifierUid); 9503 } 9504 9505 return sufficientVerifiers; 9506 } 9507 9508 private int getUidForVerifier(VerifierInfo verifierInfo) { 9509 synchronized (mPackages) { 9510 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9511 if (pkg == null) { 9512 return -1; 9513 } else if (pkg.mSignatures.length != 1) { 9514 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9515 + " has more than one signature; ignoring"); 9516 return -1; 9517 } 9518 9519 /* 9520 * If the public key of the package's signature does not match 9521 * our expected public key, then this is a different package and 9522 * we should skip. 9523 */ 9524 9525 final byte[] expectedPublicKey; 9526 try { 9527 final Signature verifierSig = pkg.mSignatures[0]; 9528 final PublicKey publicKey = verifierSig.getPublicKey(); 9529 expectedPublicKey = publicKey.getEncoded(); 9530 } catch (CertificateException e) { 9531 return -1; 9532 } 9533 9534 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9535 9536 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9537 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9538 + " does not have the expected public key; ignoring"); 9539 return -1; 9540 } 9541 9542 return pkg.applicationInfo.uid; 9543 } 9544 } 9545 9546 @Override 9547 public void finishPackageInstall(int token) { 9548 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9549 9550 if (DEBUG_INSTALL) { 9551 Slog.v(TAG, "BM finishing package install for " + token); 9552 } 9553 9554 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9555 mHandler.sendMessage(msg); 9556 } 9557 9558 /** 9559 * Get the verification agent timeout. 9560 * 9561 * @return verification timeout in milliseconds 9562 */ 9563 private long getVerificationTimeout() { 9564 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9565 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9566 DEFAULT_VERIFICATION_TIMEOUT); 9567 } 9568 9569 /** 9570 * Get the default verification agent response code. 9571 * 9572 * @return default verification response code 9573 */ 9574 private int getDefaultVerificationResponse() { 9575 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9576 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9577 DEFAULT_VERIFICATION_RESPONSE); 9578 } 9579 9580 /** 9581 * Check whether or not package verification has been enabled. 9582 * 9583 * @return true if verification should be performed 9584 */ 9585 private boolean isVerificationEnabled(int userId, int installFlags) { 9586 if (!DEFAULT_VERIFY_ENABLE) { 9587 return false; 9588 } 9589 9590 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9591 9592 // Check if installing from ADB 9593 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9594 // Do not run verification in a test harness environment 9595 if (ActivityManager.isRunningInTestHarness()) { 9596 return false; 9597 } 9598 if (ensureVerifyAppsEnabled) { 9599 return true; 9600 } 9601 // Check if the developer does not want package verification for ADB installs 9602 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9603 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9604 return false; 9605 } 9606 } 9607 9608 if (ensureVerifyAppsEnabled) { 9609 return true; 9610 } 9611 9612 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9613 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9614 } 9615 9616 @Override 9617 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9618 throws RemoteException { 9619 mContext.enforceCallingOrSelfPermission( 9620 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9621 "Only intentfilter verification agents can verify applications"); 9622 9623 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9624 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9625 Binder.getCallingUid(), verificationCode, failedDomains); 9626 msg.arg1 = id; 9627 msg.obj = response; 9628 mHandler.sendMessage(msg); 9629 } 9630 9631 @Override 9632 public int getIntentVerificationStatus(String packageName, int userId) { 9633 synchronized (mPackages) { 9634 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9635 } 9636 } 9637 9638 @Override 9639 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9640 mContext.enforceCallingOrSelfPermission( 9641 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9642 9643 boolean result = false; 9644 synchronized (mPackages) { 9645 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9646 } 9647 if (result) { 9648 scheduleWritePackageRestrictionsLocked(userId); 9649 } 9650 return result; 9651 } 9652 9653 @Override 9654 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9655 synchronized (mPackages) { 9656 return mSettings.getIntentFilterVerificationsLPr(packageName); 9657 } 9658 } 9659 9660 @Override 9661 public List<IntentFilter> getAllIntentFilters(String packageName) { 9662 if (TextUtils.isEmpty(packageName)) { 9663 return Collections.<IntentFilter>emptyList(); 9664 } 9665 synchronized (mPackages) { 9666 PackageParser.Package pkg = mPackages.get(packageName); 9667 if (pkg == null || pkg.activities == null) { 9668 return Collections.<IntentFilter>emptyList(); 9669 } 9670 final int count = pkg.activities.size(); 9671 ArrayList<IntentFilter> result = new ArrayList<>(); 9672 for (int n=0; n<count; n++) { 9673 PackageParser.Activity activity = pkg.activities.get(n); 9674 if (activity.intents != null || activity.intents.size() > 0) { 9675 result.addAll(activity.intents); 9676 } 9677 } 9678 return result; 9679 } 9680 } 9681 9682 @Override 9683 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9684 mContext.enforceCallingOrSelfPermission( 9685 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9686 9687 synchronized (mPackages) { 9688 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9689 if (packageName != null) { 9690 result |= updateIntentVerificationStatus(packageName, 9691 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9692 UserHandle.myUserId()); 9693 } 9694 return result; 9695 } 9696 } 9697 9698 @Override 9699 public String getDefaultBrowserPackageName(int userId) { 9700 synchronized (mPackages) { 9701 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9702 } 9703 } 9704 9705 /** 9706 * Get the "allow unknown sources" setting. 9707 * 9708 * @return the current "allow unknown sources" setting 9709 */ 9710 private int getUnknownSourcesSettings() { 9711 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9712 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9713 -1); 9714 } 9715 9716 @Override 9717 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9718 final int uid = Binder.getCallingUid(); 9719 // writer 9720 synchronized (mPackages) { 9721 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9722 if (targetPackageSetting == null) { 9723 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9724 } 9725 9726 PackageSetting installerPackageSetting; 9727 if (installerPackageName != null) { 9728 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9729 if (installerPackageSetting == null) { 9730 throw new IllegalArgumentException("Unknown installer package: " 9731 + installerPackageName); 9732 } 9733 } else { 9734 installerPackageSetting = null; 9735 } 9736 9737 Signature[] callerSignature; 9738 Object obj = mSettings.getUserIdLPr(uid); 9739 if (obj != null) { 9740 if (obj instanceof SharedUserSetting) { 9741 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9742 } else if (obj instanceof PackageSetting) { 9743 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9744 } else { 9745 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9746 } 9747 } else { 9748 throw new SecurityException("Unknown calling uid " + uid); 9749 } 9750 9751 // Verify: can't set installerPackageName to a package that is 9752 // not signed with the same cert as the caller. 9753 if (installerPackageSetting != null) { 9754 if (compareSignatures(callerSignature, 9755 installerPackageSetting.signatures.mSignatures) 9756 != PackageManager.SIGNATURE_MATCH) { 9757 throw new SecurityException( 9758 "Caller does not have same cert as new installer package " 9759 + installerPackageName); 9760 } 9761 } 9762 9763 // Verify: if target already has an installer package, it must 9764 // be signed with the same cert as the caller. 9765 if (targetPackageSetting.installerPackageName != null) { 9766 PackageSetting setting = mSettings.mPackages.get( 9767 targetPackageSetting.installerPackageName); 9768 // If the currently set package isn't valid, then it's always 9769 // okay to change it. 9770 if (setting != null) { 9771 if (compareSignatures(callerSignature, 9772 setting.signatures.mSignatures) 9773 != PackageManager.SIGNATURE_MATCH) { 9774 throw new SecurityException( 9775 "Caller does not have same cert as old installer package " 9776 + targetPackageSetting.installerPackageName); 9777 } 9778 } 9779 } 9780 9781 // Okay! 9782 targetPackageSetting.installerPackageName = installerPackageName; 9783 scheduleWriteSettingsLocked(); 9784 } 9785 } 9786 9787 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9788 // Queue up an async operation since the package installation may take a little while. 9789 mHandler.post(new Runnable() { 9790 public void run() { 9791 mHandler.removeCallbacks(this); 9792 // Result object to be returned 9793 PackageInstalledInfo res = new PackageInstalledInfo(); 9794 res.returnCode = currentStatus; 9795 res.uid = -1; 9796 res.pkg = null; 9797 res.removedInfo = new PackageRemovedInfo(); 9798 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9799 args.doPreInstall(res.returnCode); 9800 synchronized (mInstallLock) { 9801 installPackageLI(args, res); 9802 } 9803 args.doPostInstall(res.returnCode, res.uid); 9804 } 9805 9806 // A restore should be performed at this point if (a) the install 9807 // succeeded, (b) the operation is not an update, and (c) the new 9808 // package has not opted out of backup participation. 9809 final boolean update = res.removedInfo.removedPackage != null; 9810 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9811 boolean doRestore = !update 9812 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9813 9814 // Set up the post-install work request bookkeeping. This will be used 9815 // and cleaned up by the post-install event handling regardless of whether 9816 // there's a restore pass performed. Token values are >= 1. 9817 int token; 9818 if (mNextInstallToken < 0) mNextInstallToken = 1; 9819 token = mNextInstallToken++; 9820 9821 PostInstallData data = new PostInstallData(args, res); 9822 mRunningInstalls.put(token, data); 9823 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9824 9825 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9826 // Pass responsibility to the Backup Manager. It will perform a 9827 // restore if appropriate, then pass responsibility back to the 9828 // Package Manager to run the post-install observer callbacks 9829 // and broadcasts. 9830 IBackupManager bm = IBackupManager.Stub.asInterface( 9831 ServiceManager.getService(Context.BACKUP_SERVICE)); 9832 if (bm != null) { 9833 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9834 + " to BM for possible restore"); 9835 try { 9836 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9837 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9838 } else { 9839 doRestore = false; 9840 } 9841 } catch (RemoteException e) { 9842 // can't happen; the backup manager is local 9843 } catch (Exception e) { 9844 Slog.e(TAG, "Exception trying to enqueue restore", e); 9845 doRestore = false; 9846 } 9847 } else { 9848 Slog.e(TAG, "Backup Manager not found!"); 9849 doRestore = false; 9850 } 9851 } 9852 9853 if (!doRestore) { 9854 // No restore possible, or the Backup Manager was mysteriously not 9855 // available -- just fire the post-install work request directly. 9856 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9857 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9858 mHandler.sendMessage(msg); 9859 } 9860 } 9861 }); 9862 } 9863 9864 private abstract class HandlerParams { 9865 private static final int MAX_RETRIES = 4; 9866 9867 /** 9868 * Number of times startCopy() has been attempted and had a non-fatal 9869 * error. 9870 */ 9871 private int mRetries = 0; 9872 9873 /** User handle for the user requesting the information or installation. */ 9874 private final UserHandle mUser; 9875 9876 HandlerParams(UserHandle user) { 9877 mUser = user; 9878 } 9879 9880 UserHandle getUser() { 9881 return mUser; 9882 } 9883 9884 final boolean startCopy() { 9885 boolean res; 9886 try { 9887 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9888 9889 if (++mRetries > MAX_RETRIES) { 9890 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9891 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9892 handleServiceError(); 9893 return false; 9894 } else { 9895 handleStartCopy(); 9896 res = true; 9897 } 9898 } catch (RemoteException e) { 9899 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9900 mHandler.sendEmptyMessage(MCS_RECONNECT); 9901 res = false; 9902 } 9903 handleReturnCode(); 9904 return res; 9905 } 9906 9907 final void serviceError() { 9908 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9909 handleServiceError(); 9910 handleReturnCode(); 9911 } 9912 9913 abstract void handleStartCopy() throws RemoteException; 9914 abstract void handleServiceError(); 9915 abstract void handleReturnCode(); 9916 } 9917 9918 class MeasureParams extends HandlerParams { 9919 private final PackageStats mStats; 9920 private boolean mSuccess; 9921 9922 private final IPackageStatsObserver mObserver; 9923 9924 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9925 super(new UserHandle(stats.userHandle)); 9926 mObserver = observer; 9927 mStats = stats; 9928 } 9929 9930 @Override 9931 public String toString() { 9932 return "MeasureParams{" 9933 + Integer.toHexString(System.identityHashCode(this)) 9934 + " " + mStats.packageName + "}"; 9935 } 9936 9937 @Override 9938 void handleStartCopy() throws RemoteException { 9939 synchronized (mInstallLock) { 9940 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9941 } 9942 9943 if (mSuccess) { 9944 final boolean mounted; 9945 if (Environment.isExternalStorageEmulated()) { 9946 mounted = true; 9947 } else { 9948 final String status = Environment.getExternalStorageState(); 9949 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9950 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9951 } 9952 9953 if (mounted) { 9954 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9955 9956 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9957 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9958 9959 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9960 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9961 9962 // Always subtract cache size, since it's a subdirectory 9963 mStats.externalDataSize -= mStats.externalCacheSize; 9964 9965 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9966 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9967 9968 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9969 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9970 } 9971 } 9972 } 9973 9974 @Override 9975 void handleReturnCode() { 9976 if (mObserver != null) { 9977 try { 9978 mObserver.onGetStatsCompleted(mStats, mSuccess); 9979 } catch (RemoteException e) { 9980 Slog.i(TAG, "Observer no longer exists."); 9981 } 9982 } 9983 } 9984 9985 @Override 9986 void handleServiceError() { 9987 Slog.e(TAG, "Could not measure application " + mStats.packageName 9988 + " external storage"); 9989 } 9990 } 9991 9992 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9993 throws RemoteException { 9994 long result = 0; 9995 for (File path : paths) { 9996 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9997 } 9998 return result; 9999 } 10000 10001 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10002 for (File path : paths) { 10003 try { 10004 mcs.clearDirectory(path.getAbsolutePath()); 10005 } catch (RemoteException e) { 10006 } 10007 } 10008 } 10009 10010 static class OriginInfo { 10011 /** 10012 * Location where install is coming from, before it has been 10013 * copied/renamed into place. This could be a single monolithic APK 10014 * file, or a cluster directory. This location may be untrusted. 10015 */ 10016 final File file; 10017 final String cid; 10018 10019 /** 10020 * Flag indicating that {@link #file} or {@link #cid} has already been 10021 * staged, meaning downstream users don't need to defensively copy the 10022 * contents. 10023 */ 10024 final boolean staged; 10025 10026 /** 10027 * Flag indicating that {@link #file} or {@link #cid} is an already 10028 * installed app that is being moved. 10029 */ 10030 final boolean existing; 10031 10032 final String resolvedPath; 10033 final File resolvedFile; 10034 10035 static OriginInfo fromNothing() { 10036 return new OriginInfo(null, null, false, false); 10037 } 10038 10039 static OriginInfo fromUntrustedFile(File file) { 10040 return new OriginInfo(file, null, false, false); 10041 } 10042 10043 static OriginInfo fromExistingFile(File file) { 10044 return new OriginInfo(file, null, false, true); 10045 } 10046 10047 static OriginInfo fromStagedFile(File file) { 10048 return new OriginInfo(file, null, true, false); 10049 } 10050 10051 static OriginInfo fromStagedContainer(String cid) { 10052 return new OriginInfo(null, cid, true, false); 10053 } 10054 10055 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10056 this.file = file; 10057 this.cid = cid; 10058 this.staged = staged; 10059 this.existing = existing; 10060 10061 if (cid != null) { 10062 resolvedPath = PackageHelper.getSdDir(cid); 10063 resolvedFile = new File(resolvedPath); 10064 } else if (file != null) { 10065 resolvedPath = file.getAbsolutePath(); 10066 resolvedFile = file; 10067 } else { 10068 resolvedPath = null; 10069 resolvedFile = null; 10070 } 10071 } 10072 } 10073 10074 class MoveInfo { 10075 final int moveId; 10076 final String fromUuid; 10077 final String toUuid; 10078 final String packageName; 10079 final String dataAppName; 10080 final int appId; 10081 final String seinfo; 10082 10083 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10084 String dataAppName, int appId, String seinfo) { 10085 this.moveId = moveId; 10086 this.fromUuid = fromUuid; 10087 this.toUuid = toUuid; 10088 this.packageName = packageName; 10089 this.dataAppName = dataAppName; 10090 this.appId = appId; 10091 this.seinfo = seinfo; 10092 } 10093 } 10094 10095 class InstallParams extends HandlerParams { 10096 final OriginInfo origin; 10097 final MoveInfo move; 10098 final IPackageInstallObserver2 observer; 10099 int installFlags; 10100 final String installerPackageName; 10101 final String volumeUuid; 10102 final VerificationParams verificationParams; 10103 private InstallArgs mArgs; 10104 private int mRet; 10105 final String packageAbiOverride; 10106 10107 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10108 int installFlags, String installerPackageName, String volumeUuid, 10109 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10110 super(user); 10111 this.origin = origin; 10112 this.move = move; 10113 this.observer = observer; 10114 this.installFlags = installFlags; 10115 this.installerPackageName = installerPackageName; 10116 this.volumeUuid = volumeUuid; 10117 this.verificationParams = verificationParams; 10118 this.packageAbiOverride = packageAbiOverride; 10119 } 10120 10121 @Override 10122 public String toString() { 10123 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10124 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10125 } 10126 10127 public ManifestDigest getManifestDigest() { 10128 if (verificationParams == null) { 10129 return null; 10130 } 10131 return verificationParams.getManifestDigest(); 10132 } 10133 10134 private int installLocationPolicy(PackageInfoLite pkgLite) { 10135 String packageName = pkgLite.packageName; 10136 int installLocation = pkgLite.installLocation; 10137 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10138 // reader 10139 synchronized (mPackages) { 10140 PackageParser.Package pkg = mPackages.get(packageName); 10141 if (pkg != null) { 10142 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10143 // Check for downgrading. 10144 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10145 try { 10146 checkDowngrade(pkg, pkgLite); 10147 } catch (PackageManagerException e) { 10148 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10149 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10150 } 10151 } 10152 // Check for updated system application. 10153 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10154 if (onSd) { 10155 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10156 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10157 } 10158 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10159 } else { 10160 if (onSd) { 10161 // Install flag overrides everything. 10162 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10163 } 10164 // If current upgrade specifies particular preference 10165 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10166 // Application explicitly specified internal. 10167 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10168 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10169 // App explictly prefers external. Let policy decide 10170 } else { 10171 // Prefer previous location 10172 if (isExternal(pkg)) { 10173 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10174 } 10175 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10176 } 10177 } 10178 } else { 10179 // Invalid install. Return error code 10180 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10181 } 10182 } 10183 } 10184 // All the special cases have been taken care of. 10185 // Return result based on recommended install location. 10186 if (onSd) { 10187 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10188 } 10189 return pkgLite.recommendedInstallLocation; 10190 } 10191 10192 /* 10193 * Invoke remote method to get package information and install 10194 * location values. Override install location based on default 10195 * policy if needed and then create install arguments based 10196 * on the install location. 10197 */ 10198 public void handleStartCopy() throws RemoteException { 10199 int ret = PackageManager.INSTALL_SUCCEEDED; 10200 10201 // If we're already staged, we've firmly committed to an install location 10202 if (origin.staged) { 10203 if (origin.file != null) { 10204 installFlags |= PackageManager.INSTALL_INTERNAL; 10205 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10206 } else if (origin.cid != null) { 10207 installFlags |= PackageManager.INSTALL_EXTERNAL; 10208 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10209 } else { 10210 throw new IllegalStateException("Invalid stage location"); 10211 } 10212 } 10213 10214 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10215 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10216 10217 PackageInfoLite pkgLite = null; 10218 10219 if (onInt && onSd) { 10220 // Check if both bits are set. 10221 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10222 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10223 } else { 10224 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10225 packageAbiOverride); 10226 10227 /* 10228 * If we have too little free space, try to free cache 10229 * before giving up. 10230 */ 10231 if (!origin.staged && pkgLite.recommendedInstallLocation 10232 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10233 // TODO: focus freeing disk space on the target device 10234 final StorageManager storage = StorageManager.from(mContext); 10235 final long lowThreshold = storage.getStorageLowBytes( 10236 Environment.getDataDirectory()); 10237 10238 final long sizeBytes = mContainerService.calculateInstalledSize( 10239 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10240 10241 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10242 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10243 installFlags, packageAbiOverride); 10244 } 10245 10246 /* 10247 * The cache free must have deleted the file we 10248 * downloaded to install. 10249 * 10250 * TODO: fix the "freeCache" call to not delete 10251 * the file we care about. 10252 */ 10253 if (pkgLite.recommendedInstallLocation 10254 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10255 pkgLite.recommendedInstallLocation 10256 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10257 } 10258 } 10259 } 10260 10261 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10262 int loc = pkgLite.recommendedInstallLocation; 10263 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10264 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10265 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10266 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10267 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10268 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10269 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10270 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10271 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10272 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10273 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10274 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10275 } else { 10276 // Override with defaults if needed. 10277 loc = installLocationPolicy(pkgLite); 10278 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10279 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10280 } else if (!onSd && !onInt) { 10281 // Override install location with flags 10282 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10283 // Set the flag to install on external media. 10284 installFlags |= PackageManager.INSTALL_EXTERNAL; 10285 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10286 } else { 10287 // Make sure the flag for installing on external 10288 // media is unset 10289 installFlags |= PackageManager.INSTALL_INTERNAL; 10290 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10291 } 10292 } 10293 } 10294 } 10295 10296 final InstallArgs args = createInstallArgs(this); 10297 mArgs = args; 10298 10299 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10300 /* 10301 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10302 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10303 */ 10304 int userIdentifier = getUser().getIdentifier(); 10305 if (userIdentifier == UserHandle.USER_ALL 10306 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10307 userIdentifier = UserHandle.USER_OWNER; 10308 } 10309 10310 /* 10311 * Determine if we have any installed package verifiers. If we 10312 * do, then we'll defer to them to verify the packages. 10313 */ 10314 final int requiredUid = mRequiredVerifierPackage == null ? -1 10315 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10316 if (!origin.existing && requiredUid != -1 10317 && isVerificationEnabled(userIdentifier, installFlags)) { 10318 final Intent verification = new Intent( 10319 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10320 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10321 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10322 PACKAGE_MIME_TYPE); 10323 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10324 10325 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10326 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10327 0 /* TODO: Which userId? */); 10328 10329 if (DEBUG_VERIFY) { 10330 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10331 + verification.toString() + " with " + pkgLite.verifiers.length 10332 + " optional verifiers"); 10333 } 10334 10335 final int verificationId = mPendingVerificationToken++; 10336 10337 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10338 10339 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10340 installerPackageName); 10341 10342 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10343 installFlags); 10344 10345 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10346 pkgLite.packageName); 10347 10348 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10349 pkgLite.versionCode); 10350 10351 if (verificationParams != null) { 10352 if (verificationParams.getVerificationURI() != null) { 10353 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10354 verificationParams.getVerificationURI()); 10355 } 10356 if (verificationParams.getOriginatingURI() != null) { 10357 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10358 verificationParams.getOriginatingURI()); 10359 } 10360 if (verificationParams.getReferrer() != null) { 10361 verification.putExtra(Intent.EXTRA_REFERRER, 10362 verificationParams.getReferrer()); 10363 } 10364 if (verificationParams.getOriginatingUid() >= 0) { 10365 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10366 verificationParams.getOriginatingUid()); 10367 } 10368 if (verificationParams.getInstallerUid() >= 0) { 10369 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10370 verificationParams.getInstallerUid()); 10371 } 10372 } 10373 10374 final PackageVerificationState verificationState = new PackageVerificationState( 10375 requiredUid, args); 10376 10377 mPendingVerification.append(verificationId, verificationState); 10378 10379 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10380 receivers, verificationState); 10381 10382 /* 10383 * If any sufficient verifiers were listed in the package 10384 * manifest, attempt to ask them. 10385 */ 10386 if (sufficientVerifiers != null) { 10387 final int N = sufficientVerifiers.size(); 10388 if (N == 0) { 10389 Slog.i(TAG, "Additional verifiers required, but none installed."); 10390 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10391 } else { 10392 for (int i = 0; i < N; i++) { 10393 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10394 10395 final Intent sufficientIntent = new Intent(verification); 10396 sufficientIntent.setComponent(verifierComponent); 10397 10398 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10399 } 10400 } 10401 } 10402 10403 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10404 mRequiredVerifierPackage, receivers); 10405 if (ret == PackageManager.INSTALL_SUCCEEDED 10406 && mRequiredVerifierPackage != null) { 10407 /* 10408 * Send the intent to the required verification agent, 10409 * but only start the verification timeout after the 10410 * target BroadcastReceivers have run. 10411 */ 10412 verification.setComponent(requiredVerifierComponent); 10413 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10414 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10415 new BroadcastReceiver() { 10416 @Override 10417 public void onReceive(Context context, Intent intent) { 10418 final Message msg = mHandler 10419 .obtainMessage(CHECK_PENDING_VERIFICATION); 10420 msg.arg1 = verificationId; 10421 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10422 } 10423 }, null, 0, null, null); 10424 10425 /* 10426 * We don't want the copy to proceed until verification 10427 * succeeds, so null out this field. 10428 */ 10429 mArgs = null; 10430 } 10431 } else { 10432 /* 10433 * No package verification is enabled, so immediately start 10434 * the remote call to initiate copy using temporary file. 10435 */ 10436 ret = args.copyApk(mContainerService, true); 10437 } 10438 } 10439 10440 mRet = ret; 10441 } 10442 10443 @Override 10444 void handleReturnCode() { 10445 // If mArgs is null, then MCS couldn't be reached. When it 10446 // reconnects, it will try again to install. At that point, this 10447 // will succeed. 10448 if (mArgs != null) { 10449 processPendingInstall(mArgs, mRet); 10450 } 10451 } 10452 10453 @Override 10454 void handleServiceError() { 10455 mArgs = createInstallArgs(this); 10456 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10457 } 10458 10459 public boolean isForwardLocked() { 10460 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10461 } 10462 } 10463 10464 /** 10465 * Used during creation of InstallArgs 10466 * 10467 * @param installFlags package installation flags 10468 * @return true if should be installed on external storage 10469 */ 10470 private static boolean installOnExternalAsec(int installFlags) { 10471 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10472 return false; 10473 } 10474 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10475 return true; 10476 } 10477 return false; 10478 } 10479 10480 /** 10481 * Used during creation of InstallArgs 10482 * 10483 * @param installFlags package installation flags 10484 * @return true if should be installed as forward locked 10485 */ 10486 private static boolean installForwardLocked(int installFlags) { 10487 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10488 } 10489 10490 private InstallArgs createInstallArgs(InstallParams params) { 10491 if (params.move != null) { 10492 return new MoveInstallArgs(params); 10493 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10494 return new AsecInstallArgs(params); 10495 } else { 10496 return new FileInstallArgs(params); 10497 } 10498 } 10499 10500 /** 10501 * Create args that describe an existing installed package. Typically used 10502 * when cleaning up old installs, or used as a move source. 10503 */ 10504 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10505 String resourcePath, String[] instructionSets) { 10506 final boolean isInAsec; 10507 if (installOnExternalAsec(installFlags)) { 10508 /* Apps on SD card are always in ASEC containers. */ 10509 isInAsec = true; 10510 } else if (installForwardLocked(installFlags) 10511 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10512 /* 10513 * Forward-locked apps are only in ASEC containers if they're the 10514 * new style 10515 */ 10516 isInAsec = true; 10517 } else { 10518 isInAsec = false; 10519 } 10520 10521 if (isInAsec) { 10522 return new AsecInstallArgs(codePath, instructionSets, 10523 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10524 } else { 10525 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10526 } 10527 } 10528 10529 static abstract class InstallArgs { 10530 /** @see InstallParams#origin */ 10531 final OriginInfo origin; 10532 /** @see InstallParams#move */ 10533 final MoveInfo move; 10534 10535 final IPackageInstallObserver2 observer; 10536 // Always refers to PackageManager flags only 10537 final int installFlags; 10538 final String installerPackageName; 10539 final String volumeUuid; 10540 final ManifestDigest manifestDigest; 10541 final UserHandle user; 10542 final String abiOverride; 10543 10544 // The list of instruction sets supported by this app. This is currently 10545 // only used during the rmdex() phase to clean up resources. We can get rid of this 10546 // if we move dex files under the common app path. 10547 /* nullable */ String[] instructionSets; 10548 10549 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10550 int installFlags, String installerPackageName, String volumeUuid, 10551 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10552 String abiOverride) { 10553 this.origin = origin; 10554 this.move = move; 10555 this.installFlags = installFlags; 10556 this.observer = observer; 10557 this.installerPackageName = installerPackageName; 10558 this.volumeUuid = volumeUuid; 10559 this.manifestDigest = manifestDigest; 10560 this.user = user; 10561 this.instructionSets = instructionSets; 10562 this.abiOverride = abiOverride; 10563 } 10564 10565 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10566 abstract int doPreInstall(int status); 10567 10568 /** 10569 * Rename package into final resting place. All paths on the given 10570 * scanned package should be updated to reflect the rename. 10571 */ 10572 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10573 abstract int doPostInstall(int status, int uid); 10574 10575 /** @see PackageSettingBase#codePathString */ 10576 abstract String getCodePath(); 10577 /** @see PackageSettingBase#resourcePathString */ 10578 abstract String getResourcePath(); 10579 10580 // Need installer lock especially for dex file removal. 10581 abstract void cleanUpResourcesLI(); 10582 abstract boolean doPostDeleteLI(boolean delete); 10583 10584 /** 10585 * Called before the source arguments are copied. This is used mostly 10586 * for MoveParams when it needs to read the source file to put it in the 10587 * destination. 10588 */ 10589 int doPreCopy() { 10590 return PackageManager.INSTALL_SUCCEEDED; 10591 } 10592 10593 /** 10594 * Called after the source arguments are copied. This is used mostly for 10595 * MoveParams when it needs to read the source file to put it in the 10596 * destination. 10597 * 10598 * @return 10599 */ 10600 int doPostCopy(int uid) { 10601 return PackageManager.INSTALL_SUCCEEDED; 10602 } 10603 10604 protected boolean isFwdLocked() { 10605 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10606 } 10607 10608 protected boolean isExternalAsec() { 10609 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10610 } 10611 10612 UserHandle getUser() { 10613 return user; 10614 } 10615 } 10616 10617 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10618 if (!allCodePaths.isEmpty()) { 10619 if (instructionSets == null) { 10620 throw new IllegalStateException("instructionSet == null"); 10621 } 10622 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10623 for (String codePath : allCodePaths) { 10624 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10625 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10626 if (retCode < 0) { 10627 Slog.w(TAG, "Couldn't remove dex file for package: " 10628 + " at location " + codePath + ", retcode=" + retCode); 10629 // we don't consider this to be a failure of the core package deletion 10630 } 10631 } 10632 } 10633 } 10634 } 10635 10636 /** 10637 * Logic to handle installation of non-ASEC applications, including copying 10638 * and renaming logic. 10639 */ 10640 class FileInstallArgs extends InstallArgs { 10641 private File codeFile; 10642 private File resourceFile; 10643 10644 // Example topology: 10645 // /data/app/com.example/base.apk 10646 // /data/app/com.example/split_foo.apk 10647 // /data/app/com.example/lib/arm/libfoo.so 10648 // /data/app/com.example/lib/arm64/libfoo.so 10649 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10650 10651 /** New install */ 10652 FileInstallArgs(InstallParams params) { 10653 super(params.origin, params.move, params.observer, params.installFlags, 10654 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10655 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10656 if (isFwdLocked()) { 10657 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10658 } 10659 } 10660 10661 /** Existing install */ 10662 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10663 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10664 null); 10665 this.codeFile = (codePath != null) ? new File(codePath) : null; 10666 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10667 } 10668 10669 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10670 if (origin.staged) { 10671 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10672 codeFile = origin.file; 10673 resourceFile = origin.file; 10674 return PackageManager.INSTALL_SUCCEEDED; 10675 } 10676 10677 try { 10678 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10679 codeFile = tempDir; 10680 resourceFile = tempDir; 10681 } catch (IOException e) { 10682 Slog.w(TAG, "Failed to create copy file: " + e); 10683 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10684 } 10685 10686 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10687 @Override 10688 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10689 if (!FileUtils.isValidExtFilename(name)) { 10690 throw new IllegalArgumentException("Invalid filename: " + name); 10691 } 10692 try { 10693 final File file = new File(codeFile, name); 10694 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10695 O_RDWR | O_CREAT, 0644); 10696 Os.chmod(file.getAbsolutePath(), 0644); 10697 return new ParcelFileDescriptor(fd); 10698 } catch (ErrnoException e) { 10699 throw new RemoteException("Failed to open: " + e.getMessage()); 10700 } 10701 } 10702 }; 10703 10704 int ret = PackageManager.INSTALL_SUCCEEDED; 10705 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10706 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10707 Slog.e(TAG, "Failed to copy package"); 10708 return ret; 10709 } 10710 10711 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10712 NativeLibraryHelper.Handle handle = null; 10713 try { 10714 handle = NativeLibraryHelper.Handle.create(codeFile); 10715 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10716 abiOverride); 10717 } catch (IOException e) { 10718 Slog.e(TAG, "Copying native libraries failed", e); 10719 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10720 } finally { 10721 IoUtils.closeQuietly(handle); 10722 } 10723 10724 return ret; 10725 } 10726 10727 int doPreInstall(int status) { 10728 if (status != PackageManager.INSTALL_SUCCEEDED) { 10729 cleanUp(); 10730 } 10731 return status; 10732 } 10733 10734 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10735 if (status != PackageManager.INSTALL_SUCCEEDED) { 10736 cleanUp(); 10737 return false; 10738 } 10739 10740 final File targetDir = codeFile.getParentFile(); 10741 final File beforeCodeFile = codeFile; 10742 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10743 10744 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10745 try { 10746 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10747 } catch (ErrnoException e) { 10748 Slog.w(TAG, "Failed to rename", e); 10749 return false; 10750 } 10751 10752 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10753 Slog.w(TAG, "Failed to restorecon"); 10754 return false; 10755 } 10756 10757 // Reflect the rename internally 10758 codeFile = afterCodeFile; 10759 resourceFile = afterCodeFile; 10760 10761 // Reflect the rename in scanned details 10762 pkg.codePath = afterCodeFile.getAbsolutePath(); 10763 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10764 pkg.baseCodePath); 10765 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10766 pkg.splitCodePaths); 10767 10768 // Reflect the rename in app info 10769 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10770 pkg.applicationInfo.setCodePath(pkg.codePath); 10771 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10772 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10773 pkg.applicationInfo.setResourcePath(pkg.codePath); 10774 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10775 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10776 10777 return true; 10778 } 10779 10780 int doPostInstall(int status, int uid) { 10781 if (status != PackageManager.INSTALL_SUCCEEDED) { 10782 cleanUp(); 10783 } 10784 return status; 10785 } 10786 10787 @Override 10788 String getCodePath() { 10789 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10790 } 10791 10792 @Override 10793 String getResourcePath() { 10794 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10795 } 10796 10797 private boolean cleanUp() { 10798 if (codeFile == null || !codeFile.exists()) { 10799 return false; 10800 } 10801 10802 if (codeFile.isDirectory()) { 10803 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10804 } else { 10805 codeFile.delete(); 10806 } 10807 10808 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10809 resourceFile.delete(); 10810 } 10811 10812 return true; 10813 } 10814 10815 void cleanUpResourcesLI() { 10816 // Try enumerating all code paths before deleting 10817 List<String> allCodePaths = Collections.EMPTY_LIST; 10818 if (codeFile != null && codeFile.exists()) { 10819 try { 10820 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10821 allCodePaths = pkg.getAllCodePaths(); 10822 } catch (PackageParserException e) { 10823 // Ignored; we tried our best 10824 } 10825 } 10826 10827 cleanUp(); 10828 removeDexFiles(allCodePaths, instructionSets); 10829 } 10830 10831 boolean doPostDeleteLI(boolean delete) { 10832 // XXX err, shouldn't we respect the delete flag? 10833 cleanUpResourcesLI(); 10834 return true; 10835 } 10836 } 10837 10838 private boolean isAsecExternal(String cid) { 10839 final String asecPath = PackageHelper.getSdFilesystem(cid); 10840 return !asecPath.startsWith(mAsecInternalPath); 10841 } 10842 10843 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10844 PackageManagerException { 10845 if (copyRet < 0) { 10846 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10847 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10848 throw new PackageManagerException(copyRet, message); 10849 } 10850 } 10851 } 10852 10853 /** 10854 * Extract the MountService "container ID" from the full code path of an 10855 * .apk. 10856 */ 10857 static String cidFromCodePath(String fullCodePath) { 10858 int eidx = fullCodePath.lastIndexOf("/"); 10859 String subStr1 = fullCodePath.substring(0, eidx); 10860 int sidx = subStr1.lastIndexOf("/"); 10861 return subStr1.substring(sidx+1, eidx); 10862 } 10863 10864 /** 10865 * Logic to handle installation of ASEC applications, including copying and 10866 * renaming logic. 10867 */ 10868 class AsecInstallArgs extends InstallArgs { 10869 static final String RES_FILE_NAME = "pkg.apk"; 10870 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10871 10872 String cid; 10873 String packagePath; 10874 String resourcePath; 10875 10876 /** New install */ 10877 AsecInstallArgs(InstallParams params) { 10878 super(params.origin, params.move, params.observer, params.installFlags, 10879 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10880 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10881 } 10882 10883 /** Existing install */ 10884 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10885 boolean isExternal, boolean isForwardLocked) { 10886 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10887 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10888 instructionSets, null); 10889 // Hackily pretend we're still looking at a full code path 10890 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10891 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10892 } 10893 10894 // Extract cid from fullCodePath 10895 int eidx = fullCodePath.lastIndexOf("/"); 10896 String subStr1 = fullCodePath.substring(0, eidx); 10897 int sidx = subStr1.lastIndexOf("/"); 10898 cid = subStr1.substring(sidx+1, eidx); 10899 setMountPath(subStr1); 10900 } 10901 10902 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10903 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10904 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10905 instructionSets, null); 10906 this.cid = cid; 10907 setMountPath(PackageHelper.getSdDir(cid)); 10908 } 10909 10910 void createCopyFile() { 10911 cid = mInstallerService.allocateExternalStageCidLegacy(); 10912 } 10913 10914 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10915 if (origin.staged) { 10916 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10917 cid = origin.cid; 10918 setMountPath(PackageHelper.getSdDir(cid)); 10919 return PackageManager.INSTALL_SUCCEEDED; 10920 } 10921 10922 if (temp) { 10923 createCopyFile(); 10924 } else { 10925 /* 10926 * Pre-emptively destroy the container since it's destroyed if 10927 * copying fails due to it existing anyway. 10928 */ 10929 PackageHelper.destroySdDir(cid); 10930 } 10931 10932 final String newMountPath = imcs.copyPackageToContainer( 10933 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10934 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10935 10936 if (newMountPath != null) { 10937 setMountPath(newMountPath); 10938 return PackageManager.INSTALL_SUCCEEDED; 10939 } else { 10940 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10941 } 10942 } 10943 10944 @Override 10945 String getCodePath() { 10946 return packagePath; 10947 } 10948 10949 @Override 10950 String getResourcePath() { 10951 return resourcePath; 10952 } 10953 10954 int doPreInstall(int status) { 10955 if (status != PackageManager.INSTALL_SUCCEEDED) { 10956 // Destroy container 10957 PackageHelper.destroySdDir(cid); 10958 } else { 10959 boolean mounted = PackageHelper.isContainerMounted(cid); 10960 if (!mounted) { 10961 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10962 Process.SYSTEM_UID); 10963 if (newMountPath != null) { 10964 setMountPath(newMountPath); 10965 } else { 10966 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10967 } 10968 } 10969 } 10970 return status; 10971 } 10972 10973 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10974 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10975 String newMountPath = null; 10976 if (PackageHelper.isContainerMounted(cid)) { 10977 // Unmount the container 10978 if (!PackageHelper.unMountSdDir(cid)) { 10979 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10980 return false; 10981 } 10982 } 10983 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10984 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10985 " which might be stale. Will try to clean up."); 10986 // Clean up the stale container and proceed to recreate. 10987 if (!PackageHelper.destroySdDir(newCacheId)) { 10988 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10989 return false; 10990 } 10991 // Successfully cleaned up stale container. Try to rename again. 10992 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10993 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10994 + " inspite of cleaning it up."); 10995 return false; 10996 } 10997 } 10998 if (!PackageHelper.isContainerMounted(newCacheId)) { 10999 Slog.w(TAG, "Mounting container " + newCacheId); 11000 newMountPath = PackageHelper.mountSdDir(newCacheId, 11001 getEncryptKey(), Process.SYSTEM_UID); 11002 } else { 11003 newMountPath = PackageHelper.getSdDir(newCacheId); 11004 } 11005 if (newMountPath == null) { 11006 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11007 return false; 11008 } 11009 Log.i(TAG, "Succesfully renamed " + cid + 11010 " to " + newCacheId + 11011 " at new path: " + newMountPath); 11012 cid = newCacheId; 11013 11014 final File beforeCodeFile = new File(packagePath); 11015 setMountPath(newMountPath); 11016 final File afterCodeFile = new File(packagePath); 11017 11018 // Reflect the rename in scanned details 11019 pkg.codePath = afterCodeFile.getAbsolutePath(); 11020 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11021 pkg.baseCodePath); 11022 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11023 pkg.splitCodePaths); 11024 11025 // Reflect the rename in app info 11026 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11027 pkg.applicationInfo.setCodePath(pkg.codePath); 11028 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11029 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11030 pkg.applicationInfo.setResourcePath(pkg.codePath); 11031 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11032 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11033 11034 return true; 11035 } 11036 11037 private void setMountPath(String mountPath) { 11038 final File mountFile = new File(mountPath); 11039 11040 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11041 if (monolithicFile.exists()) { 11042 packagePath = monolithicFile.getAbsolutePath(); 11043 if (isFwdLocked()) { 11044 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11045 } else { 11046 resourcePath = packagePath; 11047 } 11048 } else { 11049 packagePath = mountFile.getAbsolutePath(); 11050 resourcePath = packagePath; 11051 } 11052 } 11053 11054 int doPostInstall(int status, int uid) { 11055 if (status != PackageManager.INSTALL_SUCCEEDED) { 11056 cleanUp(); 11057 } else { 11058 final int groupOwner; 11059 final String protectedFile; 11060 if (isFwdLocked()) { 11061 groupOwner = UserHandle.getSharedAppGid(uid); 11062 protectedFile = RES_FILE_NAME; 11063 } else { 11064 groupOwner = -1; 11065 protectedFile = null; 11066 } 11067 11068 if (uid < Process.FIRST_APPLICATION_UID 11069 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11070 Slog.e(TAG, "Failed to finalize " + cid); 11071 PackageHelper.destroySdDir(cid); 11072 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11073 } 11074 11075 boolean mounted = PackageHelper.isContainerMounted(cid); 11076 if (!mounted) { 11077 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11078 } 11079 } 11080 return status; 11081 } 11082 11083 private void cleanUp() { 11084 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11085 11086 // Destroy secure container 11087 PackageHelper.destroySdDir(cid); 11088 } 11089 11090 private List<String> getAllCodePaths() { 11091 final File codeFile = new File(getCodePath()); 11092 if (codeFile != null && codeFile.exists()) { 11093 try { 11094 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11095 return pkg.getAllCodePaths(); 11096 } catch (PackageParserException e) { 11097 // Ignored; we tried our best 11098 } 11099 } 11100 return Collections.EMPTY_LIST; 11101 } 11102 11103 void cleanUpResourcesLI() { 11104 // Enumerate all code paths before deleting 11105 cleanUpResourcesLI(getAllCodePaths()); 11106 } 11107 11108 private void cleanUpResourcesLI(List<String> allCodePaths) { 11109 cleanUp(); 11110 removeDexFiles(allCodePaths, instructionSets); 11111 } 11112 11113 String getPackageName() { 11114 return getAsecPackageName(cid); 11115 } 11116 11117 boolean doPostDeleteLI(boolean delete) { 11118 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11119 final List<String> allCodePaths = getAllCodePaths(); 11120 boolean mounted = PackageHelper.isContainerMounted(cid); 11121 if (mounted) { 11122 // Unmount first 11123 if (PackageHelper.unMountSdDir(cid)) { 11124 mounted = false; 11125 } 11126 } 11127 if (!mounted && delete) { 11128 cleanUpResourcesLI(allCodePaths); 11129 } 11130 return !mounted; 11131 } 11132 11133 @Override 11134 int doPreCopy() { 11135 if (isFwdLocked()) { 11136 if (!PackageHelper.fixSdPermissions(cid, 11137 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11138 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11139 } 11140 } 11141 11142 return PackageManager.INSTALL_SUCCEEDED; 11143 } 11144 11145 @Override 11146 int doPostCopy(int uid) { 11147 if (isFwdLocked()) { 11148 if (uid < Process.FIRST_APPLICATION_UID 11149 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11150 RES_FILE_NAME)) { 11151 Slog.e(TAG, "Failed to finalize " + cid); 11152 PackageHelper.destroySdDir(cid); 11153 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11154 } 11155 } 11156 11157 return PackageManager.INSTALL_SUCCEEDED; 11158 } 11159 } 11160 11161 /** 11162 * Logic to handle movement of existing installed applications. 11163 */ 11164 class MoveInstallArgs extends InstallArgs { 11165 private File codeFile; 11166 private File resourceFile; 11167 11168 /** New install */ 11169 MoveInstallArgs(InstallParams params) { 11170 super(params.origin, params.move, params.observer, params.installFlags, 11171 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11172 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11173 } 11174 11175 int copyApk(IMediaContainerService imcs, boolean temp) { 11176 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11177 + move.fromUuid + " to " + move.toUuid); 11178 synchronized (mInstaller) { 11179 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11180 move.dataAppName, move.appId, move.seinfo) != 0) { 11181 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11182 } 11183 } 11184 11185 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11186 resourceFile = codeFile; 11187 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11188 11189 return PackageManager.INSTALL_SUCCEEDED; 11190 } 11191 11192 int doPreInstall(int status) { 11193 if (status != PackageManager.INSTALL_SUCCEEDED) { 11194 cleanUp(); 11195 } 11196 return status; 11197 } 11198 11199 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11200 if (status != PackageManager.INSTALL_SUCCEEDED) { 11201 cleanUp(); 11202 return false; 11203 } 11204 11205 // Reflect the move in app info 11206 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11207 pkg.applicationInfo.setCodePath(pkg.codePath); 11208 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11209 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11210 pkg.applicationInfo.setResourcePath(pkg.codePath); 11211 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11212 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11213 11214 return true; 11215 } 11216 11217 int doPostInstall(int status, int uid) { 11218 if (status != PackageManager.INSTALL_SUCCEEDED) { 11219 cleanUp(); 11220 } 11221 return status; 11222 } 11223 11224 @Override 11225 String getCodePath() { 11226 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11227 } 11228 11229 @Override 11230 String getResourcePath() { 11231 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11232 } 11233 11234 private boolean cleanUp() { 11235 if (codeFile == null || !codeFile.exists()) { 11236 return false; 11237 } 11238 11239 if (codeFile.isDirectory()) { 11240 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11241 } else { 11242 codeFile.delete(); 11243 } 11244 11245 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11246 resourceFile.delete(); 11247 } 11248 11249 return true; 11250 } 11251 11252 void cleanUpResourcesLI() { 11253 cleanUp(); 11254 } 11255 11256 boolean doPostDeleteLI(boolean delete) { 11257 // XXX err, shouldn't we respect the delete flag? 11258 cleanUpResourcesLI(); 11259 return true; 11260 } 11261 } 11262 11263 static String getAsecPackageName(String packageCid) { 11264 int idx = packageCid.lastIndexOf("-"); 11265 if (idx == -1) { 11266 return packageCid; 11267 } 11268 return packageCid.substring(0, idx); 11269 } 11270 11271 // Utility method used to create code paths based on package name and available index. 11272 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11273 String idxStr = ""; 11274 int idx = 1; 11275 // Fall back to default value of idx=1 if prefix is not 11276 // part of oldCodePath 11277 if (oldCodePath != null) { 11278 String subStr = oldCodePath; 11279 // Drop the suffix right away 11280 if (suffix != null && subStr.endsWith(suffix)) { 11281 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11282 } 11283 // If oldCodePath already contains prefix find out the 11284 // ending index to either increment or decrement. 11285 int sidx = subStr.lastIndexOf(prefix); 11286 if (sidx != -1) { 11287 subStr = subStr.substring(sidx + prefix.length()); 11288 if (subStr != null) { 11289 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11290 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11291 } 11292 try { 11293 idx = Integer.parseInt(subStr); 11294 if (idx <= 1) { 11295 idx++; 11296 } else { 11297 idx--; 11298 } 11299 } catch(NumberFormatException e) { 11300 } 11301 } 11302 } 11303 } 11304 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11305 return prefix + idxStr; 11306 } 11307 11308 private File getNextCodePath(File targetDir, String packageName) { 11309 int suffix = 1; 11310 File result; 11311 do { 11312 result = new File(targetDir, packageName + "-" + suffix); 11313 suffix++; 11314 } while (result.exists()); 11315 return result; 11316 } 11317 11318 // Utility method that returns the relative package path with respect 11319 // to the installation directory. Like say for /data/data/com.test-1.apk 11320 // string com.test-1 is returned. 11321 static String deriveCodePathName(String codePath) { 11322 if (codePath == null) { 11323 return null; 11324 } 11325 final File codeFile = new File(codePath); 11326 final String name = codeFile.getName(); 11327 if (codeFile.isDirectory()) { 11328 return name; 11329 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11330 final int lastDot = name.lastIndexOf('.'); 11331 return name.substring(0, lastDot); 11332 } else { 11333 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11334 return null; 11335 } 11336 } 11337 11338 class PackageInstalledInfo { 11339 String name; 11340 int uid; 11341 // The set of users that originally had this package installed. 11342 int[] origUsers; 11343 // The set of users that now have this package installed. 11344 int[] newUsers; 11345 PackageParser.Package pkg; 11346 int returnCode; 11347 String returnMsg; 11348 PackageRemovedInfo removedInfo; 11349 11350 public void setError(int code, String msg) { 11351 returnCode = code; 11352 returnMsg = msg; 11353 Slog.w(TAG, msg); 11354 } 11355 11356 public void setError(String msg, PackageParserException e) { 11357 returnCode = e.error; 11358 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11359 Slog.w(TAG, msg, e); 11360 } 11361 11362 public void setError(String msg, PackageManagerException e) { 11363 returnCode = e.error; 11364 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11365 Slog.w(TAG, msg, e); 11366 } 11367 11368 // In some error cases we want to convey more info back to the observer 11369 String origPackage; 11370 String origPermission; 11371 } 11372 11373 /* 11374 * Install a non-existing package. 11375 */ 11376 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11377 UserHandle user, String installerPackageName, String volumeUuid, 11378 PackageInstalledInfo res) { 11379 // Remember this for later, in case we need to rollback this install 11380 String pkgName = pkg.packageName; 11381 11382 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11383 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11384 UserHandle.USER_OWNER).exists(); 11385 synchronized(mPackages) { 11386 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11387 // A package with the same name is already installed, though 11388 // it has been renamed to an older name. The package we 11389 // are trying to install should be installed as an update to 11390 // the existing one, but that has not been requested, so bail. 11391 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11392 + " without first uninstalling package running as " 11393 + mSettings.mRenamedPackages.get(pkgName)); 11394 return; 11395 } 11396 if (mPackages.containsKey(pkgName)) { 11397 // Don't allow installation over an existing package with the same name. 11398 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11399 + " without first uninstalling."); 11400 return; 11401 } 11402 } 11403 11404 try { 11405 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11406 System.currentTimeMillis(), user); 11407 11408 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11409 // delete the partially installed application. the data directory will have to be 11410 // restored if it was already existing 11411 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11412 // remove package from internal structures. Note that we want deletePackageX to 11413 // delete the package data and cache directories that it created in 11414 // scanPackageLocked, unless those directories existed before we even tried to 11415 // install. 11416 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11417 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11418 res.removedInfo, true); 11419 } 11420 11421 } catch (PackageManagerException e) { 11422 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11423 } 11424 } 11425 11426 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11427 // Can't rotate keys during boot or if sharedUser. 11428 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11429 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11430 return false; 11431 } 11432 // app is using upgradeKeySets; make sure all are valid 11433 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11434 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11435 for (int i = 0; i < upgradeKeySets.length; i++) { 11436 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11437 Slog.wtf(TAG, "Package " 11438 + (oldPs.name != null ? oldPs.name : "<null>") 11439 + " contains upgrade-key-set reference to unknown key-set: " 11440 + upgradeKeySets[i] 11441 + " reverting to signatures check."); 11442 return false; 11443 } 11444 } 11445 return true; 11446 } 11447 11448 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11449 // Upgrade keysets are being used. Determine if new package has a superset of the 11450 // required keys. 11451 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11452 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11453 for (int i = 0; i < upgradeKeySets.length; i++) { 11454 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11455 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11456 return true; 11457 } 11458 } 11459 return false; 11460 } 11461 11462 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11463 UserHandle user, String installerPackageName, String volumeUuid, 11464 PackageInstalledInfo res) { 11465 final PackageParser.Package oldPackage; 11466 final String pkgName = pkg.packageName; 11467 final int[] allUsers; 11468 final boolean[] perUserInstalled; 11469 final boolean weFroze; 11470 11471 // First find the old package info and check signatures 11472 synchronized(mPackages) { 11473 oldPackage = mPackages.get(pkgName); 11474 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11475 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11476 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11477 if(!checkUpgradeKeySetLP(ps, pkg)) { 11478 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11479 "New package not signed by keys specified by upgrade-keysets: " 11480 + pkgName); 11481 return; 11482 } 11483 } else { 11484 // default to original signature matching 11485 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11486 != PackageManager.SIGNATURE_MATCH) { 11487 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11488 "New package has a different signature: " + pkgName); 11489 return; 11490 } 11491 } 11492 11493 // In case of rollback, remember per-user/profile install state 11494 allUsers = sUserManager.getUserIds(); 11495 perUserInstalled = new boolean[allUsers.length]; 11496 for (int i = 0; i < allUsers.length; i++) { 11497 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11498 } 11499 11500 // Mark the app as frozen to prevent launching during the upgrade 11501 // process, and then kill all running instances 11502 if (!ps.frozen) { 11503 ps.frozen = true; 11504 weFroze = true; 11505 } else { 11506 weFroze = false; 11507 } 11508 } 11509 11510 // Now that we're guarded by frozen state, kill app during upgrade 11511 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11512 11513 try { 11514 boolean sysPkg = (isSystemApp(oldPackage)); 11515 if (sysPkg) { 11516 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11517 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11518 } else { 11519 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11520 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11521 } 11522 } finally { 11523 // Regardless of success or failure of upgrade steps above, always 11524 // unfreeze the package if we froze it 11525 if (weFroze) { 11526 unfreezePackage(pkgName); 11527 } 11528 } 11529 } 11530 11531 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11532 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11533 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11534 String volumeUuid, PackageInstalledInfo res) { 11535 String pkgName = deletedPackage.packageName; 11536 boolean deletedPkg = true; 11537 boolean updatedSettings = false; 11538 11539 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11540 + deletedPackage); 11541 long origUpdateTime; 11542 if (pkg.mExtras != null) { 11543 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11544 } else { 11545 origUpdateTime = 0; 11546 } 11547 11548 // First delete the existing package while retaining the data directory 11549 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11550 res.removedInfo, true)) { 11551 // If the existing package wasn't successfully deleted 11552 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11553 deletedPkg = false; 11554 } else { 11555 // Successfully deleted the old package; proceed with replace. 11556 11557 // If deleted package lived in a container, give users a chance to 11558 // relinquish resources before killing. 11559 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11560 if (DEBUG_INSTALL) { 11561 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11562 } 11563 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11564 final ArrayList<String> pkgList = new ArrayList<String>(1); 11565 pkgList.add(deletedPackage.applicationInfo.packageName); 11566 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11567 } 11568 11569 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11570 try { 11571 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11572 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11573 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11574 perUserInstalled, res, user); 11575 updatedSettings = true; 11576 } catch (PackageManagerException e) { 11577 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11578 } 11579 } 11580 11581 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11582 // remove package from internal structures. Note that we want deletePackageX to 11583 // delete the package data and cache directories that it created in 11584 // scanPackageLocked, unless those directories existed before we even tried to 11585 // install. 11586 if(updatedSettings) { 11587 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11588 deletePackageLI( 11589 pkgName, null, true, allUsers, perUserInstalled, 11590 PackageManager.DELETE_KEEP_DATA, 11591 res.removedInfo, true); 11592 } 11593 // Since we failed to install the new package we need to restore the old 11594 // package that we deleted. 11595 if (deletedPkg) { 11596 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11597 File restoreFile = new File(deletedPackage.codePath); 11598 // Parse old package 11599 boolean oldExternal = isExternal(deletedPackage); 11600 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11601 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11602 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11603 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11604 try { 11605 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11606 } catch (PackageManagerException e) { 11607 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11608 + e.getMessage()); 11609 return; 11610 } 11611 // Restore of old package succeeded. Update permissions. 11612 // writer 11613 synchronized (mPackages) { 11614 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11615 UPDATE_PERMISSIONS_ALL); 11616 // can downgrade to reader 11617 mSettings.writeLPr(); 11618 } 11619 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11620 } 11621 } 11622 } 11623 11624 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11625 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11626 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11627 String volumeUuid, PackageInstalledInfo res) { 11628 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11629 + ", old=" + deletedPackage); 11630 boolean disabledSystem = false; 11631 boolean updatedSettings = false; 11632 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11633 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11634 != 0) { 11635 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11636 } 11637 String packageName = deletedPackage.packageName; 11638 if (packageName == null) { 11639 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11640 "Attempt to delete null packageName."); 11641 return; 11642 } 11643 PackageParser.Package oldPkg; 11644 PackageSetting oldPkgSetting; 11645 // reader 11646 synchronized (mPackages) { 11647 oldPkg = mPackages.get(packageName); 11648 oldPkgSetting = mSettings.mPackages.get(packageName); 11649 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11650 (oldPkgSetting == null)) { 11651 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11652 "Couldn't find package:" + packageName + " information"); 11653 return; 11654 } 11655 } 11656 11657 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11658 res.removedInfo.removedPackage = packageName; 11659 // Remove existing system package 11660 removePackageLI(oldPkgSetting, true); 11661 // writer 11662 synchronized (mPackages) { 11663 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11664 if (!disabledSystem && deletedPackage != null) { 11665 // We didn't need to disable the .apk as a current system package, 11666 // which means we are replacing another update that is already 11667 // installed. We need to make sure to delete the older one's .apk. 11668 res.removedInfo.args = createInstallArgsForExisting(0, 11669 deletedPackage.applicationInfo.getCodePath(), 11670 deletedPackage.applicationInfo.getResourcePath(), 11671 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11672 } else { 11673 res.removedInfo.args = null; 11674 } 11675 } 11676 11677 // Successfully disabled the old package. Now proceed with re-installation 11678 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11679 11680 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11681 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11682 11683 PackageParser.Package newPackage = null; 11684 try { 11685 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11686 if (newPackage.mExtras != null) { 11687 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11688 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11689 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11690 11691 // is the update attempting to change shared user? that isn't going to work... 11692 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11693 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11694 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11695 + " to " + newPkgSetting.sharedUser); 11696 updatedSettings = true; 11697 } 11698 } 11699 11700 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11701 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11702 perUserInstalled, res, user); 11703 updatedSettings = true; 11704 } 11705 11706 } catch (PackageManagerException e) { 11707 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11708 } 11709 11710 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11711 // Re installation failed. Restore old information 11712 // Remove new pkg information 11713 if (newPackage != null) { 11714 removeInstalledPackageLI(newPackage, true); 11715 } 11716 // Add back the old system package 11717 try { 11718 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11719 } catch (PackageManagerException e) { 11720 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11721 } 11722 // Restore the old system information in Settings 11723 synchronized (mPackages) { 11724 if (disabledSystem) { 11725 mSettings.enableSystemPackageLPw(packageName); 11726 } 11727 if (updatedSettings) { 11728 mSettings.setInstallerPackageName(packageName, 11729 oldPkgSetting.installerPackageName); 11730 } 11731 mSettings.writeLPr(); 11732 } 11733 } 11734 } 11735 11736 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11737 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11738 UserHandle user) { 11739 String pkgName = newPackage.packageName; 11740 synchronized (mPackages) { 11741 //write settings. the installStatus will be incomplete at this stage. 11742 //note that the new package setting would have already been 11743 //added to mPackages. It hasn't been persisted yet. 11744 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11745 mSettings.writeLPr(); 11746 } 11747 11748 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11749 11750 synchronized (mPackages) { 11751 updatePermissionsLPw(newPackage.packageName, newPackage, 11752 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11753 ? UPDATE_PERMISSIONS_ALL : 0)); 11754 // For system-bundled packages, we assume that installing an upgraded version 11755 // of the package implies that the user actually wants to run that new code, 11756 // so we enable the package. 11757 PackageSetting ps = mSettings.mPackages.get(pkgName); 11758 if (ps != null) { 11759 if (isSystemApp(newPackage)) { 11760 // NB: implicit assumption that system package upgrades apply to all users 11761 if (DEBUG_INSTALL) { 11762 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11763 } 11764 if (res.origUsers != null) { 11765 for (int userHandle : res.origUsers) { 11766 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11767 userHandle, installerPackageName); 11768 } 11769 } 11770 // Also convey the prior install/uninstall state 11771 if (allUsers != null && perUserInstalled != null) { 11772 for (int i = 0; i < allUsers.length; i++) { 11773 if (DEBUG_INSTALL) { 11774 Slog.d(TAG, " user " + allUsers[i] 11775 + " => " + perUserInstalled[i]); 11776 } 11777 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11778 } 11779 // these install state changes will be persisted in the 11780 // upcoming call to mSettings.writeLPr(). 11781 } 11782 } 11783 // It's implied that when a user requests installation, they want the app to be 11784 // installed and enabled. 11785 int userId = user.getIdentifier(); 11786 if (userId != UserHandle.USER_ALL) { 11787 ps.setInstalled(true, userId); 11788 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11789 } 11790 } 11791 res.name = pkgName; 11792 res.uid = newPackage.applicationInfo.uid; 11793 res.pkg = newPackage; 11794 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11795 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11796 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11797 //to update install status 11798 mSettings.writeLPr(); 11799 } 11800 } 11801 11802 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11803 final int installFlags = args.installFlags; 11804 final String installerPackageName = args.installerPackageName; 11805 final String volumeUuid = args.volumeUuid; 11806 final File tmpPackageFile = new File(args.getCodePath()); 11807 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11808 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11809 || (args.volumeUuid != null)); 11810 boolean replace = false; 11811 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11812 if (args.move != null) { 11813 // moving a complete application; perfom an initial scan on the new install location 11814 scanFlags |= SCAN_INITIAL; 11815 } 11816 // Result object to be returned 11817 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11818 11819 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11820 // Retrieve PackageSettings and parse package 11821 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11822 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11823 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11824 PackageParser pp = new PackageParser(); 11825 pp.setSeparateProcesses(mSeparateProcesses); 11826 pp.setDisplayMetrics(mMetrics); 11827 11828 final PackageParser.Package pkg; 11829 try { 11830 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11831 } catch (PackageParserException e) { 11832 res.setError("Failed parse during installPackageLI", e); 11833 return; 11834 } 11835 11836 // Mark that we have an install time CPU ABI override. 11837 pkg.cpuAbiOverride = args.abiOverride; 11838 11839 String pkgName = res.name = pkg.packageName; 11840 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11841 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11842 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11843 return; 11844 } 11845 } 11846 11847 try { 11848 pp.collectCertificates(pkg, parseFlags); 11849 pp.collectManifestDigest(pkg); 11850 } catch (PackageParserException e) { 11851 res.setError("Failed collect during installPackageLI", e); 11852 return; 11853 } 11854 11855 /* If the installer passed in a manifest digest, compare it now. */ 11856 if (args.manifestDigest != null) { 11857 if (DEBUG_INSTALL) { 11858 final String parsedManifest = pkg.manifestDigest == null ? "null" 11859 : pkg.manifestDigest.toString(); 11860 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11861 + parsedManifest); 11862 } 11863 11864 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11865 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11866 return; 11867 } 11868 } else if (DEBUG_INSTALL) { 11869 final String parsedManifest = pkg.manifestDigest == null 11870 ? "null" : pkg.manifestDigest.toString(); 11871 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11872 } 11873 11874 // Get rid of all references to package scan path via parser. 11875 pp = null; 11876 String oldCodePath = null; 11877 boolean systemApp = false; 11878 synchronized (mPackages) { 11879 // Check if installing already existing package 11880 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11881 String oldName = mSettings.mRenamedPackages.get(pkgName); 11882 if (pkg.mOriginalPackages != null 11883 && pkg.mOriginalPackages.contains(oldName) 11884 && mPackages.containsKey(oldName)) { 11885 // This package is derived from an original package, 11886 // and this device has been updating from that original 11887 // name. We must continue using the original name, so 11888 // rename the new package here. 11889 pkg.setPackageName(oldName); 11890 pkgName = pkg.packageName; 11891 replace = true; 11892 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11893 + oldName + " pkgName=" + pkgName); 11894 } else if (mPackages.containsKey(pkgName)) { 11895 // This package, under its official name, already exists 11896 // on the device; we should replace it. 11897 replace = true; 11898 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11899 } 11900 11901 // Prevent apps opting out from runtime permissions 11902 if (replace) { 11903 PackageParser.Package oldPackage = mPackages.get(pkgName); 11904 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11905 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11906 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11907 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11908 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11909 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11910 + " doesn't support runtime permissions but the old" 11911 + " target SDK " + oldTargetSdk + " does."); 11912 return; 11913 } 11914 } 11915 } 11916 11917 PackageSetting ps = mSettings.mPackages.get(pkgName); 11918 if (ps != null) { 11919 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11920 11921 // Quick sanity check that we're signed correctly if updating; 11922 // we'll check this again later when scanning, but we want to 11923 // bail early here before tripping over redefined permissions. 11924 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11925 if (!checkUpgradeKeySetLP(ps, pkg)) { 11926 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11927 + pkg.packageName + " upgrade keys do not match the " 11928 + "previously installed version"); 11929 return; 11930 } 11931 } else { 11932 try { 11933 verifySignaturesLP(ps, pkg); 11934 } catch (PackageManagerException e) { 11935 res.setError(e.error, e.getMessage()); 11936 return; 11937 } 11938 } 11939 11940 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11941 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11942 systemApp = (ps.pkg.applicationInfo.flags & 11943 ApplicationInfo.FLAG_SYSTEM) != 0; 11944 } 11945 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11946 } 11947 11948 // Check whether the newly-scanned package wants to define an already-defined perm 11949 int N = pkg.permissions.size(); 11950 for (int i = N-1; i >= 0; i--) { 11951 PackageParser.Permission perm = pkg.permissions.get(i); 11952 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11953 if (bp != null) { 11954 // If the defining package is signed with our cert, it's okay. This 11955 // also includes the "updating the same package" case, of course. 11956 // "updating same package" could also involve key-rotation. 11957 final boolean sigsOk; 11958 if (bp.sourcePackage.equals(pkg.packageName) 11959 && (bp.packageSetting instanceof PackageSetting) 11960 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11961 scanFlags))) { 11962 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11963 } else { 11964 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11965 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11966 } 11967 if (!sigsOk) { 11968 // If the owning package is the system itself, we log but allow 11969 // install to proceed; we fail the install on all other permission 11970 // redefinitions. 11971 if (!bp.sourcePackage.equals("android")) { 11972 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11973 + pkg.packageName + " attempting to redeclare permission " 11974 + perm.info.name + " already owned by " + bp.sourcePackage); 11975 res.origPermission = perm.info.name; 11976 res.origPackage = bp.sourcePackage; 11977 return; 11978 } else { 11979 Slog.w(TAG, "Package " + pkg.packageName 11980 + " attempting to redeclare system permission " 11981 + perm.info.name + "; ignoring new declaration"); 11982 pkg.permissions.remove(i); 11983 } 11984 } 11985 } 11986 } 11987 11988 } 11989 11990 if (systemApp && onExternal) { 11991 // Disable updates to system apps on sdcard 11992 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11993 "Cannot install updates to system apps on sdcard"); 11994 return; 11995 } 11996 11997 if (args.move != null) { 11998 // We did an in-place move, so dex is ready to roll 11999 scanFlags |= SCAN_NO_DEX; 12000 scanFlags |= SCAN_MOVE; 12001 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12002 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12003 scanFlags |= SCAN_NO_DEX; 12004 12005 try { 12006 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12007 true /* extract libs */); 12008 } catch (PackageManagerException pme) { 12009 Slog.e(TAG, "Error deriving application ABI", pme); 12010 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12011 return; 12012 } 12013 12014 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12015 int result = mPackageDexOptimizer 12016 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12017 false /* defer */, false /* inclDependencies */); 12018 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12019 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12020 return; 12021 } 12022 } 12023 12024 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12025 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12026 return; 12027 } 12028 12029 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12030 12031 if (replace) { 12032 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12033 installerPackageName, volumeUuid, res); 12034 } else { 12035 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12036 args.user, installerPackageName, volumeUuid, res); 12037 } 12038 synchronized (mPackages) { 12039 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12040 if (ps != null) { 12041 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12042 } 12043 } 12044 } 12045 12046 private void startIntentFilterVerifications(int userId, boolean replacing, 12047 PackageParser.Package pkg) { 12048 if (mIntentFilterVerifierComponent == null) { 12049 Slog.w(TAG, "No IntentFilter verification will not be done as " 12050 + "there is no IntentFilterVerifier available!"); 12051 return; 12052 } 12053 12054 final int verifierUid = getPackageUid( 12055 mIntentFilterVerifierComponent.getPackageName(), 12056 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12057 12058 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12059 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12060 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12061 mHandler.sendMessage(msg); 12062 } 12063 12064 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12065 PackageParser.Package pkg) { 12066 int size = pkg.activities.size(); 12067 if (size == 0) { 12068 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12069 "No activity, so no need to verify any IntentFilter!"); 12070 return; 12071 } 12072 12073 final boolean hasDomainURLs = hasDomainURLs(pkg); 12074 if (!hasDomainURLs) { 12075 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12076 "No domain URLs, so no need to verify any IntentFilter!"); 12077 return; 12078 } 12079 12080 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12081 + " if any IntentFilter from the " + size 12082 + " Activities needs verification ..."); 12083 12084 int count = 0; 12085 final String packageName = pkg.packageName; 12086 12087 synchronized (mPackages) { 12088 // If this is a new install and we see that we've already run verification for this 12089 // package, we have nothing to do: it means the state was restored from backup. 12090 if (!replacing) { 12091 IntentFilterVerificationInfo ivi = 12092 mSettings.getIntentFilterVerificationLPr(packageName); 12093 if (ivi != null) { 12094 if (DEBUG_DOMAIN_VERIFICATION) { 12095 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12096 + ivi.getStatusString()); 12097 } 12098 return; 12099 } 12100 } 12101 12102 // If any filters need to be verified, then all need to be. 12103 boolean needToVerify = false; 12104 for (PackageParser.Activity a : pkg.activities) { 12105 for (ActivityIntentInfo filter : a.intents) { 12106 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12107 if (DEBUG_DOMAIN_VERIFICATION) { 12108 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12109 } 12110 needToVerify = true; 12111 break; 12112 } 12113 } 12114 } 12115 12116 if (needToVerify) { 12117 final int verificationId = mIntentFilterVerificationToken++; 12118 for (PackageParser.Activity a : pkg.activities) { 12119 for (ActivityIntentInfo filter : a.intents) { 12120 if (filter.hasOnlyWebDataURI() && needsNetworkVerificationLPr(filter)) { 12121 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12122 "Verification needed for IntentFilter:" + filter.toString()); 12123 mIntentFilterVerifier.addOneIntentFilterVerification( 12124 verifierUid, userId, verificationId, filter, packageName); 12125 count++; 12126 } 12127 } 12128 } 12129 } 12130 } 12131 12132 if (count > 0) { 12133 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12134 + " IntentFilter verification" + (count > 1 ? "s" : "") 12135 + " for userId:" + userId); 12136 mIntentFilterVerifier.startVerifications(userId); 12137 } else { 12138 if (DEBUG_DOMAIN_VERIFICATION) { 12139 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12140 } 12141 } 12142 } 12143 12144 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12145 final ComponentName cn = filter.activity.getComponentName(); 12146 final String packageName = cn.getPackageName(); 12147 12148 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12149 packageName); 12150 if (ivi == null) { 12151 return true; 12152 } 12153 int status = ivi.getStatus(); 12154 switch (status) { 12155 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12156 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12157 return true; 12158 12159 default: 12160 // Nothing to do 12161 return false; 12162 } 12163 } 12164 12165 private static boolean isMultiArch(PackageSetting ps) { 12166 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12167 } 12168 12169 private static boolean isMultiArch(ApplicationInfo info) { 12170 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12171 } 12172 12173 private static boolean isExternal(PackageParser.Package pkg) { 12174 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12175 } 12176 12177 private static boolean isExternal(PackageSetting ps) { 12178 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12179 } 12180 12181 private static boolean isExternal(ApplicationInfo info) { 12182 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12183 } 12184 12185 private static boolean isSystemApp(PackageParser.Package pkg) { 12186 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12187 } 12188 12189 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12190 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12191 } 12192 12193 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12194 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12195 } 12196 12197 private static boolean isSystemApp(PackageSetting ps) { 12198 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12199 } 12200 12201 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12202 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12203 } 12204 12205 private int packageFlagsToInstallFlags(PackageSetting ps) { 12206 int installFlags = 0; 12207 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12208 // This existing package was an external ASEC install when we have 12209 // the external flag without a UUID 12210 installFlags |= PackageManager.INSTALL_EXTERNAL; 12211 } 12212 if (ps.isForwardLocked()) { 12213 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12214 } 12215 return installFlags; 12216 } 12217 12218 private void deleteTempPackageFiles() { 12219 final FilenameFilter filter = new FilenameFilter() { 12220 public boolean accept(File dir, String name) { 12221 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12222 } 12223 }; 12224 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12225 file.delete(); 12226 } 12227 } 12228 12229 @Override 12230 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12231 int flags) { 12232 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12233 flags); 12234 } 12235 12236 @Override 12237 public void deletePackage(final String packageName, 12238 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12239 mContext.enforceCallingOrSelfPermission( 12240 android.Manifest.permission.DELETE_PACKAGES, null); 12241 final int uid = Binder.getCallingUid(); 12242 if (UserHandle.getUserId(uid) != userId) { 12243 mContext.enforceCallingPermission( 12244 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12245 "deletePackage for user " + userId); 12246 } 12247 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12248 try { 12249 observer.onPackageDeleted(packageName, 12250 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12251 } catch (RemoteException re) { 12252 } 12253 return; 12254 } 12255 12256 boolean uninstallBlocked = false; 12257 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12258 int[] users = sUserManager.getUserIds(); 12259 for (int i = 0; i < users.length; ++i) { 12260 if (getBlockUninstallForUser(packageName, users[i])) { 12261 uninstallBlocked = true; 12262 break; 12263 } 12264 } 12265 } else { 12266 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12267 } 12268 if (uninstallBlocked) { 12269 try { 12270 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12271 null); 12272 } catch (RemoteException re) { 12273 } 12274 return; 12275 } 12276 12277 if (DEBUG_REMOVE) { 12278 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12279 } 12280 // Queue up an async operation since the package deletion may take a little while. 12281 mHandler.post(new Runnable() { 12282 public void run() { 12283 mHandler.removeCallbacks(this); 12284 final int returnCode = deletePackageX(packageName, userId, flags); 12285 if (observer != null) { 12286 try { 12287 observer.onPackageDeleted(packageName, returnCode, null); 12288 } catch (RemoteException e) { 12289 Log.i(TAG, "Observer no longer exists."); 12290 } //end catch 12291 } //end if 12292 } //end run 12293 }); 12294 } 12295 12296 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12297 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12298 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12299 try { 12300 if (dpm != null) { 12301 if (dpm.isDeviceOwner(packageName)) { 12302 return true; 12303 } 12304 int[] users; 12305 if (userId == UserHandle.USER_ALL) { 12306 users = sUserManager.getUserIds(); 12307 } else { 12308 users = new int[]{userId}; 12309 } 12310 for (int i = 0; i < users.length; ++i) { 12311 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12312 return true; 12313 } 12314 } 12315 } 12316 } catch (RemoteException e) { 12317 } 12318 return false; 12319 } 12320 12321 /** 12322 * This method is an internal method that could be get invoked either 12323 * to delete an installed package or to clean up a failed installation. 12324 * After deleting an installed package, a broadcast is sent to notify any 12325 * listeners that the package has been installed. For cleaning up a failed 12326 * installation, the broadcast is not necessary since the package's 12327 * installation wouldn't have sent the initial broadcast either 12328 * The key steps in deleting a package are 12329 * deleting the package information in internal structures like mPackages, 12330 * deleting the packages base directories through installd 12331 * updating mSettings to reflect current status 12332 * persisting settings for later use 12333 * sending a broadcast if necessary 12334 */ 12335 private int deletePackageX(String packageName, int userId, int flags) { 12336 final PackageRemovedInfo info = new PackageRemovedInfo(); 12337 final boolean res; 12338 12339 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12340 ? UserHandle.ALL : new UserHandle(userId); 12341 12342 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12343 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12344 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12345 } 12346 12347 boolean removedForAllUsers = false; 12348 boolean systemUpdate = false; 12349 12350 // for the uninstall-updates case and restricted profiles, remember the per- 12351 // userhandle installed state 12352 int[] allUsers; 12353 boolean[] perUserInstalled; 12354 synchronized (mPackages) { 12355 PackageSetting ps = mSettings.mPackages.get(packageName); 12356 allUsers = sUserManager.getUserIds(); 12357 perUserInstalled = new boolean[allUsers.length]; 12358 for (int i = 0; i < allUsers.length; i++) { 12359 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12360 } 12361 } 12362 12363 synchronized (mInstallLock) { 12364 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12365 res = deletePackageLI(packageName, removeForUser, 12366 true, allUsers, perUserInstalled, 12367 flags | REMOVE_CHATTY, info, true); 12368 systemUpdate = info.isRemovedPackageSystemUpdate; 12369 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12370 removedForAllUsers = true; 12371 } 12372 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12373 + " removedForAllUsers=" + removedForAllUsers); 12374 } 12375 12376 if (res) { 12377 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12378 12379 // If the removed package was a system update, the old system package 12380 // was re-enabled; we need to broadcast this information 12381 if (systemUpdate) { 12382 Bundle extras = new Bundle(1); 12383 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12384 ? info.removedAppId : info.uid); 12385 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12386 12387 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12388 extras, null, null, null); 12389 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12390 extras, null, null, null); 12391 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12392 null, packageName, null, null); 12393 } 12394 } 12395 // Force a gc here. 12396 Runtime.getRuntime().gc(); 12397 // Delete the resources here after sending the broadcast to let 12398 // other processes clean up before deleting resources. 12399 if (info.args != null) { 12400 synchronized (mInstallLock) { 12401 info.args.doPostDeleteLI(true); 12402 } 12403 } 12404 12405 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12406 } 12407 12408 class PackageRemovedInfo { 12409 String removedPackage; 12410 int uid = -1; 12411 int removedAppId = -1; 12412 int[] removedUsers = null; 12413 boolean isRemovedPackageSystemUpdate = false; 12414 // Clean up resources deleted packages. 12415 InstallArgs args = null; 12416 12417 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12418 Bundle extras = new Bundle(1); 12419 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12420 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12421 if (replacing) { 12422 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12423 } 12424 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12425 if (removedPackage != null) { 12426 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12427 extras, null, null, removedUsers); 12428 if (fullRemove && !replacing) { 12429 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12430 extras, null, null, removedUsers); 12431 } 12432 } 12433 if (removedAppId >= 0) { 12434 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12435 removedUsers); 12436 } 12437 } 12438 } 12439 12440 /* 12441 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12442 * flag is not set, the data directory is removed as well. 12443 * make sure this flag is set for partially installed apps. If not its meaningless to 12444 * delete a partially installed application. 12445 */ 12446 private void removePackageDataLI(PackageSetting ps, 12447 int[] allUserHandles, boolean[] perUserInstalled, 12448 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12449 String packageName = ps.name; 12450 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12451 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12452 // Retrieve object to delete permissions for shared user later on 12453 final PackageSetting deletedPs; 12454 // reader 12455 synchronized (mPackages) { 12456 deletedPs = mSettings.mPackages.get(packageName); 12457 if (outInfo != null) { 12458 outInfo.removedPackage = packageName; 12459 outInfo.removedUsers = deletedPs != null 12460 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12461 : null; 12462 } 12463 } 12464 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12465 removeDataDirsLI(ps.volumeUuid, packageName); 12466 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12467 } 12468 // writer 12469 synchronized (mPackages) { 12470 if (deletedPs != null) { 12471 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12472 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12473 clearDefaultBrowserIfNeeded(packageName); 12474 if (outInfo != null) { 12475 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12476 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12477 } 12478 updatePermissionsLPw(deletedPs.name, null, 0); 12479 if (deletedPs.sharedUser != null) { 12480 // Remove permissions associated with package. Since runtime 12481 // permissions are per user we have to kill the removed package 12482 // or packages running under the shared user of the removed 12483 // package if revoking the permissions requested only by the removed 12484 // package is successful and this causes a change in gids. 12485 for (int userId : UserManagerService.getInstance().getUserIds()) { 12486 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12487 userId); 12488 if (userIdToKill == UserHandle.USER_ALL 12489 || userIdToKill >= UserHandle.USER_OWNER) { 12490 // If gids changed for this user, kill all affected packages. 12491 mHandler.post(new Runnable() { 12492 @Override 12493 public void run() { 12494 // This has to happen with no lock held. 12495 killSettingPackagesForUser(deletedPs, userIdToKill, 12496 KILL_APP_REASON_GIDS_CHANGED); 12497 } 12498 }); 12499 break; 12500 } 12501 } 12502 } 12503 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12504 } 12505 // make sure to preserve per-user disabled state if this removal was just 12506 // a downgrade of a system app to the factory package 12507 if (allUserHandles != null && perUserInstalled != null) { 12508 if (DEBUG_REMOVE) { 12509 Slog.d(TAG, "Propagating install state across downgrade"); 12510 } 12511 for (int i = 0; i < allUserHandles.length; i++) { 12512 if (DEBUG_REMOVE) { 12513 Slog.d(TAG, " user " + allUserHandles[i] 12514 + " => " + perUserInstalled[i]); 12515 } 12516 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12517 } 12518 } 12519 } 12520 // can downgrade to reader 12521 if (writeSettings) { 12522 // Save settings now 12523 mSettings.writeLPr(); 12524 } 12525 } 12526 if (outInfo != null) { 12527 // A user ID was deleted here. Go through all users and remove it 12528 // from KeyStore. 12529 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12530 } 12531 } 12532 12533 static boolean locationIsPrivileged(File path) { 12534 try { 12535 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12536 .getCanonicalPath(); 12537 return path.getCanonicalPath().startsWith(privilegedAppDir); 12538 } catch (IOException e) { 12539 Slog.e(TAG, "Unable to access code path " + path); 12540 } 12541 return false; 12542 } 12543 12544 /* 12545 * Tries to delete system package. 12546 */ 12547 private boolean deleteSystemPackageLI(PackageSetting newPs, 12548 int[] allUserHandles, boolean[] perUserInstalled, 12549 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12550 final boolean applyUserRestrictions 12551 = (allUserHandles != null) && (perUserInstalled != null); 12552 PackageSetting disabledPs = null; 12553 // Confirm if the system package has been updated 12554 // An updated system app can be deleted. This will also have to restore 12555 // the system pkg from system partition 12556 // reader 12557 synchronized (mPackages) { 12558 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12559 } 12560 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12561 + " disabledPs=" + disabledPs); 12562 if (disabledPs == null) { 12563 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12564 return false; 12565 } else if (DEBUG_REMOVE) { 12566 Slog.d(TAG, "Deleting system pkg from data partition"); 12567 } 12568 if (DEBUG_REMOVE) { 12569 if (applyUserRestrictions) { 12570 Slog.d(TAG, "Remembering install states:"); 12571 for (int i = 0; i < allUserHandles.length; i++) { 12572 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12573 } 12574 } 12575 } 12576 // Delete the updated package 12577 outInfo.isRemovedPackageSystemUpdate = true; 12578 if (disabledPs.versionCode < newPs.versionCode) { 12579 // Delete data for downgrades 12580 flags &= ~PackageManager.DELETE_KEEP_DATA; 12581 } else { 12582 // Preserve data by setting flag 12583 flags |= PackageManager.DELETE_KEEP_DATA; 12584 } 12585 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12586 allUserHandles, perUserInstalled, outInfo, writeSettings); 12587 if (!ret) { 12588 return false; 12589 } 12590 // writer 12591 synchronized (mPackages) { 12592 // Reinstate the old system package 12593 mSettings.enableSystemPackageLPw(newPs.name); 12594 // Remove any native libraries from the upgraded package. 12595 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12596 } 12597 // Install the system package 12598 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12599 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12600 if (locationIsPrivileged(disabledPs.codePath)) { 12601 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12602 } 12603 12604 final PackageParser.Package newPkg; 12605 try { 12606 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12607 } catch (PackageManagerException e) { 12608 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12609 return false; 12610 } 12611 12612 // writer 12613 synchronized (mPackages) { 12614 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12615 updatePermissionsLPw(newPkg.packageName, newPkg, 12616 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12617 if (applyUserRestrictions) { 12618 if (DEBUG_REMOVE) { 12619 Slog.d(TAG, "Propagating install state across reinstall"); 12620 } 12621 for (int i = 0; i < allUserHandles.length; i++) { 12622 if (DEBUG_REMOVE) { 12623 Slog.d(TAG, " user " + allUserHandles[i] 12624 + " => " + perUserInstalled[i]); 12625 } 12626 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12627 } 12628 // Regardless of writeSettings we need to ensure that this restriction 12629 // state propagation is persisted 12630 mSettings.writeAllUsersPackageRestrictionsLPr(); 12631 } 12632 // can downgrade to reader here 12633 if (writeSettings) { 12634 mSettings.writeLPr(); 12635 } 12636 } 12637 return true; 12638 } 12639 12640 private boolean deleteInstalledPackageLI(PackageSetting ps, 12641 boolean deleteCodeAndResources, int flags, 12642 int[] allUserHandles, boolean[] perUserInstalled, 12643 PackageRemovedInfo outInfo, boolean writeSettings) { 12644 if (outInfo != null) { 12645 outInfo.uid = ps.appId; 12646 } 12647 12648 // Delete package data from internal structures and also remove data if flag is set 12649 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12650 12651 // Delete application code and resources 12652 if (deleteCodeAndResources && (outInfo != null)) { 12653 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12654 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12655 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12656 } 12657 return true; 12658 } 12659 12660 @Override 12661 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12662 int userId) { 12663 mContext.enforceCallingOrSelfPermission( 12664 android.Manifest.permission.DELETE_PACKAGES, null); 12665 synchronized (mPackages) { 12666 PackageSetting ps = mSettings.mPackages.get(packageName); 12667 if (ps == null) { 12668 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12669 return false; 12670 } 12671 if (!ps.getInstalled(userId)) { 12672 // Can't block uninstall for an app that is not installed or enabled. 12673 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12674 return false; 12675 } 12676 ps.setBlockUninstall(blockUninstall, userId); 12677 mSettings.writePackageRestrictionsLPr(userId); 12678 } 12679 return true; 12680 } 12681 12682 @Override 12683 public boolean getBlockUninstallForUser(String packageName, int userId) { 12684 synchronized (mPackages) { 12685 PackageSetting ps = mSettings.mPackages.get(packageName); 12686 if (ps == null) { 12687 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12688 return false; 12689 } 12690 return ps.getBlockUninstall(userId); 12691 } 12692 } 12693 12694 /* 12695 * This method handles package deletion in general 12696 */ 12697 private boolean deletePackageLI(String packageName, UserHandle user, 12698 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12699 int flags, PackageRemovedInfo outInfo, 12700 boolean writeSettings) { 12701 if (packageName == null) { 12702 Slog.w(TAG, "Attempt to delete null packageName."); 12703 return false; 12704 } 12705 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12706 PackageSetting ps; 12707 boolean dataOnly = false; 12708 int removeUser = -1; 12709 int appId = -1; 12710 synchronized (mPackages) { 12711 ps = mSettings.mPackages.get(packageName); 12712 if (ps == null) { 12713 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12714 return false; 12715 } 12716 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12717 && user.getIdentifier() != UserHandle.USER_ALL) { 12718 // The caller is asking that the package only be deleted for a single 12719 // user. To do this, we just mark its uninstalled state and delete 12720 // its data. If this is a system app, we only allow this to happen if 12721 // they have set the special DELETE_SYSTEM_APP which requests different 12722 // semantics than normal for uninstalling system apps. 12723 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12724 ps.setUserState(user.getIdentifier(), 12725 COMPONENT_ENABLED_STATE_DEFAULT, 12726 false, //installed 12727 true, //stopped 12728 true, //notLaunched 12729 false, //hidden 12730 null, null, null, 12731 false, // blockUninstall 12732 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12733 if (!isSystemApp(ps)) { 12734 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12735 // Other user still have this package installed, so all 12736 // we need to do is clear this user's data and save that 12737 // it is uninstalled. 12738 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12739 removeUser = user.getIdentifier(); 12740 appId = ps.appId; 12741 scheduleWritePackageRestrictionsLocked(removeUser); 12742 } else { 12743 // We need to set it back to 'installed' so the uninstall 12744 // broadcasts will be sent correctly. 12745 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12746 ps.setInstalled(true, user.getIdentifier()); 12747 } 12748 } else { 12749 // This is a system app, so we assume that the 12750 // other users still have this package installed, so all 12751 // we need to do is clear this user's data and save that 12752 // it is uninstalled. 12753 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12754 removeUser = user.getIdentifier(); 12755 appId = ps.appId; 12756 scheduleWritePackageRestrictionsLocked(removeUser); 12757 } 12758 } 12759 } 12760 12761 if (removeUser >= 0) { 12762 // From above, we determined that we are deleting this only 12763 // for a single user. Continue the work here. 12764 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12765 if (outInfo != null) { 12766 outInfo.removedPackage = packageName; 12767 outInfo.removedAppId = appId; 12768 outInfo.removedUsers = new int[] {removeUser}; 12769 } 12770 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12771 removeKeystoreDataIfNeeded(removeUser, appId); 12772 schedulePackageCleaning(packageName, removeUser, false); 12773 synchronized (mPackages) { 12774 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12775 scheduleWritePackageRestrictionsLocked(removeUser); 12776 } 12777 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12778 removeUser); 12779 } 12780 return true; 12781 } 12782 12783 if (dataOnly) { 12784 // Delete application data first 12785 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12786 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12787 return true; 12788 } 12789 12790 boolean ret = false; 12791 if (isSystemApp(ps)) { 12792 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12793 // When an updated system application is deleted we delete the existing resources as well and 12794 // fall back to existing code in system partition 12795 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12796 flags, outInfo, writeSettings); 12797 } else { 12798 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12799 // Kill application pre-emptively especially for apps on sd. 12800 killApplication(packageName, ps.appId, "uninstall pkg"); 12801 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12802 allUserHandles, perUserInstalled, 12803 outInfo, writeSettings); 12804 } 12805 12806 return ret; 12807 } 12808 12809 private final class ClearStorageConnection implements ServiceConnection { 12810 IMediaContainerService mContainerService; 12811 12812 @Override 12813 public void onServiceConnected(ComponentName name, IBinder service) { 12814 synchronized (this) { 12815 mContainerService = IMediaContainerService.Stub.asInterface(service); 12816 notifyAll(); 12817 } 12818 } 12819 12820 @Override 12821 public void onServiceDisconnected(ComponentName name) { 12822 } 12823 } 12824 12825 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12826 final boolean mounted; 12827 if (Environment.isExternalStorageEmulated()) { 12828 mounted = true; 12829 } else { 12830 final String status = Environment.getExternalStorageState(); 12831 12832 mounted = status.equals(Environment.MEDIA_MOUNTED) 12833 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12834 } 12835 12836 if (!mounted) { 12837 return; 12838 } 12839 12840 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12841 int[] users; 12842 if (userId == UserHandle.USER_ALL) { 12843 users = sUserManager.getUserIds(); 12844 } else { 12845 users = new int[] { userId }; 12846 } 12847 final ClearStorageConnection conn = new ClearStorageConnection(); 12848 if (mContext.bindServiceAsUser( 12849 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12850 try { 12851 for (int curUser : users) { 12852 long timeout = SystemClock.uptimeMillis() + 5000; 12853 synchronized (conn) { 12854 long now = SystemClock.uptimeMillis(); 12855 while (conn.mContainerService == null && now < timeout) { 12856 try { 12857 conn.wait(timeout - now); 12858 } catch (InterruptedException e) { 12859 } 12860 } 12861 } 12862 if (conn.mContainerService == null) { 12863 return; 12864 } 12865 12866 final UserEnvironment userEnv = new UserEnvironment(curUser); 12867 clearDirectory(conn.mContainerService, 12868 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12869 if (allData) { 12870 clearDirectory(conn.mContainerService, 12871 userEnv.buildExternalStorageAppDataDirs(packageName)); 12872 clearDirectory(conn.mContainerService, 12873 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12874 } 12875 } 12876 } finally { 12877 mContext.unbindService(conn); 12878 } 12879 } 12880 } 12881 12882 @Override 12883 public void clearApplicationUserData(final String packageName, 12884 final IPackageDataObserver observer, final int userId) { 12885 mContext.enforceCallingOrSelfPermission( 12886 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12887 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12888 // Queue up an async operation since the package deletion may take a little while. 12889 mHandler.post(new Runnable() { 12890 public void run() { 12891 mHandler.removeCallbacks(this); 12892 final boolean succeeded; 12893 synchronized (mInstallLock) { 12894 succeeded = clearApplicationUserDataLI(packageName, userId); 12895 } 12896 clearExternalStorageDataSync(packageName, userId, true); 12897 if (succeeded) { 12898 // invoke DeviceStorageMonitor's update method to clear any notifications 12899 DeviceStorageMonitorInternal 12900 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12901 if (dsm != null) { 12902 dsm.checkMemory(); 12903 } 12904 } 12905 if(observer != null) { 12906 try { 12907 observer.onRemoveCompleted(packageName, succeeded); 12908 } catch (RemoteException e) { 12909 Log.i(TAG, "Observer no longer exists."); 12910 } 12911 } //end if observer 12912 } //end run 12913 }); 12914 } 12915 12916 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12917 if (packageName == null) { 12918 Slog.w(TAG, "Attempt to delete null packageName."); 12919 return false; 12920 } 12921 12922 // Try finding details about the requested package 12923 PackageParser.Package pkg; 12924 synchronized (mPackages) { 12925 pkg = mPackages.get(packageName); 12926 if (pkg == null) { 12927 final PackageSetting ps = mSettings.mPackages.get(packageName); 12928 if (ps != null) { 12929 pkg = ps.pkg; 12930 } 12931 } 12932 12933 if (pkg == null) { 12934 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12935 return false; 12936 } 12937 12938 PackageSetting ps = (PackageSetting) pkg.mExtras; 12939 PermissionsState permissionsState = ps.getPermissionsState(); 12940 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12941 } 12942 12943 // Always delete data directories for package, even if we found no other 12944 // record of app. This helps users recover from UID mismatches without 12945 // resorting to a full data wipe. 12946 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12947 if (retCode < 0) { 12948 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12949 return false; 12950 } 12951 12952 final int appId = pkg.applicationInfo.uid; 12953 removeKeystoreDataIfNeeded(userId, appId); 12954 12955 // Create a native library symlink only if we have native libraries 12956 // and if the native libraries are 32 bit libraries. We do not provide 12957 // this symlink for 64 bit libraries. 12958 if (pkg.applicationInfo.primaryCpuAbi != null && 12959 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12960 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12961 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12962 nativeLibPath, userId) < 0) { 12963 Slog.w(TAG, "Failed linking native library dir"); 12964 return false; 12965 } 12966 } 12967 12968 return true; 12969 } 12970 12971 12972 /** 12973 * Revokes granted runtime permissions and clears resettable flags 12974 * which are flags that can be set by a user interaction. 12975 * 12976 * @param permissionsState The permission state to reset. 12977 * @param userId The device user for which to do a reset. 12978 */ 12979 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12980 PermissionsState permissionsState, int userId) { 12981 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12982 | PackageManager.FLAG_PERMISSION_USER_FIXED 12983 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12984 12985 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 12986 } 12987 12988 /** 12989 * Revokes granted runtime permissions and clears all flags. 12990 * 12991 * @param permissionsState The permission state to reset. 12992 * @param userId The device user for which to do a reset. 12993 */ 12994 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 12995 PermissionsState permissionsState, int userId) { 12996 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 12997 PackageManager.MASK_PERMISSION_FLAGS); 12998 } 12999 13000 /** 13001 * Revokes granted runtime permissions and clears certain flags. 13002 * 13003 * @param permissionsState The permission state to reset. 13004 * @param userId The device user for which to do a reset. 13005 * @param flags The flags that is going to be reset. 13006 */ 13007 private void revokeRuntimePermissionsAndClearFlagsLocked( 13008 PermissionsState permissionsState, int userId, int flags) { 13009 boolean needsWrite = false; 13010 13011 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13012 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13013 if (bp != null) { 13014 permissionsState.revokeRuntimePermission(bp, userId); 13015 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13016 needsWrite = true; 13017 } 13018 } 13019 13020 // Ensure default permissions are never cleared. 13021 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13022 13023 if (needsWrite) { 13024 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13025 } 13026 } 13027 13028 /** 13029 * Remove entries from the keystore daemon. Will only remove it if the 13030 * {@code appId} is valid. 13031 */ 13032 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13033 if (appId < 0) { 13034 return; 13035 } 13036 13037 final KeyStore keyStore = KeyStore.getInstance(); 13038 if (keyStore != null) { 13039 if (userId == UserHandle.USER_ALL) { 13040 for (final int individual : sUserManager.getUserIds()) { 13041 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13042 } 13043 } else { 13044 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13045 } 13046 } else { 13047 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13048 } 13049 } 13050 13051 @Override 13052 public void deleteApplicationCacheFiles(final String packageName, 13053 final IPackageDataObserver observer) { 13054 mContext.enforceCallingOrSelfPermission( 13055 android.Manifest.permission.DELETE_CACHE_FILES, null); 13056 // Queue up an async operation since the package deletion may take a little while. 13057 final int userId = UserHandle.getCallingUserId(); 13058 mHandler.post(new Runnable() { 13059 public void run() { 13060 mHandler.removeCallbacks(this); 13061 final boolean succeded; 13062 synchronized (mInstallLock) { 13063 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13064 } 13065 clearExternalStorageDataSync(packageName, userId, false); 13066 if (observer != null) { 13067 try { 13068 observer.onRemoveCompleted(packageName, succeded); 13069 } catch (RemoteException e) { 13070 Log.i(TAG, "Observer no longer exists."); 13071 } 13072 } //end if observer 13073 } //end run 13074 }); 13075 } 13076 13077 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13078 if (packageName == null) { 13079 Slog.w(TAG, "Attempt to delete null packageName."); 13080 return false; 13081 } 13082 PackageParser.Package p; 13083 synchronized (mPackages) { 13084 p = mPackages.get(packageName); 13085 } 13086 if (p == null) { 13087 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13088 return false; 13089 } 13090 final ApplicationInfo applicationInfo = p.applicationInfo; 13091 if (applicationInfo == null) { 13092 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13093 return false; 13094 } 13095 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13096 if (retCode < 0) { 13097 Slog.w(TAG, "Couldn't remove cache files for package: " 13098 + packageName + " u" + userId); 13099 return false; 13100 } 13101 return true; 13102 } 13103 13104 @Override 13105 public void getPackageSizeInfo(final String packageName, int userHandle, 13106 final IPackageStatsObserver observer) { 13107 mContext.enforceCallingOrSelfPermission( 13108 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13109 if (packageName == null) { 13110 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13111 } 13112 13113 PackageStats stats = new PackageStats(packageName, userHandle); 13114 13115 /* 13116 * Queue up an async operation since the package measurement may take a 13117 * little while. 13118 */ 13119 Message msg = mHandler.obtainMessage(INIT_COPY); 13120 msg.obj = new MeasureParams(stats, observer); 13121 mHandler.sendMessage(msg); 13122 } 13123 13124 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13125 PackageStats pStats) { 13126 if (packageName == null) { 13127 Slog.w(TAG, "Attempt to get size of null packageName."); 13128 return false; 13129 } 13130 PackageParser.Package p; 13131 boolean dataOnly = false; 13132 String libDirRoot = null; 13133 String asecPath = null; 13134 PackageSetting ps = null; 13135 synchronized (mPackages) { 13136 p = mPackages.get(packageName); 13137 ps = mSettings.mPackages.get(packageName); 13138 if(p == null) { 13139 dataOnly = true; 13140 if((ps == null) || (ps.pkg == null)) { 13141 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13142 return false; 13143 } 13144 p = ps.pkg; 13145 } 13146 if (ps != null) { 13147 libDirRoot = ps.legacyNativeLibraryPathString; 13148 } 13149 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13150 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13151 if (secureContainerId != null) { 13152 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13153 } 13154 } 13155 } 13156 String publicSrcDir = null; 13157 if(!dataOnly) { 13158 final ApplicationInfo applicationInfo = p.applicationInfo; 13159 if (applicationInfo == null) { 13160 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13161 return false; 13162 } 13163 if (p.isForwardLocked()) { 13164 publicSrcDir = applicationInfo.getBaseResourcePath(); 13165 } 13166 } 13167 // TODO: extend to measure size of split APKs 13168 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13169 // not just the first level. 13170 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13171 // just the primary. 13172 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13173 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13174 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13175 if (res < 0) { 13176 return false; 13177 } 13178 13179 // Fix-up for forward-locked applications in ASEC containers. 13180 if (!isExternal(p)) { 13181 pStats.codeSize += pStats.externalCodeSize; 13182 pStats.externalCodeSize = 0L; 13183 } 13184 13185 return true; 13186 } 13187 13188 13189 @Override 13190 public void addPackageToPreferred(String packageName) { 13191 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13192 } 13193 13194 @Override 13195 public void removePackageFromPreferred(String packageName) { 13196 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13197 } 13198 13199 @Override 13200 public List<PackageInfo> getPreferredPackages(int flags) { 13201 return new ArrayList<PackageInfo>(); 13202 } 13203 13204 private int getUidTargetSdkVersionLockedLPr(int uid) { 13205 Object obj = mSettings.getUserIdLPr(uid); 13206 if (obj instanceof SharedUserSetting) { 13207 final SharedUserSetting sus = (SharedUserSetting) obj; 13208 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13209 final Iterator<PackageSetting> it = sus.packages.iterator(); 13210 while (it.hasNext()) { 13211 final PackageSetting ps = it.next(); 13212 if (ps.pkg != null) { 13213 int v = ps.pkg.applicationInfo.targetSdkVersion; 13214 if (v < vers) vers = v; 13215 } 13216 } 13217 return vers; 13218 } else if (obj instanceof PackageSetting) { 13219 final PackageSetting ps = (PackageSetting) obj; 13220 if (ps.pkg != null) { 13221 return ps.pkg.applicationInfo.targetSdkVersion; 13222 } 13223 } 13224 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13225 } 13226 13227 @Override 13228 public void addPreferredActivity(IntentFilter filter, int match, 13229 ComponentName[] set, ComponentName activity, int userId) { 13230 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13231 "Adding preferred"); 13232 } 13233 13234 private void addPreferredActivityInternal(IntentFilter filter, int match, 13235 ComponentName[] set, ComponentName activity, boolean always, int userId, 13236 String opname) { 13237 // writer 13238 int callingUid = Binder.getCallingUid(); 13239 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13240 if (filter.countActions() == 0) { 13241 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13242 return; 13243 } 13244 synchronized (mPackages) { 13245 if (mContext.checkCallingOrSelfPermission( 13246 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13247 != PackageManager.PERMISSION_GRANTED) { 13248 if (getUidTargetSdkVersionLockedLPr(callingUid) 13249 < Build.VERSION_CODES.FROYO) { 13250 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13251 + callingUid); 13252 return; 13253 } 13254 mContext.enforceCallingOrSelfPermission( 13255 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13256 } 13257 13258 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13259 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13260 + userId + ":"); 13261 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13262 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13263 scheduleWritePackageRestrictionsLocked(userId); 13264 } 13265 } 13266 13267 @Override 13268 public void replacePreferredActivity(IntentFilter filter, int match, 13269 ComponentName[] set, ComponentName activity, int userId) { 13270 if (filter.countActions() != 1) { 13271 throw new IllegalArgumentException( 13272 "replacePreferredActivity expects filter to have only 1 action."); 13273 } 13274 if (filter.countDataAuthorities() != 0 13275 || filter.countDataPaths() != 0 13276 || filter.countDataSchemes() > 1 13277 || filter.countDataTypes() != 0) { 13278 throw new IllegalArgumentException( 13279 "replacePreferredActivity expects filter to have no data authorities, " + 13280 "paths, or types; and at most one scheme."); 13281 } 13282 13283 final int callingUid = Binder.getCallingUid(); 13284 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13285 synchronized (mPackages) { 13286 if (mContext.checkCallingOrSelfPermission( 13287 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13288 != PackageManager.PERMISSION_GRANTED) { 13289 if (getUidTargetSdkVersionLockedLPr(callingUid) 13290 < Build.VERSION_CODES.FROYO) { 13291 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13292 + Binder.getCallingUid()); 13293 return; 13294 } 13295 mContext.enforceCallingOrSelfPermission( 13296 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13297 } 13298 13299 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13300 if (pir != null) { 13301 // Get all of the existing entries that exactly match this filter. 13302 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13303 if (existing != null && existing.size() == 1) { 13304 PreferredActivity cur = existing.get(0); 13305 if (DEBUG_PREFERRED) { 13306 Slog.i(TAG, "Checking replace of preferred:"); 13307 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13308 if (!cur.mPref.mAlways) { 13309 Slog.i(TAG, " -- CUR; not mAlways!"); 13310 } else { 13311 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13312 Slog.i(TAG, " -- CUR: mSet=" 13313 + Arrays.toString(cur.mPref.mSetComponents)); 13314 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13315 Slog.i(TAG, " -- NEW: mMatch=" 13316 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13317 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13318 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13319 } 13320 } 13321 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13322 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13323 && cur.mPref.sameSet(set)) { 13324 // Setting the preferred activity to what it happens to be already 13325 if (DEBUG_PREFERRED) { 13326 Slog.i(TAG, "Replacing with same preferred activity " 13327 + cur.mPref.mShortComponent + " for user " 13328 + userId + ":"); 13329 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13330 } 13331 return; 13332 } 13333 } 13334 13335 if (existing != null) { 13336 if (DEBUG_PREFERRED) { 13337 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13338 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13339 } 13340 for (int i = 0; i < existing.size(); i++) { 13341 PreferredActivity pa = existing.get(i); 13342 if (DEBUG_PREFERRED) { 13343 Slog.i(TAG, "Removing existing preferred activity " 13344 + pa.mPref.mComponent + ":"); 13345 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13346 } 13347 pir.removeFilter(pa); 13348 } 13349 } 13350 } 13351 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13352 "Replacing preferred"); 13353 } 13354 } 13355 13356 @Override 13357 public void clearPackagePreferredActivities(String packageName) { 13358 final int uid = Binder.getCallingUid(); 13359 // writer 13360 synchronized (mPackages) { 13361 PackageParser.Package pkg = mPackages.get(packageName); 13362 if (pkg == null || pkg.applicationInfo.uid != uid) { 13363 if (mContext.checkCallingOrSelfPermission( 13364 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13365 != PackageManager.PERMISSION_GRANTED) { 13366 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13367 < Build.VERSION_CODES.FROYO) { 13368 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13369 + Binder.getCallingUid()); 13370 return; 13371 } 13372 mContext.enforceCallingOrSelfPermission( 13373 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13374 } 13375 } 13376 13377 int user = UserHandle.getCallingUserId(); 13378 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13379 scheduleWritePackageRestrictionsLocked(user); 13380 } 13381 } 13382 } 13383 13384 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13385 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13386 ArrayList<PreferredActivity> removed = null; 13387 boolean changed = false; 13388 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13389 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13390 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13391 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13392 continue; 13393 } 13394 Iterator<PreferredActivity> it = pir.filterIterator(); 13395 while (it.hasNext()) { 13396 PreferredActivity pa = it.next(); 13397 // Mark entry for removal only if it matches the package name 13398 // and the entry is of type "always". 13399 if (packageName == null || 13400 (pa.mPref.mComponent.getPackageName().equals(packageName) 13401 && pa.mPref.mAlways)) { 13402 if (removed == null) { 13403 removed = new ArrayList<PreferredActivity>(); 13404 } 13405 removed.add(pa); 13406 } 13407 } 13408 if (removed != null) { 13409 for (int j=0; j<removed.size(); j++) { 13410 PreferredActivity pa = removed.get(j); 13411 pir.removeFilter(pa); 13412 } 13413 changed = true; 13414 } 13415 } 13416 return changed; 13417 } 13418 13419 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13420 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13421 if (userId == UserHandle.USER_ALL) { 13422 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13423 sUserManager.getUserIds())) { 13424 for (int oneUserId : sUserManager.getUserIds()) { 13425 scheduleWritePackageRestrictionsLocked(oneUserId); 13426 } 13427 } 13428 } else { 13429 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13430 scheduleWritePackageRestrictionsLocked(userId); 13431 } 13432 } 13433 } 13434 13435 13436 void clearDefaultBrowserIfNeeded(String packageName) { 13437 for (int oneUserId : sUserManager.getUserIds()) { 13438 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13439 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13440 if (packageName.equals(defaultBrowserPackageName)) { 13441 setDefaultBrowserPackageName(null, oneUserId); 13442 } 13443 } 13444 } 13445 13446 @Override 13447 public void resetPreferredActivities(int userId) { 13448 mContext.enforceCallingOrSelfPermission( 13449 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13450 // writer 13451 synchronized (mPackages) { 13452 clearPackagePreferredActivitiesLPw(null, userId); 13453 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13454 applyFactoryDefaultBrowserLPw(userId); 13455 13456 scheduleWritePackageRestrictionsLocked(userId); 13457 } 13458 } 13459 13460 @Override 13461 public int getPreferredActivities(List<IntentFilter> outFilters, 13462 List<ComponentName> outActivities, String packageName) { 13463 13464 int num = 0; 13465 final int userId = UserHandle.getCallingUserId(); 13466 // reader 13467 synchronized (mPackages) { 13468 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13469 if (pir != null) { 13470 final Iterator<PreferredActivity> it = pir.filterIterator(); 13471 while (it.hasNext()) { 13472 final PreferredActivity pa = it.next(); 13473 if (packageName == null 13474 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13475 && pa.mPref.mAlways)) { 13476 if (outFilters != null) { 13477 outFilters.add(new IntentFilter(pa)); 13478 } 13479 if (outActivities != null) { 13480 outActivities.add(pa.mPref.mComponent); 13481 } 13482 } 13483 } 13484 } 13485 } 13486 13487 return num; 13488 } 13489 13490 @Override 13491 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13492 int userId) { 13493 int callingUid = Binder.getCallingUid(); 13494 if (callingUid != Process.SYSTEM_UID) { 13495 throw new SecurityException( 13496 "addPersistentPreferredActivity can only be run by the system"); 13497 } 13498 if (filter.countActions() == 0) { 13499 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13500 return; 13501 } 13502 synchronized (mPackages) { 13503 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13504 " :"); 13505 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13506 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13507 new PersistentPreferredActivity(filter, activity)); 13508 scheduleWritePackageRestrictionsLocked(userId); 13509 } 13510 } 13511 13512 @Override 13513 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13514 int callingUid = Binder.getCallingUid(); 13515 if (callingUid != Process.SYSTEM_UID) { 13516 throw new SecurityException( 13517 "clearPackagePersistentPreferredActivities can only be run by the system"); 13518 } 13519 ArrayList<PersistentPreferredActivity> removed = null; 13520 boolean changed = false; 13521 synchronized (mPackages) { 13522 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13523 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13524 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13525 .valueAt(i); 13526 if (userId != thisUserId) { 13527 continue; 13528 } 13529 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13530 while (it.hasNext()) { 13531 PersistentPreferredActivity ppa = it.next(); 13532 // Mark entry for removal only if it matches the package name. 13533 if (ppa.mComponent.getPackageName().equals(packageName)) { 13534 if (removed == null) { 13535 removed = new ArrayList<PersistentPreferredActivity>(); 13536 } 13537 removed.add(ppa); 13538 } 13539 } 13540 if (removed != null) { 13541 for (int j=0; j<removed.size(); j++) { 13542 PersistentPreferredActivity ppa = removed.get(j); 13543 ppir.removeFilter(ppa); 13544 } 13545 changed = true; 13546 } 13547 } 13548 13549 if (changed) { 13550 scheduleWritePackageRestrictionsLocked(userId); 13551 } 13552 } 13553 } 13554 13555 /** 13556 * Common machinery for picking apart a restored XML blob and passing 13557 * it to a caller-supplied functor to be applied to the running system. 13558 */ 13559 private void restoreFromXml(XmlPullParser parser, int userId, 13560 String expectedStartTag, BlobXmlRestorer functor) 13561 throws IOException, XmlPullParserException { 13562 int type; 13563 while ((type = parser.next()) != XmlPullParser.START_TAG 13564 && type != XmlPullParser.END_DOCUMENT) { 13565 } 13566 if (type != XmlPullParser.START_TAG) { 13567 // oops didn't find a start tag?! 13568 if (DEBUG_BACKUP) { 13569 Slog.e(TAG, "Didn't find start tag during restore"); 13570 } 13571 return; 13572 } 13573 13574 // this is supposed to be TAG_PREFERRED_BACKUP 13575 if (!expectedStartTag.equals(parser.getName())) { 13576 if (DEBUG_BACKUP) { 13577 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13578 } 13579 return; 13580 } 13581 13582 // skip interfering stuff, then we're aligned with the backing implementation 13583 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13584 functor.apply(parser, userId); 13585 } 13586 13587 private interface BlobXmlRestorer { 13588 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13589 } 13590 13591 /** 13592 * Non-Binder method, support for the backup/restore mechanism: write the 13593 * full set of preferred activities in its canonical XML format. Returns the 13594 * XML output as a byte array, or null if there is none. 13595 */ 13596 @Override 13597 public byte[] getPreferredActivityBackup(int userId) { 13598 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13599 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13600 } 13601 13602 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13603 try { 13604 final XmlSerializer serializer = new FastXmlSerializer(); 13605 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13606 serializer.startDocument(null, true); 13607 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13608 13609 synchronized (mPackages) { 13610 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13611 } 13612 13613 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13614 serializer.endDocument(); 13615 serializer.flush(); 13616 } catch (Exception e) { 13617 if (DEBUG_BACKUP) { 13618 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13619 } 13620 return null; 13621 } 13622 13623 return dataStream.toByteArray(); 13624 } 13625 13626 @Override 13627 public void restorePreferredActivities(byte[] backup, int userId) { 13628 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13629 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13630 } 13631 13632 try { 13633 final XmlPullParser parser = Xml.newPullParser(); 13634 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13635 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13636 new BlobXmlRestorer() { 13637 @Override 13638 public void apply(XmlPullParser parser, int userId) 13639 throws XmlPullParserException, IOException { 13640 synchronized (mPackages) { 13641 mSettings.readPreferredActivitiesLPw(parser, userId); 13642 } 13643 } 13644 } ); 13645 } catch (Exception e) { 13646 if (DEBUG_BACKUP) { 13647 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13648 } 13649 } 13650 } 13651 13652 /** 13653 * Non-Binder method, support for the backup/restore mechanism: write the 13654 * default browser (etc) settings in its canonical XML format. Returns the default 13655 * browser XML representation as a byte array, or null if there is none. 13656 */ 13657 @Override 13658 public byte[] getDefaultAppsBackup(int userId) { 13659 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13660 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13661 } 13662 13663 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13664 try { 13665 final XmlSerializer serializer = new FastXmlSerializer(); 13666 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13667 serializer.startDocument(null, true); 13668 serializer.startTag(null, TAG_DEFAULT_APPS); 13669 13670 synchronized (mPackages) { 13671 mSettings.writeDefaultAppsLPr(serializer, userId); 13672 } 13673 13674 serializer.endTag(null, TAG_DEFAULT_APPS); 13675 serializer.endDocument(); 13676 serializer.flush(); 13677 } catch (Exception e) { 13678 if (DEBUG_BACKUP) { 13679 Slog.e(TAG, "Unable to write default apps for backup", e); 13680 } 13681 return null; 13682 } 13683 13684 return dataStream.toByteArray(); 13685 } 13686 13687 @Override 13688 public void restoreDefaultApps(byte[] backup, int userId) { 13689 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13690 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13691 } 13692 13693 try { 13694 final XmlPullParser parser = Xml.newPullParser(); 13695 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13696 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13697 new BlobXmlRestorer() { 13698 @Override 13699 public void apply(XmlPullParser parser, int userId) 13700 throws XmlPullParserException, IOException { 13701 synchronized (mPackages) { 13702 mSettings.readDefaultAppsLPw(parser, userId); 13703 } 13704 } 13705 } ); 13706 } catch (Exception e) { 13707 if (DEBUG_BACKUP) { 13708 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13709 } 13710 } 13711 } 13712 13713 @Override 13714 public byte[] getIntentFilterVerificationBackup(int userId) { 13715 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13716 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13717 } 13718 13719 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13720 try { 13721 final XmlSerializer serializer = new FastXmlSerializer(); 13722 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13723 serializer.startDocument(null, true); 13724 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13725 13726 synchronized (mPackages) { 13727 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13728 } 13729 13730 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13731 serializer.endDocument(); 13732 serializer.flush(); 13733 } catch (Exception e) { 13734 if (DEBUG_BACKUP) { 13735 Slog.e(TAG, "Unable to write default apps for backup", e); 13736 } 13737 return null; 13738 } 13739 13740 return dataStream.toByteArray(); 13741 } 13742 13743 @Override 13744 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13745 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13746 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13747 } 13748 13749 try { 13750 final XmlPullParser parser = Xml.newPullParser(); 13751 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13752 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13753 new BlobXmlRestorer() { 13754 @Override 13755 public void apply(XmlPullParser parser, int userId) 13756 throws XmlPullParserException, IOException { 13757 synchronized (mPackages) { 13758 mSettings.readAllDomainVerificationsLPr(parser, userId); 13759 mSettings.writeLPr(); 13760 } 13761 } 13762 } ); 13763 } catch (Exception e) { 13764 if (DEBUG_BACKUP) { 13765 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13766 } 13767 } 13768 } 13769 13770 @Override 13771 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13772 int sourceUserId, int targetUserId, int flags) { 13773 mContext.enforceCallingOrSelfPermission( 13774 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13775 int callingUid = Binder.getCallingUid(); 13776 enforceOwnerRights(ownerPackage, callingUid); 13777 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13778 if (intentFilter.countActions() == 0) { 13779 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13780 return; 13781 } 13782 synchronized (mPackages) { 13783 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13784 ownerPackage, targetUserId, flags); 13785 CrossProfileIntentResolver resolver = 13786 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13787 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13788 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13789 if (existing != null) { 13790 int size = existing.size(); 13791 for (int i = 0; i < size; i++) { 13792 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13793 return; 13794 } 13795 } 13796 } 13797 resolver.addFilter(newFilter); 13798 scheduleWritePackageRestrictionsLocked(sourceUserId); 13799 } 13800 } 13801 13802 @Override 13803 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13804 mContext.enforceCallingOrSelfPermission( 13805 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13806 int callingUid = Binder.getCallingUid(); 13807 enforceOwnerRights(ownerPackage, callingUid); 13808 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13809 synchronized (mPackages) { 13810 CrossProfileIntentResolver resolver = 13811 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13812 ArraySet<CrossProfileIntentFilter> set = 13813 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13814 for (CrossProfileIntentFilter filter : set) { 13815 if (filter.getOwnerPackage().equals(ownerPackage)) { 13816 resolver.removeFilter(filter); 13817 } 13818 } 13819 scheduleWritePackageRestrictionsLocked(sourceUserId); 13820 } 13821 } 13822 13823 // Enforcing that callingUid is owning pkg on userId 13824 private void enforceOwnerRights(String pkg, int callingUid) { 13825 // The system owns everything. 13826 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13827 return; 13828 } 13829 int callingUserId = UserHandle.getUserId(callingUid); 13830 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13831 if (pi == null) { 13832 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13833 + callingUserId); 13834 } 13835 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13836 throw new SecurityException("Calling uid " + callingUid 13837 + " does not own package " + pkg); 13838 } 13839 } 13840 13841 @Override 13842 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13843 Intent intent = new Intent(Intent.ACTION_MAIN); 13844 intent.addCategory(Intent.CATEGORY_HOME); 13845 13846 final int callingUserId = UserHandle.getCallingUserId(); 13847 List<ResolveInfo> list = queryIntentActivities(intent, null, 13848 PackageManager.GET_META_DATA, callingUserId); 13849 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13850 true, false, false, callingUserId); 13851 13852 allHomeCandidates.clear(); 13853 if (list != null) { 13854 for (ResolveInfo ri : list) { 13855 allHomeCandidates.add(ri); 13856 } 13857 } 13858 return (preferred == null || preferred.activityInfo == null) 13859 ? null 13860 : new ComponentName(preferred.activityInfo.packageName, 13861 preferred.activityInfo.name); 13862 } 13863 13864 @Override 13865 public void setApplicationEnabledSetting(String appPackageName, 13866 int newState, int flags, int userId, String callingPackage) { 13867 if (!sUserManager.exists(userId)) return; 13868 if (callingPackage == null) { 13869 callingPackage = Integer.toString(Binder.getCallingUid()); 13870 } 13871 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13872 } 13873 13874 @Override 13875 public void setComponentEnabledSetting(ComponentName componentName, 13876 int newState, int flags, int userId) { 13877 if (!sUserManager.exists(userId)) return; 13878 setEnabledSetting(componentName.getPackageName(), 13879 componentName.getClassName(), newState, flags, userId, null); 13880 } 13881 13882 private void setEnabledSetting(final String packageName, String className, int newState, 13883 final int flags, int userId, String callingPackage) { 13884 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13885 || newState == COMPONENT_ENABLED_STATE_ENABLED 13886 || newState == COMPONENT_ENABLED_STATE_DISABLED 13887 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13888 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13889 throw new IllegalArgumentException("Invalid new component state: " 13890 + newState); 13891 } 13892 PackageSetting pkgSetting; 13893 final int uid = Binder.getCallingUid(); 13894 final int permission = mContext.checkCallingOrSelfPermission( 13895 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13896 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13897 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13898 boolean sendNow = false; 13899 boolean isApp = (className == null); 13900 String componentName = isApp ? packageName : className; 13901 int packageUid = -1; 13902 ArrayList<String> components; 13903 13904 // writer 13905 synchronized (mPackages) { 13906 pkgSetting = mSettings.mPackages.get(packageName); 13907 if (pkgSetting == null) { 13908 if (className == null) { 13909 throw new IllegalArgumentException( 13910 "Unknown package: " + packageName); 13911 } 13912 throw new IllegalArgumentException( 13913 "Unknown component: " + packageName 13914 + "/" + className); 13915 } 13916 // Allow root and verify that userId is not being specified by a different user 13917 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13918 throw new SecurityException( 13919 "Permission Denial: attempt to change component state from pid=" 13920 + Binder.getCallingPid() 13921 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13922 } 13923 if (className == null) { 13924 // We're dealing with an application/package level state change 13925 if (pkgSetting.getEnabled(userId) == newState) { 13926 // Nothing to do 13927 return; 13928 } 13929 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13930 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13931 // Don't care about who enables an app. 13932 callingPackage = null; 13933 } 13934 pkgSetting.setEnabled(newState, userId, callingPackage); 13935 // pkgSetting.pkg.mSetEnabled = newState; 13936 } else { 13937 // We're dealing with a component level state change 13938 // First, verify that this is a valid class name. 13939 PackageParser.Package pkg = pkgSetting.pkg; 13940 if (pkg == null || !pkg.hasComponentClassName(className)) { 13941 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13942 throw new IllegalArgumentException("Component class " + className 13943 + " does not exist in " + packageName); 13944 } else { 13945 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13946 + className + " does not exist in " + packageName); 13947 } 13948 } 13949 switch (newState) { 13950 case COMPONENT_ENABLED_STATE_ENABLED: 13951 if (!pkgSetting.enableComponentLPw(className, userId)) { 13952 return; 13953 } 13954 break; 13955 case COMPONENT_ENABLED_STATE_DISABLED: 13956 if (!pkgSetting.disableComponentLPw(className, userId)) { 13957 return; 13958 } 13959 break; 13960 case COMPONENT_ENABLED_STATE_DEFAULT: 13961 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13962 return; 13963 } 13964 break; 13965 default: 13966 Slog.e(TAG, "Invalid new component state: " + newState); 13967 return; 13968 } 13969 } 13970 scheduleWritePackageRestrictionsLocked(userId); 13971 components = mPendingBroadcasts.get(userId, packageName); 13972 final boolean newPackage = components == null; 13973 if (newPackage) { 13974 components = new ArrayList<String>(); 13975 } 13976 if (!components.contains(componentName)) { 13977 components.add(componentName); 13978 } 13979 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13980 sendNow = true; 13981 // Purge entry from pending broadcast list if another one exists already 13982 // since we are sending one right away. 13983 mPendingBroadcasts.remove(userId, packageName); 13984 } else { 13985 if (newPackage) { 13986 mPendingBroadcasts.put(userId, packageName, components); 13987 } 13988 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13989 // Schedule a message 13990 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13991 } 13992 } 13993 } 13994 13995 long callingId = Binder.clearCallingIdentity(); 13996 try { 13997 if (sendNow) { 13998 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13999 sendPackageChangedBroadcast(packageName, 14000 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14001 } 14002 } finally { 14003 Binder.restoreCallingIdentity(callingId); 14004 } 14005 } 14006 14007 private void sendPackageChangedBroadcast(String packageName, 14008 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14009 if (DEBUG_INSTALL) 14010 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14011 + componentNames); 14012 Bundle extras = new Bundle(4); 14013 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14014 String nameList[] = new String[componentNames.size()]; 14015 componentNames.toArray(nameList); 14016 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14017 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14018 extras.putInt(Intent.EXTRA_UID, packageUid); 14019 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14020 new int[] {UserHandle.getUserId(packageUid)}); 14021 } 14022 14023 @Override 14024 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14025 if (!sUserManager.exists(userId)) return; 14026 final int uid = Binder.getCallingUid(); 14027 final int permission = mContext.checkCallingOrSelfPermission( 14028 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14029 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14030 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14031 // writer 14032 synchronized (mPackages) { 14033 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14034 allowedByPermission, uid, userId)) { 14035 scheduleWritePackageRestrictionsLocked(userId); 14036 } 14037 } 14038 } 14039 14040 @Override 14041 public String getInstallerPackageName(String packageName) { 14042 // reader 14043 synchronized (mPackages) { 14044 return mSettings.getInstallerPackageNameLPr(packageName); 14045 } 14046 } 14047 14048 @Override 14049 public int getApplicationEnabledSetting(String packageName, int userId) { 14050 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14051 int uid = Binder.getCallingUid(); 14052 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14053 // reader 14054 synchronized (mPackages) { 14055 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14056 } 14057 } 14058 14059 @Override 14060 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14061 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14062 int uid = Binder.getCallingUid(); 14063 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14064 // reader 14065 synchronized (mPackages) { 14066 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14067 } 14068 } 14069 14070 @Override 14071 public void enterSafeMode() { 14072 enforceSystemOrRoot("Only the system can request entering safe mode"); 14073 14074 if (!mSystemReady) { 14075 mSafeMode = true; 14076 } 14077 } 14078 14079 @Override 14080 public void systemReady() { 14081 mSystemReady = true; 14082 14083 // Read the compatibilty setting when the system is ready. 14084 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14085 mContext.getContentResolver(), 14086 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14087 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14088 if (DEBUG_SETTINGS) { 14089 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14090 } 14091 14092 synchronized (mPackages) { 14093 // Verify that all of the preferred activity components actually 14094 // exist. It is possible for applications to be updated and at 14095 // that point remove a previously declared activity component that 14096 // had been set as a preferred activity. We try to clean this up 14097 // the next time we encounter that preferred activity, but it is 14098 // possible for the user flow to never be able to return to that 14099 // situation so here we do a sanity check to make sure we haven't 14100 // left any junk around. 14101 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14102 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14103 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14104 removed.clear(); 14105 for (PreferredActivity pa : pir.filterSet()) { 14106 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14107 removed.add(pa); 14108 } 14109 } 14110 if (removed.size() > 0) { 14111 for (int r=0; r<removed.size(); r++) { 14112 PreferredActivity pa = removed.get(r); 14113 Slog.w(TAG, "Removing dangling preferred activity: " 14114 + pa.mPref.mComponent); 14115 pir.removeFilter(pa); 14116 } 14117 mSettings.writePackageRestrictionsLPr( 14118 mSettings.mPreferredActivities.keyAt(i)); 14119 } 14120 } 14121 } 14122 sUserManager.systemReady(); 14123 14124 // If we upgraded grant all default permissions before kicking off. 14125 if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) { 14126 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14127 for (int userId : UserManagerService.getInstance().getUserIds()) { 14128 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14129 } 14130 } 14131 14132 // Kick off any messages waiting for system ready 14133 if (mPostSystemReadyMessages != null) { 14134 for (Message msg : mPostSystemReadyMessages) { 14135 msg.sendToTarget(); 14136 } 14137 mPostSystemReadyMessages = null; 14138 } 14139 14140 // Watch for external volumes that come and go over time 14141 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14142 storage.registerListener(mStorageListener); 14143 14144 mInstallerService.systemReady(); 14145 mPackageDexOptimizer.systemReady(); 14146 } 14147 14148 @Override 14149 public boolean isSafeMode() { 14150 return mSafeMode; 14151 } 14152 14153 @Override 14154 public boolean hasSystemUidErrors() { 14155 return mHasSystemUidErrors; 14156 } 14157 14158 static String arrayToString(int[] array) { 14159 StringBuffer buf = new StringBuffer(128); 14160 buf.append('['); 14161 if (array != null) { 14162 for (int i=0; i<array.length; i++) { 14163 if (i > 0) buf.append(", "); 14164 buf.append(array[i]); 14165 } 14166 } 14167 buf.append(']'); 14168 return buf.toString(); 14169 } 14170 14171 static class DumpState { 14172 public static final int DUMP_LIBS = 1 << 0; 14173 public static final int DUMP_FEATURES = 1 << 1; 14174 public static final int DUMP_RESOLVERS = 1 << 2; 14175 public static final int DUMP_PERMISSIONS = 1 << 3; 14176 public static final int DUMP_PACKAGES = 1 << 4; 14177 public static final int DUMP_SHARED_USERS = 1 << 5; 14178 public static final int DUMP_MESSAGES = 1 << 6; 14179 public static final int DUMP_PROVIDERS = 1 << 7; 14180 public static final int DUMP_VERIFIERS = 1 << 8; 14181 public static final int DUMP_PREFERRED = 1 << 9; 14182 public static final int DUMP_PREFERRED_XML = 1 << 10; 14183 public static final int DUMP_KEYSETS = 1 << 11; 14184 public static final int DUMP_VERSION = 1 << 12; 14185 public static final int DUMP_INSTALLS = 1 << 13; 14186 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14187 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14188 14189 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14190 14191 private int mTypes; 14192 14193 private int mOptions; 14194 14195 private boolean mTitlePrinted; 14196 14197 private SharedUserSetting mSharedUser; 14198 14199 public boolean isDumping(int type) { 14200 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14201 return true; 14202 } 14203 14204 return (mTypes & type) != 0; 14205 } 14206 14207 public void setDump(int type) { 14208 mTypes |= type; 14209 } 14210 14211 public boolean isOptionEnabled(int option) { 14212 return (mOptions & option) != 0; 14213 } 14214 14215 public void setOptionEnabled(int option) { 14216 mOptions |= option; 14217 } 14218 14219 public boolean onTitlePrinted() { 14220 final boolean printed = mTitlePrinted; 14221 mTitlePrinted = true; 14222 return printed; 14223 } 14224 14225 public boolean getTitlePrinted() { 14226 return mTitlePrinted; 14227 } 14228 14229 public void setTitlePrinted(boolean enabled) { 14230 mTitlePrinted = enabled; 14231 } 14232 14233 public SharedUserSetting getSharedUser() { 14234 return mSharedUser; 14235 } 14236 14237 public void setSharedUser(SharedUserSetting user) { 14238 mSharedUser = user; 14239 } 14240 } 14241 14242 @Override 14243 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14244 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14245 != PackageManager.PERMISSION_GRANTED) { 14246 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14247 + Binder.getCallingPid() 14248 + ", uid=" + Binder.getCallingUid() 14249 + " without permission " 14250 + android.Manifest.permission.DUMP); 14251 return; 14252 } 14253 14254 DumpState dumpState = new DumpState(); 14255 boolean fullPreferred = false; 14256 boolean checkin = false; 14257 14258 String packageName = null; 14259 14260 int opti = 0; 14261 while (opti < args.length) { 14262 String opt = args[opti]; 14263 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14264 break; 14265 } 14266 opti++; 14267 14268 if ("-a".equals(opt)) { 14269 // Right now we only know how to print all. 14270 } else if ("-h".equals(opt)) { 14271 pw.println("Package manager dump options:"); 14272 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14273 pw.println(" --checkin: dump for a checkin"); 14274 pw.println(" -f: print details of intent filters"); 14275 pw.println(" -h: print this help"); 14276 pw.println(" cmd may be one of:"); 14277 pw.println(" l[ibraries]: list known shared libraries"); 14278 pw.println(" f[ibraries]: list device features"); 14279 pw.println(" k[eysets]: print known keysets"); 14280 pw.println(" r[esolvers]: dump intent resolvers"); 14281 pw.println(" perm[issions]: dump permissions"); 14282 pw.println(" pref[erred]: print preferred package settings"); 14283 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14284 pw.println(" prov[iders]: dump content providers"); 14285 pw.println(" p[ackages]: dump installed packages"); 14286 pw.println(" s[hared-users]: dump shared user IDs"); 14287 pw.println(" m[essages]: print collected runtime messages"); 14288 pw.println(" v[erifiers]: print package verifier info"); 14289 pw.println(" version: print database version info"); 14290 pw.println(" write: write current settings now"); 14291 pw.println(" <package.name>: info about given package"); 14292 pw.println(" installs: details about install sessions"); 14293 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14294 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14295 return; 14296 } else if ("--checkin".equals(opt)) { 14297 checkin = true; 14298 } else if ("-f".equals(opt)) { 14299 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14300 } else { 14301 pw.println("Unknown argument: " + opt + "; use -h for help"); 14302 } 14303 } 14304 14305 // Is the caller requesting to dump a particular piece of data? 14306 if (opti < args.length) { 14307 String cmd = args[opti]; 14308 opti++; 14309 // Is this a package name? 14310 if ("android".equals(cmd) || cmd.contains(".")) { 14311 packageName = cmd; 14312 // When dumping a single package, we always dump all of its 14313 // filter information since the amount of data will be reasonable. 14314 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14315 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14316 dumpState.setDump(DumpState.DUMP_LIBS); 14317 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14318 dumpState.setDump(DumpState.DUMP_FEATURES); 14319 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14320 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14321 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14322 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14323 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14324 dumpState.setDump(DumpState.DUMP_PREFERRED); 14325 } else if ("preferred-xml".equals(cmd)) { 14326 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14327 if (opti < args.length && "--full".equals(args[opti])) { 14328 fullPreferred = true; 14329 opti++; 14330 } 14331 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14332 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14333 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14334 dumpState.setDump(DumpState.DUMP_PACKAGES); 14335 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14336 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14337 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14338 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14339 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14340 dumpState.setDump(DumpState.DUMP_MESSAGES); 14341 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14342 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14343 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14344 || "intent-filter-verifiers".equals(cmd)) { 14345 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14346 } else if ("version".equals(cmd)) { 14347 dumpState.setDump(DumpState.DUMP_VERSION); 14348 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14349 dumpState.setDump(DumpState.DUMP_KEYSETS); 14350 } else if ("installs".equals(cmd)) { 14351 dumpState.setDump(DumpState.DUMP_INSTALLS); 14352 } else if ("write".equals(cmd)) { 14353 synchronized (mPackages) { 14354 mSettings.writeLPr(); 14355 pw.println("Settings written."); 14356 return; 14357 } 14358 } 14359 } 14360 14361 if (checkin) { 14362 pw.println("vers,1"); 14363 } 14364 14365 // reader 14366 synchronized (mPackages) { 14367 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14368 if (!checkin) { 14369 if (dumpState.onTitlePrinted()) 14370 pw.println(); 14371 pw.println("Database versions:"); 14372 pw.print(" SDK Version:"); 14373 pw.print(" internal="); 14374 pw.print(mSettings.mInternalSdkPlatform); 14375 pw.print(" external="); 14376 pw.println(mSettings.mExternalSdkPlatform); 14377 pw.print(" DB Version:"); 14378 pw.print(" internal="); 14379 pw.print(mSettings.mInternalDatabaseVersion); 14380 pw.print(" external="); 14381 pw.println(mSettings.mExternalDatabaseVersion); 14382 } 14383 } 14384 14385 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14386 if (!checkin) { 14387 if (dumpState.onTitlePrinted()) 14388 pw.println(); 14389 pw.println("Verifiers:"); 14390 pw.print(" Required: "); 14391 pw.print(mRequiredVerifierPackage); 14392 pw.print(" (uid="); 14393 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14394 pw.println(")"); 14395 } else if (mRequiredVerifierPackage != null) { 14396 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14397 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14398 } 14399 } 14400 14401 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14402 packageName == null) { 14403 if (mIntentFilterVerifierComponent != null) { 14404 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14405 if (!checkin) { 14406 if (dumpState.onTitlePrinted()) 14407 pw.println(); 14408 pw.println("Intent Filter Verifier:"); 14409 pw.print(" Using: "); 14410 pw.print(verifierPackageName); 14411 pw.print(" (uid="); 14412 pw.print(getPackageUid(verifierPackageName, 0)); 14413 pw.println(")"); 14414 } else if (verifierPackageName != null) { 14415 pw.print("ifv,"); pw.print(verifierPackageName); 14416 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14417 } 14418 } else { 14419 pw.println(); 14420 pw.println("No Intent Filter Verifier available!"); 14421 } 14422 } 14423 14424 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14425 boolean printedHeader = false; 14426 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14427 while (it.hasNext()) { 14428 String name = it.next(); 14429 SharedLibraryEntry ent = mSharedLibraries.get(name); 14430 if (!checkin) { 14431 if (!printedHeader) { 14432 if (dumpState.onTitlePrinted()) 14433 pw.println(); 14434 pw.println("Libraries:"); 14435 printedHeader = true; 14436 } 14437 pw.print(" "); 14438 } else { 14439 pw.print("lib,"); 14440 } 14441 pw.print(name); 14442 if (!checkin) { 14443 pw.print(" -> "); 14444 } 14445 if (ent.path != null) { 14446 if (!checkin) { 14447 pw.print("(jar) "); 14448 pw.print(ent.path); 14449 } else { 14450 pw.print(",jar,"); 14451 pw.print(ent.path); 14452 } 14453 } else { 14454 if (!checkin) { 14455 pw.print("(apk) "); 14456 pw.print(ent.apk); 14457 } else { 14458 pw.print(",apk,"); 14459 pw.print(ent.apk); 14460 } 14461 } 14462 pw.println(); 14463 } 14464 } 14465 14466 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14467 if (dumpState.onTitlePrinted()) 14468 pw.println(); 14469 if (!checkin) { 14470 pw.println("Features:"); 14471 } 14472 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14473 while (it.hasNext()) { 14474 String name = it.next(); 14475 if (!checkin) { 14476 pw.print(" "); 14477 } else { 14478 pw.print("feat,"); 14479 } 14480 pw.println(name); 14481 } 14482 } 14483 14484 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14485 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14486 : "Activity Resolver Table:", " ", packageName, 14487 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14488 dumpState.setTitlePrinted(true); 14489 } 14490 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14491 : "Receiver Resolver Table:", " ", packageName, 14492 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14493 dumpState.setTitlePrinted(true); 14494 } 14495 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14496 : "Service Resolver Table:", " ", packageName, 14497 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14498 dumpState.setTitlePrinted(true); 14499 } 14500 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14501 : "Provider Resolver Table:", " ", packageName, 14502 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14503 dumpState.setTitlePrinted(true); 14504 } 14505 } 14506 14507 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14508 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14509 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14510 int user = mSettings.mPreferredActivities.keyAt(i); 14511 if (pir.dump(pw, 14512 dumpState.getTitlePrinted() 14513 ? "\nPreferred Activities User " + user + ":" 14514 : "Preferred Activities User " + user + ":", " ", 14515 packageName, true, false)) { 14516 dumpState.setTitlePrinted(true); 14517 } 14518 } 14519 } 14520 14521 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14522 pw.flush(); 14523 FileOutputStream fout = new FileOutputStream(fd); 14524 BufferedOutputStream str = new BufferedOutputStream(fout); 14525 XmlSerializer serializer = new FastXmlSerializer(); 14526 try { 14527 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14528 serializer.startDocument(null, true); 14529 serializer.setFeature( 14530 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14531 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14532 serializer.endDocument(); 14533 serializer.flush(); 14534 } catch (IllegalArgumentException e) { 14535 pw.println("Failed writing: " + e); 14536 } catch (IllegalStateException e) { 14537 pw.println("Failed writing: " + e); 14538 } catch (IOException e) { 14539 pw.println("Failed writing: " + e); 14540 } 14541 } 14542 14543 if (!checkin 14544 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14545 && packageName == null) { 14546 pw.println(); 14547 int count = mSettings.mPackages.size(); 14548 if (count == 0) { 14549 pw.println("No domain preferred apps!"); 14550 pw.println(); 14551 } else { 14552 final String prefix = " "; 14553 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14554 if (allPackageSettings.size() == 0) { 14555 pw.println("No domain preferred apps!"); 14556 pw.println(); 14557 } else { 14558 pw.println("Domain preferred apps status:"); 14559 pw.println(); 14560 count = 0; 14561 for (PackageSetting ps : allPackageSettings) { 14562 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14563 if (ivi == null || ivi.getPackageName() == null) continue; 14564 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14565 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14566 pw.println(prefix + "Status: " + ivi.getStatusString()); 14567 pw.println(); 14568 count++; 14569 } 14570 if (count == 0) { 14571 pw.println(prefix + "No domain preferred app status!"); 14572 pw.println(); 14573 } 14574 for (int userId : sUserManager.getUserIds()) { 14575 pw.println("Domain preferred apps for User " + userId + ":"); 14576 pw.println(); 14577 count = 0; 14578 for (PackageSetting ps : allPackageSettings) { 14579 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14580 if (ivi == null || ivi.getPackageName() == null) { 14581 continue; 14582 } 14583 final int status = ps.getDomainVerificationStatusForUser(userId); 14584 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14585 continue; 14586 } 14587 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14588 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14589 String statusStr = IntentFilterVerificationInfo. 14590 getStatusStringFromValue(status); 14591 pw.println(prefix + "Status: " + statusStr); 14592 pw.println(); 14593 count++; 14594 } 14595 if (count == 0) { 14596 pw.println(prefix + "No domain preferred apps!"); 14597 pw.println(); 14598 } 14599 } 14600 } 14601 } 14602 } 14603 14604 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14605 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14606 if (packageName == null) { 14607 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14608 if (iperm == 0) { 14609 if (dumpState.onTitlePrinted()) 14610 pw.println(); 14611 pw.println("AppOp Permissions:"); 14612 } 14613 pw.print(" AppOp Permission "); 14614 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14615 pw.println(":"); 14616 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14617 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14618 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14619 } 14620 } 14621 } 14622 } 14623 14624 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14625 boolean printedSomething = false; 14626 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14627 if (packageName != null && !packageName.equals(p.info.packageName)) { 14628 continue; 14629 } 14630 if (!printedSomething) { 14631 if (dumpState.onTitlePrinted()) 14632 pw.println(); 14633 pw.println("Registered ContentProviders:"); 14634 printedSomething = true; 14635 } 14636 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14637 pw.print(" "); pw.println(p.toString()); 14638 } 14639 printedSomething = false; 14640 for (Map.Entry<String, PackageParser.Provider> entry : 14641 mProvidersByAuthority.entrySet()) { 14642 PackageParser.Provider p = entry.getValue(); 14643 if (packageName != null && !packageName.equals(p.info.packageName)) { 14644 continue; 14645 } 14646 if (!printedSomething) { 14647 if (dumpState.onTitlePrinted()) 14648 pw.println(); 14649 pw.println("ContentProvider Authorities:"); 14650 printedSomething = true; 14651 } 14652 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14653 pw.print(" "); pw.println(p.toString()); 14654 if (p.info != null && p.info.applicationInfo != null) { 14655 final String appInfo = p.info.applicationInfo.toString(); 14656 pw.print(" applicationInfo="); pw.println(appInfo); 14657 } 14658 } 14659 } 14660 14661 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14662 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14663 } 14664 14665 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14666 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14667 } 14668 14669 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14670 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14671 } 14672 14673 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14674 // XXX should handle packageName != null by dumping only install data that 14675 // the given package is involved with. 14676 if (dumpState.onTitlePrinted()) pw.println(); 14677 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14678 } 14679 14680 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14681 if (dumpState.onTitlePrinted()) pw.println(); 14682 mSettings.dumpReadMessagesLPr(pw, dumpState); 14683 14684 pw.println(); 14685 pw.println("Package warning messages:"); 14686 BufferedReader in = null; 14687 String line = null; 14688 try { 14689 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14690 while ((line = in.readLine()) != null) { 14691 if (line.contains("ignored: updated version")) continue; 14692 pw.println(line); 14693 } 14694 } catch (IOException ignored) { 14695 } finally { 14696 IoUtils.closeQuietly(in); 14697 } 14698 } 14699 14700 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14701 BufferedReader in = null; 14702 String line = null; 14703 try { 14704 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14705 while ((line = in.readLine()) != null) { 14706 if (line.contains("ignored: updated version")) continue; 14707 pw.print("msg,"); 14708 pw.println(line); 14709 } 14710 } catch (IOException ignored) { 14711 } finally { 14712 IoUtils.closeQuietly(in); 14713 } 14714 } 14715 } 14716 } 14717 14718 // ------- apps on sdcard specific code ------- 14719 static final boolean DEBUG_SD_INSTALL = false; 14720 14721 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14722 14723 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14724 14725 private boolean mMediaMounted = false; 14726 14727 static String getEncryptKey() { 14728 try { 14729 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14730 SD_ENCRYPTION_KEYSTORE_NAME); 14731 if (sdEncKey == null) { 14732 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14733 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14734 if (sdEncKey == null) { 14735 Slog.e(TAG, "Failed to create encryption keys"); 14736 return null; 14737 } 14738 } 14739 return sdEncKey; 14740 } catch (NoSuchAlgorithmException nsae) { 14741 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14742 return null; 14743 } catch (IOException ioe) { 14744 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14745 return null; 14746 } 14747 } 14748 14749 /* 14750 * Update media status on PackageManager. 14751 */ 14752 @Override 14753 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14754 int callingUid = Binder.getCallingUid(); 14755 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14756 throw new SecurityException("Media status can only be updated by the system"); 14757 } 14758 // reader; this apparently protects mMediaMounted, but should probably 14759 // be a different lock in that case. 14760 synchronized (mPackages) { 14761 Log.i(TAG, "Updating external media status from " 14762 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14763 + (mediaStatus ? "mounted" : "unmounted")); 14764 if (DEBUG_SD_INSTALL) 14765 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14766 + ", mMediaMounted=" + mMediaMounted); 14767 if (mediaStatus == mMediaMounted) { 14768 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14769 : 0, -1); 14770 mHandler.sendMessage(msg); 14771 return; 14772 } 14773 mMediaMounted = mediaStatus; 14774 } 14775 // Queue up an async operation since the package installation may take a 14776 // little while. 14777 mHandler.post(new Runnable() { 14778 public void run() { 14779 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14780 } 14781 }); 14782 } 14783 14784 /** 14785 * Called by MountService when the initial ASECs to scan are available. 14786 * Should block until all the ASEC containers are finished being scanned. 14787 */ 14788 public void scanAvailableAsecs() { 14789 updateExternalMediaStatusInner(true, false, false); 14790 if (mShouldRestoreconData) { 14791 SELinuxMMAC.setRestoreconDone(); 14792 mShouldRestoreconData = false; 14793 } 14794 } 14795 14796 /* 14797 * Collect information of applications on external media, map them against 14798 * existing containers and update information based on current mount status. 14799 * Please note that we always have to report status if reportStatus has been 14800 * set to true especially when unloading packages. 14801 */ 14802 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14803 boolean externalStorage) { 14804 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14805 int[] uidArr = EmptyArray.INT; 14806 14807 final String[] list = PackageHelper.getSecureContainerList(); 14808 if (ArrayUtils.isEmpty(list)) { 14809 Log.i(TAG, "No secure containers found"); 14810 } else { 14811 // Process list of secure containers and categorize them 14812 // as active or stale based on their package internal state. 14813 14814 // reader 14815 synchronized (mPackages) { 14816 for (String cid : list) { 14817 // Leave stages untouched for now; installer service owns them 14818 if (PackageInstallerService.isStageName(cid)) continue; 14819 14820 if (DEBUG_SD_INSTALL) 14821 Log.i(TAG, "Processing container " + cid); 14822 String pkgName = getAsecPackageName(cid); 14823 if (pkgName == null) { 14824 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14825 continue; 14826 } 14827 if (DEBUG_SD_INSTALL) 14828 Log.i(TAG, "Looking for pkg : " + pkgName); 14829 14830 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14831 if (ps == null) { 14832 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14833 continue; 14834 } 14835 14836 /* 14837 * Skip packages that are not external if we're unmounting 14838 * external storage. 14839 */ 14840 if (externalStorage && !isMounted && !isExternal(ps)) { 14841 continue; 14842 } 14843 14844 final AsecInstallArgs args = new AsecInstallArgs(cid, 14845 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14846 // The package status is changed only if the code path 14847 // matches between settings and the container id. 14848 if (ps.codePathString != null 14849 && ps.codePathString.startsWith(args.getCodePath())) { 14850 if (DEBUG_SD_INSTALL) { 14851 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14852 + " at code path: " + ps.codePathString); 14853 } 14854 14855 // We do have a valid package installed on sdcard 14856 processCids.put(args, ps.codePathString); 14857 final int uid = ps.appId; 14858 if (uid != -1) { 14859 uidArr = ArrayUtils.appendInt(uidArr, uid); 14860 } 14861 } else { 14862 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14863 + ps.codePathString); 14864 } 14865 } 14866 } 14867 14868 Arrays.sort(uidArr); 14869 } 14870 14871 // Process packages with valid entries. 14872 if (isMounted) { 14873 if (DEBUG_SD_INSTALL) 14874 Log.i(TAG, "Loading packages"); 14875 loadMediaPackages(processCids, uidArr); 14876 startCleaningPackages(); 14877 mInstallerService.onSecureContainersAvailable(); 14878 } else { 14879 if (DEBUG_SD_INSTALL) 14880 Log.i(TAG, "Unloading packages"); 14881 unloadMediaPackages(processCids, uidArr, reportStatus); 14882 } 14883 } 14884 14885 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14886 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14887 final int size = infos.size(); 14888 final String[] packageNames = new String[size]; 14889 final int[] packageUids = new int[size]; 14890 for (int i = 0; i < size; i++) { 14891 final ApplicationInfo info = infos.get(i); 14892 packageNames[i] = info.packageName; 14893 packageUids[i] = info.uid; 14894 } 14895 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14896 finishedReceiver); 14897 } 14898 14899 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14900 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14901 sendResourcesChangedBroadcast(mediaStatus, replacing, 14902 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14903 } 14904 14905 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14906 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14907 int size = pkgList.length; 14908 if (size > 0) { 14909 // Send broadcasts here 14910 Bundle extras = new Bundle(); 14911 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14912 if (uidArr != null) { 14913 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14914 } 14915 if (replacing) { 14916 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14917 } 14918 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14919 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14920 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14921 } 14922 } 14923 14924 /* 14925 * Look at potentially valid container ids from processCids If package 14926 * information doesn't match the one on record or package scanning fails, 14927 * the cid is added to list of removeCids. We currently don't delete stale 14928 * containers. 14929 */ 14930 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14931 ArrayList<String> pkgList = new ArrayList<String>(); 14932 Set<AsecInstallArgs> keys = processCids.keySet(); 14933 14934 for (AsecInstallArgs args : keys) { 14935 String codePath = processCids.get(args); 14936 if (DEBUG_SD_INSTALL) 14937 Log.i(TAG, "Loading container : " + args.cid); 14938 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14939 try { 14940 // Make sure there are no container errors first. 14941 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14942 Slog.e(TAG, "Failed to mount cid : " + args.cid 14943 + " when installing from sdcard"); 14944 continue; 14945 } 14946 // Check code path here. 14947 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14948 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14949 + " does not match one in settings " + codePath); 14950 continue; 14951 } 14952 // Parse package 14953 int parseFlags = mDefParseFlags; 14954 if (args.isExternalAsec()) { 14955 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14956 } 14957 if (args.isFwdLocked()) { 14958 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14959 } 14960 14961 synchronized (mInstallLock) { 14962 PackageParser.Package pkg = null; 14963 try { 14964 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14965 } catch (PackageManagerException e) { 14966 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14967 } 14968 // Scan the package 14969 if (pkg != null) { 14970 /* 14971 * TODO why is the lock being held? doPostInstall is 14972 * called in other places without the lock. This needs 14973 * to be straightened out. 14974 */ 14975 // writer 14976 synchronized (mPackages) { 14977 retCode = PackageManager.INSTALL_SUCCEEDED; 14978 pkgList.add(pkg.packageName); 14979 // Post process args 14980 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14981 pkg.applicationInfo.uid); 14982 } 14983 } else { 14984 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14985 } 14986 } 14987 14988 } finally { 14989 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14990 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14991 } 14992 } 14993 } 14994 // writer 14995 synchronized (mPackages) { 14996 // If the platform SDK has changed since the last time we booted, 14997 // we need to re-grant app permission to catch any new ones that 14998 // appear. This is really a hack, and means that apps can in some 14999 // cases get permissions that the user didn't initially explicitly 15000 // allow... it would be nice to have some better way to handle 15001 // this situation. 15002 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15003 if (regrantPermissions) 15004 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15005 + mSdkVersion + "; regranting permissions for external storage"); 15006 mSettings.mExternalSdkPlatform = mSdkVersion; 15007 15008 // Make sure group IDs have been assigned, and any permission 15009 // changes in other apps are accounted for 15010 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15011 | (regrantPermissions 15012 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15013 : 0)); 15014 15015 mSettings.updateExternalDatabaseVersion(); 15016 15017 // can downgrade to reader 15018 // Persist settings 15019 mSettings.writeLPr(); 15020 } 15021 // Send a broadcast to let everyone know we are done processing 15022 if (pkgList.size() > 0) { 15023 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15024 } 15025 } 15026 15027 /* 15028 * Utility method to unload a list of specified containers 15029 */ 15030 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15031 // Just unmount all valid containers. 15032 for (AsecInstallArgs arg : cidArgs) { 15033 synchronized (mInstallLock) { 15034 arg.doPostDeleteLI(false); 15035 } 15036 } 15037 } 15038 15039 /* 15040 * Unload packages mounted on external media. This involves deleting package 15041 * data from internal structures, sending broadcasts about diabled packages, 15042 * gc'ing to free up references, unmounting all secure containers 15043 * corresponding to packages on external media, and posting a 15044 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15045 * that we always have to post this message if status has been requested no 15046 * matter what. 15047 */ 15048 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15049 final boolean reportStatus) { 15050 if (DEBUG_SD_INSTALL) 15051 Log.i(TAG, "unloading media packages"); 15052 ArrayList<String> pkgList = new ArrayList<String>(); 15053 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15054 final Set<AsecInstallArgs> keys = processCids.keySet(); 15055 for (AsecInstallArgs args : keys) { 15056 String pkgName = args.getPackageName(); 15057 if (DEBUG_SD_INSTALL) 15058 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15059 // Delete package internally 15060 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15061 synchronized (mInstallLock) { 15062 boolean res = deletePackageLI(pkgName, null, false, null, null, 15063 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15064 if (res) { 15065 pkgList.add(pkgName); 15066 } else { 15067 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15068 failedList.add(args); 15069 } 15070 } 15071 } 15072 15073 // reader 15074 synchronized (mPackages) { 15075 // We didn't update the settings after removing each package; 15076 // write them now for all packages. 15077 mSettings.writeLPr(); 15078 } 15079 15080 // We have to absolutely send UPDATED_MEDIA_STATUS only 15081 // after confirming that all the receivers processed the ordered 15082 // broadcast when packages get disabled, force a gc to clean things up. 15083 // and unload all the containers. 15084 if (pkgList.size() > 0) { 15085 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15086 new IIntentReceiver.Stub() { 15087 public void performReceive(Intent intent, int resultCode, String data, 15088 Bundle extras, boolean ordered, boolean sticky, 15089 int sendingUser) throws RemoteException { 15090 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15091 reportStatus ? 1 : 0, 1, keys); 15092 mHandler.sendMessage(msg); 15093 } 15094 }); 15095 } else { 15096 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15097 keys); 15098 mHandler.sendMessage(msg); 15099 } 15100 } 15101 15102 private void loadPrivatePackages(VolumeInfo vol) { 15103 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15104 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15105 synchronized (mInstallLock) { 15106 synchronized (mPackages) { 15107 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15108 for (PackageSetting ps : packages) { 15109 final PackageParser.Package pkg; 15110 try { 15111 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15112 loaded.add(pkg.applicationInfo); 15113 } catch (PackageManagerException e) { 15114 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15115 } 15116 } 15117 15118 // TODO: regrant any permissions that changed based since original install 15119 15120 mSettings.writeLPr(); 15121 } 15122 } 15123 15124 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15125 sendResourcesChangedBroadcast(true, false, loaded, null); 15126 } 15127 15128 private void unloadPrivatePackages(VolumeInfo vol) { 15129 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15130 synchronized (mInstallLock) { 15131 synchronized (mPackages) { 15132 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15133 for (PackageSetting ps : packages) { 15134 if (ps.pkg == null) continue; 15135 15136 final ApplicationInfo info = ps.pkg.applicationInfo; 15137 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15138 if (deletePackageLI(ps.name, null, false, null, null, 15139 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15140 unloaded.add(info); 15141 } else { 15142 Slog.w(TAG, "Failed to unload " + ps.codePath); 15143 } 15144 } 15145 15146 mSettings.writeLPr(); 15147 } 15148 } 15149 15150 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15151 sendResourcesChangedBroadcast(false, false, unloaded, null); 15152 } 15153 15154 private void unfreezePackage(String packageName) { 15155 synchronized (mPackages) { 15156 final PackageSetting ps = mSettings.mPackages.get(packageName); 15157 if (ps != null) { 15158 ps.frozen = false; 15159 } 15160 } 15161 } 15162 15163 @Override 15164 public int movePackage(final String packageName, final String volumeUuid) { 15165 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15166 15167 final int moveId = mNextMoveId.getAndIncrement(); 15168 try { 15169 movePackageInternal(packageName, volumeUuid, moveId); 15170 } catch (PackageManagerException e) { 15171 Slog.w(TAG, "Failed to move " + packageName, e); 15172 mMoveCallbacks.notifyStatusChanged(moveId, 15173 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15174 } 15175 return moveId; 15176 } 15177 15178 private void movePackageInternal(final String packageName, final String volumeUuid, 15179 final int moveId) throws PackageManagerException { 15180 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15181 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15182 final PackageManager pm = mContext.getPackageManager(); 15183 15184 final boolean currentAsec; 15185 final String currentVolumeUuid; 15186 final File codeFile; 15187 final String installerPackageName; 15188 final String packageAbiOverride; 15189 final int appId; 15190 final String seinfo; 15191 final String label; 15192 15193 // reader 15194 synchronized (mPackages) { 15195 final PackageParser.Package pkg = mPackages.get(packageName); 15196 final PackageSetting ps = mSettings.mPackages.get(packageName); 15197 if (pkg == null || ps == null) { 15198 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15199 } 15200 15201 if (pkg.applicationInfo.isSystemApp()) { 15202 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15203 "Cannot move system application"); 15204 } 15205 15206 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15207 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15208 "Package already moved to " + volumeUuid); 15209 } 15210 15211 final File probe = new File(pkg.codePath); 15212 final File probeOat = new File(probe, "oat"); 15213 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15214 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15215 "Move only supported for modern cluster style installs"); 15216 } 15217 15218 if (ps.frozen) { 15219 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15220 "Failed to move already frozen package"); 15221 } 15222 ps.frozen = true; 15223 15224 currentAsec = pkg.applicationInfo.isForwardLocked() 15225 || pkg.applicationInfo.isExternalAsec(); 15226 currentVolumeUuid = ps.volumeUuid; 15227 codeFile = new File(pkg.codePath); 15228 installerPackageName = ps.installerPackageName; 15229 packageAbiOverride = ps.cpuAbiOverrideString; 15230 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15231 seinfo = pkg.applicationInfo.seinfo; 15232 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15233 } 15234 15235 // Now that we're guarded by frozen state, kill app during move 15236 killApplication(packageName, appId, "move pkg"); 15237 15238 final Bundle extras = new Bundle(); 15239 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15240 extras.putString(Intent.EXTRA_TITLE, label); 15241 mMoveCallbacks.notifyCreated(moveId, extras); 15242 15243 int installFlags; 15244 final boolean moveCompleteApp; 15245 final File measurePath; 15246 15247 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15248 installFlags = INSTALL_INTERNAL; 15249 moveCompleteApp = !currentAsec; 15250 measurePath = Environment.getDataAppDirectory(volumeUuid); 15251 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15252 installFlags = INSTALL_EXTERNAL; 15253 moveCompleteApp = false; 15254 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15255 } else { 15256 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15257 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15258 || !volume.isMountedWritable()) { 15259 unfreezePackage(packageName); 15260 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15261 "Move location not mounted private volume"); 15262 } 15263 15264 Preconditions.checkState(!currentAsec); 15265 15266 installFlags = INSTALL_INTERNAL; 15267 moveCompleteApp = true; 15268 measurePath = Environment.getDataAppDirectory(volumeUuid); 15269 } 15270 15271 final PackageStats stats = new PackageStats(null, -1); 15272 synchronized (mInstaller) { 15273 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15274 unfreezePackage(packageName); 15275 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15276 "Failed to measure package size"); 15277 } 15278 } 15279 15280 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15281 + stats.dataSize); 15282 15283 final long startFreeBytes = measurePath.getFreeSpace(); 15284 final long sizeBytes; 15285 if (moveCompleteApp) { 15286 sizeBytes = stats.codeSize + stats.dataSize; 15287 } else { 15288 sizeBytes = stats.codeSize; 15289 } 15290 15291 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15292 unfreezePackage(packageName); 15293 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15294 "Not enough free space to move"); 15295 } 15296 15297 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15298 15299 final CountDownLatch installedLatch = new CountDownLatch(1); 15300 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15301 @Override 15302 public void onUserActionRequired(Intent intent) throws RemoteException { 15303 throw new IllegalStateException(); 15304 } 15305 15306 @Override 15307 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15308 Bundle extras) throws RemoteException { 15309 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15310 + PackageManager.installStatusToString(returnCode, msg)); 15311 15312 installedLatch.countDown(); 15313 15314 // Regardless of success or failure of the move operation, 15315 // always unfreeze the package 15316 unfreezePackage(packageName); 15317 15318 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15319 switch (status) { 15320 case PackageInstaller.STATUS_SUCCESS: 15321 mMoveCallbacks.notifyStatusChanged(moveId, 15322 PackageManager.MOVE_SUCCEEDED); 15323 break; 15324 case PackageInstaller.STATUS_FAILURE_STORAGE: 15325 mMoveCallbacks.notifyStatusChanged(moveId, 15326 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15327 break; 15328 default: 15329 mMoveCallbacks.notifyStatusChanged(moveId, 15330 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15331 break; 15332 } 15333 } 15334 }; 15335 15336 final MoveInfo move; 15337 if (moveCompleteApp) { 15338 // Kick off a thread to report progress estimates 15339 new Thread() { 15340 @Override 15341 public void run() { 15342 while (true) { 15343 try { 15344 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15345 break; 15346 } 15347 } catch (InterruptedException ignored) { 15348 } 15349 15350 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15351 final int progress = 10 + (int) MathUtils.constrain( 15352 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15353 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15354 } 15355 } 15356 }.start(); 15357 15358 final String dataAppName = codeFile.getName(); 15359 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15360 dataAppName, appId, seinfo); 15361 } else { 15362 move = null; 15363 } 15364 15365 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15366 15367 final Message msg = mHandler.obtainMessage(INIT_COPY); 15368 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15369 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15370 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15371 mHandler.sendMessage(msg); 15372 } 15373 15374 @Override 15375 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15376 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15377 15378 final int realMoveId = mNextMoveId.getAndIncrement(); 15379 final Bundle extras = new Bundle(); 15380 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15381 mMoveCallbacks.notifyCreated(realMoveId, extras); 15382 15383 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15384 @Override 15385 public void onCreated(int moveId, Bundle extras) { 15386 // Ignored 15387 } 15388 15389 @Override 15390 public void onStatusChanged(int moveId, int status, long estMillis) { 15391 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15392 } 15393 }; 15394 15395 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15396 storage.setPrimaryStorageUuid(volumeUuid, callback); 15397 return realMoveId; 15398 } 15399 15400 @Override 15401 public int getMoveStatus(int moveId) { 15402 mContext.enforceCallingOrSelfPermission( 15403 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15404 return mMoveCallbacks.mLastStatus.get(moveId); 15405 } 15406 15407 @Override 15408 public void registerMoveCallback(IPackageMoveObserver callback) { 15409 mContext.enforceCallingOrSelfPermission( 15410 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15411 mMoveCallbacks.register(callback); 15412 } 15413 15414 @Override 15415 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15416 mContext.enforceCallingOrSelfPermission( 15417 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15418 mMoveCallbacks.unregister(callback); 15419 } 15420 15421 @Override 15422 public boolean setInstallLocation(int loc) { 15423 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15424 null); 15425 if (getInstallLocation() == loc) { 15426 return true; 15427 } 15428 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15429 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15430 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15431 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15432 return true; 15433 } 15434 return false; 15435 } 15436 15437 @Override 15438 public int getInstallLocation() { 15439 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15440 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15441 PackageHelper.APP_INSTALL_AUTO); 15442 } 15443 15444 /** Called by UserManagerService */ 15445 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15446 mDirtyUsers.remove(userHandle); 15447 mSettings.removeUserLPw(userHandle); 15448 mPendingBroadcasts.remove(userHandle); 15449 if (mInstaller != null) { 15450 // Technically, we shouldn't be doing this with the package lock 15451 // held. However, this is very rare, and there is already so much 15452 // other disk I/O going on, that we'll let it slide for now. 15453 final StorageManager storage = StorageManager.from(mContext); 15454 final List<VolumeInfo> vols = storage.getVolumes(); 15455 for (VolumeInfo vol : vols) { 15456 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15457 final String volumeUuid = vol.getFsUuid(); 15458 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15459 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15460 } 15461 } 15462 } 15463 mUserNeedsBadging.delete(userHandle); 15464 removeUnusedPackagesLILPw(userManager, userHandle); 15465 } 15466 15467 /** 15468 * We're removing userHandle and would like to remove any downloaded packages 15469 * that are no longer in use by any other user. 15470 * @param userHandle the user being removed 15471 */ 15472 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15473 final boolean DEBUG_CLEAN_APKS = false; 15474 int [] users = userManager.getUserIdsLPr(); 15475 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15476 while (psit.hasNext()) { 15477 PackageSetting ps = psit.next(); 15478 if (ps.pkg == null) { 15479 continue; 15480 } 15481 final String packageName = ps.pkg.packageName; 15482 // Skip over if system app 15483 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15484 continue; 15485 } 15486 if (DEBUG_CLEAN_APKS) { 15487 Slog.i(TAG, "Checking package " + packageName); 15488 } 15489 boolean keep = false; 15490 for (int i = 0; i < users.length; i++) { 15491 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15492 keep = true; 15493 if (DEBUG_CLEAN_APKS) { 15494 Slog.i(TAG, " Keeping package " + packageName + " for user " 15495 + users[i]); 15496 } 15497 break; 15498 } 15499 } 15500 if (!keep) { 15501 if (DEBUG_CLEAN_APKS) { 15502 Slog.i(TAG, " Removing package " + packageName); 15503 } 15504 mHandler.post(new Runnable() { 15505 public void run() { 15506 deletePackageX(packageName, userHandle, 0); 15507 } //end run 15508 }); 15509 } 15510 } 15511 } 15512 15513 /** Called by UserManagerService */ 15514 void createNewUserLILPw(int userHandle, File path) { 15515 if (mInstaller != null) { 15516 mInstaller.createUserConfig(userHandle); 15517 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15518 applyFactoryDefaultBrowserLPw(userHandle); 15519 } 15520 } 15521 15522 void newUserCreatedLILPw(final int userHandle) { 15523 // We cannot grant the default permissions with a lock held as 15524 // we query providers from other components for default handlers 15525 // such as enabled IMEs, etc. 15526 mHandler.post(new Runnable() { 15527 @Override 15528 public void run() { 15529 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15530 } 15531 }); 15532 } 15533 15534 @Override 15535 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15536 mContext.enforceCallingOrSelfPermission( 15537 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15538 "Only package verification agents can read the verifier device identity"); 15539 15540 synchronized (mPackages) { 15541 return mSettings.getVerifierDeviceIdentityLPw(); 15542 } 15543 } 15544 15545 @Override 15546 public void setPermissionEnforced(String permission, boolean enforced) { 15547 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15548 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15549 synchronized (mPackages) { 15550 if (mSettings.mReadExternalStorageEnforced == null 15551 || mSettings.mReadExternalStorageEnforced != enforced) { 15552 mSettings.mReadExternalStorageEnforced = enforced; 15553 mSettings.writeLPr(); 15554 } 15555 } 15556 // kill any non-foreground processes so we restart them and 15557 // grant/revoke the GID. 15558 final IActivityManager am = ActivityManagerNative.getDefault(); 15559 if (am != null) { 15560 final long token = Binder.clearCallingIdentity(); 15561 try { 15562 am.killProcessesBelowForeground("setPermissionEnforcement"); 15563 } catch (RemoteException e) { 15564 } finally { 15565 Binder.restoreCallingIdentity(token); 15566 } 15567 } 15568 } else { 15569 throw new IllegalArgumentException("No selective enforcement for " + permission); 15570 } 15571 } 15572 15573 @Override 15574 @Deprecated 15575 public boolean isPermissionEnforced(String permission) { 15576 return true; 15577 } 15578 15579 @Override 15580 public boolean isStorageLow() { 15581 final long token = Binder.clearCallingIdentity(); 15582 try { 15583 final DeviceStorageMonitorInternal 15584 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15585 if (dsm != null) { 15586 return dsm.isMemoryLow(); 15587 } else { 15588 return false; 15589 } 15590 } finally { 15591 Binder.restoreCallingIdentity(token); 15592 } 15593 } 15594 15595 @Override 15596 public IPackageInstaller getPackageInstaller() { 15597 return mInstallerService; 15598 } 15599 15600 private boolean userNeedsBadging(int userId) { 15601 int index = mUserNeedsBadging.indexOfKey(userId); 15602 if (index < 0) { 15603 final UserInfo userInfo; 15604 final long token = Binder.clearCallingIdentity(); 15605 try { 15606 userInfo = sUserManager.getUserInfo(userId); 15607 } finally { 15608 Binder.restoreCallingIdentity(token); 15609 } 15610 final boolean b; 15611 if (userInfo != null && userInfo.isManagedProfile()) { 15612 b = true; 15613 } else { 15614 b = false; 15615 } 15616 mUserNeedsBadging.put(userId, b); 15617 return b; 15618 } 15619 return mUserNeedsBadging.valueAt(index); 15620 } 15621 15622 @Override 15623 public KeySet getKeySetByAlias(String packageName, String alias) { 15624 if (packageName == null || alias == null) { 15625 return null; 15626 } 15627 synchronized(mPackages) { 15628 final PackageParser.Package pkg = mPackages.get(packageName); 15629 if (pkg == null) { 15630 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15631 throw new IllegalArgumentException("Unknown package: " + packageName); 15632 } 15633 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15634 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15635 } 15636 } 15637 15638 @Override 15639 public KeySet getSigningKeySet(String packageName) { 15640 if (packageName == null) { 15641 return null; 15642 } 15643 synchronized(mPackages) { 15644 final PackageParser.Package pkg = mPackages.get(packageName); 15645 if (pkg == null) { 15646 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15647 throw new IllegalArgumentException("Unknown package: " + packageName); 15648 } 15649 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15650 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15651 throw new SecurityException("May not access signing KeySet of other apps."); 15652 } 15653 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15654 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15655 } 15656 } 15657 15658 @Override 15659 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15660 if (packageName == null || ks == null) { 15661 return false; 15662 } 15663 synchronized(mPackages) { 15664 final PackageParser.Package pkg = mPackages.get(packageName); 15665 if (pkg == null) { 15666 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15667 throw new IllegalArgumentException("Unknown package: " + packageName); 15668 } 15669 IBinder ksh = ks.getToken(); 15670 if (ksh instanceof KeySetHandle) { 15671 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15672 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15673 } 15674 return false; 15675 } 15676 } 15677 15678 @Override 15679 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15680 if (packageName == null || ks == null) { 15681 return false; 15682 } 15683 synchronized(mPackages) { 15684 final PackageParser.Package pkg = mPackages.get(packageName); 15685 if (pkg == null) { 15686 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15687 throw new IllegalArgumentException("Unknown package: " + packageName); 15688 } 15689 IBinder ksh = ks.getToken(); 15690 if (ksh instanceof KeySetHandle) { 15691 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15692 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15693 } 15694 return false; 15695 } 15696 } 15697 15698 public void getUsageStatsIfNoPackageUsageInfo() { 15699 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15700 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15701 if (usm == null) { 15702 throw new IllegalStateException("UsageStatsManager must be initialized"); 15703 } 15704 long now = System.currentTimeMillis(); 15705 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15706 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15707 String packageName = entry.getKey(); 15708 PackageParser.Package pkg = mPackages.get(packageName); 15709 if (pkg == null) { 15710 continue; 15711 } 15712 UsageStats usage = entry.getValue(); 15713 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15714 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15715 } 15716 } 15717 } 15718 15719 /** 15720 * Check and throw if the given before/after packages would be considered a 15721 * downgrade. 15722 */ 15723 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15724 throws PackageManagerException { 15725 if (after.versionCode < before.mVersionCode) { 15726 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15727 "Update version code " + after.versionCode + " is older than current " 15728 + before.mVersionCode); 15729 } else if (after.versionCode == before.mVersionCode) { 15730 if (after.baseRevisionCode < before.baseRevisionCode) { 15731 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15732 "Update base revision code " + after.baseRevisionCode 15733 + " is older than current " + before.baseRevisionCode); 15734 } 15735 15736 if (!ArrayUtils.isEmpty(after.splitNames)) { 15737 for (int i = 0; i < after.splitNames.length; i++) { 15738 final String splitName = after.splitNames[i]; 15739 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15740 if (j != -1) { 15741 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15742 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15743 "Update split " + splitName + " revision code " 15744 + after.splitRevisionCodes[i] + " is older than current " 15745 + before.splitRevisionCodes[j]); 15746 } 15747 } 15748 } 15749 } 15750 } 15751 } 15752 15753 private static class MoveCallbacks extends Handler { 15754 private static final int MSG_CREATED = 1; 15755 private static final int MSG_STATUS_CHANGED = 2; 15756 15757 private final RemoteCallbackList<IPackageMoveObserver> 15758 mCallbacks = new RemoteCallbackList<>(); 15759 15760 private final SparseIntArray mLastStatus = new SparseIntArray(); 15761 15762 public MoveCallbacks(Looper looper) { 15763 super(looper); 15764 } 15765 15766 public void register(IPackageMoveObserver callback) { 15767 mCallbacks.register(callback); 15768 } 15769 15770 public void unregister(IPackageMoveObserver callback) { 15771 mCallbacks.unregister(callback); 15772 } 15773 15774 @Override 15775 public void handleMessage(Message msg) { 15776 final SomeArgs args = (SomeArgs) msg.obj; 15777 final int n = mCallbacks.beginBroadcast(); 15778 for (int i = 0; i < n; i++) { 15779 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15780 try { 15781 invokeCallback(callback, msg.what, args); 15782 } catch (RemoteException ignored) { 15783 } 15784 } 15785 mCallbacks.finishBroadcast(); 15786 args.recycle(); 15787 } 15788 15789 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15790 throws RemoteException { 15791 switch (what) { 15792 case MSG_CREATED: { 15793 callback.onCreated(args.argi1, (Bundle) args.arg2); 15794 break; 15795 } 15796 case MSG_STATUS_CHANGED: { 15797 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15798 break; 15799 } 15800 } 15801 } 15802 15803 private void notifyCreated(int moveId, Bundle extras) { 15804 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15805 15806 final SomeArgs args = SomeArgs.obtain(); 15807 args.argi1 = moveId; 15808 args.arg2 = extras; 15809 obtainMessage(MSG_CREATED, args).sendToTarget(); 15810 } 15811 15812 private void notifyStatusChanged(int moveId, int status) { 15813 notifyStatusChanged(moveId, status, -1); 15814 } 15815 15816 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15817 Slog.v(TAG, "Move " + moveId + " status " + status); 15818 15819 final SomeArgs args = SomeArgs.obtain(); 15820 args.argi1 = moveId; 15821 args.argi2 = status; 15822 args.arg3 = estMillis; 15823 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15824 15825 synchronized (mLastStatus) { 15826 mLastStatus.put(moveId, status); 15827 } 15828 } 15829 } 15830 15831 private final class OnPermissionChangeListeners extends Handler { 15832 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15833 15834 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15835 new RemoteCallbackList<>(); 15836 15837 public OnPermissionChangeListeners(Looper looper) { 15838 super(looper); 15839 } 15840 15841 @Override 15842 public void handleMessage(Message msg) { 15843 switch (msg.what) { 15844 case MSG_ON_PERMISSIONS_CHANGED: { 15845 final int uid = msg.arg1; 15846 handleOnPermissionsChanged(uid); 15847 } break; 15848 } 15849 } 15850 15851 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15852 mPermissionListeners.register(listener); 15853 15854 } 15855 15856 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15857 mPermissionListeners.unregister(listener); 15858 } 15859 15860 public void onPermissionsChanged(int uid) { 15861 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15862 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15863 } 15864 } 15865 15866 private void handleOnPermissionsChanged(int uid) { 15867 final int count = mPermissionListeners.beginBroadcast(); 15868 try { 15869 for (int i = 0; i < count; i++) { 15870 IOnPermissionsChangeListener callback = mPermissionListeners 15871 .getBroadcastItem(i); 15872 try { 15873 callback.onPermissionsChanged(uid); 15874 } catch (RemoteException e) { 15875 Log.e(TAG, "Permission listener is dead", e); 15876 } 15877 } 15878 } finally { 15879 mPermissionListeners.finishBroadcast(); 15880 } 15881 } 15882 } 15883 15884 private class PackageManagerInternalImpl extends PackageManagerInternal { 15885 @Override 15886 public void setLocationPackagesProvider(PackagesProvider provider) { 15887 synchronized (mPackages) { 15888 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15889 } 15890 } 15891 15892 @Override 15893 public void setImePackagesProvider(PackagesProvider provider) { 15894 synchronized (mPackages) { 15895 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15896 } 15897 } 15898 15899 @Override 15900 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15901 synchronized (mPackages) { 15902 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15903 } 15904 } 15905 } 15906 15907 @Override 15908 public void grantDefaultPermissions(final int userId) { 15909 enforceSystemOrPhoneCaller("grantDefaultPermissions"); 15910 long token = Binder.clearCallingIdentity(); 15911 try { 15912 // We cannot grant the default permissions with a lock held as 15913 // we query providers from other components for default handlers 15914 // such as enabled IMEs, etc. 15915 mHandler.post(new Runnable() { 15916 @Override 15917 public void run() { 15918 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15919 } 15920 }); 15921 } finally { 15922 Binder.restoreCallingIdentity(token); 15923 } 15924 } 15925 15926 @Override 15927 public void setCarrierAppPackagesProvider(final IPackagesProvider provider) { 15928 enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider"); 15929 long token = Binder.clearCallingIdentity(); 15930 try { 15931 PackageManagerInternal.PackagesProvider wrapper = 15932 new PackageManagerInternal.PackagesProvider() { 15933 @Override 15934 public String[] getPackages(int userId) { 15935 try { 15936 return provider.getPackages(userId); 15937 } catch (RemoteException e) { 15938 return null; 15939 } 15940 } 15941 }; 15942 synchronized (mPackages) { 15943 mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper); 15944 } 15945 } finally { 15946 Binder.restoreCallingIdentity(token); 15947 } 15948 } 15949 15950 private static void enforceSystemOrPhoneCaller(String tag) { 15951 int callingUid = Binder.getCallingUid(); 15952 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 15953 throw new SecurityException( 15954 "Cannot call " + tag + " from UID " + callingUid); 15955 } 15956 } 15957} 15958