PackageManagerService.java revision ca8e6da41c6e63e3ed17eb461171f1ef2e1d29c6
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.readDefaultPreferredAppsLPw(this, 0); 2195 } 2196 2197 // If this is first boot after an OTA, and a normal boot, then 2198 // we need to clear code cache directories. 2199 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2200 if (mIsUpgrade && !onlyCore) { 2201 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2202 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2203 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2204 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2205 } 2206 mSettings.mFingerprint = Build.FINGERPRINT; 2207 } 2208 2209 primeDomainVerificationsLPw(); 2210 checkDefaultBrowser(); 2211 2212 // All the changes are done during package scanning. 2213 mSettings.updateInternalDatabaseVersion(); 2214 2215 // can downgrade to reader 2216 mSettings.writeLPr(); 2217 2218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2219 SystemClock.uptimeMillis()); 2220 2221 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2222 2223 mInstallerService = new PackageInstallerService(context, this); 2224 2225 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2226 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2227 mIntentFilterVerifierComponent); 2228 2229 } // synchronized (mPackages) 2230 } // synchronized (mInstallLock) 2231 2232 // Now after opening every single application zip, make sure they 2233 // are all flushed. Not really needed, but keeps things nice and 2234 // tidy. 2235 Runtime.getRuntime().gc(); 2236 2237 // Expose private service for system components to use. 2238 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2239 } 2240 2241 @Override 2242 public boolean isFirstBoot() { 2243 return !mRestoredSettings; 2244 } 2245 2246 @Override 2247 public boolean isOnlyCoreApps() { 2248 return mOnlyCore; 2249 } 2250 2251 @Override 2252 public boolean isUpgrade() { 2253 return mIsUpgrade; 2254 } 2255 2256 private String getRequiredVerifierLPr() { 2257 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2258 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2259 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2260 2261 String requiredVerifier = null; 2262 2263 final int N = receivers.size(); 2264 for (int i = 0; i < N; i++) { 2265 final ResolveInfo info = receivers.get(i); 2266 2267 if (info.activityInfo == null) { 2268 continue; 2269 } 2270 2271 final String packageName = info.activityInfo.packageName; 2272 2273 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2274 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2275 continue; 2276 } 2277 2278 if (requiredVerifier != null) { 2279 throw new RuntimeException("There can be only one required verifier"); 2280 } 2281 2282 requiredVerifier = packageName; 2283 } 2284 2285 return requiredVerifier; 2286 } 2287 2288 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2289 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2290 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2291 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2292 2293 ComponentName verifierComponentName = null; 2294 2295 int priority = -1000; 2296 final int N = receivers.size(); 2297 for (int i = 0; i < N; i++) { 2298 final ResolveInfo info = receivers.get(i); 2299 2300 if (info.activityInfo == null) { 2301 continue; 2302 } 2303 2304 final String packageName = info.activityInfo.packageName; 2305 2306 final PackageSetting ps = mSettings.mPackages.get(packageName); 2307 if (ps == null) { 2308 continue; 2309 } 2310 2311 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2312 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2313 continue; 2314 } 2315 2316 // Select the IntentFilterVerifier with the highest priority 2317 if (priority < info.priority) { 2318 priority = info.priority; 2319 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2320 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2321 + verifierComponentName + " with priority: " + info.priority); 2322 } 2323 } 2324 2325 return verifierComponentName; 2326 } 2327 2328 private void primeDomainVerificationsLPw() { 2329 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2330 boolean updated = false; 2331 ArraySet<String> allHostsSet = new ArraySet<>(); 2332 for (PackageParser.Package pkg : mPackages.values()) { 2333 final String packageName = pkg.packageName; 2334 if (!hasDomainURLs(pkg)) { 2335 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2336 "package with no domain URLs: " + packageName); 2337 continue; 2338 } 2339 if (!pkg.isSystemApp()) { 2340 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2341 "No priming domain verifications for a non system package : " + 2342 packageName); 2343 continue; 2344 } 2345 for (PackageParser.Activity a : pkg.activities) { 2346 for (ActivityIntentInfo filter : a.intents) { 2347 if (hasValidDomains(filter)) { 2348 allHostsSet.addAll(filter.getHostsList()); 2349 } 2350 } 2351 } 2352 if (allHostsSet.size() == 0) { 2353 allHostsSet.add("*"); 2354 } 2355 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2356 IntentFilterVerificationInfo ivi = 2357 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2358 if (ivi != null) { 2359 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2360 "Priming domain verifications for package: " + packageName + 2361 " with hosts:" + ivi.getDomainsString()); 2362 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2363 updated = true; 2364 } 2365 else { 2366 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2367 "No priming domain verifications for package: " + packageName); 2368 } 2369 allHostsSet.clear(); 2370 } 2371 if (updated) { 2372 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2373 "Will need to write primed domain verifications"); 2374 } 2375 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2376 } 2377 2378 private void checkDefaultBrowser() { 2379 final int myUserId = UserHandle.myUserId(); 2380 final String packageName = getDefaultBrowserPackageName(myUserId); 2381 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2382 if (info == null) { 2383 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2384 setDefaultBrowserPackageName(null, myUserId); 2385 } 2386 } 2387 2388 @Override 2389 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2390 throws RemoteException { 2391 try { 2392 return super.onTransact(code, data, reply, flags); 2393 } catch (RuntimeException e) { 2394 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2395 Slog.wtf(TAG, "Package Manager Crash", e); 2396 } 2397 throw e; 2398 } 2399 } 2400 2401 void cleanupInstallFailedPackage(PackageSetting ps) { 2402 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2403 2404 removeDataDirsLI(ps.volumeUuid, ps.name); 2405 if (ps.codePath != null) { 2406 if (ps.codePath.isDirectory()) { 2407 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2408 } else { 2409 ps.codePath.delete(); 2410 } 2411 } 2412 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2413 if (ps.resourcePath.isDirectory()) { 2414 FileUtils.deleteContents(ps.resourcePath); 2415 } 2416 ps.resourcePath.delete(); 2417 } 2418 mSettings.removePackageLPw(ps.name); 2419 } 2420 2421 static int[] appendInts(int[] cur, int[] add) { 2422 if (add == null) return cur; 2423 if (cur == null) return add; 2424 final int N = add.length; 2425 for (int i=0; i<N; i++) { 2426 cur = appendInt(cur, add[i]); 2427 } 2428 return cur; 2429 } 2430 2431 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2432 if (!sUserManager.exists(userId)) return null; 2433 final PackageSetting ps = (PackageSetting) p.mExtras; 2434 if (ps == null) { 2435 return null; 2436 } 2437 2438 final PermissionsState permissionsState = ps.getPermissionsState(); 2439 2440 final int[] gids = permissionsState.computeGids(userId); 2441 final Set<String> permissions = permissionsState.getPermissions(userId); 2442 final PackageUserState state = ps.readUserState(userId); 2443 2444 return PackageParser.generatePackageInfo(p, gids, flags, 2445 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2446 } 2447 2448 @Override 2449 public boolean isPackageFrozen(String packageName) { 2450 synchronized (mPackages) { 2451 final PackageSetting ps = mSettings.mPackages.get(packageName); 2452 if (ps != null) { 2453 return ps.frozen; 2454 } 2455 } 2456 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2457 return true; 2458 } 2459 2460 @Override 2461 public boolean isPackageAvailable(String packageName, int userId) { 2462 if (!sUserManager.exists(userId)) return false; 2463 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2464 synchronized (mPackages) { 2465 PackageParser.Package p = mPackages.get(packageName); 2466 if (p != null) { 2467 final PackageSetting ps = (PackageSetting) p.mExtras; 2468 if (ps != null) { 2469 final PackageUserState state = ps.readUserState(userId); 2470 if (state != null) { 2471 return PackageParser.isAvailable(state); 2472 } 2473 } 2474 } 2475 } 2476 return false; 2477 } 2478 2479 @Override 2480 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2481 if (!sUserManager.exists(userId)) return null; 2482 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2483 // reader 2484 synchronized (mPackages) { 2485 PackageParser.Package p = mPackages.get(packageName); 2486 if (DEBUG_PACKAGE_INFO) 2487 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2488 if (p != null) { 2489 return generatePackageInfo(p, flags, userId); 2490 } 2491 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2492 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2493 } 2494 } 2495 return null; 2496 } 2497 2498 @Override 2499 public String[] currentToCanonicalPackageNames(String[] names) { 2500 String[] out = new String[names.length]; 2501 // reader 2502 synchronized (mPackages) { 2503 for (int i=names.length-1; i>=0; i--) { 2504 PackageSetting ps = mSettings.mPackages.get(names[i]); 2505 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2506 } 2507 } 2508 return out; 2509 } 2510 2511 @Override 2512 public String[] canonicalToCurrentPackageNames(String[] names) { 2513 String[] out = new String[names.length]; 2514 // reader 2515 synchronized (mPackages) { 2516 for (int i=names.length-1; i>=0; i--) { 2517 String cur = mSettings.mRenamedPackages.get(names[i]); 2518 out[i] = cur != null ? cur : names[i]; 2519 } 2520 } 2521 return out; 2522 } 2523 2524 @Override 2525 public int getPackageUid(String packageName, int userId) { 2526 if (!sUserManager.exists(userId)) return -1; 2527 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2528 2529 // reader 2530 synchronized (mPackages) { 2531 PackageParser.Package p = mPackages.get(packageName); 2532 if(p != null) { 2533 return UserHandle.getUid(userId, p.applicationInfo.uid); 2534 } 2535 PackageSetting ps = mSettings.mPackages.get(packageName); 2536 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2537 return -1; 2538 } 2539 p = ps.pkg; 2540 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2541 } 2542 } 2543 2544 @Override 2545 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2546 if (!sUserManager.exists(userId)) { 2547 return null; 2548 } 2549 2550 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2551 "getPackageGids"); 2552 2553 // reader 2554 synchronized (mPackages) { 2555 PackageParser.Package p = mPackages.get(packageName); 2556 if (DEBUG_PACKAGE_INFO) { 2557 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2558 } 2559 if (p != null) { 2560 PackageSetting ps = (PackageSetting) p.mExtras; 2561 return ps.getPermissionsState().computeGids(userId); 2562 } 2563 } 2564 2565 return null; 2566 } 2567 2568 @Override 2569 public int getMountExternalMode(int uid) { 2570 if (Process.isIsolated(uid)) { 2571 return Zygote.MOUNT_EXTERNAL_NONE; 2572 } else { 2573 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2574 return Zygote.MOUNT_EXTERNAL_WRITE; 2575 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2576 return Zygote.MOUNT_EXTERNAL_READ; 2577 } else { 2578 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2579 } 2580 } 2581 } 2582 2583 static PermissionInfo generatePermissionInfo( 2584 BasePermission bp, int flags) { 2585 if (bp.perm != null) { 2586 return PackageParser.generatePermissionInfo(bp.perm, flags); 2587 } 2588 PermissionInfo pi = new PermissionInfo(); 2589 pi.name = bp.name; 2590 pi.packageName = bp.sourcePackage; 2591 pi.nonLocalizedLabel = bp.name; 2592 pi.protectionLevel = bp.protectionLevel; 2593 return pi; 2594 } 2595 2596 @Override 2597 public PermissionInfo getPermissionInfo(String name, int flags) { 2598 // reader 2599 synchronized (mPackages) { 2600 final BasePermission p = mSettings.mPermissions.get(name); 2601 if (p != null) { 2602 return generatePermissionInfo(p, flags); 2603 } 2604 return null; 2605 } 2606 } 2607 2608 @Override 2609 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2610 // reader 2611 synchronized (mPackages) { 2612 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2613 for (BasePermission p : mSettings.mPermissions.values()) { 2614 if (group == null) { 2615 if (p.perm == null || p.perm.info.group == null) { 2616 out.add(generatePermissionInfo(p, flags)); 2617 } 2618 } else { 2619 if (p.perm != null && group.equals(p.perm.info.group)) { 2620 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2621 } 2622 } 2623 } 2624 2625 if (out.size() > 0) { 2626 return out; 2627 } 2628 return mPermissionGroups.containsKey(group) ? out : null; 2629 } 2630 } 2631 2632 @Override 2633 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2634 // reader 2635 synchronized (mPackages) { 2636 return PackageParser.generatePermissionGroupInfo( 2637 mPermissionGroups.get(name), flags); 2638 } 2639 } 2640 2641 @Override 2642 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2643 // reader 2644 synchronized (mPackages) { 2645 final int N = mPermissionGroups.size(); 2646 ArrayList<PermissionGroupInfo> out 2647 = new ArrayList<PermissionGroupInfo>(N); 2648 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2649 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2650 } 2651 return out; 2652 } 2653 } 2654 2655 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2656 int userId) { 2657 if (!sUserManager.exists(userId)) return null; 2658 PackageSetting ps = mSettings.mPackages.get(packageName); 2659 if (ps != null) { 2660 if (ps.pkg == null) { 2661 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2662 flags, userId); 2663 if (pInfo != null) { 2664 return pInfo.applicationInfo; 2665 } 2666 return null; 2667 } 2668 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2669 ps.readUserState(userId), userId); 2670 } 2671 return null; 2672 } 2673 2674 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2675 int userId) { 2676 if (!sUserManager.exists(userId)) return null; 2677 PackageSetting ps = mSettings.mPackages.get(packageName); 2678 if (ps != null) { 2679 PackageParser.Package pkg = ps.pkg; 2680 if (pkg == null) { 2681 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2682 return null; 2683 } 2684 // Only data remains, so we aren't worried about code paths 2685 pkg = new PackageParser.Package(packageName); 2686 pkg.applicationInfo.packageName = packageName; 2687 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2688 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2689 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2690 packageName, userId).getAbsolutePath(); 2691 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2692 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2693 } 2694 return generatePackageInfo(pkg, flags, userId); 2695 } 2696 return null; 2697 } 2698 2699 @Override 2700 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2701 if (!sUserManager.exists(userId)) return null; 2702 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2703 // writer 2704 synchronized (mPackages) { 2705 PackageParser.Package p = mPackages.get(packageName); 2706 if (DEBUG_PACKAGE_INFO) Log.v( 2707 TAG, "getApplicationInfo " + packageName 2708 + ": " + p); 2709 if (p != null) { 2710 PackageSetting ps = mSettings.mPackages.get(packageName); 2711 if (ps == null) return null; 2712 // Note: isEnabledLP() does not apply here - always return info 2713 return PackageParser.generateApplicationInfo( 2714 p, flags, ps.readUserState(userId), userId); 2715 } 2716 if ("android".equals(packageName)||"system".equals(packageName)) { 2717 return mAndroidApplication; 2718 } 2719 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2720 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2721 } 2722 } 2723 return null; 2724 } 2725 2726 @Override 2727 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2728 final IPackageDataObserver observer) { 2729 mContext.enforceCallingOrSelfPermission( 2730 android.Manifest.permission.CLEAR_APP_CACHE, null); 2731 // Queue up an async operation since clearing cache may take a little while. 2732 mHandler.post(new Runnable() { 2733 public void run() { 2734 mHandler.removeCallbacks(this); 2735 int retCode = -1; 2736 synchronized (mInstallLock) { 2737 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2738 if (retCode < 0) { 2739 Slog.w(TAG, "Couldn't clear application caches"); 2740 } 2741 } 2742 if (observer != null) { 2743 try { 2744 observer.onRemoveCompleted(null, (retCode >= 0)); 2745 } catch (RemoteException e) { 2746 Slog.w(TAG, "RemoveException when invoking call back"); 2747 } 2748 } 2749 } 2750 }); 2751 } 2752 2753 @Override 2754 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2755 final IntentSender pi) { 2756 mContext.enforceCallingOrSelfPermission( 2757 android.Manifest.permission.CLEAR_APP_CACHE, null); 2758 // Queue up an async operation since clearing cache may take a little while. 2759 mHandler.post(new Runnable() { 2760 public void run() { 2761 mHandler.removeCallbacks(this); 2762 int retCode = -1; 2763 synchronized (mInstallLock) { 2764 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2765 if (retCode < 0) { 2766 Slog.w(TAG, "Couldn't clear application caches"); 2767 } 2768 } 2769 if(pi != null) { 2770 try { 2771 // Callback via pending intent 2772 int code = (retCode >= 0) ? 1 : 0; 2773 pi.sendIntent(null, code, null, 2774 null, null); 2775 } catch (SendIntentException e1) { 2776 Slog.i(TAG, "Failed to send pending intent"); 2777 } 2778 } 2779 } 2780 }); 2781 } 2782 2783 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2784 synchronized (mInstallLock) { 2785 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2786 throw new IOException("Failed to free enough space"); 2787 } 2788 } 2789 } 2790 2791 @Override 2792 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2793 if (!sUserManager.exists(userId)) return null; 2794 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2795 synchronized (mPackages) { 2796 PackageParser.Activity a = mActivities.mActivities.get(component); 2797 2798 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2799 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2800 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2801 if (ps == null) return null; 2802 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2803 userId); 2804 } 2805 if (mResolveComponentName.equals(component)) { 2806 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2807 new PackageUserState(), userId); 2808 } 2809 } 2810 return null; 2811 } 2812 2813 @Override 2814 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2815 String resolvedType) { 2816 synchronized (mPackages) { 2817 PackageParser.Activity a = mActivities.mActivities.get(component); 2818 if (a == null) { 2819 return false; 2820 } 2821 for (int i=0; i<a.intents.size(); i++) { 2822 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2823 intent.getData(), intent.getCategories(), TAG) >= 0) { 2824 return true; 2825 } 2826 } 2827 return false; 2828 } 2829 } 2830 2831 @Override 2832 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2833 if (!sUserManager.exists(userId)) return null; 2834 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2835 synchronized (mPackages) { 2836 PackageParser.Activity a = mReceivers.mActivities.get(component); 2837 if (DEBUG_PACKAGE_INFO) Log.v( 2838 TAG, "getReceiverInfo " + component + ": " + a); 2839 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2840 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2841 if (ps == null) return null; 2842 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2843 userId); 2844 } 2845 } 2846 return null; 2847 } 2848 2849 @Override 2850 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2851 if (!sUserManager.exists(userId)) return null; 2852 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2853 synchronized (mPackages) { 2854 PackageParser.Service s = mServices.mServices.get(component); 2855 if (DEBUG_PACKAGE_INFO) Log.v( 2856 TAG, "getServiceInfo " + component + ": " + s); 2857 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2858 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2859 if (ps == null) return null; 2860 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2861 userId); 2862 } 2863 } 2864 return null; 2865 } 2866 2867 @Override 2868 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2869 if (!sUserManager.exists(userId)) return null; 2870 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2871 synchronized (mPackages) { 2872 PackageParser.Provider p = mProviders.mProviders.get(component); 2873 if (DEBUG_PACKAGE_INFO) Log.v( 2874 TAG, "getProviderInfo " + component + ": " + p); 2875 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2876 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2877 if (ps == null) return null; 2878 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2879 userId); 2880 } 2881 } 2882 return null; 2883 } 2884 2885 @Override 2886 public String[] getSystemSharedLibraryNames() { 2887 Set<String> libSet; 2888 synchronized (mPackages) { 2889 libSet = mSharedLibraries.keySet(); 2890 int size = libSet.size(); 2891 if (size > 0) { 2892 String[] libs = new String[size]; 2893 libSet.toArray(libs); 2894 return libs; 2895 } 2896 } 2897 return null; 2898 } 2899 2900 /** 2901 * @hide 2902 */ 2903 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2904 synchronized (mPackages) { 2905 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2906 if (lib != null && lib.apk != null) { 2907 return mPackages.get(lib.apk); 2908 } 2909 } 2910 return null; 2911 } 2912 2913 @Override 2914 public FeatureInfo[] getSystemAvailableFeatures() { 2915 Collection<FeatureInfo> featSet; 2916 synchronized (mPackages) { 2917 featSet = mAvailableFeatures.values(); 2918 int size = featSet.size(); 2919 if (size > 0) { 2920 FeatureInfo[] features = new FeatureInfo[size+1]; 2921 featSet.toArray(features); 2922 FeatureInfo fi = new FeatureInfo(); 2923 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2924 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2925 features[size] = fi; 2926 return features; 2927 } 2928 } 2929 return null; 2930 } 2931 2932 @Override 2933 public boolean hasSystemFeature(String name) { 2934 synchronized (mPackages) { 2935 return mAvailableFeatures.containsKey(name); 2936 } 2937 } 2938 2939 private void checkValidCaller(int uid, int userId) { 2940 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2941 return; 2942 2943 throw new SecurityException("Caller uid=" + uid 2944 + " is not privileged to communicate with user=" + userId); 2945 } 2946 2947 @Override 2948 public int checkPermission(String permName, String pkgName, int userId) { 2949 if (!sUserManager.exists(userId)) { 2950 return PackageManager.PERMISSION_DENIED; 2951 } 2952 2953 synchronized (mPackages) { 2954 final PackageParser.Package p = mPackages.get(pkgName); 2955 if (p != null && p.mExtras != null) { 2956 final PackageSetting ps = (PackageSetting) p.mExtras; 2957 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2958 return PackageManager.PERMISSION_GRANTED; 2959 } 2960 } 2961 } 2962 2963 return PackageManager.PERMISSION_DENIED; 2964 } 2965 2966 @Override 2967 public int checkUidPermission(String permName, int uid) { 2968 final int userId = UserHandle.getUserId(uid); 2969 2970 if (!sUserManager.exists(userId)) { 2971 return PackageManager.PERMISSION_DENIED; 2972 } 2973 2974 synchronized (mPackages) { 2975 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2976 if (obj != null) { 2977 final SettingBase ps = (SettingBase) obj; 2978 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2979 return PackageManager.PERMISSION_GRANTED; 2980 } 2981 } else { 2982 ArraySet<String> perms = mSystemPermissions.get(uid); 2983 if (perms != null && perms.contains(permName)) { 2984 return PackageManager.PERMISSION_GRANTED; 2985 } 2986 } 2987 } 2988 2989 return PackageManager.PERMISSION_DENIED; 2990 } 2991 2992 /** 2993 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2994 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2995 * @param checkShell TODO(yamasani): 2996 * @param message the message to log on security exception 2997 */ 2998 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2999 boolean checkShell, String message) { 3000 if (userId < 0) { 3001 throw new IllegalArgumentException("Invalid userId " + userId); 3002 } 3003 if (checkShell) { 3004 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3005 } 3006 if (userId == UserHandle.getUserId(callingUid)) return; 3007 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3008 if (requireFullPermission) { 3009 mContext.enforceCallingOrSelfPermission( 3010 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3011 } else { 3012 try { 3013 mContext.enforceCallingOrSelfPermission( 3014 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3015 } catch (SecurityException se) { 3016 mContext.enforceCallingOrSelfPermission( 3017 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3018 } 3019 } 3020 } 3021 } 3022 3023 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3024 if (callingUid == Process.SHELL_UID) { 3025 if (userHandle >= 0 3026 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3027 throw new SecurityException("Shell does not have permission to access user " 3028 + userHandle); 3029 } else if (userHandle < 0) { 3030 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3031 + Debug.getCallers(3)); 3032 } 3033 } 3034 } 3035 3036 private BasePermission findPermissionTreeLP(String permName) { 3037 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3038 if (permName.startsWith(bp.name) && 3039 permName.length() > bp.name.length() && 3040 permName.charAt(bp.name.length()) == '.') { 3041 return bp; 3042 } 3043 } 3044 return null; 3045 } 3046 3047 private BasePermission checkPermissionTreeLP(String permName) { 3048 if (permName != null) { 3049 BasePermission bp = findPermissionTreeLP(permName); 3050 if (bp != null) { 3051 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3052 return bp; 3053 } 3054 throw new SecurityException("Calling uid " 3055 + Binder.getCallingUid() 3056 + " is not allowed to add to permission tree " 3057 + bp.name + " owned by uid " + bp.uid); 3058 } 3059 } 3060 throw new SecurityException("No permission tree found for " + permName); 3061 } 3062 3063 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3064 if (s1 == null) { 3065 return s2 == null; 3066 } 3067 if (s2 == null) { 3068 return false; 3069 } 3070 if (s1.getClass() != s2.getClass()) { 3071 return false; 3072 } 3073 return s1.equals(s2); 3074 } 3075 3076 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3077 if (pi1.icon != pi2.icon) return false; 3078 if (pi1.logo != pi2.logo) return false; 3079 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3080 if (!compareStrings(pi1.name, pi2.name)) return false; 3081 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3082 // We'll take care of setting this one. 3083 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3084 // These are not currently stored in settings. 3085 //if (!compareStrings(pi1.group, pi2.group)) return false; 3086 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3087 //if (pi1.labelRes != pi2.labelRes) return false; 3088 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3089 return true; 3090 } 3091 3092 int permissionInfoFootprint(PermissionInfo info) { 3093 int size = info.name.length(); 3094 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3095 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3096 return size; 3097 } 3098 3099 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3100 int size = 0; 3101 for (BasePermission perm : mSettings.mPermissions.values()) { 3102 if (perm.uid == tree.uid) { 3103 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3104 } 3105 } 3106 return size; 3107 } 3108 3109 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3110 // We calculate the max size of permissions defined by this uid and throw 3111 // if that plus the size of 'info' would exceed our stated maximum. 3112 if (tree.uid != Process.SYSTEM_UID) { 3113 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3114 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3115 throw new SecurityException("Permission tree size cap exceeded"); 3116 } 3117 } 3118 } 3119 3120 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3121 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3122 throw new SecurityException("Label must be specified in permission"); 3123 } 3124 BasePermission tree = checkPermissionTreeLP(info.name); 3125 BasePermission bp = mSettings.mPermissions.get(info.name); 3126 boolean added = bp == null; 3127 boolean changed = true; 3128 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3129 if (added) { 3130 enforcePermissionCapLocked(info, tree); 3131 bp = new BasePermission(info.name, tree.sourcePackage, 3132 BasePermission.TYPE_DYNAMIC); 3133 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3134 throw new SecurityException( 3135 "Not allowed to modify non-dynamic permission " 3136 + info.name); 3137 } else { 3138 if (bp.protectionLevel == fixedLevel 3139 && bp.perm.owner.equals(tree.perm.owner) 3140 && bp.uid == tree.uid 3141 && comparePermissionInfos(bp.perm.info, info)) { 3142 changed = false; 3143 } 3144 } 3145 bp.protectionLevel = fixedLevel; 3146 info = new PermissionInfo(info); 3147 info.protectionLevel = fixedLevel; 3148 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3149 bp.perm.info.packageName = tree.perm.info.packageName; 3150 bp.uid = tree.uid; 3151 if (added) { 3152 mSettings.mPermissions.put(info.name, bp); 3153 } 3154 if (changed) { 3155 if (!async) { 3156 mSettings.writeLPr(); 3157 } else { 3158 scheduleWriteSettingsLocked(); 3159 } 3160 } 3161 return added; 3162 } 3163 3164 @Override 3165 public boolean addPermission(PermissionInfo info) { 3166 synchronized (mPackages) { 3167 return addPermissionLocked(info, false); 3168 } 3169 } 3170 3171 @Override 3172 public boolean addPermissionAsync(PermissionInfo info) { 3173 synchronized (mPackages) { 3174 return addPermissionLocked(info, true); 3175 } 3176 } 3177 3178 @Override 3179 public void removePermission(String name) { 3180 synchronized (mPackages) { 3181 checkPermissionTreeLP(name); 3182 BasePermission bp = mSettings.mPermissions.get(name); 3183 if (bp != null) { 3184 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3185 throw new SecurityException( 3186 "Not allowed to modify non-dynamic permission " 3187 + name); 3188 } 3189 mSettings.mPermissions.remove(name); 3190 mSettings.writeLPr(); 3191 } 3192 } 3193 } 3194 3195 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3196 BasePermission bp) { 3197 int index = pkg.requestedPermissions.indexOf(bp.name); 3198 if (index == -1) { 3199 throw new SecurityException("Package " + pkg.packageName 3200 + " has not requested permission " + bp.name); 3201 } 3202 if (!bp.isRuntime()) { 3203 throw new SecurityException("Permission " + bp.name 3204 + " is not a changeable permission type"); 3205 } 3206 } 3207 3208 @Override 3209 public void grantRuntimePermission(String packageName, String name, final int userId) { 3210 if (!sUserManager.exists(userId)) { 3211 Log.e(TAG, "No such user:" + userId); 3212 return; 3213 } 3214 3215 mContext.enforceCallingOrSelfPermission( 3216 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3217 "grantRuntimePermission"); 3218 3219 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3220 "grantRuntimePermission"); 3221 3222 final int uid; 3223 final SettingBase sb; 3224 3225 synchronized (mPackages) { 3226 final PackageParser.Package pkg = mPackages.get(packageName); 3227 if (pkg == null) { 3228 throw new IllegalArgumentException("Unknown package: " + packageName); 3229 } 3230 3231 final BasePermission bp = mSettings.mPermissions.get(name); 3232 if (bp == null) { 3233 throw new IllegalArgumentException("Unknown permission: " + name); 3234 } 3235 3236 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3237 3238 uid = pkg.applicationInfo.uid; 3239 sb = (SettingBase) pkg.mExtras; 3240 if (sb == null) { 3241 throw new IllegalArgumentException("Unknown package: " + packageName); 3242 } 3243 3244 final PermissionsState permissionsState = sb.getPermissionsState(); 3245 3246 final int flags = permissionsState.getPermissionFlags(name, userId); 3247 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3248 throw new SecurityException("Cannot grant system fixed permission: " 3249 + name + " for package: " + packageName); 3250 } 3251 3252 final int result = permissionsState.grantRuntimePermission(bp, userId); 3253 switch (result) { 3254 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3255 return; 3256 } 3257 3258 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3259 mHandler.post(new Runnable() { 3260 @Override 3261 public void run() { 3262 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3263 } 3264 }); 3265 } break; 3266 } 3267 3268 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3269 3270 // Not critical if that is lost - app has to request again. 3271 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3272 } 3273 3274 if (READ_EXTERNAL_STORAGE.equals(name) 3275 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3276 final long token = Binder.clearCallingIdentity(); 3277 try { 3278 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3279 storage.remountUid(uid); 3280 } finally { 3281 Binder.restoreCallingIdentity(token); 3282 } 3283 } 3284 } 3285 3286 @Override 3287 public void revokeRuntimePermission(String packageName, String name, int userId) { 3288 if (!sUserManager.exists(userId)) { 3289 Log.e(TAG, "No such user:" + userId); 3290 return; 3291 } 3292 3293 mContext.enforceCallingOrSelfPermission( 3294 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3295 "revokeRuntimePermission"); 3296 3297 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3298 "revokeRuntimePermission"); 3299 3300 final SettingBase sb; 3301 3302 synchronized (mPackages) { 3303 final PackageParser.Package pkg = mPackages.get(packageName); 3304 if (pkg == null) { 3305 throw new IllegalArgumentException("Unknown package: " + packageName); 3306 } 3307 3308 final BasePermission bp = mSettings.mPermissions.get(name); 3309 if (bp == null) { 3310 throw new IllegalArgumentException("Unknown permission: " + name); 3311 } 3312 3313 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3314 3315 sb = (SettingBase) pkg.mExtras; 3316 if (sb == null) { 3317 throw new IllegalArgumentException("Unknown package: " + packageName); 3318 } 3319 3320 final PermissionsState permissionsState = sb.getPermissionsState(); 3321 3322 final int flags = permissionsState.getPermissionFlags(name, userId); 3323 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3324 throw new SecurityException("Cannot revoke system fixed permission: " 3325 + name + " for package: " + packageName); 3326 } 3327 3328 if (permissionsState.revokeRuntimePermission(bp, userId) == 3329 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3330 return; 3331 } 3332 3333 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3334 3335 // Critical, after this call app should never have the permission. 3336 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3337 } 3338 3339 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3340 } 3341 3342 @Override 3343 public void resetRuntimePermissions() { 3344 mContext.enforceCallingOrSelfPermission( 3345 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3346 "revokeRuntimePermission"); 3347 3348 int callingUid = Binder.getCallingUid(); 3349 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3350 mContext.enforceCallingOrSelfPermission( 3351 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3352 "resetRuntimePermissions"); 3353 } 3354 3355 synchronized (mPackages) { 3356 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3357 for (int userId : UserManagerService.getInstance().getUserIds()) { 3358 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3359 } 3360 } 3361 } 3362 3363 @Override 3364 public int getPermissionFlags(String name, String packageName, int userId) { 3365 if (!sUserManager.exists(userId)) { 3366 return 0; 3367 } 3368 3369 mContext.enforceCallingOrSelfPermission( 3370 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3371 "getPermissionFlags"); 3372 3373 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3374 "getPermissionFlags"); 3375 3376 synchronized (mPackages) { 3377 final PackageParser.Package pkg = mPackages.get(packageName); 3378 if (pkg == null) { 3379 throw new IllegalArgumentException("Unknown package: " + packageName); 3380 } 3381 3382 final BasePermission bp = mSettings.mPermissions.get(name); 3383 if (bp == null) { 3384 throw new IllegalArgumentException("Unknown permission: " + name); 3385 } 3386 3387 SettingBase sb = (SettingBase) pkg.mExtras; 3388 if (sb == null) { 3389 throw new IllegalArgumentException("Unknown package: " + packageName); 3390 } 3391 3392 PermissionsState permissionsState = sb.getPermissionsState(); 3393 return permissionsState.getPermissionFlags(name, userId); 3394 } 3395 } 3396 3397 @Override 3398 public void updatePermissionFlags(String name, String packageName, int flagMask, 3399 int flagValues, int userId) { 3400 if (!sUserManager.exists(userId)) { 3401 return; 3402 } 3403 3404 mContext.enforceCallingOrSelfPermission( 3405 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3406 "updatePermissionFlags"); 3407 3408 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3409 "updatePermissionFlags"); 3410 3411 // Only the system can change system fixed flags. 3412 if (getCallingUid() != Process.SYSTEM_UID) { 3413 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3414 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3415 } 3416 3417 synchronized (mPackages) { 3418 final PackageParser.Package pkg = mPackages.get(packageName); 3419 if (pkg == null) { 3420 throw new IllegalArgumentException("Unknown package: " + packageName); 3421 } 3422 3423 final BasePermission bp = mSettings.mPermissions.get(name); 3424 if (bp == null) { 3425 throw new IllegalArgumentException("Unknown permission: " + name); 3426 } 3427 3428 SettingBase sb = (SettingBase) pkg.mExtras; 3429 if (sb == null) { 3430 throw new IllegalArgumentException("Unknown package: " + packageName); 3431 } 3432 3433 PermissionsState permissionsState = sb.getPermissionsState(); 3434 3435 // Only the package manager can change flags for system component permissions. 3436 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3437 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3438 return; 3439 } 3440 3441 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3442 3443 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3444 // Install and runtime permissions are stored in different places, 3445 // so figure out what permission changed and persist the change. 3446 if (permissionsState.getInstallPermissionState(name) != null) { 3447 scheduleWriteSettingsLocked(); 3448 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3449 || hadState) { 3450 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3451 } 3452 } 3453 } 3454 } 3455 3456 /** 3457 * Update the permission flags for all packages and runtime permissions of a user in order 3458 * to allow device or profile owner to remove POLICY_FIXED. 3459 */ 3460 @Override 3461 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3462 if (!sUserManager.exists(userId)) { 3463 return; 3464 } 3465 3466 mContext.enforceCallingOrSelfPermission( 3467 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3468 "updatePermissionFlagsForAllApps"); 3469 3470 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3471 "updatePermissionFlagsForAllApps"); 3472 3473 // Only the system can change system fixed flags. 3474 if (getCallingUid() != Process.SYSTEM_UID) { 3475 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3476 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3477 } 3478 3479 synchronized (mPackages) { 3480 boolean changed = false; 3481 final int packageCount = mPackages.size(); 3482 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3483 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3484 SettingBase sb = (SettingBase) pkg.mExtras; 3485 if (sb == null) { 3486 continue; 3487 } 3488 PermissionsState permissionsState = sb.getPermissionsState(); 3489 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3490 userId, flagMask, flagValues); 3491 } 3492 if (changed) { 3493 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3494 } 3495 } 3496 } 3497 3498 @Override 3499 public boolean shouldShowRequestPermissionRationale(String permissionName, 3500 String packageName, int userId) { 3501 if (UserHandle.getCallingUserId() != userId) { 3502 mContext.enforceCallingPermission( 3503 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3504 "canShowRequestPermissionRationale for user " + userId); 3505 } 3506 3507 final int uid = getPackageUid(packageName, userId); 3508 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3509 return false; 3510 } 3511 3512 if (checkPermission(permissionName, packageName, userId) 3513 == PackageManager.PERMISSION_GRANTED) { 3514 return false; 3515 } 3516 3517 final int flags; 3518 3519 final long identity = Binder.clearCallingIdentity(); 3520 try { 3521 flags = getPermissionFlags(permissionName, 3522 packageName, userId); 3523 } finally { 3524 Binder.restoreCallingIdentity(identity); 3525 } 3526 3527 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3528 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3529 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3530 3531 if ((flags & fixedFlags) != 0) { 3532 return false; 3533 } 3534 3535 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3536 } 3537 3538 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3539 BasePermission bp = mSettings.mPermissions.get(permission); 3540 if (bp == null) { 3541 throw new SecurityException("Missing " + permission + " permission"); 3542 } 3543 3544 SettingBase sb = (SettingBase) pkg.mExtras; 3545 PermissionsState permissionsState = sb.getPermissionsState(); 3546 3547 if (permissionsState.grantInstallPermission(bp) != 3548 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3549 scheduleWriteSettingsLocked(); 3550 } 3551 } 3552 3553 @Override 3554 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3555 mContext.enforceCallingOrSelfPermission( 3556 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3557 "addOnPermissionsChangeListener"); 3558 3559 synchronized (mPackages) { 3560 mOnPermissionChangeListeners.addListenerLocked(listener); 3561 } 3562 } 3563 3564 @Override 3565 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3566 synchronized (mPackages) { 3567 mOnPermissionChangeListeners.removeListenerLocked(listener); 3568 } 3569 } 3570 3571 @Override 3572 public boolean isProtectedBroadcast(String actionName) { 3573 synchronized (mPackages) { 3574 return mProtectedBroadcasts.contains(actionName); 3575 } 3576 } 3577 3578 @Override 3579 public int checkSignatures(String pkg1, String pkg2) { 3580 synchronized (mPackages) { 3581 final PackageParser.Package p1 = mPackages.get(pkg1); 3582 final PackageParser.Package p2 = mPackages.get(pkg2); 3583 if (p1 == null || p1.mExtras == null 3584 || p2 == null || p2.mExtras == null) { 3585 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3586 } 3587 return compareSignatures(p1.mSignatures, p2.mSignatures); 3588 } 3589 } 3590 3591 @Override 3592 public int checkUidSignatures(int uid1, int uid2) { 3593 // Map to base uids. 3594 uid1 = UserHandle.getAppId(uid1); 3595 uid2 = UserHandle.getAppId(uid2); 3596 // reader 3597 synchronized (mPackages) { 3598 Signature[] s1; 3599 Signature[] s2; 3600 Object obj = mSettings.getUserIdLPr(uid1); 3601 if (obj != null) { 3602 if (obj instanceof SharedUserSetting) { 3603 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3604 } else if (obj instanceof PackageSetting) { 3605 s1 = ((PackageSetting)obj).signatures.mSignatures; 3606 } else { 3607 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3608 } 3609 } else { 3610 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3611 } 3612 obj = mSettings.getUserIdLPr(uid2); 3613 if (obj != null) { 3614 if (obj instanceof SharedUserSetting) { 3615 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3616 } else if (obj instanceof PackageSetting) { 3617 s2 = ((PackageSetting)obj).signatures.mSignatures; 3618 } else { 3619 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3620 } 3621 } else { 3622 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3623 } 3624 return compareSignatures(s1, s2); 3625 } 3626 } 3627 3628 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3629 final long identity = Binder.clearCallingIdentity(); 3630 try { 3631 if (sb instanceof SharedUserSetting) { 3632 SharedUserSetting sus = (SharedUserSetting) sb; 3633 final int packageCount = sus.packages.size(); 3634 for (int i = 0; i < packageCount; i++) { 3635 PackageSetting susPs = sus.packages.valueAt(i); 3636 if (userId == UserHandle.USER_ALL) { 3637 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3638 } else { 3639 final int uid = UserHandle.getUid(userId, susPs.appId); 3640 killUid(uid, reason); 3641 } 3642 } 3643 } else if (sb instanceof PackageSetting) { 3644 PackageSetting ps = (PackageSetting) sb; 3645 if (userId == UserHandle.USER_ALL) { 3646 killApplication(ps.pkg.packageName, ps.appId, reason); 3647 } else { 3648 final int uid = UserHandle.getUid(userId, ps.appId); 3649 killUid(uid, reason); 3650 } 3651 } 3652 } finally { 3653 Binder.restoreCallingIdentity(identity); 3654 } 3655 } 3656 3657 private static void killUid(int uid, String reason) { 3658 IActivityManager am = ActivityManagerNative.getDefault(); 3659 if (am != null) { 3660 try { 3661 am.killUid(uid, reason); 3662 } catch (RemoteException e) { 3663 /* ignore - same process */ 3664 } 3665 } 3666 } 3667 3668 /** 3669 * Compares two sets of signatures. Returns: 3670 * <br /> 3671 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3672 * <br /> 3673 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3674 * <br /> 3675 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3676 * <br /> 3677 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3678 * <br /> 3679 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3680 */ 3681 static int compareSignatures(Signature[] s1, Signature[] s2) { 3682 if (s1 == null) { 3683 return s2 == null 3684 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3685 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3686 } 3687 3688 if (s2 == null) { 3689 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3690 } 3691 3692 if (s1.length != s2.length) { 3693 return PackageManager.SIGNATURE_NO_MATCH; 3694 } 3695 3696 // Since both signature sets are of size 1, we can compare without HashSets. 3697 if (s1.length == 1) { 3698 return s1[0].equals(s2[0]) ? 3699 PackageManager.SIGNATURE_MATCH : 3700 PackageManager.SIGNATURE_NO_MATCH; 3701 } 3702 3703 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3704 for (Signature sig : s1) { 3705 set1.add(sig); 3706 } 3707 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3708 for (Signature sig : s2) { 3709 set2.add(sig); 3710 } 3711 // Make sure s2 contains all signatures in s1. 3712 if (set1.equals(set2)) { 3713 return PackageManager.SIGNATURE_MATCH; 3714 } 3715 return PackageManager.SIGNATURE_NO_MATCH; 3716 } 3717 3718 /** 3719 * If the database version for this type of package (internal storage or 3720 * external storage) is less than the version where package signatures 3721 * were updated, return true. 3722 */ 3723 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3724 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3725 DatabaseVersion.SIGNATURE_END_ENTITY)) 3726 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3727 DatabaseVersion.SIGNATURE_END_ENTITY)); 3728 } 3729 3730 /** 3731 * Used for backward compatibility to make sure any packages with 3732 * certificate chains get upgraded to the new style. {@code existingSigs} 3733 * will be in the old format (since they were stored on disk from before the 3734 * system upgrade) and {@code scannedSigs} will be in the newer format. 3735 */ 3736 private int compareSignaturesCompat(PackageSignatures existingSigs, 3737 PackageParser.Package scannedPkg) { 3738 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3739 return PackageManager.SIGNATURE_NO_MATCH; 3740 } 3741 3742 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3743 for (Signature sig : existingSigs.mSignatures) { 3744 existingSet.add(sig); 3745 } 3746 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3747 for (Signature sig : scannedPkg.mSignatures) { 3748 try { 3749 Signature[] chainSignatures = sig.getChainSignatures(); 3750 for (Signature chainSig : chainSignatures) { 3751 scannedCompatSet.add(chainSig); 3752 } 3753 } catch (CertificateEncodingException e) { 3754 scannedCompatSet.add(sig); 3755 } 3756 } 3757 /* 3758 * Make sure the expanded scanned set contains all signatures in the 3759 * existing one. 3760 */ 3761 if (scannedCompatSet.equals(existingSet)) { 3762 // Migrate the old signatures to the new scheme. 3763 existingSigs.assignSignatures(scannedPkg.mSignatures); 3764 // The new KeySets will be re-added later in the scanning process. 3765 synchronized (mPackages) { 3766 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3767 } 3768 return PackageManager.SIGNATURE_MATCH; 3769 } 3770 return PackageManager.SIGNATURE_NO_MATCH; 3771 } 3772 3773 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3774 if (isExternal(scannedPkg)) { 3775 return mSettings.isExternalDatabaseVersionOlderThan( 3776 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3777 } else { 3778 return mSettings.isInternalDatabaseVersionOlderThan( 3779 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3780 } 3781 } 3782 3783 private int compareSignaturesRecover(PackageSignatures existingSigs, 3784 PackageParser.Package scannedPkg) { 3785 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3786 return PackageManager.SIGNATURE_NO_MATCH; 3787 } 3788 3789 String msg = null; 3790 try { 3791 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3792 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3793 + scannedPkg.packageName); 3794 return PackageManager.SIGNATURE_MATCH; 3795 } 3796 } catch (CertificateException e) { 3797 msg = e.getMessage(); 3798 } 3799 3800 logCriticalInfo(Log.INFO, 3801 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3802 return PackageManager.SIGNATURE_NO_MATCH; 3803 } 3804 3805 @Override 3806 public String[] getPackagesForUid(int uid) { 3807 uid = UserHandle.getAppId(uid); 3808 // reader 3809 synchronized (mPackages) { 3810 Object obj = mSettings.getUserIdLPr(uid); 3811 if (obj instanceof SharedUserSetting) { 3812 final SharedUserSetting sus = (SharedUserSetting) obj; 3813 final int N = sus.packages.size(); 3814 final String[] res = new String[N]; 3815 final Iterator<PackageSetting> it = sus.packages.iterator(); 3816 int i = 0; 3817 while (it.hasNext()) { 3818 res[i++] = it.next().name; 3819 } 3820 return res; 3821 } else if (obj instanceof PackageSetting) { 3822 final PackageSetting ps = (PackageSetting) obj; 3823 return new String[] { ps.name }; 3824 } 3825 } 3826 return null; 3827 } 3828 3829 @Override 3830 public String getNameForUid(int uid) { 3831 // reader 3832 synchronized (mPackages) { 3833 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3834 if (obj instanceof SharedUserSetting) { 3835 final SharedUserSetting sus = (SharedUserSetting) obj; 3836 return sus.name + ":" + sus.userId; 3837 } else if (obj instanceof PackageSetting) { 3838 final PackageSetting ps = (PackageSetting) obj; 3839 return ps.name; 3840 } 3841 } 3842 return null; 3843 } 3844 3845 @Override 3846 public int getUidForSharedUser(String sharedUserName) { 3847 if(sharedUserName == null) { 3848 return -1; 3849 } 3850 // reader 3851 synchronized (mPackages) { 3852 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3853 if (suid == null) { 3854 return -1; 3855 } 3856 return suid.userId; 3857 } 3858 } 3859 3860 @Override 3861 public int getFlagsForUid(int uid) { 3862 synchronized (mPackages) { 3863 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3864 if (obj instanceof SharedUserSetting) { 3865 final SharedUserSetting sus = (SharedUserSetting) obj; 3866 return sus.pkgFlags; 3867 } else if (obj instanceof PackageSetting) { 3868 final PackageSetting ps = (PackageSetting) obj; 3869 return ps.pkgFlags; 3870 } 3871 } 3872 return 0; 3873 } 3874 3875 @Override 3876 public int getPrivateFlagsForUid(int uid) { 3877 synchronized (mPackages) { 3878 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3879 if (obj instanceof SharedUserSetting) { 3880 final SharedUserSetting sus = (SharedUserSetting) obj; 3881 return sus.pkgPrivateFlags; 3882 } else if (obj instanceof PackageSetting) { 3883 final PackageSetting ps = (PackageSetting) obj; 3884 return ps.pkgPrivateFlags; 3885 } 3886 } 3887 return 0; 3888 } 3889 3890 @Override 3891 public boolean isUidPrivileged(int uid) { 3892 uid = UserHandle.getAppId(uid); 3893 // reader 3894 synchronized (mPackages) { 3895 Object obj = mSettings.getUserIdLPr(uid); 3896 if (obj instanceof SharedUserSetting) { 3897 final SharedUserSetting sus = (SharedUserSetting) obj; 3898 final Iterator<PackageSetting> it = sus.packages.iterator(); 3899 while (it.hasNext()) { 3900 if (it.next().isPrivileged()) { 3901 return true; 3902 } 3903 } 3904 } else if (obj instanceof PackageSetting) { 3905 final PackageSetting ps = (PackageSetting) obj; 3906 return ps.isPrivileged(); 3907 } 3908 } 3909 return false; 3910 } 3911 3912 @Override 3913 public String[] getAppOpPermissionPackages(String permissionName) { 3914 synchronized (mPackages) { 3915 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3916 if (pkgs == null) { 3917 return null; 3918 } 3919 return pkgs.toArray(new String[pkgs.size()]); 3920 } 3921 } 3922 3923 @Override 3924 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3925 int flags, int userId) { 3926 if (!sUserManager.exists(userId)) return null; 3927 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3928 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3929 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3930 } 3931 3932 @Override 3933 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3934 IntentFilter filter, int match, ComponentName activity) { 3935 final int userId = UserHandle.getCallingUserId(); 3936 if (DEBUG_PREFERRED) { 3937 Log.v(TAG, "setLastChosenActivity intent=" + intent 3938 + " resolvedType=" + resolvedType 3939 + " flags=" + flags 3940 + " filter=" + filter 3941 + " match=" + match 3942 + " activity=" + activity); 3943 filter.dump(new PrintStreamPrinter(System.out), " "); 3944 } 3945 intent.setComponent(null); 3946 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3947 // Find any earlier preferred or last chosen entries and nuke them 3948 findPreferredActivity(intent, resolvedType, 3949 flags, query, 0, false, true, false, userId); 3950 // Add the new activity as the last chosen for this filter 3951 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3952 "Setting last chosen"); 3953 } 3954 3955 @Override 3956 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3957 final int userId = UserHandle.getCallingUserId(); 3958 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3959 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3960 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3961 false, false, false, userId); 3962 } 3963 3964 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3965 int flags, List<ResolveInfo> query, int userId) { 3966 if (query != null) { 3967 final int N = query.size(); 3968 if (N == 1) { 3969 return query.get(0); 3970 } else if (N > 1) { 3971 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3972 // If there is more than one activity with the same priority, 3973 // then let the user decide between them. 3974 ResolveInfo r0 = query.get(0); 3975 ResolveInfo r1 = query.get(1); 3976 if (DEBUG_INTENT_MATCHING || debug) { 3977 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3978 + r1.activityInfo.name + "=" + r1.priority); 3979 } 3980 // If the first activity has a higher priority, or a different 3981 // default, then it is always desireable to pick it. 3982 if (r0.priority != r1.priority 3983 || r0.preferredOrder != r1.preferredOrder 3984 || r0.isDefault != r1.isDefault) { 3985 return query.get(0); 3986 } 3987 // If we have saved a preference for a preferred activity for 3988 // this Intent, use that. 3989 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3990 flags, query, r0.priority, true, false, debug, userId); 3991 if (ri != null) { 3992 return ri; 3993 } 3994 if (userId != 0) { 3995 ri = new ResolveInfo(mResolveInfo); 3996 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3997 ri.activityInfo.applicationInfo = new ApplicationInfo( 3998 ri.activityInfo.applicationInfo); 3999 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4000 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4001 return ri; 4002 } 4003 return mResolveInfo; 4004 } 4005 } 4006 return null; 4007 } 4008 4009 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4010 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4011 final int N = query.size(); 4012 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4013 .get(userId); 4014 // Get the list of persistent preferred activities that handle the intent 4015 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4016 List<PersistentPreferredActivity> pprefs = ppir != null 4017 ? ppir.queryIntent(intent, resolvedType, 4018 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4019 : null; 4020 if (pprefs != null && pprefs.size() > 0) { 4021 final int M = pprefs.size(); 4022 for (int i=0; i<M; i++) { 4023 final PersistentPreferredActivity ppa = pprefs.get(i); 4024 if (DEBUG_PREFERRED || debug) { 4025 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4026 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4027 + "\n component=" + ppa.mComponent); 4028 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4029 } 4030 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4031 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4032 if (DEBUG_PREFERRED || debug) { 4033 Slog.v(TAG, "Found persistent preferred activity:"); 4034 if (ai != null) { 4035 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4036 } else { 4037 Slog.v(TAG, " null"); 4038 } 4039 } 4040 if (ai == null) { 4041 // This previously registered persistent preferred activity 4042 // component is no longer known. Ignore it and do NOT remove it. 4043 continue; 4044 } 4045 for (int j=0; j<N; j++) { 4046 final ResolveInfo ri = query.get(j); 4047 if (!ri.activityInfo.applicationInfo.packageName 4048 .equals(ai.applicationInfo.packageName)) { 4049 continue; 4050 } 4051 if (!ri.activityInfo.name.equals(ai.name)) { 4052 continue; 4053 } 4054 // Found a persistent preference that can handle the intent. 4055 if (DEBUG_PREFERRED || debug) { 4056 Slog.v(TAG, "Returning persistent preferred activity: " + 4057 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4058 } 4059 return ri; 4060 } 4061 } 4062 } 4063 return null; 4064 } 4065 4066 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4067 List<ResolveInfo> query, int priority, boolean always, 4068 boolean removeMatches, boolean debug, int userId) { 4069 if (!sUserManager.exists(userId)) return null; 4070 // writer 4071 synchronized (mPackages) { 4072 if (intent.getSelector() != null) { 4073 intent = intent.getSelector(); 4074 } 4075 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4076 4077 // Try to find a matching persistent preferred activity. 4078 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4079 debug, userId); 4080 4081 // If a persistent preferred activity matched, use it. 4082 if (pri != null) { 4083 return pri; 4084 } 4085 4086 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4087 // Get the list of preferred activities that handle the intent 4088 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4089 List<PreferredActivity> prefs = pir != null 4090 ? pir.queryIntent(intent, resolvedType, 4091 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4092 : null; 4093 if (prefs != null && prefs.size() > 0) { 4094 boolean changed = false; 4095 try { 4096 // First figure out how good the original match set is. 4097 // We will only allow preferred activities that came 4098 // from the same match quality. 4099 int match = 0; 4100 4101 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4102 4103 final int N = query.size(); 4104 for (int j=0; j<N; j++) { 4105 final ResolveInfo ri = query.get(j); 4106 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4107 + ": 0x" + Integer.toHexString(match)); 4108 if (ri.match > match) { 4109 match = ri.match; 4110 } 4111 } 4112 4113 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4114 + Integer.toHexString(match)); 4115 4116 match &= IntentFilter.MATCH_CATEGORY_MASK; 4117 final int M = prefs.size(); 4118 for (int i=0; i<M; i++) { 4119 final PreferredActivity pa = prefs.get(i); 4120 if (DEBUG_PREFERRED || debug) { 4121 Slog.v(TAG, "Checking PreferredActivity ds=" 4122 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4123 + "\n component=" + pa.mPref.mComponent); 4124 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4125 } 4126 if (pa.mPref.mMatch != match) { 4127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4128 + Integer.toHexString(pa.mPref.mMatch)); 4129 continue; 4130 } 4131 // If it's not an "always" type preferred activity and that's what we're 4132 // looking for, skip it. 4133 if (always && !pa.mPref.mAlways) { 4134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4135 continue; 4136 } 4137 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4138 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4139 if (DEBUG_PREFERRED || debug) { 4140 Slog.v(TAG, "Found preferred activity:"); 4141 if (ai != null) { 4142 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4143 } else { 4144 Slog.v(TAG, " null"); 4145 } 4146 } 4147 if (ai == null) { 4148 // This previously registered preferred activity 4149 // component is no longer known. Most likely an update 4150 // to the app was installed and in the new version this 4151 // component no longer exists. Clean it up by removing 4152 // it from the preferred activities list, and skip it. 4153 Slog.w(TAG, "Removing dangling preferred activity: " 4154 + pa.mPref.mComponent); 4155 pir.removeFilter(pa); 4156 changed = true; 4157 continue; 4158 } 4159 for (int j=0; j<N; j++) { 4160 final ResolveInfo ri = query.get(j); 4161 if (!ri.activityInfo.applicationInfo.packageName 4162 .equals(ai.applicationInfo.packageName)) { 4163 continue; 4164 } 4165 if (!ri.activityInfo.name.equals(ai.name)) { 4166 continue; 4167 } 4168 4169 if (removeMatches) { 4170 pir.removeFilter(pa); 4171 changed = true; 4172 if (DEBUG_PREFERRED) { 4173 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4174 } 4175 break; 4176 } 4177 4178 // Okay we found a previously set preferred or last chosen app. 4179 // If the result set is different from when this 4180 // was created, we need to clear it and re-ask the 4181 // user their preference, if we're looking for an "always" type entry. 4182 if (always && !pa.mPref.sameSet(query)) { 4183 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4184 + intent + " type " + resolvedType); 4185 if (DEBUG_PREFERRED) { 4186 Slog.v(TAG, "Removing preferred activity since set changed " 4187 + pa.mPref.mComponent); 4188 } 4189 pir.removeFilter(pa); 4190 // Re-add the filter as a "last chosen" entry (!always) 4191 PreferredActivity lastChosen = new PreferredActivity( 4192 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4193 pir.addFilter(lastChosen); 4194 changed = true; 4195 return null; 4196 } 4197 4198 // Yay! Either the set matched or we're looking for the last chosen 4199 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4200 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4201 return ri; 4202 } 4203 } 4204 } finally { 4205 if (changed) { 4206 if (DEBUG_PREFERRED) { 4207 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4208 } 4209 scheduleWritePackageRestrictionsLocked(userId); 4210 } 4211 } 4212 } 4213 } 4214 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4215 return null; 4216 } 4217 4218 /* 4219 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4220 */ 4221 @Override 4222 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4223 int targetUserId) { 4224 mContext.enforceCallingOrSelfPermission( 4225 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4226 List<CrossProfileIntentFilter> matches = 4227 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4228 if (matches != null) { 4229 int size = matches.size(); 4230 for (int i = 0; i < size; i++) { 4231 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4232 } 4233 } 4234 if (hasWebURI(intent)) { 4235 // cross-profile app linking works only towards the parent. 4236 final UserInfo parent = getProfileParent(sourceUserId); 4237 synchronized(mPackages) { 4238 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4239 parent.id) != null; 4240 } 4241 } 4242 return false; 4243 } 4244 4245 private UserInfo getProfileParent(int userId) { 4246 final long identity = Binder.clearCallingIdentity(); 4247 try { 4248 return sUserManager.getProfileParent(userId); 4249 } finally { 4250 Binder.restoreCallingIdentity(identity); 4251 } 4252 } 4253 4254 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4255 String resolvedType, int userId) { 4256 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4257 if (resolver != null) { 4258 return resolver.queryIntent(intent, resolvedType, false, userId); 4259 } 4260 return null; 4261 } 4262 4263 @Override 4264 public List<ResolveInfo> queryIntentActivities(Intent intent, 4265 String resolvedType, int flags, int userId) { 4266 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4267 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4268 ComponentName comp = intent.getComponent(); 4269 if (comp == null) { 4270 if (intent.getSelector() != null) { 4271 intent = intent.getSelector(); 4272 comp = intent.getComponent(); 4273 } 4274 } 4275 4276 if (comp != null) { 4277 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4278 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4279 if (ai != null) { 4280 final ResolveInfo ri = new ResolveInfo(); 4281 ri.activityInfo = ai; 4282 list.add(ri); 4283 } 4284 return list; 4285 } 4286 4287 // reader 4288 synchronized (mPackages) { 4289 final String pkgName = intent.getPackage(); 4290 if (pkgName == null) { 4291 List<CrossProfileIntentFilter> matchingFilters = 4292 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4293 // Check for results that need to skip the current profile. 4294 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4295 resolvedType, flags, userId); 4296 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4297 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4298 result.add(xpResolveInfo); 4299 return filterIfNotPrimaryUser(result, userId); 4300 } 4301 4302 // Check for results in the current profile. 4303 List<ResolveInfo> result = mActivities.queryIntent( 4304 intent, resolvedType, flags, userId); 4305 4306 // Check for cross profile results. 4307 xpResolveInfo = queryCrossProfileIntents( 4308 matchingFilters, intent, resolvedType, flags, userId); 4309 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4310 result.add(xpResolveInfo); 4311 Collections.sort(result, mResolvePrioritySorter); 4312 } 4313 result = filterIfNotPrimaryUser(result, userId); 4314 if (hasWebURI(intent)) { 4315 CrossProfileDomainInfo xpDomainInfo = null; 4316 final UserInfo parent = getProfileParent(userId); 4317 if (parent != null) { 4318 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4319 flags, userId, parent.id); 4320 } 4321 if (xpDomainInfo != null) { 4322 if (xpResolveInfo != null) { 4323 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4324 // in the result. 4325 result.remove(xpResolveInfo); 4326 } 4327 if (result.size() == 0) { 4328 result.add(xpDomainInfo.resolveInfo); 4329 return result; 4330 } 4331 } else if (result.size() <= 1) { 4332 return result; 4333 } 4334 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4335 xpDomainInfo); 4336 Collections.sort(result, mResolvePrioritySorter); 4337 } 4338 return result; 4339 } 4340 final PackageParser.Package pkg = mPackages.get(pkgName); 4341 if (pkg != null) { 4342 return filterIfNotPrimaryUser( 4343 mActivities.queryIntentForPackage( 4344 intent, resolvedType, flags, pkg.activities, userId), 4345 userId); 4346 } 4347 return new ArrayList<ResolveInfo>(); 4348 } 4349 } 4350 4351 private static class CrossProfileDomainInfo { 4352 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4353 ResolveInfo resolveInfo; 4354 /* Best domain verification status of the activities found in the other profile */ 4355 int bestDomainVerificationStatus; 4356 } 4357 4358 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4359 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4360 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING, 4361 sourceUserId)) { 4362 return null; 4363 } 4364 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4365 resolvedType, flags, parentUserId); 4366 4367 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4368 return null; 4369 } 4370 CrossProfileDomainInfo result = null; 4371 int size = resultTargetUser.size(); 4372 for (int i = 0; i < size; i++) { 4373 ResolveInfo riTargetUser = resultTargetUser.get(i); 4374 // Intent filter verification is only for filters that specify a host. So don't return 4375 // those that handle all web uris. 4376 if (riTargetUser.handleAllWebDataURI) { 4377 continue; 4378 } 4379 String packageName = riTargetUser.activityInfo.packageName; 4380 PackageSetting ps = mSettings.mPackages.get(packageName); 4381 if (ps == null) { 4382 continue; 4383 } 4384 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4385 if (result == null) { 4386 result = new CrossProfileDomainInfo(); 4387 result.resolveInfo = 4388 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4389 result.bestDomainVerificationStatus = status; 4390 } else { 4391 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4392 result.bestDomainVerificationStatus); 4393 } 4394 } 4395 return result; 4396 } 4397 4398 /** 4399 * Verification statuses are ordered from the worse to the best, except for 4400 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4401 */ 4402 private int bestDomainVerificationStatus(int status1, int status2) { 4403 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4404 return status2; 4405 } 4406 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4407 return status1; 4408 } 4409 return (int) MathUtils.max(status1, status2); 4410 } 4411 4412 private boolean isUserEnabled(int userId) { 4413 long callingId = Binder.clearCallingIdentity(); 4414 try { 4415 UserInfo userInfo = sUserManager.getUserInfo(userId); 4416 return userInfo != null && userInfo.isEnabled(); 4417 } finally { 4418 Binder.restoreCallingIdentity(callingId); 4419 } 4420 } 4421 4422 /** 4423 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4424 * 4425 * @return filtered list 4426 */ 4427 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4428 if (userId == UserHandle.USER_OWNER) { 4429 return resolveInfos; 4430 } 4431 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4432 ResolveInfo info = resolveInfos.get(i); 4433 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4434 resolveInfos.remove(i); 4435 } 4436 } 4437 return resolveInfos; 4438 } 4439 4440 private static boolean hasWebURI(Intent intent) { 4441 if (intent.getData() == null) { 4442 return false; 4443 } 4444 final String scheme = intent.getScheme(); 4445 if (TextUtils.isEmpty(scheme)) { 4446 return false; 4447 } 4448 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4449 } 4450 4451 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4452 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4453 if (DEBUG_PREFERRED) { 4454 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4455 candidates.size()); 4456 } 4457 4458 final int userId = UserHandle.getCallingUserId(); 4459 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4460 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4461 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4462 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4463 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4464 4465 synchronized (mPackages) { 4466 final int count = candidates.size(); 4467 // First, try to use the domain prefered App. Partition the candidates into four lists: 4468 // one for the final results, one for the "do not use ever", one for "undefined status" 4469 // and finally one for "Browser App type". 4470 for (int n=0; n<count; n++) { 4471 ResolveInfo info = candidates.get(n); 4472 String packageName = info.activityInfo.packageName; 4473 PackageSetting ps = mSettings.mPackages.get(packageName); 4474 if (ps != null) { 4475 // Add to the special match all list (Browser use case) 4476 if (info.handleAllWebDataURI) { 4477 matchAllList.add(info); 4478 continue; 4479 } 4480 // Try to get the status from User settings first 4481 int status = getDomainVerificationStatusLPr(ps, userId); 4482 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4483 alwaysList.add(info); 4484 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4485 neverList.add(info); 4486 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4487 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4488 undefinedList.add(info); 4489 } 4490 } 4491 } 4492 // First try to add the "always" resolution for the current user if there is any 4493 if (alwaysList.size() > 0) { 4494 result.addAll(alwaysList); 4495 // if there is an "always" for the parent user, add it. 4496 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4497 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4498 result.add(xpDomainInfo.resolveInfo); 4499 } else { 4500 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4501 result.addAll(undefinedList); 4502 if (xpDomainInfo != null && ( 4503 xpDomainInfo.bestDomainVerificationStatus 4504 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4505 || xpDomainInfo.bestDomainVerificationStatus 4506 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4507 result.add(xpDomainInfo.resolveInfo); 4508 } 4509 // Also add Browsers (all of them or only the default one) 4510 if ((flags & MATCH_ALL) != 0) { 4511 result.addAll(matchAllList); 4512 } else { 4513 // Try to add the Default Browser if we can 4514 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4515 UserHandle.myUserId()); 4516 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4517 boolean defaultBrowserFound = false; 4518 final int browserCount = matchAllList.size(); 4519 for (int n=0; n<browserCount; n++) { 4520 ResolveInfo browser = matchAllList.get(n); 4521 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4522 result.add(browser); 4523 defaultBrowserFound = true; 4524 break; 4525 } 4526 } 4527 if (!defaultBrowserFound) { 4528 result.addAll(matchAllList); 4529 } 4530 } else { 4531 result.addAll(matchAllList); 4532 } 4533 } 4534 4535 // If there is nothing selected, add all candidates and remove the ones that the User 4536 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4537 if (result.size() == 0) { 4538 result.addAll(candidates); 4539 result.removeAll(neverList); 4540 } 4541 } 4542 } 4543 if (DEBUG_PREFERRED) { 4544 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4545 result.size()); 4546 } 4547 return result; 4548 } 4549 4550 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4551 int status = ps.getDomainVerificationStatusForUser(userId); 4552 // if none available, get the master status 4553 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4554 if (ps.getIntentFilterVerificationInfo() != null) { 4555 status = ps.getIntentFilterVerificationInfo().getStatus(); 4556 } 4557 } 4558 return status; 4559 } 4560 4561 private ResolveInfo querySkipCurrentProfileIntents( 4562 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4563 int flags, int sourceUserId) { 4564 if (matchingFilters != null) { 4565 int size = matchingFilters.size(); 4566 for (int i = 0; i < size; i ++) { 4567 CrossProfileIntentFilter filter = matchingFilters.get(i); 4568 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4569 // Checking if there are activities in the target user that can handle the 4570 // intent. 4571 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4572 flags, sourceUserId); 4573 if (resolveInfo != null) { 4574 return resolveInfo; 4575 } 4576 } 4577 } 4578 } 4579 return null; 4580 } 4581 4582 // Return matching ResolveInfo if any for skip current profile intent filters. 4583 private ResolveInfo queryCrossProfileIntents( 4584 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4585 int flags, int sourceUserId) { 4586 if (matchingFilters != null) { 4587 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4588 // match the same intent. For performance reasons, it is better not to 4589 // run queryIntent twice for the same userId 4590 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4591 int size = matchingFilters.size(); 4592 for (int i = 0; i < size; i++) { 4593 CrossProfileIntentFilter filter = matchingFilters.get(i); 4594 int targetUserId = filter.getTargetUserId(); 4595 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4596 && !alreadyTriedUserIds.get(targetUserId)) { 4597 // Checking if there are activities in the target user that can handle the 4598 // intent. 4599 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4600 flags, sourceUserId); 4601 if (resolveInfo != null) return resolveInfo; 4602 alreadyTriedUserIds.put(targetUserId, true); 4603 } 4604 } 4605 } 4606 return null; 4607 } 4608 4609 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4610 String resolvedType, int flags, int sourceUserId) { 4611 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4612 resolvedType, flags, filter.getTargetUserId()); 4613 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4614 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4615 } 4616 return null; 4617 } 4618 4619 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4620 int sourceUserId, int targetUserId) { 4621 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4622 String className; 4623 if (targetUserId == UserHandle.USER_OWNER) { 4624 className = FORWARD_INTENT_TO_USER_OWNER; 4625 } else { 4626 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4627 } 4628 ComponentName forwardingActivityComponentName = new ComponentName( 4629 mAndroidApplication.packageName, className); 4630 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4631 sourceUserId); 4632 if (targetUserId == UserHandle.USER_OWNER) { 4633 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4634 forwardingResolveInfo.noResourceId = true; 4635 } 4636 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4637 forwardingResolveInfo.priority = 0; 4638 forwardingResolveInfo.preferredOrder = 0; 4639 forwardingResolveInfo.match = 0; 4640 forwardingResolveInfo.isDefault = true; 4641 forwardingResolveInfo.filter = filter; 4642 forwardingResolveInfo.targetUserId = targetUserId; 4643 return forwardingResolveInfo; 4644 } 4645 4646 @Override 4647 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4648 Intent[] specifics, String[] specificTypes, Intent intent, 4649 String resolvedType, int flags, int userId) { 4650 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4651 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4652 false, "query intent activity options"); 4653 final String resultsAction = intent.getAction(); 4654 4655 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4656 | PackageManager.GET_RESOLVED_FILTER, userId); 4657 4658 if (DEBUG_INTENT_MATCHING) { 4659 Log.v(TAG, "Query " + intent + ": " + results); 4660 } 4661 4662 int specificsPos = 0; 4663 int N; 4664 4665 // todo: note that the algorithm used here is O(N^2). This 4666 // isn't a problem in our current environment, but if we start running 4667 // into situations where we have more than 5 or 10 matches then this 4668 // should probably be changed to something smarter... 4669 4670 // First we go through and resolve each of the specific items 4671 // that were supplied, taking care of removing any corresponding 4672 // duplicate items in the generic resolve list. 4673 if (specifics != null) { 4674 for (int i=0; i<specifics.length; i++) { 4675 final Intent sintent = specifics[i]; 4676 if (sintent == null) { 4677 continue; 4678 } 4679 4680 if (DEBUG_INTENT_MATCHING) { 4681 Log.v(TAG, "Specific #" + i + ": " + sintent); 4682 } 4683 4684 String action = sintent.getAction(); 4685 if (resultsAction != null && resultsAction.equals(action)) { 4686 // If this action was explicitly requested, then don't 4687 // remove things that have it. 4688 action = null; 4689 } 4690 4691 ResolveInfo ri = null; 4692 ActivityInfo ai = null; 4693 4694 ComponentName comp = sintent.getComponent(); 4695 if (comp == null) { 4696 ri = resolveIntent( 4697 sintent, 4698 specificTypes != null ? specificTypes[i] : null, 4699 flags, userId); 4700 if (ri == null) { 4701 continue; 4702 } 4703 if (ri == mResolveInfo) { 4704 // ACK! Must do something better with this. 4705 } 4706 ai = ri.activityInfo; 4707 comp = new ComponentName(ai.applicationInfo.packageName, 4708 ai.name); 4709 } else { 4710 ai = getActivityInfo(comp, flags, userId); 4711 if (ai == null) { 4712 continue; 4713 } 4714 } 4715 4716 // Look for any generic query activities that are duplicates 4717 // of this specific one, and remove them from the results. 4718 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4719 N = results.size(); 4720 int j; 4721 for (j=specificsPos; j<N; j++) { 4722 ResolveInfo sri = results.get(j); 4723 if ((sri.activityInfo.name.equals(comp.getClassName()) 4724 && sri.activityInfo.applicationInfo.packageName.equals( 4725 comp.getPackageName())) 4726 || (action != null && sri.filter.matchAction(action))) { 4727 results.remove(j); 4728 if (DEBUG_INTENT_MATCHING) Log.v( 4729 TAG, "Removing duplicate item from " + j 4730 + " due to specific " + specificsPos); 4731 if (ri == null) { 4732 ri = sri; 4733 } 4734 j--; 4735 N--; 4736 } 4737 } 4738 4739 // Add this specific item to its proper place. 4740 if (ri == null) { 4741 ri = new ResolveInfo(); 4742 ri.activityInfo = ai; 4743 } 4744 results.add(specificsPos, ri); 4745 ri.specificIndex = i; 4746 specificsPos++; 4747 } 4748 } 4749 4750 // Now we go through the remaining generic results and remove any 4751 // duplicate actions that are found here. 4752 N = results.size(); 4753 for (int i=specificsPos; i<N-1; i++) { 4754 final ResolveInfo rii = results.get(i); 4755 if (rii.filter == null) { 4756 continue; 4757 } 4758 4759 // Iterate over all of the actions of this result's intent 4760 // filter... typically this should be just one. 4761 final Iterator<String> it = rii.filter.actionsIterator(); 4762 if (it == null) { 4763 continue; 4764 } 4765 while (it.hasNext()) { 4766 final String action = it.next(); 4767 if (resultsAction != null && resultsAction.equals(action)) { 4768 // If this action was explicitly requested, then don't 4769 // remove things that have it. 4770 continue; 4771 } 4772 for (int j=i+1; j<N; j++) { 4773 final ResolveInfo rij = results.get(j); 4774 if (rij.filter != null && rij.filter.hasAction(action)) { 4775 results.remove(j); 4776 if (DEBUG_INTENT_MATCHING) Log.v( 4777 TAG, "Removing duplicate item from " + j 4778 + " due to action " + action + " at " + i); 4779 j--; 4780 N--; 4781 } 4782 } 4783 } 4784 4785 // If the caller didn't request filter information, drop it now 4786 // so we don't have to marshall/unmarshall it. 4787 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4788 rii.filter = null; 4789 } 4790 } 4791 4792 // Filter out the caller activity if so requested. 4793 if (caller != null) { 4794 N = results.size(); 4795 for (int i=0; i<N; i++) { 4796 ActivityInfo ainfo = results.get(i).activityInfo; 4797 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4798 && caller.getClassName().equals(ainfo.name)) { 4799 results.remove(i); 4800 break; 4801 } 4802 } 4803 } 4804 4805 // If the caller didn't request filter information, 4806 // drop them now so we don't have to 4807 // marshall/unmarshall it. 4808 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4809 N = results.size(); 4810 for (int i=0; i<N; i++) { 4811 results.get(i).filter = null; 4812 } 4813 } 4814 4815 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4816 return results; 4817 } 4818 4819 @Override 4820 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4821 int userId) { 4822 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4823 ComponentName comp = intent.getComponent(); 4824 if (comp == null) { 4825 if (intent.getSelector() != null) { 4826 intent = intent.getSelector(); 4827 comp = intent.getComponent(); 4828 } 4829 } 4830 if (comp != null) { 4831 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4832 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4833 if (ai != null) { 4834 ResolveInfo ri = new ResolveInfo(); 4835 ri.activityInfo = ai; 4836 list.add(ri); 4837 } 4838 return list; 4839 } 4840 4841 // reader 4842 synchronized (mPackages) { 4843 String pkgName = intent.getPackage(); 4844 if (pkgName == null) { 4845 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4846 } 4847 final PackageParser.Package pkg = mPackages.get(pkgName); 4848 if (pkg != null) { 4849 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4850 userId); 4851 } 4852 return null; 4853 } 4854 } 4855 4856 @Override 4857 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4858 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4859 if (!sUserManager.exists(userId)) return null; 4860 if (query != null) { 4861 if (query.size() >= 1) { 4862 // If there is more than one service with the same priority, 4863 // just arbitrarily pick the first one. 4864 return query.get(0); 4865 } 4866 } 4867 return null; 4868 } 4869 4870 @Override 4871 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4872 int userId) { 4873 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4874 ComponentName comp = intent.getComponent(); 4875 if (comp == null) { 4876 if (intent.getSelector() != null) { 4877 intent = intent.getSelector(); 4878 comp = intent.getComponent(); 4879 } 4880 } 4881 if (comp != null) { 4882 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4883 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4884 if (si != null) { 4885 final ResolveInfo ri = new ResolveInfo(); 4886 ri.serviceInfo = si; 4887 list.add(ri); 4888 } 4889 return list; 4890 } 4891 4892 // reader 4893 synchronized (mPackages) { 4894 String pkgName = intent.getPackage(); 4895 if (pkgName == null) { 4896 return mServices.queryIntent(intent, resolvedType, flags, userId); 4897 } 4898 final PackageParser.Package pkg = mPackages.get(pkgName); 4899 if (pkg != null) { 4900 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4901 userId); 4902 } 4903 return null; 4904 } 4905 } 4906 4907 @Override 4908 public List<ResolveInfo> queryIntentContentProviders( 4909 Intent intent, String resolvedType, int flags, int userId) { 4910 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4911 ComponentName comp = intent.getComponent(); 4912 if (comp == null) { 4913 if (intent.getSelector() != null) { 4914 intent = intent.getSelector(); 4915 comp = intent.getComponent(); 4916 } 4917 } 4918 if (comp != null) { 4919 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4920 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4921 if (pi != null) { 4922 final ResolveInfo ri = new ResolveInfo(); 4923 ri.providerInfo = pi; 4924 list.add(ri); 4925 } 4926 return list; 4927 } 4928 4929 // reader 4930 synchronized (mPackages) { 4931 String pkgName = intent.getPackage(); 4932 if (pkgName == null) { 4933 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4934 } 4935 final PackageParser.Package pkg = mPackages.get(pkgName); 4936 if (pkg != null) { 4937 return mProviders.queryIntentForPackage( 4938 intent, resolvedType, flags, pkg.providers, userId); 4939 } 4940 return null; 4941 } 4942 } 4943 4944 @Override 4945 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4946 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4947 4948 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4949 4950 // writer 4951 synchronized (mPackages) { 4952 ArrayList<PackageInfo> list; 4953 if (listUninstalled) { 4954 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4955 for (PackageSetting ps : mSettings.mPackages.values()) { 4956 PackageInfo pi; 4957 if (ps.pkg != null) { 4958 pi = generatePackageInfo(ps.pkg, flags, userId); 4959 } else { 4960 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4961 } 4962 if (pi != null) { 4963 list.add(pi); 4964 } 4965 } 4966 } else { 4967 list = new ArrayList<PackageInfo>(mPackages.size()); 4968 for (PackageParser.Package p : mPackages.values()) { 4969 PackageInfo pi = generatePackageInfo(p, flags, userId); 4970 if (pi != null) { 4971 list.add(pi); 4972 } 4973 } 4974 } 4975 4976 return new ParceledListSlice<PackageInfo>(list); 4977 } 4978 } 4979 4980 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4981 String[] permissions, boolean[] tmp, int flags, int userId) { 4982 int numMatch = 0; 4983 final PermissionsState permissionsState = ps.getPermissionsState(); 4984 for (int i=0; i<permissions.length; i++) { 4985 final String permission = permissions[i]; 4986 if (permissionsState.hasPermission(permission, userId)) { 4987 tmp[i] = true; 4988 numMatch++; 4989 } else { 4990 tmp[i] = false; 4991 } 4992 } 4993 if (numMatch == 0) { 4994 return; 4995 } 4996 PackageInfo pi; 4997 if (ps.pkg != null) { 4998 pi = generatePackageInfo(ps.pkg, flags, userId); 4999 } else { 5000 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5001 } 5002 // The above might return null in cases of uninstalled apps or install-state 5003 // skew across users/profiles. 5004 if (pi != null) { 5005 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5006 if (numMatch == permissions.length) { 5007 pi.requestedPermissions = permissions; 5008 } else { 5009 pi.requestedPermissions = new String[numMatch]; 5010 numMatch = 0; 5011 for (int i=0; i<permissions.length; i++) { 5012 if (tmp[i]) { 5013 pi.requestedPermissions[numMatch] = permissions[i]; 5014 numMatch++; 5015 } 5016 } 5017 } 5018 } 5019 list.add(pi); 5020 } 5021 } 5022 5023 @Override 5024 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5025 String[] permissions, int flags, int userId) { 5026 if (!sUserManager.exists(userId)) return null; 5027 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5028 5029 // writer 5030 synchronized (mPackages) { 5031 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5032 boolean[] tmpBools = new boolean[permissions.length]; 5033 if (listUninstalled) { 5034 for (PackageSetting ps : mSettings.mPackages.values()) { 5035 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5036 } 5037 } else { 5038 for (PackageParser.Package pkg : mPackages.values()) { 5039 PackageSetting ps = (PackageSetting)pkg.mExtras; 5040 if (ps != null) { 5041 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5042 userId); 5043 } 5044 } 5045 } 5046 5047 return new ParceledListSlice<PackageInfo>(list); 5048 } 5049 } 5050 5051 @Override 5052 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5053 if (!sUserManager.exists(userId)) return null; 5054 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5055 5056 // writer 5057 synchronized (mPackages) { 5058 ArrayList<ApplicationInfo> list; 5059 if (listUninstalled) { 5060 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5061 for (PackageSetting ps : mSettings.mPackages.values()) { 5062 ApplicationInfo ai; 5063 if (ps.pkg != null) { 5064 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5065 ps.readUserState(userId), userId); 5066 } else { 5067 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5068 } 5069 if (ai != null) { 5070 list.add(ai); 5071 } 5072 } 5073 } else { 5074 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5075 for (PackageParser.Package p : mPackages.values()) { 5076 if (p.mExtras != null) { 5077 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5078 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5079 if (ai != null) { 5080 list.add(ai); 5081 } 5082 } 5083 } 5084 } 5085 5086 return new ParceledListSlice<ApplicationInfo>(list); 5087 } 5088 } 5089 5090 public List<ApplicationInfo> getPersistentApplications(int flags) { 5091 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5092 5093 // reader 5094 synchronized (mPackages) { 5095 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5096 final int userId = UserHandle.getCallingUserId(); 5097 while (i.hasNext()) { 5098 final PackageParser.Package p = i.next(); 5099 if (p.applicationInfo != null 5100 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5101 && (!mSafeMode || isSystemApp(p))) { 5102 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5103 if (ps != null) { 5104 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5105 ps.readUserState(userId), userId); 5106 if (ai != null) { 5107 finalList.add(ai); 5108 } 5109 } 5110 } 5111 } 5112 } 5113 5114 return finalList; 5115 } 5116 5117 @Override 5118 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5119 if (!sUserManager.exists(userId)) return null; 5120 // reader 5121 synchronized (mPackages) { 5122 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5123 PackageSetting ps = provider != null 5124 ? mSettings.mPackages.get(provider.owner.packageName) 5125 : null; 5126 return ps != null 5127 && mSettings.isEnabledLPr(provider.info, flags, userId) 5128 && (!mSafeMode || (provider.info.applicationInfo.flags 5129 &ApplicationInfo.FLAG_SYSTEM) != 0) 5130 ? PackageParser.generateProviderInfo(provider, flags, 5131 ps.readUserState(userId), userId) 5132 : null; 5133 } 5134 } 5135 5136 /** 5137 * @deprecated 5138 */ 5139 @Deprecated 5140 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5141 // reader 5142 synchronized (mPackages) { 5143 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5144 .entrySet().iterator(); 5145 final int userId = UserHandle.getCallingUserId(); 5146 while (i.hasNext()) { 5147 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5148 PackageParser.Provider p = entry.getValue(); 5149 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5150 5151 if (ps != null && p.syncable 5152 && (!mSafeMode || (p.info.applicationInfo.flags 5153 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5154 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5155 ps.readUserState(userId), userId); 5156 if (info != null) { 5157 outNames.add(entry.getKey()); 5158 outInfo.add(info); 5159 } 5160 } 5161 } 5162 } 5163 } 5164 5165 @Override 5166 public List<ProviderInfo> queryContentProviders(String processName, 5167 int uid, int flags) { 5168 ArrayList<ProviderInfo> finalList = null; 5169 // reader 5170 synchronized (mPackages) { 5171 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5172 final int userId = processName != null ? 5173 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5174 while (i.hasNext()) { 5175 final PackageParser.Provider p = i.next(); 5176 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5177 if (ps != null && p.info.authority != null 5178 && (processName == null 5179 || (p.info.processName.equals(processName) 5180 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5181 && mSettings.isEnabledLPr(p.info, flags, userId) 5182 && (!mSafeMode 5183 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5184 if (finalList == null) { 5185 finalList = new ArrayList<ProviderInfo>(3); 5186 } 5187 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5188 ps.readUserState(userId), userId); 5189 if (info != null) { 5190 finalList.add(info); 5191 } 5192 } 5193 } 5194 } 5195 5196 if (finalList != null) { 5197 Collections.sort(finalList, mProviderInitOrderSorter); 5198 } 5199 5200 return finalList; 5201 } 5202 5203 @Override 5204 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5205 int flags) { 5206 // reader 5207 synchronized (mPackages) { 5208 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5209 return PackageParser.generateInstrumentationInfo(i, flags); 5210 } 5211 } 5212 5213 @Override 5214 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5215 int flags) { 5216 ArrayList<InstrumentationInfo> finalList = 5217 new ArrayList<InstrumentationInfo>(); 5218 5219 // reader 5220 synchronized (mPackages) { 5221 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5222 while (i.hasNext()) { 5223 final PackageParser.Instrumentation p = i.next(); 5224 if (targetPackage == null 5225 || targetPackage.equals(p.info.targetPackage)) { 5226 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5227 flags); 5228 if (ii != null) { 5229 finalList.add(ii); 5230 } 5231 } 5232 } 5233 } 5234 5235 return finalList; 5236 } 5237 5238 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5239 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5240 if (overlays == null) { 5241 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5242 return; 5243 } 5244 for (PackageParser.Package opkg : overlays.values()) { 5245 // Not much to do if idmap fails: we already logged the error 5246 // and we certainly don't want to abort installation of pkg simply 5247 // because an overlay didn't fit properly. For these reasons, 5248 // ignore the return value of createIdmapForPackagePairLI. 5249 createIdmapForPackagePairLI(pkg, opkg); 5250 } 5251 } 5252 5253 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5254 PackageParser.Package opkg) { 5255 if (!opkg.mTrustedOverlay) { 5256 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5257 opkg.baseCodePath + ": overlay not trusted"); 5258 return false; 5259 } 5260 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5261 if (overlaySet == null) { 5262 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5263 opkg.baseCodePath + " but target package has no known overlays"); 5264 return false; 5265 } 5266 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5267 // TODO: generate idmap for split APKs 5268 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5269 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5270 + opkg.baseCodePath); 5271 return false; 5272 } 5273 PackageParser.Package[] overlayArray = 5274 overlaySet.values().toArray(new PackageParser.Package[0]); 5275 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5276 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5277 return p1.mOverlayPriority - p2.mOverlayPriority; 5278 } 5279 }; 5280 Arrays.sort(overlayArray, cmp); 5281 5282 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5283 int i = 0; 5284 for (PackageParser.Package p : overlayArray) { 5285 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5286 } 5287 return true; 5288 } 5289 5290 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5291 final File[] files = dir.listFiles(); 5292 if (ArrayUtils.isEmpty(files)) { 5293 Log.d(TAG, "No files in app dir " + dir); 5294 return; 5295 } 5296 5297 if (DEBUG_PACKAGE_SCANNING) { 5298 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5299 + " flags=0x" + Integer.toHexString(parseFlags)); 5300 } 5301 5302 for (File file : files) { 5303 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5304 && !PackageInstallerService.isStageName(file.getName()); 5305 if (!isPackage) { 5306 // Ignore entries which are not packages 5307 continue; 5308 } 5309 try { 5310 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5311 scanFlags, currentTime, null); 5312 } catch (PackageManagerException e) { 5313 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5314 5315 // Delete invalid userdata apps 5316 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5317 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5318 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5319 if (file.isDirectory()) { 5320 mInstaller.rmPackageDir(file.getAbsolutePath()); 5321 } else { 5322 file.delete(); 5323 } 5324 } 5325 } 5326 } 5327 } 5328 5329 private static File getSettingsProblemFile() { 5330 File dataDir = Environment.getDataDirectory(); 5331 File systemDir = new File(dataDir, "system"); 5332 File fname = new File(systemDir, "uiderrors.txt"); 5333 return fname; 5334 } 5335 5336 static void reportSettingsProblem(int priority, String msg) { 5337 logCriticalInfo(priority, msg); 5338 } 5339 5340 static void logCriticalInfo(int priority, String msg) { 5341 Slog.println(priority, TAG, msg); 5342 EventLogTags.writePmCriticalInfo(msg); 5343 try { 5344 File fname = getSettingsProblemFile(); 5345 FileOutputStream out = new FileOutputStream(fname, true); 5346 PrintWriter pw = new FastPrintWriter(out); 5347 SimpleDateFormat formatter = new SimpleDateFormat(); 5348 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5349 pw.println(dateString + ": " + msg); 5350 pw.close(); 5351 FileUtils.setPermissions( 5352 fname.toString(), 5353 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5354 -1, -1); 5355 } catch (java.io.IOException e) { 5356 } 5357 } 5358 5359 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5360 PackageParser.Package pkg, File srcFile, int parseFlags) 5361 throws PackageManagerException { 5362 if (ps != null 5363 && ps.codePath.equals(srcFile) 5364 && ps.timeStamp == srcFile.lastModified() 5365 && !isCompatSignatureUpdateNeeded(pkg) 5366 && !isRecoverSignatureUpdateNeeded(pkg)) { 5367 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5368 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5369 ArraySet<PublicKey> signingKs; 5370 synchronized (mPackages) { 5371 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5372 } 5373 if (ps.signatures.mSignatures != null 5374 && ps.signatures.mSignatures.length != 0 5375 && signingKs != null) { 5376 // Optimization: reuse the existing cached certificates 5377 // if the package appears to be unchanged. 5378 pkg.mSignatures = ps.signatures.mSignatures; 5379 pkg.mSigningKeys = signingKs; 5380 return; 5381 } 5382 5383 Slog.w(TAG, "PackageSetting for " + ps.name 5384 + " is missing signatures. Collecting certs again to recover them."); 5385 } else { 5386 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5387 } 5388 5389 try { 5390 pp.collectCertificates(pkg, parseFlags); 5391 pp.collectManifestDigest(pkg); 5392 } catch (PackageParserException e) { 5393 throw PackageManagerException.from(e); 5394 } 5395 } 5396 5397 /* 5398 * Scan a package and return the newly parsed package. 5399 * Returns null in case of errors and the error code is stored in mLastScanError 5400 */ 5401 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5402 long currentTime, UserHandle user) throws PackageManagerException { 5403 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5404 parseFlags |= mDefParseFlags; 5405 PackageParser pp = new PackageParser(); 5406 pp.setSeparateProcesses(mSeparateProcesses); 5407 pp.setOnlyCoreApps(mOnlyCore); 5408 pp.setDisplayMetrics(mMetrics); 5409 5410 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5411 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5412 } 5413 5414 final PackageParser.Package pkg; 5415 try { 5416 pkg = pp.parsePackage(scanFile, parseFlags); 5417 } catch (PackageParserException e) { 5418 throw PackageManagerException.from(e); 5419 } 5420 5421 PackageSetting ps = null; 5422 PackageSetting updatedPkg; 5423 // reader 5424 synchronized (mPackages) { 5425 // Look to see if we already know about this package. 5426 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5427 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5428 // This package has been renamed to its original name. Let's 5429 // use that. 5430 ps = mSettings.peekPackageLPr(oldName); 5431 } 5432 // If there was no original package, see one for the real package name. 5433 if (ps == null) { 5434 ps = mSettings.peekPackageLPr(pkg.packageName); 5435 } 5436 // Check to see if this package could be hiding/updating a system 5437 // package. Must look for it either under the original or real 5438 // package name depending on our state. 5439 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5440 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5441 } 5442 boolean updatedPkgBetter = false; 5443 // First check if this is a system package that may involve an update 5444 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5445 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5446 // it needs to drop FLAG_PRIVILEGED. 5447 if (locationIsPrivileged(scanFile)) { 5448 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5449 } else { 5450 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5451 } 5452 5453 if (ps != null && !ps.codePath.equals(scanFile)) { 5454 // The path has changed from what was last scanned... check the 5455 // version of the new path against what we have stored to determine 5456 // what to do. 5457 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5458 if (pkg.mVersionCode <= ps.versionCode) { 5459 // The system package has been updated and the code path does not match 5460 // Ignore entry. Skip it. 5461 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5462 + " ignored: updated version " + ps.versionCode 5463 + " better than this " + pkg.mVersionCode); 5464 if (!updatedPkg.codePath.equals(scanFile)) { 5465 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5466 + ps.name + " changing from " + updatedPkg.codePathString 5467 + " to " + scanFile); 5468 updatedPkg.codePath = scanFile; 5469 updatedPkg.codePathString = scanFile.toString(); 5470 updatedPkg.resourcePath = scanFile; 5471 updatedPkg.resourcePathString = scanFile.toString(); 5472 } 5473 updatedPkg.pkg = pkg; 5474 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5475 } else { 5476 // The current app on the system partition is better than 5477 // what we have updated to on the data partition; switch 5478 // back to the system partition version. 5479 // At this point, its safely assumed that package installation for 5480 // apps in system partition will go through. If not there won't be a working 5481 // version of the app 5482 // writer 5483 synchronized (mPackages) { 5484 // Just remove the loaded entries from package lists. 5485 mPackages.remove(ps.name); 5486 } 5487 5488 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5489 + " reverting from " + ps.codePathString 5490 + ": new version " + pkg.mVersionCode 5491 + " better than installed " + ps.versionCode); 5492 5493 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5494 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5495 synchronized (mInstallLock) { 5496 args.cleanUpResourcesLI(); 5497 } 5498 synchronized (mPackages) { 5499 mSettings.enableSystemPackageLPw(ps.name); 5500 } 5501 updatedPkgBetter = true; 5502 } 5503 } 5504 } 5505 5506 if (updatedPkg != null) { 5507 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5508 // initially 5509 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5510 5511 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5512 // flag set initially 5513 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5514 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5515 } 5516 } 5517 5518 // Verify certificates against what was last scanned 5519 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5520 5521 /* 5522 * A new system app appeared, but we already had a non-system one of the 5523 * same name installed earlier. 5524 */ 5525 boolean shouldHideSystemApp = false; 5526 if (updatedPkg == null && ps != null 5527 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5528 /* 5529 * Check to make sure the signatures match first. If they don't, 5530 * wipe the installed application and its data. 5531 */ 5532 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5533 != PackageManager.SIGNATURE_MATCH) { 5534 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5535 + " signatures don't match existing userdata copy; removing"); 5536 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5537 ps = null; 5538 } else { 5539 /* 5540 * If the newly-added system app is an older version than the 5541 * already installed version, hide it. It will be scanned later 5542 * and re-added like an update. 5543 */ 5544 if (pkg.mVersionCode <= ps.versionCode) { 5545 shouldHideSystemApp = true; 5546 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5547 + " but new version " + pkg.mVersionCode + " better than installed " 5548 + ps.versionCode + "; hiding system"); 5549 } else { 5550 /* 5551 * The newly found system app is a newer version that the 5552 * one previously installed. Simply remove the 5553 * already-installed application and replace it with our own 5554 * while keeping the application data. 5555 */ 5556 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5557 + " reverting from " + ps.codePathString + ": new version " 5558 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5559 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5560 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5561 synchronized (mInstallLock) { 5562 args.cleanUpResourcesLI(); 5563 } 5564 } 5565 } 5566 } 5567 5568 // The apk is forward locked (not public) if its code and resources 5569 // are kept in different files. (except for app in either system or 5570 // vendor path). 5571 // TODO grab this value from PackageSettings 5572 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5573 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5574 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5575 } 5576 } 5577 5578 // TODO: extend to support forward-locked splits 5579 String resourcePath = null; 5580 String baseResourcePath = null; 5581 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5582 if (ps != null && ps.resourcePathString != null) { 5583 resourcePath = ps.resourcePathString; 5584 baseResourcePath = ps.resourcePathString; 5585 } else { 5586 // Should not happen at all. Just log an error. 5587 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5588 } 5589 } else { 5590 resourcePath = pkg.codePath; 5591 baseResourcePath = pkg.baseCodePath; 5592 } 5593 5594 // Set application objects path explicitly. 5595 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5596 pkg.applicationInfo.setCodePath(pkg.codePath); 5597 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5598 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5599 pkg.applicationInfo.setResourcePath(resourcePath); 5600 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5601 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5602 5603 // Note that we invoke the following method only if we are about to unpack an application 5604 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5605 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5606 5607 /* 5608 * If the system app should be overridden by a previously installed 5609 * data, hide the system app now and let the /data/app scan pick it up 5610 * again. 5611 */ 5612 if (shouldHideSystemApp) { 5613 synchronized (mPackages) { 5614 /* 5615 * We have to grant systems permissions before we hide, because 5616 * grantPermissions will assume the package update is trying to 5617 * expand its permissions. 5618 */ 5619 grantPermissionsLPw(pkg, true, pkg.packageName); 5620 mSettings.disableSystemPackageLPw(pkg.packageName); 5621 } 5622 } 5623 5624 return scannedPkg; 5625 } 5626 5627 private static String fixProcessName(String defProcessName, 5628 String processName, int uid) { 5629 if (processName == null) { 5630 return defProcessName; 5631 } 5632 return processName; 5633 } 5634 5635 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5636 throws PackageManagerException { 5637 if (pkgSetting.signatures.mSignatures != null) { 5638 // Already existing package. Make sure signatures match 5639 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5640 == PackageManager.SIGNATURE_MATCH; 5641 if (!match) { 5642 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5643 == PackageManager.SIGNATURE_MATCH; 5644 } 5645 if (!match) { 5646 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5647 == PackageManager.SIGNATURE_MATCH; 5648 } 5649 if (!match) { 5650 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5651 + pkg.packageName + " signatures do not match the " 5652 + "previously installed version; ignoring!"); 5653 } 5654 } 5655 5656 // Check for shared user signatures 5657 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5658 // Already existing package. Make sure signatures match 5659 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5660 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5661 if (!match) { 5662 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5663 == PackageManager.SIGNATURE_MATCH; 5664 } 5665 if (!match) { 5666 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5667 == PackageManager.SIGNATURE_MATCH; 5668 } 5669 if (!match) { 5670 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5671 "Package " + pkg.packageName 5672 + " has no signatures that match those in shared user " 5673 + pkgSetting.sharedUser.name + "; ignoring!"); 5674 } 5675 } 5676 } 5677 5678 /** 5679 * Enforces that only the system UID or root's UID can call a method exposed 5680 * via Binder. 5681 * 5682 * @param message used as message if SecurityException is thrown 5683 * @throws SecurityException if the caller is not system or root 5684 */ 5685 private static final void enforceSystemOrRoot(String message) { 5686 final int uid = Binder.getCallingUid(); 5687 if (uid != Process.SYSTEM_UID && uid != 0) { 5688 throw new SecurityException(message); 5689 } 5690 } 5691 5692 @Override 5693 public void performBootDexOpt() { 5694 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5695 5696 // Before everything else, see whether we need to fstrim. 5697 try { 5698 IMountService ms = PackageHelper.getMountService(); 5699 if (ms != null) { 5700 final boolean isUpgrade = isUpgrade(); 5701 boolean doTrim = isUpgrade; 5702 if (doTrim) { 5703 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5704 } else { 5705 final long interval = android.provider.Settings.Global.getLong( 5706 mContext.getContentResolver(), 5707 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5708 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5709 if (interval > 0) { 5710 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5711 if (timeSinceLast > interval) { 5712 doTrim = true; 5713 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5714 + "; running immediately"); 5715 } 5716 } 5717 } 5718 if (doTrim) { 5719 if (!isFirstBoot()) { 5720 try { 5721 ActivityManagerNative.getDefault().showBootMessage( 5722 mContext.getResources().getString( 5723 R.string.android_upgrading_fstrim), true); 5724 } catch (RemoteException e) { 5725 } 5726 } 5727 ms.runMaintenance(); 5728 } 5729 } else { 5730 Slog.e(TAG, "Mount service unavailable!"); 5731 } 5732 } catch (RemoteException e) { 5733 // Can't happen; MountService is local 5734 } 5735 5736 final ArraySet<PackageParser.Package> pkgs; 5737 synchronized (mPackages) { 5738 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5739 } 5740 5741 if (pkgs != null) { 5742 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5743 // in case the device runs out of space. 5744 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5745 // Give priority to core apps. 5746 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5747 PackageParser.Package pkg = it.next(); 5748 if (pkg.coreApp) { 5749 if (DEBUG_DEXOPT) { 5750 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5751 } 5752 sortedPkgs.add(pkg); 5753 it.remove(); 5754 } 5755 } 5756 // Give priority to system apps that listen for pre boot complete. 5757 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5758 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5759 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5760 PackageParser.Package pkg = it.next(); 5761 if (pkgNames.contains(pkg.packageName)) { 5762 if (DEBUG_DEXOPT) { 5763 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5764 } 5765 sortedPkgs.add(pkg); 5766 it.remove(); 5767 } 5768 } 5769 // Give priority to system apps. 5770 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5771 PackageParser.Package pkg = it.next(); 5772 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5773 if (DEBUG_DEXOPT) { 5774 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5775 } 5776 sortedPkgs.add(pkg); 5777 it.remove(); 5778 } 5779 } 5780 // Give priority to updated system apps. 5781 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5782 PackageParser.Package pkg = it.next(); 5783 if (pkg.isUpdatedSystemApp()) { 5784 if (DEBUG_DEXOPT) { 5785 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5786 } 5787 sortedPkgs.add(pkg); 5788 it.remove(); 5789 } 5790 } 5791 // Give priority to apps that listen for boot complete. 5792 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5793 pkgNames = getPackageNamesForIntent(intent); 5794 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5795 PackageParser.Package pkg = it.next(); 5796 if (pkgNames.contains(pkg.packageName)) { 5797 if (DEBUG_DEXOPT) { 5798 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5799 } 5800 sortedPkgs.add(pkg); 5801 it.remove(); 5802 } 5803 } 5804 // Filter out packages that aren't recently used. 5805 filterRecentlyUsedApps(pkgs); 5806 // Add all remaining apps. 5807 for (PackageParser.Package pkg : pkgs) { 5808 if (DEBUG_DEXOPT) { 5809 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5810 } 5811 sortedPkgs.add(pkg); 5812 } 5813 5814 // If we want to be lazy, filter everything that wasn't recently used. 5815 if (mLazyDexOpt) { 5816 filterRecentlyUsedApps(sortedPkgs); 5817 } 5818 5819 int i = 0; 5820 int total = sortedPkgs.size(); 5821 File dataDir = Environment.getDataDirectory(); 5822 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5823 if (lowThreshold == 0) { 5824 throw new IllegalStateException("Invalid low memory threshold"); 5825 } 5826 for (PackageParser.Package pkg : sortedPkgs) { 5827 long usableSpace = dataDir.getUsableSpace(); 5828 if (usableSpace < lowThreshold) { 5829 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5830 break; 5831 } 5832 performBootDexOpt(pkg, ++i, total); 5833 } 5834 } 5835 } 5836 5837 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5838 // Filter out packages that aren't recently used. 5839 // 5840 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5841 // should do a full dexopt. 5842 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5843 int total = pkgs.size(); 5844 int skipped = 0; 5845 long now = System.currentTimeMillis(); 5846 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5847 PackageParser.Package pkg = i.next(); 5848 long then = pkg.mLastPackageUsageTimeInMills; 5849 if (then + mDexOptLRUThresholdInMills < now) { 5850 if (DEBUG_DEXOPT) { 5851 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5852 ((then == 0) ? "never" : new Date(then))); 5853 } 5854 i.remove(); 5855 skipped++; 5856 } 5857 } 5858 if (DEBUG_DEXOPT) { 5859 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5860 } 5861 } 5862 } 5863 5864 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5865 List<ResolveInfo> ris = null; 5866 try { 5867 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5868 intent, null, 0, UserHandle.USER_OWNER); 5869 } catch (RemoteException e) { 5870 } 5871 ArraySet<String> pkgNames = new ArraySet<String>(); 5872 if (ris != null) { 5873 for (ResolveInfo ri : ris) { 5874 pkgNames.add(ri.activityInfo.packageName); 5875 } 5876 } 5877 return pkgNames; 5878 } 5879 5880 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5881 if (DEBUG_DEXOPT) { 5882 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5883 } 5884 if (!isFirstBoot()) { 5885 try { 5886 ActivityManagerNative.getDefault().showBootMessage( 5887 mContext.getResources().getString(R.string.android_upgrading_apk, 5888 curr, total), true); 5889 } catch (RemoteException e) { 5890 } 5891 } 5892 PackageParser.Package p = pkg; 5893 synchronized (mInstallLock) { 5894 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5895 false /* force dex */, false /* defer */, true /* include dependencies */); 5896 } 5897 } 5898 5899 @Override 5900 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5901 return performDexOpt(packageName, instructionSet, false); 5902 } 5903 5904 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5905 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5906 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5907 if (!dexopt && !updateUsage) { 5908 // We aren't going to dexopt or update usage, so bail early. 5909 return false; 5910 } 5911 PackageParser.Package p; 5912 final String targetInstructionSet; 5913 synchronized (mPackages) { 5914 p = mPackages.get(packageName); 5915 if (p == null) { 5916 return false; 5917 } 5918 if (updateUsage) { 5919 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5920 } 5921 mPackageUsage.write(false); 5922 if (!dexopt) { 5923 // We aren't going to dexopt, so bail early. 5924 return false; 5925 } 5926 5927 targetInstructionSet = instructionSet != null ? instructionSet : 5928 getPrimaryInstructionSet(p.applicationInfo); 5929 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5930 return false; 5931 } 5932 } 5933 5934 synchronized (mInstallLock) { 5935 final String[] instructionSets = new String[] { targetInstructionSet }; 5936 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5937 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5938 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5939 } 5940 } 5941 5942 public ArraySet<String> getPackagesThatNeedDexOpt() { 5943 ArraySet<String> pkgs = null; 5944 synchronized (mPackages) { 5945 for (PackageParser.Package p : mPackages.values()) { 5946 if (DEBUG_DEXOPT) { 5947 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5948 } 5949 if (!p.mDexOptPerformed.isEmpty()) { 5950 continue; 5951 } 5952 if (pkgs == null) { 5953 pkgs = new ArraySet<String>(); 5954 } 5955 pkgs.add(p.packageName); 5956 } 5957 } 5958 return pkgs; 5959 } 5960 5961 public void shutdown() { 5962 mPackageUsage.write(true); 5963 } 5964 5965 @Override 5966 public void forceDexOpt(String packageName) { 5967 enforceSystemOrRoot("forceDexOpt"); 5968 5969 PackageParser.Package pkg; 5970 synchronized (mPackages) { 5971 pkg = mPackages.get(packageName); 5972 if (pkg == null) { 5973 throw new IllegalArgumentException("Missing package: " + packageName); 5974 } 5975 } 5976 5977 synchronized (mInstallLock) { 5978 final String[] instructionSets = new String[] { 5979 getPrimaryInstructionSet(pkg.applicationInfo) }; 5980 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5981 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5982 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5983 throw new IllegalStateException("Failed to dexopt: " + res); 5984 } 5985 } 5986 } 5987 5988 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5989 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5990 Slog.w(TAG, "Unable to update from " + oldPkg.name 5991 + " to " + newPkg.packageName 5992 + ": old package not in system partition"); 5993 return false; 5994 } else if (mPackages.get(oldPkg.name) != null) { 5995 Slog.w(TAG, "Unable to update from " + oldPkg.name 5996 + " to " + newPkg.packageName 5997 + ": old package still exists"); 5998 return false; 5999 } 6000 return true; 6001 } 6002 6003 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6004 int[] users = sUserManager.getUserIds(); 6005 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6006 if (res < 0) { 6007 return res; 6008 } 6009 for (int user : users) { 6010 if (user != 0) { 6011 res = mInstaller.createUserData(volumeUuid, packageName, 6012 UserHandle.getUid(user, uid), user, seinfo); 6013 if (res < 0) { 6014 return res; 6015 } 6016 } 6017 } 6018 return res; 6019 } 6020 6021 private int removeDataDirsLI(String volumeUuid, String packageName) { 6022 int[] users = sUserManager.getUserIds(); 6023 int res = 0; 6024 for (int user : users) { 6025 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6026 if (resInner < 0) { 6027 res = resInner; 6028 } 6029 } 6030 6031 return res; 6032 } 6033 6034 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6035 int[] users = sUserManager.getUserIds(); 6036 int res = 0; 6037 for (int user : users) { 6038 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6039 if (resInner < 0) { 6040 res = resInner; 6041 } 6042 } 6043 return res; 6044 } 6045 6046 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6047 PackageParser.Package changingLib) { 6048 if (file.path != null) { 6049 usesLibraryFiles.add(file.path); 6050 return; 6051 } 6052 PackageParser.Package p = mPackages.get(file.apk); 6053 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6054 // If we are doing this while in the middle of updating a library apk, 6055 // then we need to make sure to use that new apk for determining the 6056 // dependencies here. (We haven't yet finished committing the new apk 6057 // to the package manager state.) 6058 if (p == null || p.packageName.equals(changingLib.packageName)) { 6059 p = changingLib; 6060 } 6061 } 6062 if (p != null) { 6063 usesLibraryFiles.addAll(p.getAllCodePaths()); 6064 } 6065 } 6066 6067 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6068 PackageParser.Package changingLib) throws PackageManagerException { 6069 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6070 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6071 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6072 for (int i=0; i<N; i++) { 6073 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6074 if (file == null) { 6075 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6076 "Package " + pkg.packageName + " requires unavailable shared library " 6077 + pkg.usesLibraries.get(i) + "; failing!"); 6078 } 6079 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6080 } 6081 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6082 for (int i=0; i<N; i++) { 6083 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6084 if (file == null) { 6085 Slog.w(TAG, "Package " + pkg.packageName 6086 + " desires unavailable shared library " 6087 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6088 } else { 6089 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6090 } 6091 } 6092 N = usesLibraryFiles.size(); 6093 if (N > 0) { 6094 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6095 } else { 6096 pkg.usesLibraryFiles = null; 6097 } 6098 } 6099 } 6100 6101 private static boolean hasString(List<String> list, List<String> which) { 6102 if (list == null) { 6103 return false; 6104 } 6105 for (int i=list.size()-1; i>=0; i--) { 6106 for (int j=which.size()-1; j>=0; j--) { 6107 if (which.get(j).equals(list.get(i))) { 6108 return true; 6109 } 6110 } 6111 } 6112 return false; 6113 } 6114 6115 private void updateAllSharedLibrariesLPw() { 6116 for (PackageParser.Package pkg : mPackages.values()) { 6117 try { 6118 updateSharedLibrariesLPw(pkg, null); 6119 } catch (PackageManagerException e) { 6120 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6121 } 6122 } 6123 } 6124 6125 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6126 PackageParser.Package changingPkg) { 6127 ArrayList<PackageParser.Package> res = null; 6128 for (PackageParser.Package pkg : mPackages.values()) { 6129 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6130 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6131 if (res == null) { 6132 res = new ArrayList<PackageParser.Package>(); 6133 } 6134 res.add(pkg); 6135 try { 6136 updateSharedLibrariesLPw(pkg, changingPkg); 6137 } catch (PackageManagerException e) { 6138 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6139 } 6140 } 6141 } 6142 return res; 6143 } 6144 6145 /** 6146 * Derive the value of the {@code cpuAbiOverride} based on the provided 6147 * value and an optional stored value from the package settings. 6148 */ 6149 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6150 String cpuAbiOverride = null; 6151 6152 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6153 cpuAbiOverride = null; 6154 } else if (abiOverride != null) { 6155 cpuAbiOverride = abiOverride; 6156 } else if (settings != null) { 6157 cpuAbiOverride = settings.cpuAbiOverrideString; 6158 } 6159 6160 return cpuAbiOverride; 6161 } 6162 6163 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6164 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6165 boolean success = false; 6166 try { 6167 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6168 currentTime, user); 6169 success = true; 6170 return res; 6171 } finally { 6172 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6173 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6174 } 6175 } 6176 } 6177 6178 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6179 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6180 final File scanFile = new File(pkg.codePath); 6181 if (pkg.applicationInfo.getCodePath() == null || 6182 pkg.applicationInfo.getResourcePath() == null) { 6183 // Bail out. The resource and code paths haven't been set. 6184 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6185 "Code and resource paths haven't been set correctly"); 6186 } 6187 6188 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6189 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6190 } else { 6191 // Only allow system apps to be flagged as core apps. 6192 pkg.coreApp = false; 6193 } 6194 6195 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6196 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6197 } 6198 6199 if (mCustomResolverComponentName != null && 6200 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6201 setUpCustomResolverActivity(pkg); 6202 } 6203 6204 if (pkg.packageName.equals("android")) { 6205 synchronized (mPackages) { 6206 if (mAndroidApplication != null) { 6207 Slog.w(TAG, "*************************************************"); 6208 Slog.w(TAG, "Core android package being redefined. Skipping."); 6209 Slog.w(TAG, " file=" + scanFile); 6210 Slog.w(TAG, "*************************************************"); 6211 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6212 "Core android package being redefined. Skipping."); 6213 } 6214 6215 // Set up information for our fall-back user intent resolution activity. 6216 mPlatformPackage = pkg; 6217 pkg.mVersionCode = mSdkVersion; 6218 mAndroidApplication = pkg.applicationInfo; 6219 6220 if (!mResolverReplaced) { 6221 mResolveActivity.applicationInfo = mAndroidApplication; 6222 mResolveActivity.name = ResolverActivity.class.getName(); 6223 mResolveActivity.packageName = mAndroidApplication.packageName; 6224 mResolveActivity.processName = "system:ui"; 6225 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6226 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6227 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6228 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6229 mResolveActivity.exported = true; 6230 mResolveActivity.enabled = true; 6231 mResolveInfo.activityInfo = mResolveActivity; 6232 mResolveInfo.priority = 0; 6233 mResolveInfo.preferredOrder = 0; 6234 mResolveInfo.match = 0; 6235 mResolveComponentName = new ComponentName( 6236 mAndroidApplication.packageName, mResolveActivity.name); 6237 } 6238 } 6239 } 6240 6241 if (DEBUG_PACKAGE_SCANNING) { 6242 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6243 Log.d(TAG, "Scanning package " + pkg.packageName); 6244 } 6245 6246 if (mPackages.containsKey(pkg.packageName) 6247 || mSharedLibraries.containsKey(pkg.packageName)) { 6248 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6249 "Application package " + pkg.packageName 6250 + " already installed. Skipping duplicate."); 6251 } 6252 6253 // If we're only installing presumed-existing packages, require that the 6254 // scanned APK is both already known and at the path previously established 6255 // for it. Previously unknown packages we pick up normally, but if we have an 6256 // a priori expectation about this package's install presence, enforce it. 6257 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6258 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6259 if (known != null) { 6260 if (DEBUG_PACKAGE_SCANNING) { 6261 Log.d(TAG, "Examining " + pkg.codePath 6262 + " and requiring known paths " + known.codePathString 6263 + " & " + known.resourcePathString); 6264 } 6265 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6266 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6267 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6268 "Application package " + pkg.packageName 6269 + " found at " + pkg.applicationInfo.getCodePath() 6270 + " but expected at " + known.codePathString + "; ignoring."); 6271 } 6272 } 6273 } 6274 6275 // Initialize package source and resource directories 6276 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6277 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6278 6279 SharedUserSetting suid = null; 6280 PackageSetting pkgSetting = null; 6281 6282 if (!isSystemApp(pkg)) { 6283 // Only system apps can use these features. 6284 pkg.mOriginalPackages = null; 6285 pkg.mRealPackage = null; 6286 pkg.mAdoptPermissions = null; 6287 } 6288 6289 // writer 6290 synchronized (mPackages) { 6291 if (pkg.mSharedUserId != null) { 6292 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6293 if (suid == null) { 6294 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6295 "Creating application package " + pkg.packageName 6296 + " for shared user failed"); 6297 } 6298 if (DEBUG_PACKAGE_SCANNING) { 6299 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6300 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6301 + "): packages=" + suid.packages); 6302 } 6303 } 6304 6305 // Check if we are renaming from an original package name. 6306 PackageSetting origPackage = null; 6307 String realName = null; 6308 if (pkg.mOriginalPackages != null) { 6309 // This package may need to be renamed to a previously 6310 // installed name. Let's check on that... 6311 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6312 if (pkg.mOriginalPackages.contains(renamed)) { 6313 // This package had originally been installed as the 6314 // original name, and we have already taken care of 6315 // transitioning to the new one. Just update the new 6316 // one to continue using the old name. 6317 realName = pkg.mRealPackage; 6318 if (!pkg.packageName.equals(renamed)) { 6319 // Callers into this function may have already taken 6320 // care of renaming the package; only do it here if 6321 // it is not already done. 6322 pkg.setPackageName(renamed); 6323 } 6324 6325 } else { 6326 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6327 if ((origPackage = mSettings.peekPackageLPr( 6328 pkg.mOriginalPackages.get(i))) != null) { 6329 // We do have the package already installed under its 6330 // original name... should we use it? 6331 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6332 // New package is not compatible with original. 6333 origPackage = null; 6334 continue; 6335 } else if (origPackage.sharedUser != null) { 6336 // Make sure uid is compatible between packages. 6337 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6338 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6339 + " to " + pkg.packageName + ": old uid " 6340 + origPackage.sharedUser.name 6341 + " differs from " + pkg.mSharedUserId); 6342 origPackage = null; 6343 continue; 6344 } 6345 } else { 6346 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6347 + pkg.packageName + " to old name " + origPackage.name); 6348 } 6349 break; 6350 } 6351 } 6352 } 6353 } 6354 6355 if (mTransferedPackages.contains(pkg.packageName)) { 6356 Slog.w(TAG, "Package " + pkg.packageName 6357 + " was transferred to another, but its .apk remains"); 6358 } 6359 6360 // Just create the setting, don't add it yet. For already existing packages 6361 // the PkgSetting exists already and doesn't have to be created. 6362 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6363 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6364 pkg.applicationInfo.primaryCpuAbi, 6365 pkg.applicationInfo.secondaryCpuAbi, 6366 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6367 user, false); 6368 if (pkgSetting == null) { 6369 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6370 "Creating application package " + pkg.packageName + " failed"); 6371 } 6372 6373 if (pkgSetting.origPackage != null) { 6374 // If we are first transitioning from an original package, 6375 // fix up the new package's name now. We need to do this after 6376 // looking up the package under its new name, so getPackageLP 6377 // can take care of fiddling things correctly. 6378 pkg.setPackageName(origPackage.name); 6379 6380 // File a report about this. 6381 String msg = "New package " + pkgSetting.realName 6382 + " renamed to replace old package " + pkgSetting.name; 6383 reportSettingsProblem(Log.WARN, msg); 6384 6385 // Make a note of it. 6386 mTransferedPackages.add(origPackage.name); 6387 6388 // No longer need to retain this. 6389 pkgSetting.origPackage = null; 6390 } 6391 6392 if (realName != null) { 6393 // Make a note of it. 6394 mTransferedPackages.add(pkg.packageName); 6395 } 6396 6397 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6398 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6399 } 6400 6401 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6402 // Check all shared libraries and map to their actual file path. 6403 // We only do this here for apps not on a system dir, because those 6404 // are the only ones that can fail an install due to this. We 6405 // will take care of the system apps by updating all of their 6406 // library paths after the scan is done. 6407 updateSharedLibrariesLPw(pkg, null); 6408 } 6409 6410 if (mFoundPolicyFile) { 6411 SELinuxMMAC.assignSeinfoValue(pkg); 6412 } 6413 6414 pkg.applicationInfo.uid = pkgSetting.appId; 6415 pkg.mExtras = pkgSetting; 6416 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6417 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6418 // We just determined the app is signed correctly, so bring 6419 // over the latest parsed certs. 6420 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6421 } else { 6422 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6423 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6424 "Package " + pkg.packageName + " upgrade keys do not match the " 6425 + "previously installed version"); 6426 } else { 6427 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6428 String msg = "System package " + pkg.packageName 6429 + " signature changed; retaining data."; 6430 reportSettingsProblem(Log.WARN, msg); 6431 } 6432 } 6433 } else { 6434 try { 6435 verifySignaturesLP(pkgSetting, pkg); 6436 // We just determined the app is signed correctly, so bring 6437 // over the latest parsed certs. 6438 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6439 } catch (PackageManagerException e) { 6440 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6441 throw e; 6442 } 6443 // The signature has changed, but this package is in the system 6444 // image... let's recover! 6445 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6446 // However... if this package is part of a shared user, but it 6447 // doesn't match the signature of the shared user, let's fail. 6448 // What this means is that you can't change the signatures 6449 // associated with an overall shared user, which doesn't seem all 6450 // that unreasonable. 6451 if (pkgSetting.sharedUser != null) { 6452 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6453 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6454 throw new PackageManagerException( 6455 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6456 "Signature mismatch for shared user : " 6457 + pkgSetting.sharedUser); 6458 } 6459 } 6460 // File a report about this. 6461 String msg = "System package " + pkg.packageName 6462 + " signature changed; retaining data."; 6463 reportSettingsProblem(Log.WARN, msg); 6464 } 6465 } 6466 // Verify that this new package doesn't have any content providers 6467 // that conflict with existing packages. Only do this if the 6468 // package isn't already installed, since we don't want to break 6469 // things that are installed. 6470 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6471 final int N = pkg.providers.size(); 6472 int i; 6473 for (i=0; i<N; i++) { 6474 PackageParser.Provider p = pkg.providers.get(i); 6475 if (p.info.authority != null) { 6476 String names[] = p.info.authority.split(";"); 6477 for (int j = 0; j < names.length; j++) { 6478 if (mProvidersByAuthority.containsKey(names[j])) { 6479 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6480 final String otherPackageName = 6481 ((other != null && other.getComponentName() != null) ? 6482 other.getComponentName().getPackageName() : "?"); 6483 throw new PackageManagerException( 6484 INSTALL_FAILED_CONFLICTING_PROVIDER, 6485 "Can't install because provider name " + names[j] 6486 + " (in package " + pkg.applicationInfo.packageName 6487 + ") is already used by " + otherPackageName); 6488 } 6489 } 6490 } 6491 } 6492 } 6493 6494 if (pkg.mAdoptPermissions != null) { 6495 // This package wants to adopt ownership of permissions from 6496 // another package. 6497 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6498 final String origName = pkg.mAdoptPermissions.get(i); 6499 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6500 if (orig != null) { 6501 if (verifyPackageUpdateLPr(orig, pkg)) { 6502 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6503 + pkg.packageName); 6504 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6505 } 6506 } 6507 } 6508 } 6509 } 6510 6511 final String pkgName = pkg.packageName; 6512 6513 final long scanFileTime = scanFile.lastModified(); 6514 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6515 pkg.applicationInfo.processName = fixProcessName( 6516 pkg.applicationInfo.packageName, 6517 pkg.applicationInfo.processName, 6518 pkg.applicationInfo.uid); 6519 6520 File dataPath; 6521 if (mPlatformPackage == pkg) { 6522 // The system package is special. 6523 dataPath = new File(Environment.getDataDirectory(), "system"); 6524 6525 pkg.applicationInfo.dataDir = dataPath.getPath(); 6526 6527 } else { 6528 // This is a normal package, need to make its data directory. 6529 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6530 UserHandle.USER_OWNER); 6531 6532 boolean uidError = false; 6533 if (dataPath.exists()) { 6534 int currentUid = 0; 6535 try { 6536 StructStat stat = Os.stat(dataPath.getPath()); 6537 currentUid = stat.st_uid; 6538 } catch (ErrnoException e) { 6539 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6540 } 6541 6542 // If we have mismatched owners for the data path, we have a problem. 6543 if (currentUid != pkg.applicationInfo.uid) { 6544 boolean recovered = false; 6545 if (currentUid == 0) { 6546 // The directory somehow became owned by root. Wow. 6547 // This is probably because the system was stopped while 6548 // installd was in the middle of messing with its libs 6549 // directory. Ask installd to fix that. 6550 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6551 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6552 if (ret >= 0) { 6553 recovered = true; 6554 String msg = "Package " + pkg.packageName 6555 + " unexpectedly changed to uid 0; recovered to " + 6556 + pkg.applicationInfo.uid; 6557 reportSettingsProblem(Log.WARN, msg); 6558 } 6559 } 6560 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6561 || (scanFlags&SCAN_BOOTING) != 0)) { 6562 // If this is a system app, we can at least delete its 6563 // current data so the application will still work. 6564 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6565 if (ret >= 0) { 6566 // TODO: Kill the processes first 6567 // Old data gone! 6568 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6569 ? "System package " : "Third party package "; 6570 String msg = prefix + pkg.packageName 6571 + " has changed from uid: " 6572 + currentUid + " to " 6573 + pkg.applicationInfo.uid + "; old data erased"; 6574 reportSettingsProblem(Log.WARN, msg); 6575 recovered = true; 6576 6577 // And now re-install the app. 6578 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6579 pkg.applicationInfo.seinfo); 6580 if (ret == -1) { 6581 // Ack should not happen! 6582 msg = prefix + pkg.packageName 6583 + " could not have data directory re-created after delete."; 6584 reportSettingsProblem(Log.WARN, msg); 6585 throw new PackageManagerException( 6586 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6587 } 6588 } 6589 if (!recovered) { 6590 mHasSystemUidErrors = true; 6591 } 6592 } else if (!recovered) { 6593 // If we allow this install to proceed, we will be broken. 6594 // Abort, abort! 6595 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6596 "scanPackageLI"); 6597 } 6598 if (!recovered) { 6599 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6600 + pkg.applicationInfo.uid + "/fs_" 6601 + currentUid; 6602 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6603 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6604 String msg = "Package " + pkg.packageName 6605 + " has mismatched uid: " 6606 + currentUid + " on disk, " 6607 + pkg.applicationInfo.uid + " in settings"; 6608 // writer 6609 synchronized (mPackages) { 6610 mSettings.mReadMessages.append(msg); 6611 mSettings.mReadMessages.append('\n'); 6612 uidError = true; 6613 if (!pkgSetting.uidError) { 6614 reportSettingsProblem(Log.ERROR, msg); 6615 } 6616 } 6617 } 6618 } 6619 pkg.applicationInfo.dataDir = dataPath.getPath(); 6620 if (mShouldRestoreconData) { 6621 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6622 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6623 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6624 } 6625 } else { 6626 if (DEBUG_PACKAGE_SCANNING) { 6627 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6628 Log.v(TAG, "Want this data dir: " + dataPath); 6629 } 6630 //invoke installer to do the actual installation 6631 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6632 pkg.applicationInfo.seinfo); 6633 if (ret < 0) { 6634 // Error from installer 6635 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6636 "Unable to create data dirs [errorCode=" + ret + "]"); 6637 } 6638 6639 if (dataPath.exists()) { 6640 pkg.applicationInfo.dataDir = dataPath.getPath(); 6641 } else { 6642 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6643 pkg.applicationInfo.dataDir = null; 6644 } 6645 } 6646 6647 pkgSetting.uidError = uidError; 6648 } 6649 6650 final String path = scanFile.getPath(); 6651 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6652 6653 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6654 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6655 6656 // Some system apps still use directory structure for native libraries 6657 // in which case we might end up not detecting abi solely based on apk 6658 // structure. Try to detect abi based on directory structure. 6659 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6660 pkg.applicationInfo.primaryCpuAbi == null) { 6661 setBundledAppAbisAndRoots(pkg, pkgSetting); 6662 setNativeLibraryPaths(pkg); 6663 } 6664 6665 } else { 6666 if ((scanFlags & SCAN_MOVE) != 0) { 6667 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6668 // but we already have this packages package info in the PackageSetting. We just 6669 // use that and derive the native library path based on the new codepath. 6670 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6671 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6672 } 6673 6674 // Set native library paths again. For moves, the path will be updated based on the 6675 // ABIs we've determined above. For non-moves, the path will be updated based on the 6676 // ABIs we determined during compilation, but the path will depend on the final 6677 // package path (after the rename away from the stage path). 6678 setNativeLibraryPaths(pkg); 6679 } 6680 6681 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6682 final int[] userIds = sUserManager.getUserIds(); 6683 synchronized (mInstallLock) { 6684 // Create a native library symlink only if we have native libraries 6685 // and if the native libraries are 32 bit libraries. We do not provide 6686 // this symlink for 64 bit libraries. 6687 if (pkg.applicationInfo.primaryCpuAbi != null && 6688 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6689 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6690 for (int userId : userIds) { 6691 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6692 nativeLibPath, userId) < 0) { 6693 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6694 "Failed linking native library dir (user=" + userId + ")"); 6695 } 6696 } 6697 } 6698 } 6699 6700 // This is a special case for the "system" package, where the ABI is 6701 // dictated by the zygote configuration (and init.rc). We should keep track 6702 // of this ABI so that we can deal with "normal" applications that run under 6703 // the same UID correctly. 6704 if (mPlatformPackage == pkg) { 6705 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6706 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6707 } 6708 6709 // If there's a mismatch between the abi-override in the package setting 6710 // and the abiOverride specified for the install. Warn about this because we 6711 // would've already compiled the app without taking the package setting into 6712 // account. 6713 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6714 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6715 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6716 " for package: " + pkg.packageName); 6717 } 6718 } 6719 6720 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6721 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6722 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6723 6724 // Copy the derived override back to the parsed package, so that we can 6725 // update the package settings accordingly. 6726 pkg.cpuAbiOverride = cpuAbiOverride; 6727 6728 if (DEBUG_ABI_SELECTION) { 6729 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6730 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6731 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6732 } 6733 6734 // Push the derived path down into PackageSettings so we know what to 6735 // clean up at uninstall time. 6736 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6737 6738 if (DEBUG_ABI_SELECTION) { 6739 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6740 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6741 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6742 } 6743 6744 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6745 // We don't do this here during boot because we can do it all 6746 // at once after scanning all existing packages. 6747 // 6748 // We also do this *before* we perform dexopt on this package, so that 6749 // we can avoid redundant dexopts, and also to make sure we've got the 6750 // code and package path correct. 6751 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6752 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6753 } 6754 6755 if ((scanFlags & SCAN_NO_DEX) == 0) { 6756 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6757 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6758 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6759 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6760 } 6761 } 6762 if (mFactoryTest && pkg.requestedPermissions.contains( 6763 android.Manifest.permission.FACTORY_TEST)) { 6764 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6765 } 6766 6767 ArrayList<PackageParser.Package> clientLibPkgs = null; 6768 6769 // writer 6770 synchronized (mPackages) { 6771 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6772 // Only system apps can add new shared libraries. 6773 if (pkg.libraryNames != null) { 6774 for (int i=0; i<pkg.libraryNames.size(); i++) { 6775 String name = pkg.libraryNames.get(i); 6776 boolean allowed = false; 6777 if (pkg.isUpdatedSystemApp()) { 6778 // New library entries can only be added through the 6779 // system image. This is important to get rid of a lot 6780 // of nasty edge cases: for example if we allowed a non- 6781 // system update of the app to add a library, then uninstalling 6782 // the update would make the library go away, and assumptions 6783 // we made such as through app install filtering would now 6784 // have allowed apps on the device which aren't compatible 6785 // with it. Better to just have the restriction here, be 6786 // conservative, and create many fewer cases that can negatively 6787 // impact the user experience. 6788 final PackageSetting sysPs = mSettings 6789 .getDisabledSystemPkgLPr(pkg.packageName); 6790 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6791 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6792 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6793 allowed = true; 6794 allowed = true; 6795 break; 6796 } 6797 } 6798 } 6799 } else { 6800 allowed = true; 6801 } 6802 if (allowed) { 6803 if (!mSharedLibraries.containsKey(name)) { 6804 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6805 } else if (!name.equals(pkg.packageName)) { 6806 Slog.w(TAG, "Package " + pkg.packageName + " library " 6807 + name + " already exists; skipping"); 6808 } 6809 } else { 6810 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6811 + name + " that is not declared on system image; skipping"); 6812 } 6813 } 6814 if ((scanFlags&SCAN_BOOTING) == 0) { 6815 // If we are not booting, we need to update any applications 6816 // that are clients of our shared library. If we are booting, 6817 // this will all be done once the scan is complete. 6818 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6819 } 6820 } 6821 } 6822 } 6823 6824 // We also need to dexopt any apps that are dependent on this library. Note that 6825 // if these fail, we should abort the install since installing the library will 6826 // result in some apps being broken. 6827 if (clientLibPkgs != null) { 6828 if ((scanFlags & SCAN_NO_DEX) == 0) { 6829 for (int i = 0; i < clientLibPkgs.size(); i++) { 6830 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6831 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6832 null /* instruction sets */, forceDex, 6833 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6834 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6835 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6836 "scanPackageLI failed to dexopt clientLibPkgs"); 6837 } 6838 } 6839 } 6840 } 6841 6842 // Also need to kill any apps that are dependent on the library. 6843 if (clientLibPkgs != null) { 6844 for (int i=0; i<clientLibPkgs.size(); i++) { 6845 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6846 killApplication(clientPkg.applicationInfo.packageName, 6847 clientPkg.applicationInfo.uid, "update lib"); 6848 } 6849 } 6850 6851 // Make sure we're not adding any bogus keyset info 6852 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6853 ksms.assertScannedPackageValid(pkg); 6854 6855 // writer 6856 synchronized (mPackages) { 6857 // We don't expect installation to fail beyond this point 6858 6859 // Add the new setting to mSettings 6860 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6861 // Add the new setting to mPackages 6862 mPackages.put(pkg.applicationInfo.packageName, pkg); 6863 // Make sure we don't accidentally delete its data. 6864 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6865 while (iter.hasNext()) { 6866 PackageCleanItem item = iter.next(); 6867 if (pkgName.equals(item.packageName)) { 6868 iter.remove(); 6869 } 6870 } 6871 6872 // Take care of first install / last update times. 6873 if (currentTime != 0) { 6874 if (pkgSetting.firstInstallTime == 0) { 6875 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6876 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6877 pkgSetting.lastUpdateTime = currentTime; 6878 } 6879 } else if (pkgSetting.firstInstallTime == 0) { 6880 // We need *something*. Take time time stamp of the file. 6881 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6882 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6883 if (scanFileTime != pkgSetting.timeStamp) { 6884 // A package on the system image has changed; consider this 6885 // to be an update. 6886 pkgSetting.lastUpdateTime = scanFileTime; 6887 } 6888 } 6889 6890 // Add the package's KeySets to the global KeySetManagerService 6891 ksms.addScannedPackageLPw(pkg); 6892 6893 int N = pkg.providers.size(); 6894 StringBuilder r = null; 6895 int i; 6896 for (i=0; i<N; i++) { 6897 PackageParser.Provider p = pkg.providers.get(i); 6898 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6899 p.info.processName, pkg.applicationInfo.uid); 6900 mProviders.addProvider(p); 6901 p.syncable = p.info.isSyncable; 6902 if (p.info.authority != null) { 6903 String names[] = p.info.authority.split(";"); 6904 p.info.authority = null; 6905 for (int j = 0; j < names.length; j++) { 6906 if (j == 1 && p.syncable) { 6907 // We only want the first authority for a provider to possibly be 6908 // syncable, so if we already added this provider using a different 6909 // authority clear the syncable flag. We copy the provider before 6910 // changing it because the mProviders object contains a reference 6911 // to a provider that we don't want to change. 6912 // Only do this for the second authority since the resulting provider 6913 // object can be the same for all future authorities for this provider. 6914 p = new PackageParser.Provider(p); 6915 p.syncable = false; 6916 } 6917 if (!mProvidersByAuthority.containsKey(names[j])) { 6918 mProvidersByAuthority.put(names[j], p); 6919 if (p.info.authority == null) { 6920 p.info.authority = names[j]; 6921 } else { 6922 p.info.authority = p.info.authority + ";" + names[j]; 6923 } 6924 if (DEBUG_PACKAGE_SCANNING) { 6925 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6926 Log.d(TAG, "Registered content provider: " + names[j] 6927 + ", className = " + p.info.name + ", isSyncable = " 6928 + p.info.isSyncable); 6929 } 6930 } else { 6931 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6932 Slog.w(TAG, "Skipping provider name " + names[j] + 6933 " (in package " + pkg.applicationInfo.packageName + 6934 "): name already used by " 6935 + ((other != null && other.getComponentName() != null) 6936 ? other.getComponentName().getPackageName() : "?")); 6937 } 6938 } 6939 } 6940 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6941 if (r == null) { 6942 r = new StringBuilder(256); 6943 } else { 6944 r.append(' '); 6945 } 6946 r.append(p.info.name); 6947 } 6948 } 6949 if (r != null) { 6950 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6951 } 6952 6953 N = pkg.services.size(); 6954 r = null; 6955 for (i=0; i<N; i++) { 6956 PackageParser.Service s = pkg.services.get(i); 6957 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6958 s.info.processName, pkg.applicationInfo.uid); 6959 mServices.addService(s); 6960 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6961 if (r == null) { 6962 r = new StringBuilder(256); 6963 } else { 6964 r.append(' '); 6965 } 6966 r.append(s.info.name); 6967 } 6968 } 6969 if (r != null) { 6970 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6971 } 6972 6973 N = pkg.receivers.size(); 6974 r = null; 6975 for (i=0; i<N; i++) { 6976 PackageParser.Activity a = pkg.receivers.get(i); 6977 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6978 a.info.processName, pkg.applicationInfo.uid); 6979 mReceivers.addActivity(a, "receiver"); 6980 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6981 if (r == null) { 6982 r = new StringBuilder(256); 6983 } else { 6984 r.append(' '); 6985 } 6986 r.append(a.info.name); 6987 } 6988 } 6989 if (r != null) { 6990 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6991 } 6992 6993 N = pkg.activities.size(); 6994 r = null; 6995 for (i=0; i<N; i++) { 6996 PackageParser.Activity a = pkg.activities.get(i); 6997 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6998 a.info.processName, pkg.applicationInfo.uid); 6999 mActivities.addActivity(a, "activity"); 7000 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7001 if (r == null) { 7002 r = new StringBuilder(256); 7003 } else { 7004 r.append(' '); 7005 } 7006 r.append(a.info.name); 7007 } 7008 } 7009 if (r != null) { 7010 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7011 } 7012 7013 N = pkg.permissionGroups.size(); 7014 r = null; 7015 for (i=0; i<N; i++) { 7016 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7017 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7018 if (cur == null) { 7019 mPermissionGroups.put(pg.info.name, pg); 7020 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7021 if (r == null) { 7022 r = new StringBuilder(256); 7023 } else { 7024 r.append(' '); 7025 } 7026 r.append(pg.info.name); 7027 } 7028 } else { 7029 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7030 + pg.info.packageName + " ignored: original from " 7031 + cur.info.packageName); 7032 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7033 if (r == null) { 7034 r = new StringBuilder(256); 7035 } else { 7036 r.append(' '); 7037 } 7038 r.append("DUP:"); 7039 r.append(pg.info.name); 7040 } 7041 } 7042 } 7043 if (r != null) { 7044 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7045 } 7046 7047 N = pkg.permissions.size(); 7048 r = null; 7049 for (i=0; i<N; i++) { 7050 PackageParser.Permission p = pkg.permissions.get(i); 7051 7052 // Now that permission groups have a special meaning, we ignore permission 7053 // groups for legacy apps to prevent unexpected behavior. In particular, 7054 // permissions for one app being granted to someone just becuase they happen 7055 // to be in a group defined by another app (before this had no implications). 7056 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7057 p.group = mPermissionGroups.get(p.info.group); 7058 // Warn for a permission in an unknown group. 7059 if (p.info.group != null && p.group == null) { 7060 Slog.w(TAG, "Permission " + p.info.name + " from package " 7061 + p.info.packageName + " in an unknown group " + p.info.group); 7062 } 7063 } 7064 7065 ArrayMap<String, BasePermission> permissionMap = 7066 p.tree ? mSettings.mPermissionTrees 7067 : mSettings.mPermissions; 7068 BasePermission bp = permissionMap.get(p.info.name); 7069 7070 // Allow system apps to redefine non-system permissions 7071 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7072 final boolean currentOwnerIsSystem = (bp.perm != null 7073 && isSystemApp(bp.perm.owner)); 7074 if (isSystemApp(p.owner)) { 7075 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7076 // It's a built-in permission and no owner, take ownership now 7077 bp.packageSetting = pkgSetting; 7078 bp.perm = p; 7079 bp.uid = pkg.applicationInfo.uid; 7080 bp.sourcePackage = p.info.packageName; 7081 } else if (!currentOwnerIsSystem) { 7082 String msg = "New decl " + p.owner + " of permission " 7083 + p.info.name + " is system; overriding " + bp.sourcePackage; 7084 reportSettingsProblem(Log.WARN, msg); 7085 bp = null; 7086 } 7087 } 7088 } 7089 7090 if (bp == null) { 7091 bp = new BasePermission(p.info.name, p.info.packageName, 7092 BasePermission.TYPE_NORMAL); 7093 permissionMap.put(p.info.name, bp); 7094 } 7095 7096 if (bp.perm == null) { 7097 if (bp.sourcePackage == null 7098 || bp.sourcePackage.equals(p.info.packageName)) { 7099 BasePermission tree = findPermissionTreeLP(p.info.name); 7100 if (tree == null 7101 || tree.sourcePackage.equals(p.info.packageName)) { 7102 bp.packageSetting = pkgSetting; 7103 bp.perm = p; 7104 bp.uid = pkg.applicationInfo.uid; 7105 bp.sourcePackage = p.info.packageName; 7106 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7107 if (r == null) { 7108 r = new StringBuilder(256); 7109 } else { 7110 r.append(' '); 7111 } 7112 r.append(p.info.name); 7113 } 7114 } else { 7115 Slog.w(TAG, "Permission " + p.info.name + " from package " 7116 + p.info.packageName + " ignored: base tree " 7117 + tree.name + " is from package " 7118 + tree.sourcePackage); 7119 } 7120 } else { 7121 Slog.w(TAG, "Permission " + p.info.name + " from package " 7122 + p.info.packageName + " ignored: original from " 7123 + bp.sourcePackage); 7124 } 7125 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7126 if (r == null) { 7127 r = new StringBuilder(256); 7128 } else { 7129 r.append(' '); 7130 } 7131 r.append("DUP:"); 7132 r.append(p.info.name); 7133 } 7134 if (bp.perm == p) { 7135 bp.protectionLevel = p.info.protectionLevel; 7136 } 7137 } 7138 7139 if (r != null) { 7140 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7141 } 7142 7143 N = pkg.instrumentation.size(); 7144 r = null; 7145 for (i=0; i<N; i++) { 7146 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7147 a.info.packageName = pkg.applicationInfo.packageName; 7148 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7149 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7150 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7151 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7152 a.info.dataDir = pkg.applicationInfo.dataDir; 7153 7154 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7155 // need other information about the application, like the ABI and what not ? 7156 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7157 mInstrumentation.put(a.getComponentName(), a); 7158 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7159 if (r == null) { 7160 r = new StringBuilder(256); 7161 } else { 7162 r.append(' '); 7163 } 7164 r.append(a.info.name); 7165 } 7166 } 7167 if (r != null) { 7168 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7169 } 7170 7171 if (pkg.protectedBroadcasts != null) { 7172 N = pkg.protectedBroadcasts.size(); 7173 for (i=0; i<N; i++) { 7174 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7175 } 7176 } 7177 7178 pkgSetting.setTimeStamp(scanFileTime); 7179 7180 // Create idmap files for pairs of (packages, overlay packages). 7181 // Note: "android", ie framework-res.apk, is handled by native layers. 7182 if (pkg.mOverlayTarget != null) { 7183 // This is an overlay package. 7184 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7185 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7186 mOverlays.put(pkg.mOverlayTarget, 7187 new ArrayMap<String, PackageParser.Package>()); 7188 } 7189 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7190 map.put(pkg.packageName, pkg); 7191 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7192 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7193 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7194 "scanPackageLI failed to createIdmap"); 7195 } 7196 } 7197 } else if (mOverlays.containsKey(pkg.packageName) && 7198 !pkg.packageName.equals("android")) { 7199 // This is a regular package, with one or more known overlay packages. 7200 createIdmapsForPackageLI(pkg); 7201 } 7202 } 7203 7204 return pkg; 7205 } 7206 7207 /** 7208 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7209 * is derived purely on the basis of the contents of {@code scanFile} and 7210 * {@code cpuAbiOverride}. 7211 * 7212 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7213 */ 7214 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7215 String cpuAbiOverride, boolean extractLibs) 7216 throws PackageManagerException { 7217 // TODO: We can probably be smarter about this stuff. For installed apps, 7218 // we can calculate this information at install time once and for all. For 7219 // system apps, we can probably assume that this information doesn't change 7220 // after the first boot scan. As things stand, we do lots of unnecessary work. 7221 7222 // Give ourselves some initial paths; we'll come back for another 7223 // pass once we've determined ABI below. 7224 setNativeLibraryPaths(pkg); 7225 7226 // We would never need to extract libs for forward-locked and external packages, 7227 // since the container service will do it for us. We shouldn't attempt to 7228 // extract libs from system app when it was not updated. 7229 if (pkg.isForwardLocked() || isExternal(pkg) || 7230 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7231 extractLibs = false; 7232 } 7233 7234 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7235 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7236 7237 NativeLibraryHelper.Handle handle = null; 7238 try { 7239 handle = NativeLibraryHelper.Handle.create(scanFile); 7240 // TODO(multiArch): This can be null for apps that didn't go through the 7241 // usual installation process. We can calculate it again, like we 7242 // do during install time. 7243 // 7244 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7245 // unnecessary. 7246 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7247 7248 // Null out the abis so that they can be recalculated. 7249 pkg.applicationInfo.primaryCpuAbi = null; 7250 pkg.applicationInfo.secondaryCpuAbi = null; 7251 if (isMultiArch(pkg.applicationInfo)) { 7252 // Warn if we've set an abiOverride for multi-lib packages.. 7253 // By definition, we need to copy both 32 and 64 bit libraries for 7254 // such packages. 7255 if (pkg.cpuAbiOverride != null 7256 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7257 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7258 } 7259 7260 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7261 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7262 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7263 if (extractLibs) { 7264 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7265 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7266 useIsaSpecificSubdirs); 7267 } else { 7268 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7269 } 7270 } 7271 7272 maybeThrowExceptionForMultiArchCopy( 7273 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7274 7275 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7276 if (extractLibs) { 7277 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7278 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7279 useIsaSpecificSubdirs); 7280 } else { 7281 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7282 } 7283 } 7284 7285 maybeThrowExceptionForMultiArchCopy( 7286 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7287 7288 if (abi64 >= 0) { 7289 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7290 } 7291 7292 if (abi32 >= 0) { 7293 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7294 if (abi64 >= 0) { 7295 pkg.applicationInfo.secondaryCpuAbi = abi; 7296 } else { 7297 pkg.applicationInfo.primaryCpuAbi = abi; 7298 } 7299 } 7300 } else { 7301 String[] abiList = (cpuAbiOverride != null) ? 7302 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7303 7304 // Enable gross and lame hacks for apps that are built with old 7305 // SDK tools. We must scan their APKs for renderscript bitcode and 7306 // not launch them if it's present. Don't bother checking on devices 7307 // that don't have 64 bit support. 7308 boolean needsRenderScriptOverride = false; 7309 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7310 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7311 abiList = Build.SUPPORTED_32_BIT_ABIS; 7312 needsRenderScriptOverride = true; 7313 } 7314 7315 final int copyRet; 7316 if (extractLibs) { 7317 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7318 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7319 } else { 7320 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7321 } 7322 7323 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7324 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7325 "Error unpackaging native libs for app, errorCode=" + copyRet); 7326 } 7327 7328 if (copyRet >= 0) { 7329 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7330 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7331 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7332 } else if (needsRenderScriptOverride) { 7333 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7334 } 7335 } 7336 } catch (IOException ioe) { 7337 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7338 } finally { 7339 IoUtils.closeQuietly(handle); 7340 } 7341 7342 // Now that we've calculated the ABIs and determined if it's an internal app, 7343 // we will go ahead and populate the nativeLibraryPath. 7344 setNativeLibraryPaths(pkg); 7345 } 7346 7347 /** 7348 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7349 * i.e, so that all packages can be run inside a single process if required. 7350 * 7351 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7352 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7353 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7354 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7355 * updating a package that belongs to a shared user. 7356 * 7357 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7358 * adds unnecessary complexity. 7359 */ 7360 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7361 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7362 String requiredInstructionSet = null; 7363 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7364 requiredInstructionSet = VMRuntime.getInstructionSet( 7365 scannedPackage.applicationInfo.primaryCpuAbi); 7366 } 7367 7368 PackageSetting requirer = null; 7369 for (PackageSetting ps : packagesForUser) { 7370 // If packagesForUser contains scannedPackage, we skip it. This will happen 7371 // when scannedPackage is an update of an existing package. Without this check, 7372 // we will never be able to change the ABI of any package belonging to a shared 7373 // user, even if it's compatible with other packages. 7374 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7375 if (ps.primaryCpuAbiString == null) { 7376 continue; 7377 } 7378 7379 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7380 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7381 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7382 // this but there's not much we can do. 7383 String errorMessage = "Instruction set mismatch, " 7384 + ((requirer == null) ? "[caller]" : requirer) 7385 + " requires " + requiredInstructionSet + " whereas " + ps 7386 + " requires " + instructionSet; 7387 Slog.w(TAG, errorMessage); 7388 } 7389 7390 if (requiredInstructionSet == null) { 7391 requiredInstructionSet = instructionSet; 7392 requirer = ps; 7393 } 7394 } 7395 } 7396 7397 if (requiredInstructionSet != null) { 7398 String adjustedAbi; 7399 if (requirer != null) { 7400 // requirer != null implies that either scannedPackage was null or that scannedPackage 7401 // did not require an ABI, in which case we have to adjust scannedPackage to match 7402 // the ABI of the set (which is the same as requirer's ABI) 7403 adjustedAbi = requirer.primaryCpuAbiString; 7404 if (scannedPackage != null) { 7405 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7406 } 7407 } else { 7408 // requirer == null implies that we're updating all ABIs in the set to 7409 // match scannedPackage. 7410 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7411 } 7412 7413 for (PackageSetting ps : packagesForUser) { 7414 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7415 if (ps.primaryCpuAbiString != null) { 7416 continue; 7417 } 7418 7419 ps.primaryCpuAbiString = adjustedAbi; 7420 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7421 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7422 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7423 7424 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7425 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7426 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7427 ps.primaryCpuAbiString = null; 7428 ps.pkg.applicationInfo.primaryCpuAbi = null; 7429 return; 7430 } else { 7431 mInstaller.rmdex(ps.codePathString, 7432 getDexCodeInstructionSet(getPreferredInstructionSet())); 7433 } 7434 } 7435 } 7436 } 7437 } 7438 } 7439 7440 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7441 synchronized (mPackages) { 7442 mResolverReplaced = true; 7443 // Set up information for custom user intent resolution activity. 7444 mResolveActivity.applicationInfo = pkg.applicationInfo; 7445 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7446 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7447 mResolveActivity.processName = pkg.applicationInfo.packageName; 7448 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7449 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7450 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7451 mResolveActivity.theme = 0; 7452 mResolveActivity.exported = true; 7453 mResolveActivity.enabled = true; 7454 mResolveInfo.activityInfo = mResolveActivity; 7455 mResolveInfo.priority = 0; 7456 mResolveInfo.preferredOrder = 0; 7457 mResolveInfo.match = 0; 7458 mResolveComponentName = mCustomResolverComponentName; 7459 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7460 mResolveComponentName); 7461 } 7462 } 7463 7464 private static String calculateBundledApkRoot(final String codePathString) { 7465 final File codePath = new File(codePathString); 7466 final File codeRoot; 7467 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7468 codeRoot = Environment.getRootDirectory(); 7469 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7470 codeRoot = Environment.getOemDirectory(); 7471 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7472 codeRoot = Environment.getVendorDirectory(); 7473 } else { 7474 // Unrecognized code path; take its top real segment as the apk root: 7475 // e.g. /something/app/blah.apk => /something 7476 try { 7477 File f = codePath.getCanonicalFile(); 7478 File parent = f.getParentFile(); // non-null because codePath is a file 7479 File tmp; 7480 while ((tmp = parent.getParentFile()) != null) { 7481 f = parent; 7482 parent = tmp; 7483 } 7484 codeRoot = f; 7485 Slog.w(TAG, "Unrecognized code path " 7486 + codePath + " - using " + codeRoot); 7487 } catch (IOException e) { 7488 // Can't canonicalize the code path -- shenanigans? 7489 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7490 return Environment.getRootDirectory().getPath(); 7491 } 7492 } 7493 return codeRoot.getPath(); 7494 } 7495 7496 /** 7497 * Derive and set the location of native libraries for the given package, 7498 * which varies depending on where and how the package was installed. 7499 */ 7500 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7501 final ApplicationInfo info = pkg.applicationInfo; 7502 final String codePath = pkg.codePath; 7503 final File codeFile = new File(codePath); 7504 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7505 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7506 7507 info.nativeLibraryRootDir = null; 7508 info.nativeLibraryRootRequiresIsa = false; 7509 info.nativeLibraryDir = null; 7510 info.secondaryNativeLibraryDir = null; 7511 7512 if (isApkFile(codeFile)) { 7513 // Monolithic install 7514 if (bundledApp) { 7515 // If "/system/lib64/apkname" exists, assume that is the per-package 7516 // native library directory to use; otherwise use "/system/lib/apkname". 7517 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7518 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7519 getPrimaryInstructionSet(info)); 7520 7521 // This is a bundled system app so choose the path based on the ABI. 7522 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7523 // is just the default path. 7524 final String apkName = deriveCodePathName(codePath); 7525 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7526 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7527 apkName).getAbsolutePath(); 7528 7529 if (info.secondaryCpuAbi != null) { 7530 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7531 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7532 secondaryLibDir, apkName).getAbsolutePath(); 7533 } 7534 } else if (asecApp) { 7535 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7536 .getAbsolutePath(); 7537 } else { 7538 final String apkName = deriveCodePathName(codePath); 7539 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7540 .getAbsolutePath(); 7541 } 7542 7543 info.nativeLibraryRootRequiresIsa = false; 7544 info.nativeLibraryDir = info.nativeLibraryRootDir; 7545 } else { 7546 // Cluster install 7547 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7548 info.nativeLibraryRootRequiresIsa = true; 7549 7550 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7551 getPrimaryInstructionSet(info)).getAbsolutePath(); 7552 7553 if (info.secondaryCpuAbi != null) { 7554 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7555 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7556 } 7557 } 7558 } 7559 7560 /** 7561 * Calculate the abis and roots for a bundled app. These can uniquely 7562 * be determined from the contents of the system partition, i.e whether 7563 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7564 * of this information, and instead assume that the system was built 7565 * sensibly. 7566 */ 7567 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7568 PackageSetting pkgSetting) { 7569 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7570 7571 // If "/system/lib64/apkname" exists, assume that is the per-package 7572 // native library directory to use; otherwise use "/system/lib/apkname". 7573 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7574 setBundledAppAbi(pkg, apkRoot, apkName); 7575 // pkgSetting might be null during rescan following uninstall of updates 7576 // to a bundled app, so accommodate that possibility. The settings in 7577 // that case will be established later from the parsed package. 7578 // 7579 // If the settings aren't null, sync them up with what we've just derived. 7580 // note that apkRoot isn't stored in the package settings. 7581 if (pkgSetting != null) { 7582 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7583 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7584 } 7585 } 7586 7587 /** 7588 * Deduces the ABI of a bundled app and sets the relevant fields on the 7589 * parsed pkg object. 7590 * 7591 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7592 * under which system libraries are installed. 7593 * @param apkName the name of the installed package. 7594 */ 7595 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7596 final File codeFile = new File(pkg.codePath); 7597 7598 final boolean has64BitLibs; 7599 final boolean has32BitLibs; 7600 if (isApkFile(codeFile)) { 7601 // Monolithic install 7602 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7603 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7604 } else { 7605 // Cluster install 7606 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7607 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7608 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7609 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7610 has64BitLibs = (new File(rootDir, isa)).exists(); 7611 } else { 7612 has64BitLibs = false; 7613 } 7614 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7615 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7616 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7617 has32BitLibs = (new File(rootDir, isa)).exists(); 7618 } else { 7619 has32BitLibs = false; 7620 } 7621 } 7622 7623 if (has64BitLibs && !has32BitLibs) { 7624 // The package has 64 bit libs, but not 32 bit libs. Its primary 7625 // ABI should be 64 bit. We can safely assume here that the bundled 7626 // native libraries correspond to the most preferred ABI in the list. 7627 7628 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7629 pkg.applicationInfo.secondaryCpuAbi = null; 7630 } else if (has32BitLibs && !has64BitLibs) { 7631 // The package has 32 bit libs but not 64 bit libs. Its primary 7632 // ABI should be 32 bit. 7633 7634 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7635 pkg.applicationInfo.secondaryCpuAbi = null; 7636 } else if (has32BitLibs && has64BitLibs) { 7637 // The application has both 64 and 32 bit bundled libraries. We check 7638 // here that the app declares multiArch support, and warn if it doesn't. 7639 // 7640 // We will be lenient here and record both ABIs. The primary will be the 7641 // ABI that's higher on the list, i.e, a device that's configured to prefer 7642 // 64 bit apps will see a 64 bit primary ABI, 7643 7644 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7645 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7646 } 7647 7648 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7649 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7650 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7651 } else { 7652 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7653 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7654 } 7655 } else { 7656 pkg.applicationInfo.primaryCpuAbi = null; 7657 pkg.applicationInfo.secondaryCpuAbi = null; 7658 } 7659 } 7660 7661 private void killApplication(String pkgName, int appId, String reason) { 7662 // Request the ActivityManager to kill the process(only for existing packages) 7663 // so that we do not end up in a confused state while the user is still using the older 7664 // version of the application while the new one gets installed. 7665 IActivityManager am = ActivityManagerNative.getDefault(); 7666 if (am != null) { 7667 try { 7668 am.killApplicationWithAppId(pkgName, appId, reason); 7669 } catch (RemoteException e) { 7670 } 7671 } 7672 } 7673 7674 void removePackageLI(PackageSetting ps, boolean chatty) { 7675 if (DEBUG_INSTALL) { 7676 if (chatty) 7677 Log.d(TAG, "Removing package " + ps.name); 7678 } 7679 7680 // writer 7681 synchronized (mPackages) { 7682 mPackages.remove(ps.name); 7683 final PackageParser.Package pkg = ps.pkg; 7684 if (pkg != null) { 7685 cleanPackageDataStructuresLILPw(pkg, chatty); 7686 } 7687 } 7688 } 7689 7690 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7691 if (DEBUG_INSTALL) { 7692 if (chatty) 7693 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7694 } 7695 7696 // writer 7697 synchronized (mPackages) { 7698 mPackages.remove(pkg.applicationInfo.packageName); 7699 cleanPackageDataStructuresLILPw(pkg, chatty); 7700 } 7701 } 7702 7703 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7704 int N = pkg.providers.size(); 7705 StringBuilder r = null; 7706 int i; 7707 for (i=0; i<N; i++) { 7708 PackageParser.Provider p = pkg.providers.get(i); 7709 mProviders.removeProvider(p); 7710 if (p.info.authority == null) { 7711 7712 /* There was another ContentProvider with this authority when 7713 * this app was installed so this authority is null, 7714 * Ignore it as we don't have to unregister the provider. 7715 */ 7716 continue; 7717 } 7718 String names[] = p.info.authority.split(";"); 7719 for (int j = 0; j < names.length; j++) { 7720 if (mProvidersByAuthority.get(names[j]) == p) { 7721 mProvidersByAuthority.remove(names[j]); 7722 if (DEBUG_REMOVE) { 7723 if (chatty) 7724 Log.d(TAG, "Unregistered content provider: " + names[j] 7725 + ", className = " + p.info.name + ", isSyncable = " 7726 + p.info.isSyncable); 7727 } 7728 } 7729 } 7730 if (DEBUG_REMOVE && chatty) { 7731 if (r == null) { 7732 r = new StringBuilder(256); 7733 } else { 7734 r.append(' '); 7735 } 7736 r.append(p.info.name); 7737 } 7738 } 7739 if (r != null) { 7740 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7741 } 7742 7743 N = pkg.services.size(); 7744 r = null; 7745 for (i=0; i<N; i++) { 7746 PackageParser.Service s = pkg.services.get(i); 7747 mServices.removeService(s); 7748 if (chatty) { 7749 if (r == null) { 7750 r = new StringBuilder(256); 7751 } else { 7752 r.append(' '); 7753 } 7754 r.append(s.info.name); 7755 } 7756 } 7757 if (r != null) { 7758 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7759 } 7760 7761 N = pkg.receivers.size(); 7762 r = null; 7763 for (i=0; i<N; i++) { 7764 PackageParser.Activity a = pkg.receivers.get(i); 7765 mReceivers.removeActivity(a, "receiver"); 7766 if (DEBUG_REMOVE && chatty) { 7767 if (r == null) { 7768 r = new StringBuilder(256); 7769 } else { 7770 r.append(' '); 7771 } 7772 r.append(a.info.name); 7773 } 7774 } 7775 if (r != null) { 7776 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7777 } 7778 7779 N = pkg.activities.size(); 7780 r = null; 7781 for (i=0; i<N; i++) { 7782 PackageParser.Activity a = pkg.activities.get(i); 7783 mActivities.removeActivity(a, "activity"); 7784 if (DEBUG_REMOVE && chatty) { 7785 if (r == null) { 7786 r = new StringBuilder(256); 7787 } else { 7788 r.append(' '); 7789 } 7790 r.append(a.info.name); 7791 } 7792 } 7793 if (r != null) { 7794 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7795 } 7796 7797 N = pkg.permissions.size(); 7798 r = null; 7799 for (i=0; i<N; i++) { 7800 PackageParser.Permission p = pkg.permissions.get(i); 7801 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7802 if (bp == null) { 7803 bp = mSettings.mPermissionTrees.get(p.info.name); 7804 } 7805 if (bp != null && bp.perm == p) { 7806 bp.perm = null; 7807 if (DEBUG_REMOVE && chatty) { 7808 if (r == null) { 7809 r = new StringBuilder(256); 7810 } else { 7811 r.append(' '); 7812 } 7813 r.append(p.info.name); 7814 } 7815 } 7816 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7817 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7818 if (appOpPerms != null) { 7819 appOpPerms.remove(pkg.packageName); 7820 } 7821 } 7822 } 7823 if (r != null) { 7824 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7825 } 7826 7827 N = pkg.requestedPermissions.size(); 7828 r = null; 7829 for (i=0; i<N; i++) { 7830 String perm = pkg.requestedPermissions.get(i); 7831 BasePermission bp = mSettings.mPermissions.get(perm); 7832 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7833 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7834 if (appOpPerms != null) { 7835 appOpPerms.remove(pkg.packageName); 7836 if (appOpPerms.isEmpty()) { 7837 mAppOpPermissionPackages.remove(perm); 7838 } 7839 } 7840 } 7841 } 7842 if (r != null) { 7843 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7844 } 7845 7846 N = pkg.instrumentation.size(); 7847 r = null; 7848 for (i=0; i<N; i++) { 7849 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7850 mInstrumentation.remove(a.getComponentName()); 7851 if (DEBUG_REMOVE && chatty) { 7852 if (r == null) { 7853 r = new StringBuilder(256); 7854 } else { 7855 r.append(' '); 7856 } 7857 r.append(a.info.name); 7858 } 7859 } 7860 if (r != null) { 7861 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7862 } 7863 7864 r = null; 7865 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7866 // Only system apps can hold shared libraries. 7867 if (pkg.libraryNames != null) { 7868 for (i=0; i<pkg.libraryNames.size(); i++) { 7869 String name = pkg.libraryNames.get(i); 7870 SharedLibraryEntry cur = mSharedLibraries.get(name); 7871 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7872 mSharedLibraries.remove(name); 7873 if (DEBUG_REMOVE && chatty) { 7874 if (r == null) { 7875 r = new StringBuilder(256); 7876 } else { 7877 r.append(' '); 7878 } 7879 r.append(name); 7880 } 7881 } 7882 } 7883 } 7884 } 7885 if (r != null) { 7886 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7887 } 7888 } 7889 7890 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7891 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7892 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7893 return true; 7894 } 7895 } 7896 return false; 7897 } 7898 7899 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7900 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7901 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7902 7903 private void updatePermissionsLPw(String changingPkg, 7904 PackageParser.Package pkgInfo, int flags) { 7905 // Make sure there are no dangling permission trees. 7906 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7907 while (it.hasNext()) { 7908 final BasePermission bp = it.next(); 7909 if (bp.packageSetting == null) { 7910 // We may not yet have parsed the package, so just see if 7911 // we still know about its settings. 7912 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7913 } 7914 if (bp.packageSetting == null) { 7915 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7916 + " from package " + bp.sourcePackage); 7917 it.remove(); 7918 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7919 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7920 Slog.i(TAG, "Removing old permission tree: " + bp.name 7921 + " from package " + bp.sourcePackage); 7922 flags |= UPDATE_PERMISSIONS_ALL; 7923 it.remove(); 7924 } 7925 } 7926 } 7927 7928 // Make sure all dynamic permissions have been assigned to a package, 7929 // and make sure there are no dangling permissions. 7930 it = mSettings.mPermissions.values().iterator(); 7931 while (it.hasNext()) { 7932 final BasePermission bp = it.next(); 7933 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7934 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7935 + bp.name + " pkg=" + bp.sourcePackage 7936 + " info=" + bp.pendingInfo); 7937 if (bp.packageSetting == null && bp.pendingInfo != null) { 7938 final BasePermission tree = findPermissionTreeLP(bp.name); 7939 if (tree != null && tree.perm != null) { 7940 bp.packageSetting = tree.packageSetting; 7941 bp.perm = new PackageParser.Permission(tree.perm.owner, 7942 new PermissionInfo(bp.pendingInfo)); 7943 bp.perm.info.packageName = tree.perm.info.packageName; 7944 bp.perm.info.name = bp.name; 7945 bp.uid = tree.uid; 7946 } 7947 } 7948 } 7949 if (bp.packageSetting == null) { 7950 // We may not yet have parsed the package, so just see if 7951 // we still know about its settings. 7952 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7953 } 7954 if (bp.packageSetting == null) { 7955 Slog.w(TAG, "Removing dangling permission: " + bp.name 7956 + " from package " + bp.sourcePackage); 7957 it.remove(); 7958 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7959 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7960 Slog.i(TAG, "Removing old permission: " + bp.name 7961 + " from package " + bp.sourcePackage); 7962 flags |= UPDATE_PERMISSIONS_ALL; 7963 it.remove(); 7964 } 7965 } 7966 } 7967 7968 // Now update the permissions for all packages, in particular 7969 // replace the granted permissions of the system packages. 7970 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7971 for (PackageParser.Package pkg : mPackages.values()) { 7972 if (pkg != pkgInfo) { 7973 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7974 changingPkg); 7975 } 7976 } 7977 } 7978 7979 if (pkgInfo != null) { 7980 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7981 } 7982 } 7983 7984 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7985 String packageOfInterest) { 7986 // IMPORTANT: There are two types of permissions: install and runtime. 7987 // Install time permissions are granted when the app is installed to 7988 // all device users and users added in the future. Runtime permissions 7989 // are granted at runtime explicitly to specific users. Normal and signature 7990 // protected permissions are install time permissions. Dangerous permissions 7991 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7992 // otherwise they are runtime permissions. This function does not manage 7993 // runtime permissions except for the case an app targeting Lollipop MR1 7994 // being upgraded to target a newer SDK, in which case dangerous permissions 7995 // are transformed from install time to runtime ones. 7996 7997 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7998 if (ps == null) { 7999 return; 8000 } 8001 8002 PermissionsState permissionsState = ps.getPermissionsState(); 8003 PermissionsState origPermissions = permissionsState; 8004 8005 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8006 8007 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8008 8009 boolean changedInstallPermission = false; 8010 8011 if (replace) { 8012 ps.installPermissionsFixed = false; 8013 if (!ps.isSharedUser()) { 8014 origPermissions = new PermissionsState(permissionsState); 8015 permissionsState.reset(); 8016 } 8017 } 8018 8019 permissionsState.setGlobalGids(mGlobalGids); 8020 8021 final int N = pkg.requestedPermissions.size(); 8022 for (int i=0; i<N; i++) { 8023 final String name = pkg.requestedPermissions.get(i); 8024 final BasePermission bp = mSettings.mPermissions.get(name); 8025 8026 if (DEBUG_INSTALL) { 8027 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8028 } 8029 8030 if (bp == null || bp.packageSetting == null) { 8031 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8032 Slog.w(TAG, "Unknown permission " + name 8033 + " in package " + pkg.packageName); 8034 } 8035 continue; 8036 } 8037 8038 final String perm = bp.name; 8039 boolean allowedSig = false; 8040 int grant = GRANT_DENIED; 8041 8042 // Keep track of app op permissions. 8043 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8044 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8045 if (pkgs == null) { 8046 pkgs = new ArraySet<>(); 8047 mAppOpPermissionPackages.put(bp.name, pkgs); 8048 } 8049 pkgs.add(pkg.packageName); 8050 } 8051 8052 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8053 switch (level) { 8054 case PermissionInfo.PROTECTION_NORMAL: { 8055 // For all apps normal permissions are install time ones. 8056 grant = GRANT_INSTALL; 8057 } break; 8058 8059 case PermissionInfo.PROTECTION_DANGEROUS: { 8060 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8061 // For legacy apps dangerous permissions are install time ones. 8062 grant = GRANT_INSTALL_LEGACY; 8063 } else if (origPermissions.hasInstallPermission(bp.name)) { 8064 // For legacy apps that became modern, install becomes runtime. 8065 grant = GRANT_UPGRADE; 8066 } else { 8067 // For modern apps keep runtime permissions unchanged. 8068 grant = GRANT_RUNTIME; 8069 } 8070 } break; 8071 8072 case PermissionInfo.PROTECTION_SIGNATURE: { 8073 // For all apps signature permissions are install time ones. 8074 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8075 if (allowedSig) { 8076 grant = GRANT_INSTALL; 8077 } 8078 } break; 8079 } 8080 8081 if (DEBUG_INSTALL) { 8082 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8083 } 8084 8085 if (grant != GRANT_DENIED) { 8086 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8087 // If this is an existing, non-system package, then 8088 // we can't add any new permissions to it. 8089 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8090 // Except... if this is a permission that was added 8091 // to the platform (note: need to only do this when 8092 // updating the platform). 8093 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8094 grant = GRANT_DENIED; 8095 } 8096 } 8097 } 8098 8099 switch (grant) { 8100 case GRANT_INSTALL: { 8101 // Revoke this as runtime permission to handle the case of 8102 // a runtime permission being downgraded to an install one. 8103 for (int userId : UserManagerService.getInstance().getUserIds()) { 8104 if (origPermissions.getRuntimePermissionState( 8105 bp.name, userId) != null) { 8106 // Revoke the runtime permission and clear the flags. 8107 origPermissions.revokeRuntimePermission(bp, userId); 8108 origPermissions.updatePermissionFlags(bp, userId, 8109 PackageManager.MASK_PERMISSION_FLAGS, 0); 8110 // If we revoked a permission permission, we have to write. 8111 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8112 changedRuntimePermissionUserIds, userId); 8113 } 8114 } 8115 // Grant an install permission. 8116 if (permissionsState.grantInstallPermission(bp) != 8117 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8118 changedInstallPermission = true; 8119 } 8120 } break; 8121 8122 case GRANT_INSTALL_LEGACY: { 8123 // Grant an install permission. 8124 if (permissionsState.grantInstallPermission(bp) != 8125 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8126 changedInstallPermission = true; 8127 } 8128 } break; 8129 8130 case GRANT_RUNTIME: { 8131 // Grant previously granted runtime permissions. 8132 for (int userId : UserManagerService.getInstance().getUserIds()) { 8133 PermissionState permissionState = origPermissions 8134 .getRuntimePermissionState(bp.name, userId); 8135 final int flags = permissionState != null 8136 ? permissionState.getFlags() : 0; 8137 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8138 if (permissionsState.grantRuntimePermission(bp, userId) == 8139 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8140 // If we cannot put the permission as it was, we have to write. 8141 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8142 changedRuntimePermissionUserIds, userId); 8143 } 8144 } 8145 // Propagate the permission flags. 8146 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8147 } 8148 } break; 8149 8150 case GRANT_UPGRADE: { 8151 // Grant runtime permissions for a previously held install permission. 8152 PermissionState permissionState = origPermissions 8153 .getInstallPermissionState(bp.name); 8154 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8155 8156 if (origPermissions.revokeInstallPermission(bp) 8157 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8158 // We will be transferring the permission flags, so clear them. 8159 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8160 PackageManager.MASK_PERMISSION_FLAGS, 0); 8161 changedInstallPermission = true; 8162 } 8163 8164 // If the permission is not to be promoted to runtime we ignore it and 8165 // also its other flags as they are not applicable to install permissions. 8166 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8167 for (int userId : currentUserIds) { 8168 if (permissionsState.grantRuntimePermission(bp, userId) != 8169 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8170 // Transfer the permission flags. 8171 permissionsState.updatePermissionFlags(bp, userId, 8172 flags, flags); 8173 // If we granted the permission, we have to write. 8174 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8175 changedRuntimePermissionUserIds, userId); 8176 } 8177 } 8178 } 8179 } break; 8180 8181 default: { 8182 if (packageOfInterest == null 8183 || packageOfInterest.equals(pkg.packageName)) { 8184 Slog.w(TAG, "Not granting permission " + perm 8185 + " to package " + pkg.packageName 8186 + " because it was previously installed without"); 8187 } 8188 } break; 8189 } 8190 } else { 8191 if (permissionsState.revokeInstallPermission(bp) != 8192 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8193 // Also drop the permission flags. 8194 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8195 PackageManager.MASK_PERMISSION_FLAGS, 0); 8196 changedInstallPermission = true; 8197 Slog.i(TAG, "Un-granting permission " + perm 8198 + " from package " + pkg.packageName 8199 + " (protectionLevel=" + bp.protectionLevel 8200 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8201 + ")"); 8202 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8203 // Don't print warning for app op permissions, since it is fine for them 8204 // not to be granted, there is a UI for the user to decide. 8205 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8206 Slog.w(TAG, "Not granting permission " + perm 8207 + " to package " + pkg.packageName 8208 + " (protectionLevel=" + bp.protectionLevel 8209 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8210 + ")"); 8211 } 8212 } 8213 } 8214 } 8215 8216 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8217 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8218 // This is the first that we have heard about this package, so the 8219 // permissions we have now selected are fixed until explicitly 8220 // changed. 8221 ps.installPermissionsFixed = true; 8222 } 8223 8224 // Persist the runtime permissions state for users with changes. 8225 for (int userId : changedRuntimePermissionUserIds) { 8226 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8227 } 8228 } 8229 8230 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8231 boolean allowed = false; 8232 final int NP = PackageParser.NEW_PERMISSIONS.length; 8233 for (int ip=0; ip<NP; ip++) { 8234 final PackageParser.NewPermissionInfo npi 8235 = PackageParser.NEW_PERMISSIONS[ip]; 8236 if (npi.name.equals(perm) 8237 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8238 allowed = true; 8239 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8240 + pkg.packageName); 8241 break; 8242 } 8243 } 8244 return allowed; 8245 } 8246 8247 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8248 BasePermission bp, PermissionsState origPermissions) { 8249 boolean allowed; 8250 allowed = (compareSignatures( 8251 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8252 == PackageManager.SIGNATURE_MATCH) 8253 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8254 == PackageManager.SIGNATURE_MATCH); 8255 if (!allowed && (bp.protectionLevel 8256 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8257 if (isSystemApp(pkg)) { 8258 // For updated system applications, a system permission 8259 // is granted only if it had been defined by the original application. 8260 if (pkg.isUpdatedSystemApp()) { 8261 final PackageSetting sysPs = mSettings 8262 .getDisabledSystemPkgLPr(pkg.packageName); 8263 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8264 // If the original was granted this permission, we take 8265 // that grant decision as read and propagate it to the 8266 // update. 8267 if (sysPs.isPrivileged()) { 8268 allowed = true; 8269 } 8270 } else { 8271 // The system apk may have been updated with an older 8272 // version of the one on the data partition, but which 8273 // granted a new system permission that it didn't have 8274 // before. In this case we do want to allow the app to 8275 // now get the new permission if the ancestral apk is 8276 // privileged to get it. 8277 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8278 for (int j=0; 8279 j<sysPs.pkg.requestedPermissions.size(); j++) { 8280 if (perm.equals( 8281 sysPs.pkg.requestedPermissions.get(j))) { 8282 allowed = true; 8283 break; 8284 } 8285 } 8286 } 8287 } 8288 } else { 8289 allowed = isPrivilegedApp(pkg); 8290 } 8291 } 8292 } 8293 if (!allowed && (bp.protectionLevel 8294 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8295 // For development permissions, a development permission 8296 // is granted only if it was already granted. 8297 allowed = origPermissions.hasInstallPermission(perm); 8298 } 8299 return allowed; 8300 } 8301 8302 final class ActivityIntentResolver 8303 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8304 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8305 boolean defaultOnly, int userId) { 8306 if (!sUserManager.exists(userId)) return null; 8307 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8308 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8309 } 8310 8311 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8312 int userId) { 8313 if (!sUserManager.exists(userId)) return null; 8314 mFlags = flags; 8315 return super.queryIntent(intent, resolvedType, 8316 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8317 } 8318 8319 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8320 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8321 if (!sUserManager.exists(userId)) return null; 8322 if (packageActivities == null) { 8323 return null; 8324 } 8325 mFlags = flags; 8326 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8327 final int N = packageActivities.size(); 8328 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8329 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8330 8331 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8332 for (int i = 0; i < N; ++i) { 8333 intentFilters = packageActivities.get(i).intents; 8334 if (intentFilters != null && intentFilters.size() > 0) { 8335 PackageParser.ActivityIntentInfo[] array = 8336 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8337 intentFilters.toArray(array); 8338 listCut.add(array); 8339 } 8340 } 8341 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8342 } 8343 8344 public final void addActivity(PackageParser.Activity a, String type) { 8345 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8346 mActivities.put(a.getComponentName(), a); 8347 if (DEBUG_SHOW_INFO) 8348 Log.v( 8349 TAG, " " + type + " " + 8350 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8351 if (DEBUG_SHOW_INFO) 8352 Log.v(TAG, " Class=" + a.info.name); 8353 final int NI = a.intents.size(); 8354 for (int j=0; j<NI; j++) { 8355 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8356 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8357 intent.setPriority(0); 8358 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8359 + a.className + " with priority > 0, forcing to 0"); 8360 } 8361 if (DEBUG_SHOW_INFO) { 8362 Log.v(TAG, " IntentFilter:"); 8363 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8364 } 8365 if (!intent.debugCheck()) { 8366 Log.w(TAG, "==> For Activity " + a.info.name); 8367 } 8368 addFilter(intent); 8369 } 8370 } 8371 8372 public final void removeActivity(PackageParser.Activity a, String type) { 8373 mActivities.remove(a.getComponentName()); 8374 if (DEBUG_SHOW_INFO) { 8375 Log.v(TAG, " " + type + " " 8376 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8377 : a.info.name) + ":"); 8378 Log.v(TAG, " Class=" + a.info.name); 8379 } 8380 final int NI = a.intents.size(); 8381 for (int j=0; j<NI; j++) { 8382 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8383 if (DEBUG_SHOW_INFO) { 8384 Log.v(TAG, " IntentFilter:"); 8385 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8386 } 8387 removeFilter(intent); 8388 } 8389 } 8390 8391 @Override 8392 protected boolean allowFilterResult( 8393 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8394 ActivityInfo filterAi = filter.activity.info; 8395 for (int i=dest.size()-1; i>=0; i--) { 8396 ActivityInfo destAi = dest.get(i).activityInfo; 8397 if (destAi.name == filterAi.name 8398 && destAi.packageName == filterAi.packageName) { 8399 return false; 8400 } 8401 } 8402 return true; 8403 } 8404 8405 @Override 8406 protected ActivityIntentInfo[] newArray(int size) { 8407 return new ActivityIntentInfo[size]; 8408 } 8409 8410 @Override 8411 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8412 if (!sUserManager.exists(userId)) return true; 8413 PackageParser.Package p = filter.activity.owner; 8414 if (p != null) { 8415 PackageSetting ps = (PackageSetting)p.mExtras; 8416 if (ps != null) { 8417 // System apps are never considered stopped for purposes of 8418 // filtering, because there may be no way for the user to 8419 // actually re-launch them. 8420 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8421 && ps.getStopped(userId); 8422 } 8423 } 8424 return false; 8425 } 8426 8427 @Override 8428 protected boolean isPackageForFilter(String packageName, 8429 PackageParser.ActivityIntentInfo info) { 8430 return packageName.equals(info.activity.owner.packageName); 8431 } 8432 8433 @Override 8434 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8435 int match, int userId) { 8436 if (!sUserManager.exists(userId)) return null; 8437 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8438 return null; 8439 } 8440 final PackageParser.Activity activity = info.activity; 8441 if (mSafeMode && (activity.info.applicationInfo.flags 8442 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8443 return null; 8444 } 8445 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8446 if (ps == null) { 8447 return null; 8448 } 8449 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8450 ps.readUserState(userId), userId); 8451 if (ai == null) { 8452 return null; 8453 } 8454 final ResolveInfo res = new ResolveInfo(); 8455 res.activityInfo = ai; 8456 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8457 res.filter = info; 8458 } 8459 if (info != null) { 8460 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8461 } 8462 res.priority = info.getPriority(); 8463 res.preferredOrder = activity.owner.mPreferredOrder; 8464 //System.out.println("Result: " + res.activityInfo.className + 8465 // " = " + res.priority); 8466 res.match = match; 8467 res.isDefault = info.hasDefault; 8468 res.labelRes = info.labelRes; 8469 res.nonLocalizedLabel = info.nonLocalizedLabel; 8470 if (userNeedsBadging(userId)) { 8471 res.noResourceId = true; 8472 } else { 8473 res.icon = info.icon; 8474 } 8475 res.iconResourceId = info.icon; 8476 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8477 return res; 8478 } 8479 8480 @Override 8481 protected void sortResults(List<ResolveInfo> results) { 8482 Collections.sort(results, mResolvePrioritySorter); 8483 } 8484 8485 @Override 8486 protected void dumpFilter(PrintWriter out, String prefix, 8487 PackageParser.ActivityIntentInfo filter) { 8488 out.print(prefix); out.print( 8489 Integer.toHexString(System.identityHashCode(filter.activity))); 8490 out.print(' '); 8491 filter.activity.printComponentShortName(out); 8492 out.print(" filter "); 8493 out.println(Integer.toHexString(System.identityHashCode(filter))); 8494 } 8495 8496 @Override 8497 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8498 return filter.activity; 8499 } 8500 8501 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8502 PackageParser.Activity activity = (PackageParser.Activity)label; 8503 out.print(prefix); out.print( 8504 Integer.toHexString(System.identityHashCode(activity))); 8505 out.print(' '); 8506 activity.printComponentShortName(out); 8507 if (count > 1) { 8508 out.print(" ("); out.print(count); out.print(" filters)"); 8509 } 8510 out.println(); 8511 } 8512 8513// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8514// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8515// final List<ResolveInfo> retList = Lists.newArrayList(); 8516// while (i.hasNext()) { 8517// final ResolveInfo resolveInfo = i.next(); 8518// if (isEnabledLP(resolveInfo.activityInfo)) { 8519// retList.add(resolveInfo); 8520// } 8521// } 8522// return retList; 8523// } 8524 8525 // Keys are String (activity class name), values are Activity. 8526 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8527 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8528 private int mFlags; 8529 } 8530 8531 private final class ServiceIntentResolver 8532 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8533 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8534 boolean defaultOnly, int userId) { 8535 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8536 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8537 } 8538 8539 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8540 int userId) { 8541 if (!sUserManager.exists(userId)) return null; 8542 mFlags = flags; 8543 return super.queryIntent(intent, resolvedType, 8544 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8545 } 8546 8547 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8548 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8549 if (!sUserManager.exists(userId)) return null; 8550 if (packageServices == null) { 8551 return null; 8552 } 8553 mFlags = flags; 8554 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8555 final int N = packageServices.size(); 8556 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8557 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8558 8559 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8560 for (int i = 0; i < N; ++i) { 8561 intentFilters = packageServices.get(i).intents; 8562 if (intentFilters != null && intentFilters.size() > 0) { 8563 PackageParser.ServiceIntentInfo[] array = 8564 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8565 intentFilters.toArray(array); 8566 listCut.add(array); 8567 } 8568 } 8569 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8570 } 8571 8572 public final void addService(PackageParser.Service s) { 8573 mServices.put(s.getComponentName(), s); 8574 if (DEBUG_SHOW_INFO) { 8575 Log.v(TAG, " " 8576 + (s.info.nonLocalizedLabel != null 8577 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8578 Log.v(TAG, " Class=" + s.info.name); 8579 } 8580 final int NI = s.intents.size(); 8581 int j; 8582 for (j=0; j<NI; j++) { 8583 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8584 if (DEBUG_SHOW_INFO) { 8585 Log.v(TAG, " IntentFilter:"); 8586 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8587 } 8588 if (!intent.debugCheck()) { 8589 Log.w(TAG, "==> For Service " + s.info.name); 8590 } 8591 addFilter(intent); 8592 } 8593 } 8594 8595 public final void removeService(PackageParser.Service s) { 8596 mServices.remove(s.getComponentName()); 8597 if (DEBUG_SHOW_INFO) { 8598 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8599 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8600 Log.v(TAG, " Class=" + s.info.name); 8601 } 8602 final int NI = s.intents.size(); 8603 int j; 8604 for (j=0; j<NI; j++) { 8605 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8606 if (DEBUG_SHOW_INFO) { 8607 Log.v(TAG, " IntentFilter:"); 8608 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8609 } 8610 removeFilter(intent); 8611 } 8612 } 8613 8614 @Override 8615 protected boolean allowFilterResult( 8616 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8617 ServiceInfo filterSi = filter.service.info; 8618 for (int i=dest.size()-1; i>=0; i--) { 8619 ServiceInfo destAi = dest.get(i).serviceInfo; 8620 if (destAi.name == filterSi.name 8621 && destAi.packageName == filterSi.packageName) { 8622 return false; 8623 } 8624 } 8625 return true; 8626 } 8627 8628 @Override 8629 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8630 return new PackageParser.ServiceIntentInfo[size]; 8631 } 8632 8633 @Override 8634 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8635 if (!sUserManager.exists(userId)) return true; 8636 PackageParser.Package p = filter.service.owner; 8637 if (p != null) { 8638 PackageSetting ps = (PackageSetting)p.mExtras; 8639 if (ps != null) { 8640 // System apps are never considered stopped for purposes of 8641 // filtering, because there may be no way for the user to 8642 // actually re-launch them. 8643 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8644 && ps.getStopped(userId); 8645 } 8646 } 8647 return false; 8648 } 8649 8650 @Override 8651 protected boolean isPackageForFilter(String packageName, 8652 PackageParser.ServiceIntentInfo info) { 8653 return packageName.equals(info.service.owner.packageName); 8654 } 8655 8656 @Override 8657 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8658 int match, int userId) { 8659 if (!sUserManager.exists(userId)) return null; 8660 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8661 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8662 return null; 8663 } 8664 final PackageParser.Service service = info.service; 8665 if (mSafeMode && (service.info.applicationInfo.flags 8666 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8667 return null; 8668 } 8669 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8670 if (ps == null) { 8671 return null; 8672 } 8673 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8674 ps.readUserState(userId), userId); 8675 if (si == null) { 8676 return null; 8677 } 8678 final ResolveInfo res = new ResolveInfo(); 8679 res.serviceInfo = si; 8680 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8681 res.filter = filter; 8682 } 8683 res.priority = info.getPriority(); 8684 res.preferredOrder = service.owner.mPreferredOrder; 8685 res.match = match; 8686 res.isDefault = info.hasDefault; 8687 res.labelRes = info.labelRes; 8688 res.nonLocalizedLabel = info.nonLocalizedLabel; 8689 res.icon = info.icon; 8690 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8691 return res; 8692 } 8693 8694 @Override 8695 protected void sortResults(List<ResolveInfo> results) { 8696 Collections.sort(results, mResolvePrioritySorter); 8697 } 8698 8699 @Override 8700 protected void dumpFilter(PrintWriter out, String prefix, 8701 PackageParser.ServiceIntentInfo filter) { 8702 out.print(prefix); out.print( 8703 Integer.toHexString(System.identityHashCode(filter.service))); 8704 out.print(' '); 8705 filter.service.printComponentShortName(out); 8706 out.print(" filter "); 8707 out.println(Integer.toHexString(System.identityHashCode(filter))); 8708 } 8709 8710 @Override 8711 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8712 return filter.service; 8713 } 8714 8715 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8716 PackageParser.Service service = (PackageParser.Service)label; 8717 out.print(prefix); out.print( 8718 Integer.toHexString(System.identityHashCode(service))); 8719 out.print(' '); 8720 service.printComponentShortName(out); 8721 if (count > 1) { 8722 out.print(" ("); out.print(count); out.print(" filters)"); 8723 } 8724 out.println(); 8725 } 8726 8727// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8728// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8729// final List<ResolveInfo> retList = Lists.newArrayList(); 8730// while (i.hasNext()) { 8731// final ResolveInfo resolveInfo = (ResolveInfo) i; 8732// if (isEnabledLP(resolveInfo.serviceInfo)) { 8733// retList.add(resolveInfo); 8734// } 8735// } 8736// return retList; 8737// } 8738 8739 // Keys are String (activity class name), values are Activity. 8740 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8741 = new ArrayMap<ComponentName, PackageParser.Service>(); 8742 private int mFlags; 8743 }; 8744 8745 private final class ProviderIntentResolver 8746 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8747 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8748 boolean defaultOnly, int userId) { 8749 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8750 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8751 } 8752 8753 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8754 int userId) { 8755 if (!sUserManager.exists(userId)) 8756 return null; 8757 mFlags = flags; 8758 return super.queryIntent(intent, resolvedType, 8759 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8760 } 8761 8762 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8763 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8764 if (!sUserManager.exists(userId)) 8765 return null; 8766 if (packageProviders == null) { 8767 return null; 8768 } 8769 mFlags = flags; 8770 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8771 final int N = packageProviders.size(); 8772 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8773 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8774 8775 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8776 for (int i = 0; i < N; ++i) { 8777 intentFilters = packageProviders.get(i).intents; 8778 if (intentFilters != null && intentFilters.size() > 0) { 8779 PackageParser.ProviderIntentInfo[] array = 8780 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8781 intentFilters.toArray(array); 8782 listCut.add(array); 8783 } 8784 } 8785 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8786 } 8787 8788 public final void addProvider(PackageParser.Provider p) { 8789 if (mProviders.containsKey(p.getComponentName())) { 8790 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8791 return; 8792 } 8793 8794 mProviders.put(p.getComponentName(), p); 8795 if (DEBUG_SHOW_INFO) { 8796 Log.v(TAG, " " 8797 + (p.info.nonLocalizedLabel != null 8798 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8799 Log.v(TAG, " Class=" + p.info.name); 8800 } 8801 final int NI = p.intents.size(); 8802 int j; 8803 for (j = 0; j < NI; j++) { 8804 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8805 if (DEBUG_SHOW_INFO) { 8806 Log.v(TAG, " IntentFilter:"); 8807 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8808 } 8809 if (!intent.debugCheck()) { 8810 Log.w(TAG, "==> For Provider " + p.info.name); 8811 } 8812 addFilter(intent); 8813 } 8814 } 8815 8816 public final void removeProvider(PackageParser.Provider p) { 8817 mProviders.remove(p.getComponentName()); 8818 if (DEBUG_SHOW_INFO) { 8819 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8820 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8821 Log.v(TAG, " Class=" + p.info.name); 8822 } 8823 final int NI = p.intents.size(); 8824 int j; 8825 for (j = 0; j < NI; j++) { 8826 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8827 if (DEBUG_SHOW_INFO) { 8828 Log.v(TAG, " IntentFilter:"); 8829 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8830 } 8831 removeFilter(intent); 8832 } 8833 } 8834 8835 @Override 8836 protected boolean allowFilterResult( 8837 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8838 ProviderInfo filterPi = filter.provider.info; 8839 for (int i = dest.size() - 1; i >= 0; i--) { 8840 ProviderInfo destPi = dest.get(i).providerInfo; 8841 if (destPi.name == filterPi.name 8842 && destPi.packageName == filterPi.packageName) { 8843 return false; 8844 } 8845 } 8846 return true; 8847 } 8848 8849 @Override 8850 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8851 return new PackageParser.ProviderIntentInfo[size]; 8852 } 8853 8854 @Override 8855 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8856 if (!sUserManager.exists(userId)) 8857 return true; 8858 PackageParser.Package p = filter.provider.owner; 8859 if (p != null) { 8860 PackageSetting ps = (PackageSetting) p.mExtras; 8861 if (ps != null) { 8862 // System apps are never considered stopped for purposes of 8863 // filtering, because there may be no way for the user to 8864 // actually re-launch them. 8865 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8866 && ps.getStopped(userId); 8867 } 8868 } 8869 return false; 8870 } 8871 8872 @Override 8873 protected boolean isPackageForFilter(String packageName, 8874 PackageParser.ProviderIntentInfo info) { 8875 return packageName.equals(info.provider.owner.packageName); 8876 } 8877 8878 @Override 8879 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8880 int match, int userId) { 8881 if (!sUserManager.exists(userId)) 8882 return null; 8883 final PackageParser.ProviderIntentInfo info = filter; 8884 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8885 return null; 8886 } 8887 final PackageParser.Provider provider = info.provider; 8888 if (mSafeMode && (provider.info.applicationInfo.flags 8889 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8890 return null; 8891 } 8892 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8893 if (ps == null) { 8894 return null; 8895 } 8896 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8897 ps.readUserState(userId), userId); 8898 if (pi == null) { 8899 return null; 8900 } 8901 final ResolveInfo res = new ResolveInfo(); 8902 res.providerInfo = pi; 8903 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8904 res.filter = filter; 8905 } 8906 res.priority = info.getPriority(); 8907 res.preferredOrder = provider.owner.mPreferredOrder; 8908 res.match = match; 8909 res.isDefault = info.hasDefault; 8910 res.labelRes = info.labelRes; 8911 res.nonLocalizedLabel = info.nonLocalizedLabel; 8912 res.icon = info.icon; 8913 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8914 return res; 8915 } 8916 8917 @Override 8918 protected void sortResults(List<ResolveInfo> results) { 8919 Collections.sort(results, mResolvePrioritySorter); 8920 } 8921 8922 @Override 8923 protected void dumpFilter(PrintWriter out, String prefix, 8924 PackageParser.ProviderIntentInfo filter) { 8925 out.print(prefix); 8926 out.print( 8927 Integer.toHexString(System.identityHashCode(filter.provider))); 8928 out.print(' '); 8929 filter.provider.printComponentShortName(out); 8930 out.print(" filter "); 8931 out.println(Integer.toHexString(System.identityHashCode(filter))); 8932 } 8933 8934 @Override 8935 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8936 return filter.provider; 8937 } 8938 8939 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8940 PackageParser.Provider provider = (PackageParser.Provider)label; 8941 out.print(prefix); out.print( 8942 Integer.toHexString(System.identityHashCode(provider))); 8943 out.print(' '); 8944 provider.printComponentShortName(out); 8945 if (count > 1) { 8946 out.print(" ("); out.print(count); out.print(" filters)"); 8947 } 8948 out.println(); 8949 } 8950 8951 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8952 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8953 private int mFlags; 8954 }; 8955 8956 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8957 new Comparator<ResolveInfo>() { 8958 public int compare(ResolveInfo r1, ResolveInfo r2) { 8959 int v1 = r1.priority; 8960 int v2 = r2.priority; 8961 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8962 if (v1 != v2) { 8963 return (v1 > v2) ? -1 : 1; 8964 } 8965 v1 = r1.preferredOrder; 8966 v2 = r2.preferredOrder; 8967 if (v1 != v2) { 8968 return (v1 > v2) ? -1 : 1; 8969 } 8970 if (r1.isDefault != r2.isDefault) { 8971 return r1.isDefault ? -1 : 1; 8972 } 8973 v1 = r1.match; 8974 v2 = r2.match; 8975 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8976 if (v1 != v2) { 8977 return (v1 > v2) ? -1 : 1; 8978 } 8979 if (r1.system != r2.system) { 8980 return r1.system ? -1 : 1; 8981 } 8982 return 0; 8983 } 8984 }; 8985 8986 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8987 new Comparator<ProviderInfo>() { 8988 public int compare(ProviderInfo p1, ProviderInfo p2) { 8989 final int v1 = p1.initOrder; 8990 final int v2 = p2.initOrder; 8991 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8992 } 8993 }; 8994 8995 final void sendPackageBroadcast(final String action, final String pkg, 8996 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8997 final int[] userIds) { 8998 mHandler.post(new Runnable() { 8999 @Override 9000 public void run() { 9001 try { 9002 final IActivityManager am = ActivityManagerNative.getDefault(); 9003 if (am == null) return; 9004 final int[] resolvedUserIds; 9005 if (userIds == null) { 9006 resolvedUserIds = am.getRunningUserIds(); 9007 } else { 9008 resolvedUserIds = userIds; 9009 } 9010 for (int id : resolvedUserIds) { 9011 final Intent intent = new Intent(action, 9012 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9013 if (extras != null) { 9014 intent.putExtras(extras); 9015 } 9016 if (targetPkg != null) { 9017 intent.setPackage(targetPkg); 9018 } 9019 // Modify the UID when posting to other users 9020 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9021 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9022 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9023 intent.putExtra(Intent.EXTRA_UID, uid); 9024 } 9025 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9026 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9027 if (DEBUG_BROADCASTS) { 9028 RuntimeException here = new RuntimeException("here"); 9029 here.fillInStackTrace(); 9030 Slog.d(TAG, "Sending to user " + id + ": " 9031 + intent.toShortString(false, true, false, false) 9032 + " " + intent.getExtras(), here); 9033 } 9034 am.broadcastIntent(null, intent, null, finishedReceiver, 9035 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9036 null, finishedReceiver != null, false, id); 9037 } 9038 } catch (RemoteException ex) { 9039 } 9040 } 9041 }); 9042 } 9043 9044 /** 9045 * Check if the external storage media is available. This is true if there 9046 * is a mounted external storage medium or if the external storage is 9047 * emulated. 9048 */ 9049 private boolean isExternalMediaAvailable() { 9050 return mMediaMounted || Environment.isExternalStorageEmulated(); 9051 } 9052 9053 @Override 9054 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9055 // writer 9056 synchronized (mPackages) { 9057 if (!isExternalMediaAvailable()) { 9058 // If the external storage is no longer mounted at this point, 9059 // the caller may not have been able to delete all of this 9060 // packages files and can not delete any more. Bail. 9061 return null; 9062 } 9063 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9064 if (lastPackage != null) { 9065 pkgs.remove(lastPackage); 9066 } 9067 if (pkgs.size() > 0) { 9068 return pkgs.get(0); 9069 } 9070 } 9071 return null; 9072 } 9073 9074 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9075 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9076 userId, andCode ? 1 : 0, packageName); 9077 if (mSystemReady) { 9078 msg.sendToTarget(); 9079 } else { 9080 if (mPostSystemReadyMessages == null) { 9081 mPostSystemReadyMessages = new ArrayList<>(); 9082 } 9083 mPostSystemReadyMessages.add(msg); 9084 } 9085 } 9086 9087 void startCleaningPackages() { 9088 // reader 9089 synchronized (mPackages) { 9090 if (!isExternalMediaAvailable()) { 9091 return; 9092 } 9093 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9094 return; 9095 } 9096 } 9097 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9098 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9099 IActivityManager am = ActivityManagerNative.getDefault(); 9100 if (am != null) { 9101 try { 9102 am.startService(null, intent, null, UserHandle.USER_OWNER); 9103 } catch (RemoteException e) { 9104 } 9105 } 9106 } 9107 9108 @Override 9109 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9110 int installFlags, String installerPackageName, VerificationParams verificationParams, 9111 String packageAbiOverride) { 9112 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9113 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9114 } 9115 9116 @Override 9117 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9118 int installFlags, String installerPackageName, VerificationParams verificationParams, 9119 String packageAbiOverride, int userId) { 9120 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9121 9122 final int callingUid = Binder.getCallingUid(); 9123 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9124 9125 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9126 try { 9127 if (observer != null) { 9128 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9129 } 9130 } catch (RemoteException re) { 9131 } 9132 return; 9133 } 9134 9135 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9136 installFlags |= PackageManager.INSTALL_FROM_ADB; 9137 9138 } else { 9139 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9140 // about installerPackageName. 9141 9142 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9143 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9144 } 9145 9146 UserHandle user; 9147 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9148 user = UserHandle.ALL; 9149 } else { 9150 user = new UserHandle(userId); 9151 } 9152 9153 // Only system components can circumvent runtime permissions when installing. 9154 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9155 && mContext.checkCallingOrSelfPermission(Manifest.permission 9156 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9157 throw new SecurityException("You need the " 9158 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9159 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9160 } 9161 9162 verificationParams.setInstallerUid(callingUid); 9163 9164 final File originFile = new File(originPath); 9165 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9166 9167 final Message msg = mHandler.obtainMessage(INIT_COPY); 9168 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9169 null, verificationParams, user, packageAbiOverride); 9170 mHandler.sendMessage(msg); 9171 } 9172 9173 void installStage(String packageName, File stagedDir, String stagedCid, 9174 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9175 String installerPackageName, int installerUid, UserHandle user) { 9176 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9177 params.referrerUri, installerUid, null); 9178 verifParams.setInstallerUid(installerUid); 9179 9180 final OriginInfo origin; 9181 if (stagedDir != null) { 9182 origin = OriginInfo.fromStagedFile(stagedDir); 9183 } else { 9184 origin = OriginInfo.fromStagedContainer(stagedCid); 9185 } 9186 9187 final Message msg = mHandler.obtainMessage(INIT_COPY); 9188 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9189 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9190 mHandler.sendMessage(msg); 9191 } 9192 9193 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9194 Bundle extras = new Bundle(1); 9195 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9196 9197 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9198 packageName, extras, null, null, new int[] {userId}); 9199 try { 9200 IActivityManager am = ActivityManagerNative.getDefault(); 9201 final boolean isSystem = 9202 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9203 if (isSystem && am.isUserRunning(userId, false)) { 9204 // The just-installed/enabled app is bundled on the system, so presumed 9205 // to be able to run automatically without needing an explicit launch. 9206 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9207 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9208 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9209 .setPackage(packageName); 9210 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9211 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9212 } 9213 } catch (RemoteException e) { 9214 // shouldn't happen 9215 Slog.w(TAG, "Unable to bootstrap installed package", e); 9216 } 9217 } 9218 9219 @Override 9220 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9221 int userId) { 9222 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9223 PackageSetting pkgSetting; 9224 final int uid = Binder.getCallingUid(); 9225 enforceCrossUserPermission(uid, userId, true, true, 9226 "setApplicationHiddenSetting for user " + userId); 9227 9228 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9229 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9230 return false; 9231 } 9232 9233 long callingId = Binder.clearCallingIdentity(); 9234 try { 9235 boolean sendAdded = false; 9236 boolean sendRemoved = false; 9237 // writer 9238 synchronized (mPackages) { 9239 pkgSetting = mSettings.mPackages.get(packageName); 9240 if (pkgSetting == null) { 9241 return false; 9242 } 9243 if (pkgSetting.getHidden(userId) != hidden) { 9244 pkgSetting.setHidden(hidden, userId); 9245 mSettings.writePackageRestrictionsLPr(userId); 9246 if (hidden) { 9247 sendRemoved = true; 9248 } else { 9249 sendAdded = true; 9250 } 9251 } 9252 } 9253 if (sendAdded) { 9254 sendPackageAddedForUser(packageName, pkgSetting, userId); 9255 return true; 9256 } 9257 if (sendRemoved) { 9258 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9259 "hiding pkg"); 9260 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9261 } 9262 } finally { 9263 Binder.restoreCallingIdentity(callingId); 9264 } 9265 return false; 9266 } 9267 9268 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9269 int userId) { 9270 final PackageRemovedInfo info = new PackageRemovedInfo(); 9271 info.removedPackage = packageName; 9272 info.removedUsers = new int[] {userId}; 9273 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9274 info.sendBroadcast(false, false, false); 9275 } 9276 9277 /** 9278 * Returns true if application is not found or there was an error. Otherwise it returns 9279 * the hidden state of the package for the given user. 9280 */ 9281 @Override 9282 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9283 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9284 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9285 false, "getApplicationHidden for user " + userId); 9286 PackageSetting pkgSetting; 9287 long callingId = Binder.clearCallingIdentity(); 9288 try { 9289 // writer 9290 synchronized (mPackages) { 9291 pkgSetting = mSettings.mPackages.get(packageName); 9292 if (pkgSetting == null) { 9293 return true; 9294 } 9295 return pkgSetting.getHidden(userId); 9296 } 9297 } finally { 9298 Binder.restoreCallingIdentity(callingId); 9299 } 9300 } 9301 9302 /** 9303 * @hide 9304 */ 9305 @Override 9306 public int installExistingPackageAsUser(String packageName, int userId) { 9307 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9308 null); 9309 PackageSetting pkgSetting; 9310 final int uid = Binder.getCallingUid(); 9311 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9312 + userId); 9313 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9314 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9315 } 9316 9317 long callingId = Binder.clearCallingIdentity(); 9318 try { 9319 boolean sendAdded = false; 9320 9321 // writer 9322 synchronized (mPackages) { 9323 pkgSetting = mSettings.mPackages.get(packageName); 9324 if (pkgSetting == null) { 9325 return PackageManager.INSTALL_FAILED_INVALID_URI; 9326 } 9327 if (!pkgSetting.getInstalled(userId)) { 9328 pkgSetting.setInstalled(true, userId); 9329 pkgSetting.setHidden(false, userId); 9330 mSettings.writePackageRestrictionsLPr(userId); 9331 sendAdded = true; 9332 } 9333 } 9334 9335 if (sendAdded) { 9336 sendPackageAddedForUser(packageName, pkgSetting, userId); 9337 } 9338 } finally { 9339 Binder.restoreCallingIdentity(callingId); 9340 } 9341 9342 return PackageManager.INSTALL_SUCCEEDED; 9343 } 9344 9345 boolean isUserRestricted(int userId, String restrictionKey) { 9346 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9347 if (restrictions.getBoolean(restrictionKey, false)) { 9348 Log.w(TAG, "User is restricted: " + restrictionKey); 9349 return true; 9350 } 9351 return false; 9352 } 9353 9354 @Override 9355 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9356 mContext.enforceCallingOrSelfPermission( 9357 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9358 "Only package verification agents can verify applications"); 9359 9360 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9361 final PackageVerificationResponse response = new PackageVerificationResponse( 9362 verificationCode, Binder.getCallingUid()); 9363 msg.arg1 = id; 9364 msg.obj = response; 9365 mHandler.sendMessage(msg); 9366 } 9367 9368 @Override 9369 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9370 long millisecondsToDelay) { 9371 mContext.enforceCallingOrSelfPermission( 9372 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9373 "Only package verification agents can extend verification timeouts"); 9374 9375 final PackageVerificationState state = mPendingVerification.get(id); 9376 final PackageVerificationResponse response = new PackageVerificationResponse( 9377 verificationCodeAtTimeout, Binder.getCallingUid()); 9378 9379 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9380 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9381 } 9382 if (millisecondsToDelay < 0) { 9383 millisecondsToDelay = 0; 9384 } 9385 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9386 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9387 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9388 } 9389 9390 if ((state != null) && !state.timeoutExtended()) { 9391 state.extendTimeout(); 9392 9393 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9394 msg.arg1 = id; 9395 msg.obj = response; 9396 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9397 } 9398 } 9399 9400 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9401 int verificationCode, UserHandle user) { 9402 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9403 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9404 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9405 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9406 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9407 9408 mContext.sendBroadcastAsUser(intent, user, 9409 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9410 } 9411 9412 private ComponentName matchComponentForVerifier(String packageName, 9413 List<ResolveInfo> receivers) { 9414 ActivityInfo targetReceiver = null; 9415 9416 final int NR = receivers.size(); 9417 for (int i = 0; i < NR; i++) { 9418 final ResolveInfo info = receivers.get(i); 9419 if (info.activityInfo == null) { 9420 continue; 9421 } 9422 9423 if (packageName.equals(info.activityInfo.packageName)) { 9424 targetReceiver = info.activityInfo; 9425 break; 9426 } 9427 } 9428 9429 if (targetReceiver == null) { 9430 return null; 9431 } 9432 9433 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9434 } 9435 9436 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9437 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9438 if (pkgInfo.verifiers.length == 0) { 9439 return null; 9440 } 9441 9442 final int N = pkgInfo.verifiers.length; 9443 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9444 for (int i = 0; i < N; i++) { 9445 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9446 9447 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9448 receivers); 9449 if (comp == null) { 9450 continue; 9451 } 9452 9453 final int verifierUid = getUidForVerifier(verifierInfo); 9454 if (verifierUid == -1) { 9455 continue; 9456 } 9457 9458 if (DEBUG_VERIFY) { 9459 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9460 + " with the correct signature"); 9461 } 9462 sufficientVerifiers.add(comp); 9463 verificationState.addSufficientVerifier(verifierUid); 9464 } 9465 9466 return sufficientVerifiers; 9467 } 9468 9469 private int getUidForVerifier(VerifierInfo verifierInfo) { 9470 synchronized (mPackages) { 9471 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9472 if (pkg == null) { 9473 return -1; 9474 } else if (pkg.mSignatures.length != 1) { 9475 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9476 + " has more than one signature; ignoring"); 9477 return -1; 9478 } 9479 9480 /* 9481 * If the public key of the package's signature does not match 9482 * our expected public key, then this is a different package and 9483 * we should skip. 9484 */ 9485 9486 final byte[] expectedPublicKey; 9487 try { 9488 final Signature verifierSig = pkg.mSignatures[0]; 9489 final PublicKey publicKey = verifierSig.getPublicKey(); 9490 expectedPublicKey = publicKey.getEncoded(); 9491 } catch (CertificateException e) { 9492 return -1; 9493 } 9494 9495 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9496 9497 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9498 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9499 + " does not have the expected public key; ignoring"); 9500 return -1; 9501 } 9502 9503 return pkg.applicationInfo.uid; 9504 } 9505 } 9506 9507 @Override 9508 public void finishPackageInstall(int token) { 9509 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9510 9511 if (DEBUG_INSTALL) { 9512 Slog.v(TAG, "BM finishing package install for " + token); 9513 } 9514 9515 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9516 mHandler.sendMessage(msg); 9517 } 9518 9519 /** 9520 * Get the verification agent timeout. 9521 * 9522 * @return verification timeout in milliseconds 9523 */ 9524 private long getVerificationTimeout() { 9525 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9526 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9527 DEFAULT_VERIFICATION_TIMEOUT); 9528 } 9529 9530 /** 9531 * Get the default verification agent response code. 9532 * 9533 * @return default verification response code 9534 */ 9535 private int getDefaultVerificationResponse() { 9536 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9537 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9538 DEFAULT_VERIFICATION_RESPONSE); 9539 } 9540 9541 /** 9542 * Check whether or not package verification has been enabled. 9543 * 9544 * @return true if verification should be performed 9545 */ 9546 private boolean isVerificationEnabled(int userId, int installFlags) { 9547 if (!DEFAULT_VERIFY_ENABLE) { 9548 return false; 9549 } 9550 9551 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9552 9553 // Check if installing from ADB 9554 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9555 // Do not run verification in a test harness environment 9556 if (ActivityManager.isRunningInTestHarness()) { 9557 return false; 9558 } 9559 if (ensureVerifyAppsEnabled) { 9560 return true; 9561 } 9562 // Check if the developer does not want package verification for ADB installs 9563 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9564 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9565 return false; 9566 } 9567 } 9568 9569 if (ensureVerifyAppsEnabled) { 9570 return true; 9571 } 9572 9573 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9574 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9575 } 9576 9577 @Override 9578 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9579 throws RemoteException { 9580 mContext.enforceCallingOrSelfPermission( 9581 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9582 "Only intentfilter verification agents can verify applications"); 9583 9584 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9585 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9586 Binder.getCallingUid(), verificationCode, failedDomains); 9587 msg.arg1 = id; 9588 msg.obj = response; 9589 mHandler.sendMessage(msg); 9590 } 9591 9592 @Override 9593 public int getIntentVerificationStatus(String packageName, int userId) { 9594 synchronized (mPackages) { 9595 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9596 } 9597 } 9598 9599 @Override 9600 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9601 boolean result = false; 9602 synchronized (mPackages) { 9603 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9604 } 9605 if (result) { 9606 scheduleWritePackageRestrictionsLocked(userId); 9607 } 9608 return result; 9609 } 9610 9611 @Override 9612 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9613 synchronized (mPackages) { 9614 return mSettings.getIntentFilterVerificationsLPr(packageName); 9615 } 9616 } 9617 9618 @Override 9619 public List<IntentFilter> getAllIntentFilters(String packageName) { 9620 if (TextUtils.isEmpty(packageName)) { 9621 return Collections.<IntentFilter>emptyList(); 9622 } 9623 synchronized (mPackages) { 9624 PackageParser.Package pkg = mPackages.get(packageName); 9625 if (pkg == null || pkg.activities == null) { 9626 return Collections.<IntentFilter>emptyList(); 9627 } 9628 final int count = pkg.activities.size(); 9629 ArrayList<IntentFilter> result = new ArrayList<>(); 9630 for (int n=0; n<count; n++) { 9631 PackageParser.Activity activity = pkg.activities.get(n); 9632 if (activity.intents != null || activity.intents.size() > 0) { 9633 result.addAll(activity.intents); 9634 } 9635 } 9636 return result; 9637 } 9638 } 9639 9640 @Override 9641 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9642 synchronized (mPackages) { 9643 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9644 if (packageName != null) { 9645 result |= updateIntentVerificationStatus(packageName, 9646 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9647 UserHandle.myUserId()); 9648 } 9649 return result; 9650 } 9651 } 9652 9653 @Override 9654 public String getDefaultBrowserPackageName(int userId) { 9655 synchronized (mPackages) { 9656 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9657 } 9658 } 9659 9660 /** 9661 * Get the "allow unknown sources" setting. 9662 * 9663 * @return the current "allow unknown sources" setting 9664 */ 9665 private int getUnknownSourcesSettings() { 9666 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9667 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9668 -1); 9669 } 9670 9671 @Override 9672 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9673 final int uid = Binder.getCallingUid(); 9674 // writer 9675 synchronized (mPackages) { 9676 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9677 if (targetPackageSetting == null) { 9678 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9679 } 9680 9681 PackageSetting installerPackageSetting; 9682 if (installerPackageName != null) { 9683 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9684 if (installerPackageSetting == null) { 9685 throw new IllegalArgumentException("Unknown installer package: " 9686 + installerPackageName); 9687 } 9688 } else { 9689 installerPackageSetting = null; 9690 } 9691 9692 Signature[] callerSignature; 9693 Object obj = mSettings.getUserIdLPr(uid); 9694 if (obj != null) { 9695 if (obj instanceof SharedUserSetting) { 9696 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9697 } else if (obj instanceof PackageSetting) { 9698 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9699 } else { 9700 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9701 } 9702 } else { 9703 throw new SecurityException("Unknown calling uid " + uid); 9704 } 9705 9706 // Verify: can't set installerPackageName to a package that is 9707 // not signed with the same cert as the caller. 9708 if (installerPackageSetting != null) { 9709 if (compareSignatures(callerSignature, 9710 installerPackageSetting.signatures.mSignatures) 9711 != PackageManager.SIGNATURE_MATCH) { 9712 throw new SecurityException( 9713 "Caller does not have same cert as new installer package " 9714 + installerPackageName); 9715 } 9716 } 9717 9718 // Verify: if target already has an installer package, it must 9719 // be signed with the same cert as the caller. 9720 if (targetPackageSetting.installerPackageName != null) { 9721 PackageSetting setting = mSettings.mPackages.get( 9722 targetPackageSetting.installerPackageName); 9723 // If the currently set package isn't valid, then it's always 9724 // okay to change it. 9725 if (setting != null) { 9726 if (compareSignatures(callerSignature, 9727 setting.signatures.mSignatures) 9728 != PackageManager.SIGNATURE_MATCH) { 9729 throw new SecurityException( 9730 "Caller does not have same cert as old installer package " 9731 + targetPackageSetting.installerPackageName); 9732 } 9733 } 9734 } 9735 9736 // Okay! 9737 targetPackageSetting.installerPackageName = installerPackageName; 9738 scheduleWriteSettingsLocked(); 9739 } 9740 } 9741 9742 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9743 // Queue up an async operation since the package installation may take a little while. 9744 mHandler.post(new Runnable() { 9745 public void run() { 9746 mHandler.removeCallbacks(this); 9747 // Result object to be returned 9748 PackageInstalledInfo res = new PackageInstalledInfo(); 9749 res.returnCode = currentStatus; 9750 res.uid = -1; 9751 res.pkg = null; 9752 res.removedInfo = new PackageRemovedInfo(); 9753 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9754 args.doPreInstall(res.returnCode); 9755 synchronized (mInstallLock) { 9756 installPackageLI(args, res); 9757 } 9758 args.doPostInstall(res.returnCode, res.uid); 9759 } 9760 9761 // A restore should be performed at this point if (a) the install 9762 // succeeded, (b) the operation is not an update, and (c) the new 9763 // package has not opted out of backup participation. 9764 final boolean update = res.removedInfo.removedPackage != null; 9765 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9766 boolean doRestore = !update 9767 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9768 9769 // Set up the post-install work request bookkeeping. This will be used 9770 // and cleaned up by the post-install event handling regardless of whether 9771 // there's a restore pass performed. Token values are >= 1. 9772 int token; 9773 if (mNextInstallToken < 0) mNextInstallToken = 1; 9774 token = mNextInstallToken++; 9775 9776 PostInstallData data = new PostInstallData(args, res); 9777 mRunningInstalls.put(token, data); 9778 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9779 9780 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9781 // Pass responsibility to the Backup Manager. It will perform a 9782 // restore if appropriate, then pass responsibility back to the 9783 // Package Manager to run the post-install observer callbacks 9784 // and broadcasts. 9785 IBackupManager bm = IBackupManager.Stub.asInterface( 9786 ServiceManager.getService(Context.BACKUP_SERVICE)); 9787 if (bm != null) { 9788 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9789 + " to BM for possible restore"); 9790 try { 9791 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9792 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9793 } else { 9794 doRestore = false; 9795 } 9796 } catch (RemoteException e) { 9797 // can't happen; the backup manager is local 9798 } catch (Exception e) { 9799 Slog.e(TAG, "Exception trying to enqueue restore", e); 9800 doRestore = false; 9801 } 9802 } else { 9803 Slog.e(TAG, "Backup Manager not found!"); 9804 doRestore = false; 9805 } 9806 } 9807 9808 if (!doRestore) { 9809 // No restore possible, or the Backup Manager was mysteriously not 9810 // available -- just fire the post-install work request directly. 9811 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9812 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9813 mHandler.sendMessage(msg); 9814 } 9815 } 9816 }); 9817 } 9818 9819 private abstract class HandlerParams { 9820 private static final int MAX_RETRIES = 4; 9821 9822 /** 9823 * Number of times startCopy() has been attempted and had a non-fatal 9824 * error. 9825 */ 9826 private int mRetries = 0; 9827 9828 /** User handle for the user requesting the information or installation. */ 9829 private final UserHandle mUser; 9830 9831 HandlerParams(UserHandle user) { 9832 mUser = user; 9833 } 9834 9835 UserHandle getUser() { 9836 return mUser; 9837 } 9838 9839 final boolean startCopy() { 9840 boolean res; 9841 try { 9842 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9843 9844 if (++mRetries > MAX_RETRIES) { 9845 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9846 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9847 handleServiceError(); 9848 return false; 9849 } else { 9850 handleStartCopy(); 9851 res = true; 9852 } 9853 } catch (RemoteException e) { 9854 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9855 mHandler.sendEmptyMessage(MCS_RECONNECT); 9856 res = false; 9857 } 9858 handleReturnCode(); 9859 return res; 9860 } 9861 9862 final void serviceError() { 9863 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9864 handleServiceError(); 9865 handleReturnCode(); 9866 } 9867 9868 abstract void handleStartCopy() throws RemoteException; 9869 abstract void handleServiceError(); 9870 abstract void handleReturnCode(); 9871 } 9872 9873 class MeasureParams extends HandlerParams { 9874 private final PackageStats mStats; 9875 private boolean mSuccess; 9876 9877 private final IPackageStatsObserver mObserver; 9878 9879 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9880 super(new UserHandle(stats.userHandle)); 9881 mObserver = observer; 9882 mStats = stats; 9883 } 9884 9885 @Override 9886 public String toString() { 9887 return "MeasureParams{" 9888 + Integer.toHexString(System.identityHashCode(this)) 9889 + " " + mStats.packageName + "}"; 9890 } 9891 9892 @Override 9893 void handleStartCopy() throws RemoteException { 9894 synchronized (mInstallLock) { 9895 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9896 } 9897 9898 if (mSuccess) { 9899 final boolean mounted; 9900 if (Environment.isExternalStorageEmulated()) { 9901 mounted = true; 9902 } else { 9903 final String status = Environment.getExternalStorageState(); 9904 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9905 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9906 } 9907 9908 if (mounted) { 9909 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9910 9911 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9912 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9913 9914 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9915 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9916 9917 // Always subtract cache size, since it's a subdirectory 9918 mStats.externalDataSize -= mStats.externalCacheSize; 9919 9920 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9921 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9922 9923 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9924 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9925 } 9926 } 9927 } 9928 9929 @Override 9930 void handleReturnCode() { 9931 if (mObserver != null) { 9932 try { 9933 mObserver.onGetStatsCompleted(mStats, mSuccess); 9934 } catch (RemoteException e) { 9935 Slog.i(TAG, "Observer no longer exists."); 9936 } 9937 } 9938 } 9939 9940 @Override 9941 void handleServiceError() { 9942 Slog.e(TAG, "Could not measure application " + mStats.packageName 9943 + " external storage"); 9944 } 9945 } 9946 9947 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9948 throws RemoteException { 9949 long result = 0; 9950 for (File path : paths) { 9951 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9952 } 9953 return result; 9954 } 9955 9956 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9957 for (File path : paths) { 9958 try { 9959 mcs.clearDirectory(path.getAbsolutePath()); 9960 } catch (RemoteException e) { 9961 } 9962 } 9963 } 9964 9965 static class OriginInfo { 9966 /** 9967 * Location where install is coming from, before it has been 9968 * copied/renamed into place. This could be a single monolithic APK 9969 * file, or a cluster directory. This location may be untrusted. 9970 */ 9971 final File file; 9972 final String cid; 9973 9974 /** 9975 * Flag indicating that {@link #file} or {@link #cid} has already been 9976 * staged, meaning downstream users don't need to defensively copy the 9977 * contents. 9978 */ 9979 final boolean staged; 9980 9981 /** 9982 * Flag indicating that {@link #file} or {@link #cid} is an already 9983 * installed app that is being moved. 9984 */ 9985 final boolean existing; 9986 9987 final String resolvedPath; 9988 final File resolvedFile; 9989 9990 static OriginInfo fromNothing() { 9991 return new OriginInfo(null, null, false, false); 9992 } 9993 9994 static OriginInfo fromUntrustedFile(File file) { 9995 return new OriginInfo(file, null, false, false); 9996 } 9997 9998 static OriginInfo fromExistingFile(File file) { 9999 return new OriginInfo(file, null, false, true); 10000 } 10001 10002 static OriginInfo fromStagedFile(File file) { 10003 return new OriginInfo(file, null, true, false); 10004 } 10005 10006 static OriginInfo fromStagedContainer(String cid) { 10007 return new OriginInfo(null, cid, true, false); 10008 } 10009 10010 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10011 this.file = file; 10012 this.cid = cid; 10013 this.staged = staged; 10014 this.existing = existing; 10015 10016 if (cid != null) { 10017 resolvedPath = PackageHelper.getSdDir(cid); 10018 resolvedFile = new File(resolvedPath); 10019 } else if (file != null) { 10020 resolvedPath = file.getAbsolutePath(); 10021 resolvedFile = file; 10022 } else { 10023 resolvedPath = null; 10024 resolvedFile = null; 10025 } 10026 } 10027 } 10028 10029 class MoveInfo { 10030 final int moveId; 10031 final String fromUuid; 10032 final String toUuid; 10033 final String packageName; 10034 final String dataAppName; 10035 final int appId; 10036 final String seinfo; 10037 10038 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10039 String dataAppName, int appId, String seinfo) { 10040 this.moveId = moveId; 10041 this.fromUuid = fromUuid; 10042 this.toUuid = toUuid; 10043 this.packageName = packageName; 10044 this.dataAppName = dataAppName; 10045 this.appId = appId; 10046 this.seinfo = seinfo; 10047 } 10048 } 10049 10050 class InstallParams extends HandlerParams { 10051 final OriginInfo origin; 10052 final MoveInfo move; 10053 final IPackageInstallObserver2 observer; 10054 int installFlags; 10055 final String installerPackageName; 10056 final String volumeUuid; 10057 final VerificationParams verificationParams; 10058 private InstallArgs mArgs; 10059 private int mRet; 10060 final String packageAbiOverride; 10061 10062 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10063 int installFlags, String installerPackageName, String volumeUuid, 10064 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10065 super(user); 10066 this.origin = origin; 10067 this.move = move; 10068 this.observer = observer; 10069 this.installFlags = installFlags; 10070 this.installerPackageName = installerPackageName; 10071 this.volumeUuid = volumeUuid; 10072 this.verificationParams = verificationParams; 10073 this.packageAbiOverride = packageAbiOverride; 10074 } 10075 10076 @Override 10077 public String toString() { 10078 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10079 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10080 } 10081 10082 public ManifestDigest getManifestDigest() { 10083 if (verificationParams == null) { 10084 return null; 10085 } 10086 return verificationParams.getManifestDigest(); 10087 } 10088 10089 private int installLocationPolicy(PackageInfoLite pkgLite) { 10090 String packageName = pkgLite.packageName; 10091 int installLocation = pkgLite.installLocation; 10092 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10093 // reader 10094 synchronized (mPackages) { 10095 PackageParser.Package pkg = mPackages.get(packageName); 10096 if (pkg != null) { 10097 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10098 // Check for downgrading. 10099 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10100 try { 10101 checkDowngrade(pkg, pkgLite); 10102 } catch (PackageManagerException e) { 10103 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10104 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10105 } 10106 } 10107 // Check for updated system application. 10108 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10109 if (onSd) { 10110 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10111 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10112 } 10113 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10114 } else { 10115 if (onSd) { 10116 // Install flag overrides everything. 10117 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10118 } 10119 // If current upgrade specifies particular preference 10120 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10121 // Application explicitly specified internal. 10122 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10123 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10124 // App explictly prefers external. Let policy decide 10125 } else { 10126 // Prefer previous location 10127 if (isExternal(pkg)) { 10128 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10129 } 10130 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10131 } 10132 } 10133 } else { 10134 // Invalid install. Return error code 10135 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10136 } 10137 } 10138 } 10139 // All the special cases have been taken care of. 10140 // Return result based on recommended install location. 10141 if (onSd) { 10142 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10143 } 10144 return pkgLite.recommendedInstallLocation; 10145 } 10146 10147 /* 10148 * Invoke remote method to get package information and install 10149 * location values. Override install location based on default 10150 * policy if needed and then create install arguments based 10151 * on the install location. 10152 */ 10153 public void handleStartCopy() throws RemoteException { 10154 int ret = PackageManager.INSTALL_SUCCEEDED; 10155 10156 // If we're already staged, we've firmly committed to an install location 10157 if (origin.staged) { 10158 if (origin.file != null) { 10159 installFlags |= PackageManager.INSTALL_INTERNAL; 10160 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10161 } else if (origin.cid != null) { 10162 installFlags |= PackageManager.INSTALL_EXTERNAL; 10163 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10164 } else { 10165 throw new IllegalStateException("Invalid stage location"); 10166 } 10167 } 10168 10169 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10170 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10171 10172 PackageInfoLite pkgLite = null; 10173 10174 if (onInt && onSd) { 10175 // Check if both bits are set. 10176 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10177 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10178 } else { 10179 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10180 packageAbiOverride); 10181 10182 /* 10183 * If we have too little free space, try to free cache 10184 * before giving up. 10185 */ 10186 if (!origin.staged && pkgLite.recommendedInstallLocation 10187 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10188 // TODO: focus freeing disk space on the target device 10189 final StorageManager storage = StorageManager.from(mContext); 10190 final long lowThreshold = storage.getStorageLowBytes( 10191 Environment.getDataDirectory()); 10192 10193 final long sizeBytes = mContainerService.calculateInstalledSize( 10194 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10195 10196 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10197 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10198 installFlags, packageAbiOverride); 10199 } 10200 10201 /* 10202 * The cache free must have deleted the file we 10203 * downloaded to install. 10204 * 10205 * TODO: fix the "freeCache" call to not delete 10206 * the file we care about. 10207 */ 10208 if (pkgLite.recommendedInstallLocation 10209 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10210 pkgLite.recommendedInstallLocation 10211 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10212 } 10213 } 10214 } 10215 10216 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10217 int loc = pkgLite.recommendedInstallLocation; 10218 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10219 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10220 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10221 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10222 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10223 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10224 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10225 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10226 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10227 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10228 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10229 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10230 } else { 10231 // Override with defaults if needed. 10232 loc = installLocationPolicy(pkgLite); 10233 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10234 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10235 } else if (!onSd && !onInt) { 10236 // Override install location with flags 10237 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10238 // Set the flag to install on external media. 10239 installFlags |= PackageManager.INSTALL_EXTERNAL; 10240 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10241 } else { 10242 // Make sure the flag for installing on external 10243 // media is unset 10244 installFlags |= PackageManager.INSTALL_INTERNAL; 10245 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10246 } 10247 } 10248 } 10249 } 10250 10251 final InstallArgs args = createInstallArgs(this); 10252 mArgs = args; 10253 10254 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10255 /* 10256 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10257 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10258 */ 10259 int userIdentifier = getUser().getIdentifier(); 10260 if (userIdentifier == UserHandle.USER_ALL 10261 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10262 userIdentifier = UserHandle.USER_OWNER; 10263 } 10264 10265 /* 10266 * Determine if we have any installed package verifiers. If we 10267 * do, then we'll defer to them to verify the packages. 10268 */ 10269 final int requiredUid = mRequiredVerifierPackage == null ? -1 10270 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10271 if (!origin.existing && requiredUid != -1 10272 && isVerificationEnabled(userIdentifier, installFlags)) { 10273 final Intent verification = new Intent( 10274 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10275 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10276 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10277 PACKAGE_MIME_TYPE); 10278 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10279 10280 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10281 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10282 0 /* TODO: Which userId? */); 10283 10284 if (DEBUG_VERIFY) { 10285 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10286 + verification.toString() + " with " + pkgLite.verifiers.length 10287 + " optional verifiers"); 10288 } 10289 10290 final int verificationId = mPendingVerificationToken++; 10291 10292 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10293 10294 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10295 installerPackageName); 10296 10297 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10298 installFlags); 10299 10300 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10301 pkgLite.packageName); 10302 10303 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10304 pkgLite.versionCode); 10305 10306 if (verificationParams != null) { 10307 if (verificationParams.getVerificationURI() != null) { 10308 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10309 verificationParams.getVerificationURI()); 10310 } 10311 if (verificationParams.getOriginatingURI() != null) { 10312 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10313 verificationParams.getOriginatingURI()); 10314 } 10315 if (verificationParams.getReferrer() != null) { 10316 verification.putExtra(Intent.EXTRA_REFERRER, 10317 verificationParams.getReferrer()); 10318 } 10319 if (verificationParams.getOriginatingUid() >= 0) { 10320 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10321 verificationParams.getOriginatingUid()); 10322 } 10323 if (verificationParams.getInstallerUid() >= 0) { 10324 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10325 verificationParams.getInstallerUid()); 10326 } 10327 } 10328 10329 final PackageVerificationState verificationState = new PackageVerificationState( 10330 requiredUid, args); 10331 10332 mPendingVerification.append(verificationId, verificationState); 10333 10334 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10335 receivers, verificationState); 10336 10337 /* 10338 * If any sufficient verifiers were listed in the package 10339 * manifest, attempt to ask them. 10340 */ 10341 if (sufficientVerifiers != null) { 10342 final int N = sufficientVerifiers.size(); 10343 if (N == 0) { 10344 Slog.i(TAG, "Additional verifiers required, but none installed."); 10345 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10346 } else { 10347 for (int i = 0; i < N; i++) { 10348 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10349 10350 final Intent sufficientIntent = new Intent(verification); 10351 sufficientIntent.setComponent(verifierComponent); 10352 10353 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10354 } 10355 } 10356 } 10357 10358 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10359 mRequiredVerifierPackage, receivers); 10360 if (ret == PackageManager.INSTALL_SUCCEEDED 10361 && mRequiredVerifierPackage != null) { 10362 /* 10363 * Send the intent to the required verification agent, 10364 * but only start the verification timeout after the 10365 * target BroadcastReceivers have run. 10366 */ 10367 verification.setComponent(requiredVerifierComponent); 10368 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10369 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10370 new BroadcastReceiver() { 10371 @Override 10372 public void onReceive(Context context, Intent intent) { 10373 final Message msg = mHandler 10374 .obtainMessage(CHECK_PENDING_VERIFICATION); 10375 msg.arg1 = verificationId; 10376 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10377 } 10378 }, null, 0, null, null); 10379 10380 /* 10381 * We don't want the copy to proceed until verification 10382 * succeeds, so null out this field. 10383 */ 10384 mArgs = null; 10385 } 10386 } else { 10387 /* 10388 * No package verification is enabled, so immediately start 10389 * the remote call to initiate copy using temporary file. 10390 */ 10391 ret = args.copyApk(mContainerService, true); 10392 } 10393 } 10394 10395 mRet = ret; 10396 } 10397 10398 @Override 10399 void handleReturnCode() { 10400 // If mArgs is null, then MCS couldn't be reached. When it 10401 // reconnects, it will try again to install. At that point, this 10402 // will succeed. 10403 if (mArgs != null) { 10404 processPendingInstall(mArgs, mRet); 10405 } 10406 } 10407 10408 @Override 10409 void handleServiceError() { 10410 mArgs = createInstallArgs(this); 10411 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10412 } 10413 10414 public boolean isForwardLocked() { 10415 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10416 } 10417 } 10418 10419 /** 10420 * Used during creation of InstallArgs 10421 * 10422 * @param installFlags package installation flags 10423 * @return true if should be installed on external storage 10424 */ 10425 private static boolean installOnExternalAsec(int installFlags) { 10426 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10427 return false; 10428 } 10429 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10430 return true; 10431 } 10432 return false; 10433 } 10434 10435 /** 10436 * Used during creation of InstallArgs 10437 * 10438 * @param installFlags package installation flags 10439 * @return true if should be installed as forward locked 10440 */ 10441 private static boolean installForwardLocked(int installFlags) { 10442 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10443 } 10444 10445 private InstallArgs createInstallArgs(InstallParams params) { 10446 if (params.move != null) { 10447 return new MoveInstallArgs(params); 10448 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10449 return new AsecInstallArgs(params); 10450 } else { 10451 return new FileInstallArgs(params); 10452 } 10453 } 10454 10455 /** 10456 * Create args that describe an existing installed package. Typically used 10457 * when cleaning up old installs, or used as a move source. 10458 */ 10459 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10460 String resourcePath, String[] instructionSets) { 10461 final boolean isInAsec; 10462 if (installOnExternalAsec(installFlags)) { 10463 /* Apps on SD card are always in ASEC containers. */ 10464 isInAsec = true; 10465 } else if (installForwardLocked(installFlags) 10466 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10467 /* 10468 * Forward-locked apps are only in ASEC containers if they're the 10469 * new style 10470 */ 10471 isInAsec = true; 10472 } else { 10473 isInAsec = false; 10474 } 10475 10476 if (isInAsec) { 10477 return new AsecInstallArgs(codePath, instructionSets, 10478 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10479 } else { 10480 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10481 } 10482 } 10483 10484 static abstract class InstallArgs { 10485 /** @see InstallParams#origin */ 10486 final OriginInfo origin; 10487 /** @see InstallParams#move */ 10488 final MoveInfo move; 10489 10490 final IPackageInstallObserver2 observer; 10491 // Always refers to PackageManager flags only 10492 final int installFlags; 10493 final String installerPackageName; 10494 final String volumeUuid; 10495 final ManifestDigest manifestDigest; 10496 final UserHandle user; 10497 final String abiOverride; 10498 10499 // The list of instruction sets supported by this app. This is currently 10500 // only used during the rmdex() phase to clean up resources. We can get rid of this 10501 // if we move dex files under the common app path. 10502 /* nullable */ String[] instructionSets; 10503 10504 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10505 int installFlags, String installerPackageName, String volumeUuid, 10506 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10507 String abiOverride) { 10508 this.origin = origin; 10509 this.move = move; 10510 this.installFlags = installFlags; 10511 this.observer = observer; 10512 this.installerPackageName = installerPackageName; 10513 this.volumeUuid = volumeUuid; 10514 this.manifestDigest = manifestDigest; 10515 this.user = user; 10516 this.instructionSets = instructionSets; 10517 this.abiOverride = abiOverride; 10518 } 10519 10520 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10521 abstract int doPreInstall(int status); 10522 10523 /** 10524 * Rename package into final resting place. All paths on the given 10525 * scanned package should be updated to reflect the rename. 10526 */ 10527 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10528 abstract int doPostInstall(int status, int uid); 10529 10530 /** @see PackageSettingBase#codePathString */ 10531 abstract String getCodePath(); 10532 /** @see PackageSettingBase#resourcePathString */ 10533 abstract String getResourcePath(); 10534 10535 // Need installer lock especially for dex file removal. 10536 abstract void cleanUpResourcesLI(); 10537 abstract boolean doPostDeleteLI(boolean delete); 10538 10539 /** 10540 * Called before the source arguments are copied. This is used mostly 10541 * for MoveParams when it needs to read the source file to put it in the 10542 * destination. 10543 */ 10544 int doPreCopy() { 10545 return PackageManager.INSTALL_SUCCEEDED; 10546 } 10547 10548 /** 10549 * Called after the source arguments are copied. This is used mostly for 10550 * MoveParams when it needs to read the source file to put it in the 10551 * destination. 10552 * 10553 * @return 10554 */ 10555 int doPostCopy(int uid) { 10556 return PackageManager.INSTALL_SUCCEEDED; 10557 } 10558 10559 protected boolean isFwdLocked() { 10560 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10561 } 10562 10563 protected boolean isExternalAsec() { 10564 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10565 } 10566 10567 UserHandle getUser() { 10568 return user; 10569 } 10570 } 10571 10572 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10573 if (!allCodePaths.isEmpty()) { 10574 if (instructionSets == null) { 10575 throw new IllegalStateException("instructionSet == null"); 10576 } 10577 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10578 for (String codePath : allCodePaths) { 10579 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10580 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10581 if (retCode < 0) { 10582 Slog.w(TAG, "Couldn't remove dex file for package: " 10583 + " at location " + codePath + ", retcode=" + retCode); 10584 // we don't consider this to be a failure of the core package deletion 10585 } 10586 } 10587 } 10588 } 10589 } 10590 10591 /** 10592 * Logic to handle installation of non-ASEC applications, including copying 10593 * and renaming logic. 10594 */ 10595 class FileInstallArgs extends InstallArgs { 10596 private File codeFile; 10597 private File resourceFile; 10598 10599 // Example topology: 10600 // /data/app/com.example/base.apk 10601 // /data/app/com.example/split_foo.apk 10602 // /data/app/com.example/lib/arm/libfoo.so 10603 // /data/app/com.example/lib/arm64/libfoo.so 10604 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10605 10606 /** New install */ 10607 FileInstallArgs(InstallParams params) { 10608 super(params.origin, params.move, params.observer, params.installFlags, 10609 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10610 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10611 if (isFwdLocked()) { 10612 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10613 } 10614 } 10615 10616 /** Existing install */ 10617 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10618 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10619 null); 10620 this.codeFile = (codePath != null) ? new File(codePath) : null; 10621 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10622 } 10623 10624 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10625 if (origin.staged) { 10626 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10627 codeFile = origin.file; 10628 resourceFile = origin.file; 10629 return PackageManager.INSTALL_SUCCEEDED; 10630 } 10631 10632 try { 10633 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10634 codeFile = tempDir; 10635 resourceFile = tempDir; 10636 } catch (IOException e) { 10637 Slog.w(TAG, "Failed to create copy file: " + e); 10638 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10639 } 10640 10641 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10642 @Override 10643 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10644 if (!FileUtils.isValidExtFilename(name)) { 10645 throw new IllegalArgumentException("Invalid filename: " + name); 10646 } 10647 try { 10648 final File file = new File(codeFile, name); 10649 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10650 O_RDWR | O_CREAT, 0644); 10651 Os.chmod(file.getAbsolutePath(), 0644); 10652 return new ParcelFileDescriptor(fd); 10653 } catch (ErrnoException e) { 10654 throw new RemoteException("Failed to open: " + e.getMessage()); 10655 } 10656 } 10657 }; 10658 10659 int ret = PackageManager.INSTALL_SUCCEEDED; 10660 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10661 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10662 Slog.e(TAG, "Failed to copy package"); 10663 return ret; 10664 } 10665 10666 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10667 NativeLibraryHelper.Handle handle = null; 10668 try { 10669 handle = NativeLibraryHelper.Handle.create(codeFile); 10670 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10671 abiOverride); 10672 } catch (IOException e) { 10673 Slog.e(TAG, "Copying native libraries failed", e); 10674 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10675 } finally { 10676 IoUtils.closeQuietly(handle); 10677 } 10678 10679 return ret; 10680 } 10681 10682 int doPreInstall(int status) { 10683 if (status != PackageManager.INSTALL_SUCCEEDED) { 10684 cleanUp(); 10685 } 10686 return status; 10687 } 10688 10689 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10690 if (status != PackageManager.INSTALL_SUCCEEDED) { 10691 cleanUp(); 10692 return false; 10693 } 10694 10695 final File targetDir = codeFile.getParentFile(); 10696 final File beforeCodeFile = codeFile; 10697 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10698 10699 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10700 try { 10701 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10702 } catch (ErrnoException e) { 10703 Slog.w(TAG, "Failed to rename", e); 10704 return false; 10705 } 10706 10707 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10708 Slog.w(TAG, "Failed to restorecon"); 10709 return false; 10710 } 10711 10712 // Reflect the rename internally 10713 codeFile = afterCodeFile; 10714 resourceFile = afterCodeFile; 10715 10716 // Reflect the rename in scanned details 10717 pkg.codePath = afterCodeFile.getAbsolutePath(); 10718 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10719 pkg.baseCodePath); 10720 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10721 pkg.splitCodePaths); 10722 10723 // Reflect the rename in app info 10724 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10725 pkg.applicationInfo.setCodePath(pkg.codePath); 10726 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10727 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10728 pkg.applicationInfo.setResourcePath(pkg.codePath); 10729 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10730 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10731 10732 return true; 10733 } 10734 10735 int doPostInstall(int status, int uid) { 10736 if (status != PackageManager.INSTALL_SUCCEEDED) { 10737 cleanUp(); 10738 } 10739 return status; 10740 } 10741 10742 @Override 10743 String getCodePath() { 10744 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10745 } 10746 10747 @Override 10748 String getResourcePath() { 10749 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10750 } 10751 10752 private boolean cleanUp() { 10753 if (codeFile == null || !codeFile.exists()) { 10754 return false; 10755 } 10756 10757 if (codeFile.isDirectory()) { 10758 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10759 } else { 10760 codeFile.delete(); 10761 } 10762 10763 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10764 resourceFile.delete(); 10765 } 10766 10767 return true; 10768 } 10769 10770 void cleanUpResourcesLI() { 10771 // Try enumerating all code paths before deleting 10772 List<String> allCodePaths = Collections.EMPTY_LIST; 10773 if (codeFile != null && codeFile.exists()) { 10774 try { 10775 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10776 allCodePaths = pkg.getAllCodePaths(); 10777 } catch (PackageParserException e) { 10778 // Ignored; we tried our best 10779 } 10780 } 10781 10782 cleanUp(); 10783 removeDexFiles(allCodePaths, instructionSets); 10784 } 10785 10786 boolean doPostDeleteLI(boolean delete) { 10787 // XXX err, shouldn't we respect the delete flag? 10788 cleanUpResourcesLI(); 10789 return true; 10790 } 10791 } 10792 10793 private boolean isAsecExternal(String cid) { 10794 final String asecPath = PackageHelper.getSdFilesystem(cid); 10795 return !asecPath.startsWith(mAsecInternalPath); 10796 } 10797 10798 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10799 PackageManagerException { 10800 if (copyRet < 0) { 10801 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10802 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10803 throw new PackageManagerException(copyRet, message); 10804 } 10805 } 10806 } 10807 10808 /** 10809 * Extract the MountService "container ID" from the full code path of an 10810 * .apk. 10811 */ 10812 static String cidFromCodePath(String fullCodePath) { 10813 int eidx = fullCodePath.lastIndexOf("/"); 10814 String subStr1 = fullCodePath.substring(0, eidx); 10815 int sidx = subStr1.lastIndexOf("/"); 10816 return subStr1.substring(sidx+1, eidx); 10817 } 10818 10819 /** 10820 * Logic to handle installation of ASEC applications, including copying and 10821 * renaming logic. 10822 */ 10823 class AsecInstallArgs extends InstallArgs { 10824 static final String RES_FILE_NAME = "pkg.apk"; 10825 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10826 10827 String cid; 10828 String packagePath; 10829 String resourcePath; 10830 10831 /** New install */ 10832 AsecInstallArgs(InstallParams params) { 10833 super(params.origin, params.move, params.observer, params.installFlags, 10834 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10835 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10836 } 10837 10838 /** Existing install */ 10839 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10840 boolean isExternal, boolean isForwardLocked) { 10841 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10842 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10843 instructionSets, null); 10844 // Hackily pretend we're still looking at a full code path 10845 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10846 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10847 } 10848 10849 // Extract cid from fullCodePath 10850 int eidx = fullCodePath.lastIndexOf("/"); 10851 String subStr1 = fullCodePath.substring(0, eidx); 10852 int sidx = subStr1.lastIndexOf("/"); 10853 cid = subStr1.substring(sidx+1, eidx); 10854 setMountPath(subStr1); 10855 } 10856 10857 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10858 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10859 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10860 instructionSets, null); 10861 this.cid = cid; 10862 setMountPath(PackageHelper.getSdDir(cid)); 10863 } 10864 10865 void createCopyFile() { 10866 cid = mInstallerService.allocateExternalStageCidLegacy(); 10867 } 10868 10869 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10870 if (origin.staged) { 10871 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10872 cid = origin.cid; 10873 setMountPath(PackageHelper.getSdDir(cid)); 10874 return PackageManager.INSTALL_SUCCEEDED; 10875 } 10876 10877 if (temp) { 10878 createCopyFile(); 10879 } else { 10880 /* 10881 * Pre-emptively destroy the container since it's destroyed if 10882 * copying fails due to it existing anyway. 10883 */ 10884 PackageHelper.destroySdDir(cid); 10885 } 10886 10887 final String newMountPath = imcs.copyPackageToContainer( 10888 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10889 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10890 10891 if (newMountPath != null) { 10892 setMountPath(newMountPath); 10893 return PackageManager.INSTALL_SUCCEEDED; 10894 } else { 10895 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10896 } 10897 } 10898 10899 @Override 10900 String getCodePath() { 10901 return packagePath; 10902 } 10903 10904 @Override 10905 String getResourcePath() { 10906 return resourcePath; 10907 } 10908 10909 int doPreInstall(int status) { 10910 if (status != PackageManager.INSTALL_SUCCEEDED) { 10911 // Destroy container 10912 PackageHelper.destroySdDir(cid); 10913 } else { 10914 boolean mounted = PackageHelper.isContainerMounted(cid); 10915 if (!mounted) { 10916 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10917 Process.SYSTEM_UID); 10918 if (newMountPath != null) { 10919 setMountPath(newMountPath); 10920 } else { 10921 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10922 } 10923 } 10924 } 10925 return status; 10926 } 10927 10928 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10929 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10930 String newMountPath = null; 10931 if (PackageHelper.isContainerMounted(cid)) { 10932 // Unmount the container 10933 if (!PackageHelper.unMountSdDir(cid)) { 10934 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10935 return false; 10936 } 10937 } 10938 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10939 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10940 " which might be stale. Will try to clean up."); 10941 // Clean up the stale container and proceed to recreate. 10942 if (!PackageHelper.destroySdDir(newCacheId)) { 10943 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10944 return false; 10945 } 10946 // Successfully cleaned up stale container. Try to rename again. 10947 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10948 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10949 + " inspite of cleaning it up."); 10950 return false; 10951 } 10952 } 10953 if (!PackageHelper.isContainerMounted(newCacheId)) { 10954 Slog.w(TAG, "Mounting container " + newCacheId); 10955 newMountPath = PackageHelper.mountSdDir(newCacheId, 10956 getEncryptKey(), Process.SYSTEM_UID); 10957 } else { 10958 newMountPath = PackageHelper.getSdDir(newCacheId); 10959 } 10960 if (newMountPath == null) { 10961 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10962 return false; 10963 } 10964 Log.i(TAG, "Succesfully renamed " + cid + 10965 " to " + newCacheId + 10966 " at new path: " + newMountPath); 10967 cid = newCacheId; 10968 10969 final File beforeCodeFile = new File(packagePath); 10970 setMountPath(newMountPath); 10971 final File afterCodeFile = new File(packagePath); 10972 10973 // Reflect the rename in scanned details 10974 pkg.codePath = afterCodeFile.getAbsolutePath(); 10975 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10976 pkg.baseCodePath); 10977 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10978 pkg.splitCodePaths); 10979 10980 // Reflect the rename in app info 10981 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10982 pkg.applicationInfo.setCodePath(pkg.codePath); 10983 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10984 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10985 pkg.applicationInfo.setResourcePath(pkg.codePath); 10986 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10987 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10988 10989 return true; 10990 } 10991 10992 private void setMountPath(String mountPath) { 10993 final File mountFile = new File(mountPath); 10994 10995 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10996 if (monolithicFile.exists()) { 10997 packagePath = monolithicFile.getAbsolutePath(); 10998 if (isFwdLocked()) { 10999 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11000 } else { 11001 resourcePath = packagePath; 11002 } 11003 } else { 11004 packagePath = mountFile.getAbsolutePath(); 11005 resourcePath = packagePath; 11006 } 11007 } 11008 11009 int doPostInstall(int status, int uid) { 11010 if (status != PackageManager.INSTALL_SUCCEEDED) { 11011 cleanUp(); 11012 } else { 11013 final int groupOwner; 11014 final String protectedFile; 11015 if (isFwdLocked()) { 11016 groupOwner = UserHandle.getSharedAppGid(uid); 11017 protectedFile = RES_FILE_NAME; 11018 } else { 11019 groupOwner = -1; 11020 protectedFile = null; 11021 } 11022 11023 if (uid < Process.FIRST_APPLICATION_UID 11024 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11025 Slog.e(TAG, "Failed to finalize " + cid); 11026 PackageHelper.destroySdDir(cid); 11027 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11028 } 11029 11030 boolean mounted = PackageHelper.isContainerMounted(cid); 11031 if (!mounted) { 11032 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11033 } 11034 } 11035 return status; 11036 } 11037 11038 private void cleanUp() { 11039 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11040 11041 // Destroy secure container 11042 PackageHelper.destroySdDir(cid); 11043 } 11044 11045 private List<String> getAllCodePaths() { 11046 final File codeFile = new File(getCodePath()); 11047 if (codeFile != null && codeFile.exists()) { 11048 try { 11049 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11050 return pkg.getAllCodePaths(); 11051 } catch (PackageParserException e) { 11052 // Ignored; we tried our best 11053 } 11054 } 11055 return Collections.EMPTY_LIST; 11056 } 11057 11058 void cleanUpResourcesLI() { 11059 // Enumerate all code paths before deleting 11060 cleanUpResourcesLI(getAllCodePaths()); 11061 } 11062 11063 private void cleanUpResourcesLI(List<String> allCodePaths) { 11064 cleanUp(); 11065 removeDexFiles(allCodePaths, instructionSets); 11066 } 11067 11068 String getPackageName() { 11069 return getAsecPackageName(cid); 11070 } 11071 11072 boolean doPostDeleteLI(boolean delete) { 11073 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11074 final List<String> allCodePaths = getAllCodePaths(); 11075 boolean mounted = PackageHelper.isContainerMounted(cid); 11076 if (mounted) { 11077 // Unmount first 11078 if (PackageHelper.unMountSdDir(cid)) { 11079 mounted = false; 11080 } 11081 } 11082 if (!mounted && delete) { 11083 cleanUpResourcesLI(allCodePaths); 11084 } 11085 return !mounted; 11086 } 11087 11088 @Override 11089 int doPreCopy() { 11090 if (isFwdLocked()) { 11091 if (!PackageHelper.fixSdPermissions(cid, 11092 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11093 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11094 } 11095 } 11096 11097 return PackageManager.INSTALL_SUCCEEDED; 11098 } 11099 11100 @Override 11101 int doPostCopy(int uid) { 11102 if (isFwdLocked()) { 11103 if (uid < Process.FIRST_APPLICATION_UID 11104 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11105 RES_FILE_NAME)) { 11106 Slog.e(TAG, "Failed to finalize " + cid); 11107 PackageHelper.destroySdDir(cid); 11108 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11109 } 11110 } 11111 11112 return PackageManager.INSTALL_SUCCEEDED; 11113 } 11114 } 11115 11116 /** 11117 * Logic to handle movement of existing installed applications. 11118 */ 11119 class MoveInstallArgs extends InstallArgs { 11120 private File codeFile; 11121 private File resourceFile; 11122 11123 /** New install */ 11124 MoveInstallArgs(InstallParams params) { 11125 super(params.origin, params.move, params.observer, params.installFlags, 11126 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11127 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11128 } 11129 11130 int copyApk(IMediaContainerService imcs, boolean temp) { 11131 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11132 + move.fromUuid + " to " + move.toUuid); 11133 synchronized (mInstaller) { 11134 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11135 move.dataAppName, move.appId, move.seinfo) != 0) { 11136 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11137 } 11138 } 11139 11140 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11141 resourceFile = codeFile; 11142 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11143 11144 return PackageManager.INSTALL_SUCCEEDED; 11145 } 11146 11147 int doPreInstall(int status) { 11148 if (status != PackageManager.INSTALL_SUCCEEDED) { 11149 cleanUp(); 11150 } 11151 return status; 11152 } 11153 11154 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11155 if (status != PackageManager.INSTALL_SUCCEEDED) { 11156 cleanUp(); 11157 return false; 11158 } 11159 11160 // Reflect the move in app info 11161 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11162 pkg.applicationInfo.setCodePath(pkg.codePath); 11163 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11164 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11165 pkg.applicationInfo.setResourcePath(pkg.codePath); 11166 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11167 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11168 11169 return true; 11170 } 11171 11172 int doPostInstall(int status, int uid) { 11173 if (status != PackageManager.INSTALL_SUCCEEDED) { 11174 cleanUp(); 11175 } 11176 return status; 11177 } 11178 11179 @Override 11180 String getCodePath() { 11181 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11182 } 11183 11184 @Override 11185 String getResourcePath() { 11186 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11187 } 11188 11189 private boolean cleanUp() { 11190 if (codeFile == null || !codeFile.exists()) { 11191 return false; 11192 } 11193 11194 if (codeFile.isDirectory()) { 11195 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11196 } else { 11197 codeFile.delete(); 11198 } 11199 11200 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11201 resourceFile.delete(); 11202 } 11203 11204 return true; 11205 } 11206 11207 void cleanUpResourcesLI() { 11208 cleanUp(); 11209 } 11210 11211 boolean doPostDeleteLI(boolean delete) { 11212 // XXX err, shouldn't we respect the delete flag? 11213 cleanUpResourcesLI(); 11214 return true; 11215 } 11216 } 11217 11218 static String getAsecPackageName(String packageCid) { 11219 int idx = packageCid.lastIndexOf("-"); 11220 if (idx == -1) { 11221 return packageCid; 11222 } 11223 return packageCid.substring(0, idx); 11224 } 11225 11226 // Utility method used to create code paths based on package name and available index. 11227 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11228 String idxStr = ""; 11229 int idx = 1; 11230 // Fall back to default value of idx=1 if prefix is not 11231 // part of oldCodePath 11232 if (oldCodePath != null) { 11233 String subStr = oldCodePath; 11234 // Drop the suffix right away 11235 if (suffix != null && subStr.endsWith(suffix)) { 11236 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11237 } 11238 // If oldCodePath already contains prefix find out the 11239 // ending index to either increment or decrement. 11240 int sidx = subStr.lastIndexOf(prefix); 11241 if (sidx != -1) { 11242 subStr = subStr.substring(sidx + prefix.length()); 11243 if (subStr != null) { 11244 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11245 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11246 } 11247 try { 11248 idx = Integer.parseInt(subStr); 11249 if (idx <= 1) { 11250 idx++; 11251 } else { 11252 idx--; 11253 } 11254 } catch(NumberFormatException e) { 11255 } 11256 } 11257 } 11258 } 11259 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11260 return prefix + idxStr; 11261 } 11262 11263 private File getNextCodePath(File targetDir, String packageName) { 11264 int suffix = 1; 11265 File result; 11266 do { 11267 result = new File(targetDir, packageName + "-" + suffix); 11268 suffix++; 11269 } while (result.exists()); 11270 return result; 11271 } 11272 11273 // Utility method that returns the relative package path with respect 11274 // to the installation directory. Like say for /data/data/com.test-1.apk 11275 // string com.test-1 is returned. 11276 static String deriveCodePathName(String codePath) { 11277 if (codePath == null) { 11278 return null; 11279 } 11280 final File codeFile = new File(codePath); 11281 final String name = codeFile.getName(); 11282 if (codeFile.isDirectory()) { 11283 return name; 11284 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11285 final int lastDot = name.lastIndexOf('.'); 11286 return name.substring(0, lastDot); 11287 } else { 11288 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11289 return null; 11290 } 11291 } 11292 11293 class PackageInstalledInfo { 11294 String name; 11295 int uid; 11296 // The set of users that originally had this package installed. 11297 int[] origUsers; 11298 // The set of users that now have this package installed. 11299 int[] newUsers; 11300 PackageParser.Package pkg; 11301 int returnCode; 11302 String returnMsg; 11303 PackageRemovedInfo removedInfo; 11304 11305 public void setError(int code, String msg) { 11306 returnCode = code; 11307 returnMsg = msg; 11308 Slog.w(TAG, msg); 11309 } 11310 11311 public void setError(String msg, PackageParserException e) { 11312 returnCode = e.error; 11313 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11314 Slog.w(TAG, msg, e); 11315 } 11316 11317 public void setError(String msg, PackageManagerException e) { 11318 returnCode = e.error; 11319 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11320 Slog.w(TAG, msg, e); 11321 } 11322 11323 // In some error cases we want to convey more info back to the observer 11324 String origPackage; 11325 String origPermission; 11326 } 11327 11328 /* 11329 * Install a non-existing package. 11330 */ 11331 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11332 UserHandle user, String installerPackageName, String volumeUuid, 11333 PackageInstalledInfo res) { 11334 // Remember this for later, in case we need to rollback this install 11335 String pkgName = pkg.packageName; 11336 11337 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11338 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11339 UserHandle.USER_OWNER).exists(); 11340 synchronized(mPackages) { 11341 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11342 // A package with the same name is already installed, though 11343 // it has been renamed to an older name. The package we 11344 // are trying to install should be installed as an update to 11345 // the existing one, but that has not been requested, so bail. 11346 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11347 + " without first uninstalling package running as " 11348 + mSettings.mRenamedPackages.get(pkgName)); 11349 return; 11350 } 11351 if (mPackages.containsKey(pkgName)) { 11352 // Don't allow installation over an existing package with the same name. 11353 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11354 + " without first uninstalling."); 11355 return; 11356 } 11357 } 11358 11359 try { 11360 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11361 System.currentTimeMillis(), user); 11362 11363 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11364 // delete the partially installed application. the data directory will have to be 11365 // restored if it was already existing 11366 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11367 // remove package from internal structures. Note that we want deletePackageX to 11368 // delete the package data and cache directories that it created in 11369 // scanPackageLocked, unless those directories existed before we even tried to 11370 // install. 11371 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11372 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11373 res.removedInfo, true); 11374 } 11375 11376 } catch (PackageManagerException e) { 11377 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11378 } 11379 } 11380 11381 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11382 // Can't rotate keys during boot or if sharedUser. 11383 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11384 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11385 return false; 11386 } 11387 // app is using upgradeKeySets; make sure all are valid 11388 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11389 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11390 for (int i = 0; i < upgradeKeySets.length; i++) { 11391 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11392 Slog.wtf(TAG, "Package " 11393 + (oldPs.name != null ? oldPs.name : "<null>") 11394 + " contains upgrade-key-set reference to unknown key-set: " 11395 + upgradeKeySets[i] 11396 + " reverting to signatures check."); 11397 return false; 11398 } 11399 } 11400 return true; 11401 } 11402 11403 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11404 // Upgrade keysets are being used. Determine if new package has a superset of the 11405 // required keys. 11406 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11407 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11408 for (int i = 0; i < upgradeKeySets.length; i++) { 11409 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11410 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11411 return true; 11412 } 11413 } 11414 return false; 11415 } 11416 11417 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11418 UserHandle user, String installerPackageName, String volumeUuid, 11419 PackageInstalledInfo res) { 11420 final PackageParser.Package oldPackage; 11421 final String pkgName = pkg.packageName; 11422 final int[] allUsers; 11423 final boolean[] perUserInstalled; 11424 final boolean weFroze; 11425 11426 // First find the old package info and check signatures 11427 synchronized(mPackages) { 11428 oldPackage = mPackages.get(pkgName); 11429 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11430 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11431 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11432 if(!checkUpgradeKeySetLP(ps, pkg)) { 11433 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11434 "New package not signed by keys specified by upgrade-keysets: " 11435 + pkgName); 11436 return; 11437 } 11438 } else { 11439 // default to original signature matching 11440 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11441 != PackageManager.SIGNATURE_MATCH) { 11442 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11443 "New package has a different signature: " + pkgName); 11444 return; 11445 } 11446 } 11447 11448 // In case of rollback, remember per-user/profile install state 11449 allUsers = sUserManager.getUserIds(); 11450 perUserInstalled = new boolean[allUsers.length]; 11451 for (int i = 0; i < allUsers.length; i++) { 11452 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11453 } 11454 11455 // Mark the app as frozen to prevent launching during the upgrade 11456 // process, and then kill all running instances 11457 if (!ps.frozen) { 11458 ps.frozen = true; 11459 weFroze = true; 11460 } else { 11461 weFroze = false; 11462 } 11463 } 11464 11465 // Now that we're guarded by frozen state, kill app during upgrade 11466 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11467 11468 try { 11469 boolean sysPkg = (isSystemApp(oldPackage)); 11470 if (sysPkg) { 11471 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11472 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11473 } else { 11474 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11475 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11476 } 11477 } finally { 11478 // Regardless of success or failure of upgrade steps above, always 11479 // unfreeze the package if we froze it 11480 if (weFroze) { 11481 unfreezePackage(pkgName); 11482 } 11483 } 11484 } 11485 11486 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11487 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11488 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11489 String volumeUuid, PackageInstalledInfo res) { 11490 String pkgName = deletedPackage.packageName; 11491 boolean deletedPkg = true; 11492 boolean updatedSettings = false; 11493 11494 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11495 + deletedPackage); 11496 long origUpdateTime; 11497 if (pkg.mExtras != null) { 11498 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11499 } else { 11500 origUpdateTime = 0; 11501 } 11502 11503 // First delete the existing package while retaining the data directory 11504 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11505 res.removedInfo, true)) { 11506 // If the existing package wasn't successfully deleted 11507 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11508 deletedPkg = false; 11509 } else { 11510 // Successfully deleted the old package; proceed with replace. 11511 11512 // If deleted package lived in a container, give users a chance to 11513 // relinquish resources before killing. 11514 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11515 if (DEBUG_INSTALL) { 11516 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11517 } 11518 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11519 final ArrayList<String> pkgList = new ArrayList<String>(1); 11520 pkgList.add(deletedPackage.applicationInfo.packageName); 11521 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11522 } 11523 11524 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11525 try { 11526 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11527 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11528 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11529 perUserInstalled, res, user); 11530 updatedSettings = true; 11531 } catch (PackageManagerException e) { 11532 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11533 } 11534 } 11535 11536 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11537 // remove package from internal structures. Note that we want deletePackageX to 11538 // delete the package data and cache directories that it created in 11539 // scanPackageLocked, unless those directories existed before we even tried to 11540 // install. 11541 if(updatedSettings) { 11542 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11543 deletePackageLI( 11544 pkgName, null, true, allUsers, perUserInstalled, 11545 PackageManager.DELETE_KEEP_DATA, 11546 res.removedInfo, true); 11547 } 11548 // Since we failed to install the new package we need to restore the old 11549 // package that we deleted. 11550 if (deletedPkg) { 11551 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11552 File restoreFile = new File(deletedPackage.codePath); 11553 // Parse old package 11554 boolean oldExternal = isExternal(deletedPackage); 11555 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11556 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11557 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11558 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11559 try { 11560 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11561 } catch (PackageManagerException e) { 11562 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11563 + e.getMessage()); 11564 return; 11565 } 11566 // Restore of old package succeeded. Update permissions. 11567 // writer 11568 synchronized (mPackages) { 11569 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11570 UPDATE_PERMISSIONS_ALL); 11571 // can downgrade to reader 11572 mSettings.writeLPr(); 11573 } 11574 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11575 } 11576 } 11577 } 11578 11579 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11580 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11581 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11582 String volumeUuid, PackageInstalledInfo res) { 11583 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11584 + ", old=" + deletedPackage); 11585 boolean disabledSystem = false; 11586 boolean updatedSettings = false; 11587 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11588 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11589 != 0) { 11590 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11591 } 11592 String packageName = deletedPackage.packageName; 11593 if (packageName == null) { 11594 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11595 "Attempt to delete null packageName."); 11596 return; 11597 } 11598 PackageParser.Package oldPkg; 11599 PackageSetting oldPkgSetting; 11600 // reader 11601 synchronized (mPackages) { 11602 oldPkg = mPackages.get(packageName); 11603 oldPkgSetting = mSettings.mPackages.get(packageName); 11604 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11605 (oldPkgSetting == null)) { 11606 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11607 "Couldn't find package:" + packageName + " information"); 11608 return; 11609 } 11610 } 11611 11612 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11613 res.removedInfo.removedPackage = packageName; 11614 // Remove existing system package 11615 removePackageLI(oldPkgSetting, true); 11616 // writer 11617 synchronized (mPackages) { 11618 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11619 if (!disabledSystem && deletedPackage != null) { 11620 // We didn't need to disable the .apk as a current system package, 11621 // which means we are replacing another update that is already 11622 // installed. We need to make sure to delete the older one's .apk. 11623 res.removedInfo.args = createInstallArgsForExisting(0, 11624 deletedPackage.applicationInfo.getCodePath(), 11625 deletedPackage.applicationInfo.getResourcePath(), 11626 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11627 } else { 11628 res.removedInfo.args = null; 11629 } 11630 } 11631 11632 // Successfully disabled the old package. Now proceed with re-installation 11633 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11634 11635 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11636 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11637 11638 PackageParser.Package newPackage = null; 11639 try { 11640 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11641 if (newPackage.mExtras != null) { 11642 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11643 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11644 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11645 11646 // is the update attempting to change shared user? that isn't going to work... 11647 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11648 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11649 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11650 + " to " + newPkgSetting.sharedUser); 11651 updatedSettings = true; 11652 } 11653 } 11654 11655 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11656 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11657 perUserInstalled, res, user); 11658 updatedSettings = true; 11659 } 11660 11661 } catch (PackageManagerException e) { 11662 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11663 } 11664 11665 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11666 // Re installation failed. Restore old information 11667 // Remove new pkg information 11668 if (newPackage != null) { 11669 removeInstalledPackageLI(newPackage, true); 11670 } 11671 // Add back the old system package 11672 try { 11673 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11674 } catch (PackageManagerException e) { 11675 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11676 } 11677 // Restore the old system information in Settings 11678 synchronized (mPackages) { 11679 if (disabledSystem) { 11680 mSettings.enableSystemPackageLPw(packageName); 11681 } 11682 if (updatedSettings) { 11683 mSettings.setInstallerPackageName(packageName, 11684 oldPkgSetting.installerPackageName); 11685 } 11686 mSettings.writeLPr(); 11687 } 11688 } 11689 } 11690 11691 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11692 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11693 UserHandle user) { 11694 String pkgName = newPackage.packageName; 11695 synchronized (mPackages) { 11696 //write settings. the installStatus will be incomplete at this stage. 11697 //note that the new package setting would have already been 11698 //added to mPackages. It hasn't been persisted yet. 11699 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11700 mSettings.writeLPr(); 11701 } 11702 11703 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11704 11705 synchronized (mPackages) { 11706 updatePermissionsLPw(newPackage.packageName, newPackage, 11707 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11708 ? UPDATE_PERMISSIONS_ALL : 0)); 11709 // For system-bundled packages, we assume that installing an upgraded version 11710 // of the package implies that the user actually wants to run that new code, 11711 // so we enable the package. 11712 PackageSetting ps = mSettings.mPackages.get(pkgName); 11713 if (ps != null) { 11714 if (isSystemApp(newPackage)) { 11715 // NB: implicit assumption that system package upgrades apply to all users 11716 if (DEBUG_INSTALL) { 11717 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11718 } 11719 if (res.origUsers != null) { 11720 for (int userHandle : res.origUsers) { 11721 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11722 userHandle, installerPackageName); 11723 } 11724 } 11725 // Also convey the prior install/uninstall state 11726 if (allUsers != null && perUserInstalled != null) { 11727 for (int i = 0; i < allUsers.length; i++) { 11728 if (DEBUG_INSTALL) { 11729 Slog.d(TAG, " user " + allUsers[i] 11730 + " => " + perUserInstalled[i]); 11731 } 11732 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11733 } 11734 // these install state changes will be persisted in the 11735 // upcoming call to mSettings.writeLPr(). 11736 } 11737 } 11738 // It's implied that when a user requests installation, they want the app to be 11739 // installed and enabled. 11740 int userId = user.getIdentifier(); 11741 if (userId != UserHandle.USER_ALL) { 11742 ps.setInstalled(true, userId); 11743 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11744 } 11745 } 11746 res.name = pkgName; 11747 res.uid = newPackage.applicationInfo.uid; 11748 res.pkg = newPackage; 11749 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11750 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11751 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11752 //to update install status 11753 mSettings.writeLPr(); 11754 } 11755 } 11756 11757 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11758 final int installFlags = args.installFlags; 11759 final String installerPackageName = args.installerPackageName; 11760 final String volumeUuid = args.volumeUuid; 11761 final File tmpPackageFile = new File(args.getCodePath()); 11762 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11763 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11764 || (args.volumeUuid != null)); 11765 boolean replace = false; 11766 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11767 if (args.move != null) { 11768 // moving a complete application; perfom an initial scan on the new install location 11769 scanFlags |= SCAN_INITIAL; 11770 } 11771 // Result object to be returned 11772 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11773 11774 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11775 // Retrieve PackageSettings and parse package 11776 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11777 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11778 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11779 PackageParser pp = new PackageParser(); 11780 pp.setSeparateProcesses(mSeparateProcesses); 11781 pp.setDisplayMetrics(mMetrics); 11782 11783 final PackageParser.Package pkg; 11784 try { 11785 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11786 } catch (PackageParserException e) { 11787 res.setError("Failed parse during installPackageLI", e); 11788 return; 11789 } 11790 11791 // Mark that we have an install time CPU ABI override. 11792 pkg.cpuAbiOverride = args.abiOverride; 11793 11794 String pkgName = res.name = pkg.packageName; 11795 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11796 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11797 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11798 return; 11799 } 11800 } 11801 11802 try { 11803 pp.collectCertificates(pkg, parseFlags); 11804 pp.collectManifestDigest(pkg); 11805 } catch (PackageParserException e) { 11806 res.setError("Failed collect during installPackageLI", e); 11807 return; 11808 } 11809 11810 /* If the installer passed in a manifest digest, compare it now. */ 11811 if (args.manifestDigest != null) { 11812 if (DEBUG_INSTALL) { 11813 final String parsedManifest = pkg.manifestDigest == null ? "null" 11814 : pkg.manifestDigest.toString(); 11815 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11816 + parsedManifest); 11817 } 11818 11819 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11820 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11821 return; 11822 } 11823 } else if (DEBUG_INSTALL) { 11824 final String parsedManifest = pkg.manifestDigest == null 11825 ? "null" : pkg.manifestDigest.toString(); 11826 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11827 } 11828 11829 // Get rid of all references to package scan path via parser. 11830 pp = null; 11831 String oldCodePath = null; 11832 boolean systemApp = false; 11833 synchronized (mPackages) { 11834 // Check if installing already existing package 11835 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11836 String oldName = mSettings.mRenamedPackages.get(pkgName); 11837 if (pkg.mOriginalPackages != null 11838 && pkg.mOriginalPackages.contains(oldName) 11839 && mPackages.containsKey(oldName)) { 11840 // This package is derived from an original package, 11841 // and this device has been updating from that original 11842 // name. We must continue using the original name, so 11843 // rename the new package here. 11844 pkg.setPackageName(oldName); 11845 pkgName = pkg.packageName; 11846 replace = true; 11847 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11848 + oldName + " pkgName=" + pkgName); 11849 } else if (mPackages.containsKey(pkgName)) { 11850 // This package, under its official name, already exists 11851 // on the device; we should replace it. 11852 replace = true; 11853 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11854 } 11855 11856 // Prevent apps opting out from runtime permissions 11857 if (replace) { 11858 PackageParser.Package oldPackage = mPackages.get(pkgName); 11859 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11860 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11861 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11862 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11863 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11864 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11865 + " doesn't support runtime permissions but the old" 11866 + " target SDK " + oldTargetSdk + " does."); 11867 return; 11868 } 11869 } 11870 } 11871 11872 PackageSetting ps = mSettings.mPackages.get(pkgName); 11873 if (ps != null) { 11874 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11875 11876 // Quick sanity check that we're signed correctly if updating; 11877 // we'll check this again later when scanning, but we want to 11878 // bail early here before tripping over redefined permissions. 11879 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11880 if (!checkUpgradeKeySetLP(ps, pkg)) { 11881 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11882 + pkg.packageName + " upgrade keys do not match the " 11883 + "previously installed version"); 11884 return; 11885 } 11886 } else { 11887 try { 11888 verifySignaturesLP(ps, pkg); 11889 } catch (PackageManagerException e) { 11890 res.setError(e.error, e.getMessage()); 11891 return; 11892 } 11893 } 11894 11895 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11896 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11897 systemApp = (ps.pkg.applicationInfo.flags & 11898 ApplicationInfo.FLAG_SYSTEM) != 0; 11899 } 11900 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11901 } 11902 11903 // Check whether the newly-scanned package wants to define an already-defined perm 11904 int N = pkg.permissions.size(); 11905 for (int i = N-1; i >= 0; i--) { 11906 PackageParser.Permission perm = pkg.permissions.get(i); 11907 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11908 if (bp != null) { 11909 // If the defining package is signed with our cert, it's okay. This 11910 // also includes the "updating the same package" case, of course. 11911 // "updating same package" could also involve key-rotation. 11912 final boolean sigsOk; 11913 if (bp.sourcePackage.equals(pkg.packageName) 11914 && (bp.packageSetting instanceof PackageSetting) 11915 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11916 scanFlags))) { 11917 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11918 } else { 11919 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11920 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11921 } 11922 if (!sigsOk) { 11923 // If the owning package is the system itself, we log but allow 11924 // install to proceed; we fail the install on all other permission 11925 // redefinitions. 11926 if (!bp.sourcePackage.equals("android")) { 11927 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11928 + pkg.packageName + " attempting to redeclare permission " 11929 + perm.info.name + " already owned by " + bp.sourcePackage); 11930 res.origPermission = perm.info.name; 11931 res.origPackage = bp.sourcePackage; 11932 return; 11933 } else { 11934 Slog.w(TAG, "Package " + pkg.packageName 11935 + " attempting to redeclare system permission " 11936 + perm.info.name + "; ignoring new declaration"); 11937 pkg.permissions.remove(i); 11938 } 11939 } 11940 } 11941 } 11942 11943 } 11944 11945 if (systemApp && onExternal) { 11946 // Disable updates to system apps on sdcard 11947 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11948 "Cannot install updates to system apps on sdcard"); 11949 return; 11950 } 11951 11952 if (args.move != null) { 11953 // We did an in-place move, so dex is ready to roll 11954 scanFlags |= SCAN_NO_DEX; 11955 scanFlags |= SCAN_MOVE; 11956 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11957 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11958 scanFlags |= SCAN_NO_DEX; 11959 11960 try { 11961 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11962 true /* extract libs */); 11963 } catch (PackageManagerException pme) { 11964 Slog.e(TAG, "Error deriving application ABI", pme); 11965 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11966 return; 11967 } 11968 11969 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11970 int result = mPackageDexOptimizer 11971 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11972 false /* defer */, false /* inclDependencies */); 11973 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11974 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11975 return; 11976 } 11977 } 11978 11979 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11980 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11981 return; 11982 } 11983 11984 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 11985 11986 if (replace) { 11987 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11988 installerPackageName, volumeUuid, res); 11989 } else { 11990 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11991 args.user, installerPackageName, volumeUuid, res); 11992 } 11993 synchronized (mPackages) { 11994 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11995 if (ps != null) { 11996 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11997 } 11998 } 11999 } 12000 12001 private void startIntentFilterVerifications(int userId, boolean replacing, 12002 PackageParser.Package pkg) { 12003 if (mIntentFilterVerifierComponent == null) { 12004 Slog.w(TAG, "No IntentFilter verification will not be done as " 12005 + "there is no IntentFilterVerifier available!"); 12006 return; 12007 } 12008 12009 final int verifierUid = getPackageUid( 12010 mIntentFilterVerifierComponent.getPackageName(), 12011 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12012 12013 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12014 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12015 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12016 mHandler.sendMessage(msg); 12017 } 12018 12019 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12020 PackageParser.Package pkg) { 12021 int size = pkg.activities.size(); 12022 if (size == 0) { 12023 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12024 "No activity, so no need to verify any IntentFilter!"); 12025 return; 12026 } 12027 12028 final boolean hasDomainURLs = hasDomainURLs(pkg); 12029 if (!hasDomainURLs) { 12030 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12031 "No domain URLs, so no need to verify any IntentFilter!"); 12032 return; 12033 } 12034 12035 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12036 + " if any IntentFilter from the " + size 12037 + " Activities needs verification ..."); 12038 12039 int count = 0; 12040 final String packageName = pkg.packageName; 12041 12042 synchronized (mPackages) { 12043 // If this is a new install and we see that we've already run verification for this 12044 // package, we have nothing to do: it means the state was restored from backup. 12045 if (!replacing) { 12046 IntentFilterVerificationInfo ivi = 12047 mSettings.getIntentFilterVerificationLPr(packageName); 12048 if (ivi != null) { 12049 if (DEBUG_DOMAIN_VERIFICATION) { 12050 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12051 + ivi.getStatusString()); 12052 } 12053 return; 12054 } 12055 } 12056 12057 // If any filters need to be verified, then all need to be. 12058 boolean needToVerify = false; 12059 for (PackageParser.Activity a : pkg.activities) { 12060 for (ActivityIntentInfo filter : a.intents) { 12061 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12062 if (DEBUG_DOMAIN_VERIFICATION) { 12063 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12064 } 12065 needToVerify = true; 12066 break; 12067 } 12068 } 12069 } 12070 12071 if (needToVerify) { 12072 final int verificationId = mIntentFilterVerificationToken++; 12073 for (PackageParser.Activity a : pkg.activities) { 12074 for (ActivityIntentInfo filter : a.intents) { 12075 if (filter.hasOnlyWebDataURI() && needsNetworkVerificationLPr(filter)) { 12076 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12077 "Verification needed for IntentFilter:" + filter.toString()); 12078 mIntentFilterVerifier.addOneIntentFilterVerification( 12079 verifierUid, userId, verificationId, filter, packageName); 12080 count++; 12081 } 12082 } 12083 } 12084 } 12085 } 12086 12087 if (count > 0) { 12088 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12089 + " IntentFilter verification" + (count > 1 ? "s" : "") 12090 + " for userId:" + userId); 12091 mIntentFilterVerifier.startVerifications(userId); 12092 } else { 12093 if (DEBUG_DOMAIN_VERIFICATION) { 12094 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12095 } 12096 } 12097 } 12098 12099 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12100 final ComponentName cn = filter.activity.getComponentName(); 12101 final String packageName = cn.getPackageName(); 12102 12103 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12104 packageName); 12105 if (ivi == null) { 12106 return true; 12107 } 12108 int status = ivi.getStatus(); 12109 switch (status) { 12110 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12111 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12112 return true; 12113 12114 default: 12115 // Nothing to do 12116 return false; 12117 } 12118 } 12119 12120 private static boolean isMultiArch(PackageSetting ps) { 12121 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12122 } 12123 12124 private static boolean isMultiArch(ApplicationInfo info) { 12125 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12126 } 12127 12128 private static boolean isExternal(PackageParser.Package pkg) { 12129 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12130 } 12131 12132 private static boolean isExternal(PackageSetting ps) { 12133 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12134 } 12135 12136 private static boolean isExternal(ApplicationInfo info) { 12137 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12138 } 12139 12140 private static boolean isSystemApp(PackageParser.Package pkg) { 12141 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12142 } 12143 12144 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12145 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12146 } 12147 12148 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12149 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12150 } 12151 12152 private static boolean isSystemApp(PackageSetting ps) { 12153 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12154 } 12155 12156 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12157 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12158 } 12159 12160 private int packageFlagsToInstallFlags(PackageSetting ps) { 12161 int installFlags = 0; 12162 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12163 // This existing package was an external ASEC install when we have 12164 // the external flag without a UUID 12165 installFlags |= PackageManager.INSTALL_EXTERNAL; 12166 } 12167 if (ps.isForwardLocked()) { 12168 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12169 } 12170 return installFlags; 12171 } 12172 12173 private void deleteTempPackageFiles() { 12174 final FilenameFilter filter = new FilenameFilter() { 12175 public boolean accept(File dir, String name) { 12176 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12177 } 12178 }; 12179 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12180 file.delete(); 12181 } 12182 } 12183 12184 @Override 12185 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12186 int flags) { 12187 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12188 flags); 12189 } 12190 12191 @Override 12192 public void deletePackage(final String packageName, 12193 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12194 mContext.enforceCallingOrSelfPermission( 12195 android.Manifest.permission.DELETE_PACKAGES, null); 12196 final int uid = Binder.getCallingUid(); 12197 if (UserHandle.getUserId(uid) != userId) { 12198 mContext.enforceCallingPermission( 12199 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12200 "deletePackage for user " + userId); 12201 } 12202 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12203 try { 12204 observer.onPackageDeleted(packageName, 12205 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12206 } catch (RemoteException re) { 12207 } 12208 return; 12209 } 12210 12211 boolean uninstallBlocked = false; 12212 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12213 int[] users = sUserManager.getUserIds(); 12214 for (int i = 0; i < users.length; ++i) { 12215 if (getBlockUninstallForUser(packageName, users[i])) { 12216 uninstallBlocked = true; 12217 break; 12218 } 12219 } 12220 } else { 12221 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12222 } 12223 if (uninstallBlocked) { 12224 try { 12225 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12226 null); 12227 } catch (RemoteException re) { 12228 } 12229 return; 12230 } 12231 12232 if (DEBUG_REMOVE) { 12233 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12234 } 12235 // Queue up an async operation since the package deletion may take a little while. 12236 mHandler.post(new Runnable() { 12237 public void run() { 12238 mHandler.removeCallbacks(this); 12239 final int returnCode = deletePackageX(packageName, userId, flags); 12240 if (observer != null) { 12241 try { 12242 observer.onPackageDeleted(packageName, returnCode, null); 12243 } catch (RemoteException e) { 12244 Log.i(TAG, "Observer no longer exists."); 12245 } //end catch 12246 } //end if 12247 } //end run 12248 }); 12249 } 12250 12251 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12252 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12253 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12254 try { 12255 if (dpm != null) { 12256 if (dpm.isDeviceOwner(packageName)) { 12257 return true; 12258 } 12259 int[] users; 12260 if (userId == UserHandle.USER_ALL) { 12261 users = sUserManager.getUserIds(); 12262 } else { 12263 users = new int[]{userId}; 12264 } 12265 for (int i = 0; i < users.length; ++i) { 12266 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12267 return true; 12268 } 12269 } 12270 } 12271 } catch (RemoteException e) { 12272 } 12273 return false; 12274 } 12275 12276 /** 12277 * This method is an internal method that could be get invoked either 12278 * to delete an installed package or to clean up a failed installation. 12279 * After deleting an installed package, a broadcast is sent to notify any 12280 * listeners that the package has been installed. For cleaning up a failed 12281 * installation, the broadcast is not necessary since the package's 12282 * installation wouldn't have sent the initial broadcast either 12283 * The key steps in deleting a package are 12284 * deleting the package information in internal structures like mPackages, 12285 * deleting the packages base directories through installd 12286 * updating mSettings to reflect current status 12287 * persisting settings for later use 12288 * sending a broadcast if necessary 12289 */ 12290 private int deletePackageX(String packageName, int userId, int flags) { 12291 final PackageRemovedInfo info = new PackageRemovedInfo(); 12292 final boolean res; 12293 12294 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12295 ? UserHandle.ALL : new UserHandle(userId); 12296 12297 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12298 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12299 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12300 } 12301 12302 boolean removedForAllUsers = false; 12303 boolean systemUpdate = false; 12304 12305 // for the uninstall-updates case and restricted profiles, remember the per- 12306 // userhandle installed state 12307 int[] allUsers; 12308 boolean[] perUserInstalled; 12309 synchronized (mPackages) { 12310 PackageSetting ps = mSettings.mPackages.get(packageName); 12311 allUsers = sUserManager.getUserIds(); 12312 perUserInstalled = new boolean[allUsers.length]; 12313 for (int i = 0; i < allUsers.length; i++) { 12314 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12315 } 12316 } 12317 12318 synchronized (mInstallLock) { 12319 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12320 res = deletePackageLI(packageName, removeForUser, 12321 true, allUsers, perUserInstalled, 12322 flags | REMOVE_CHATTY, info, true); 12323 systemUpdate = info.isRemovedPackageSystemUpdate; 12324 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12325 removedForAllUsers = true; 12326 } 12327 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12328 + " removedForAllUsers=" + removedForAllUsers); 12329 } 12330 12331 if (res) { 12332 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12333 12334 // If the removed package was a system update, the old system package 12335 // was re-enabled; we need to broadcast this information 12336 if (systemUpdate) { 12337 Bundle extras = new Bundle(1); 12338 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12339 ? info.removedAppId : info.uid); 12340 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12341 12342 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12343 extras, null, null, null); 12344 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12345 extras, null, null, null); 12346 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12347 null, packageName, null, null); 12348 } 12349 } 12350 // Force a gc here. 12351 Runtime.getRuntime().gc(); 12352 // Delete the resources here after sending the broadcast to let 12353 // other processes clean up before deleting resources. 12354 if (info.args != null) { 12355 synchronized (mInstallLock) { 12356 info.args.doPostDeleteLI(true); 12357 } 12358 } 12359 12360 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12361 } 12362 12363 class PackageRemovedInfo { 12364 String removedPackage; 12365 int uid = -1; 12366 int removedAppId = -1; 12367 int[] removedUsers = null; 12368 boolean isRemovedPackageSystemUpdate = false; 12369 // Clean up resources deleted packages. 12370 InstallArgs args = null; 12371 12372 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12373 Bundle extras = new Bundle(1); 12374 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12375 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12376 if (replacing) { 12377 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12378 } 12379 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12380 if (removedPackage != null) { 12381 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12382 extras, null, null, removedUsers); 12383 if (fullRemove && !replacing) { 12384 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12385 extras, null, null, removedUsers); 12386 } 12387 } 12388 if (removedAppId >= 0) { 12389 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12390 removedUsers); 12391 } 12392 } 12393 } 12394 12395 /* 12396 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12397 * flag is not set, the data directory is removed as well. 12398 * make sure this flag is set for partially installed apps. If not its meaningless to 12399 * delete a partially installed application. 12400 */ 12401 private void removePackageDataLI(PackageSetting ps, 12402 int[] allUserHandles, boolean[] perUserInstalled, 12403 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12404 String packageName = ps.name; 12405 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12406 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12407 // Retrieve object to delete permissions for shared user later on 12408 final PackageSetting deletedPs; 12409 // reader 12410 synchronized (mPackages) { 12411 deletedPs = mSettings.mPackages.get(packageName); 12412 if (outInfo != null) { 12413 outInfo.removedPackage = packageName; 12414 outInfo.removedUsers = deletedPs != null 12415 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12416 : null; 12417 } 12418 } 12419 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12420 removeDataDirsLI(ps.volumeUuid, packageName); 12421 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12422 } 12423 // writer 12424 synchronized (mPackages) { 12425 if (deletedPs != null) { 12426 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12427 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12428 clearDefaultBrowserIfNeeded(packageName); 12429 if (outInfo != null) { 12430 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12431 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12432 } 12433 updatePermissionsLPw(deletedPs.name, null, 0); 12434 if (deletedPs.sharedUser != null) { 12435 // Remove permissions associated with package. Since runtime 12436 // permissions are per user we have to kill the removed package 12437 // or packages running under the shared user of the removed 12438 // package if revoking the permissions requested only by the removed 12439 // package is successful and this causes a change in gids. 12440 for (int userId : UserManagerService.getInstance().getUserIds()) { 12441 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12442 userId); 12443 if (userIdToKill == UserHandle.USER_ALL 12444 || userIdToKill >= UserHandle.USER_OWNER) { 12445 // If gids changed for this user, kill all affected packages. 12446 mHandler.post(new Runnable() { 12447 @Override 12448 public void run() { 12449 // This has to happen with no lock held. 12450 killSettingPackagesForUser(deletedPs, userIdToKill, 12451 KILL_APP_REASON_GIDS_CHANGED); 12452 } 12453 }); 12454 break; 12455 } 12456 } 12457 } 12458 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12459 } 12460 // make sure to preserve per-user disabled state if this removal was just 12461 // a downgrade of a system app to the factory package 12462 if (allUserHandles != null && perUserInstalled != null) { 12463 if (DEBUG_REMOVE) { 12464 Slog.d(TAG, "Propagating install state across downgrade"); 12465 } 12466 for (int i = 0; i < allUserHandles.length; i++) { 12467 if (DEBUG_REMOVE) { 12468 Slog.d(TAG, " user " + allUserHandles[i] 12469 + " => " + perUserInstalled[i]); 12470 } 12471 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12472 } 12473 } 12474 } 12475 // can downgrade to reader 12476 if (writeSettings) { 12477 // Save settings now 12478 mSettings.writeLPr(); 12479 } 12480 } 12481 if (outInfo != null) { 12482 // A user ID was deleted here. Go through all users and remove it 12483 // from KeyStore. 12484 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12485 } 12486 } 12487 12488 static boolean locationIsPrivileged(File path) { 12489 try { 12490 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12491 .getCanonicalPath(); 12492 return path.getCanonicalPath().startsWith(privilegedAppDir); 12493 } catch (IOException e) { 12494 Slog.e(TAG, "Unable to access code path " + path); 12495 } 12496 return false; 12497 } 12498 12499 /* 12500 * Tries to delete system package. 12501 */ 12502 private boolean deleteSystemPackageLI(PackageSetting newPs, 12503 int[] allUserHandles, boolean[] perUserInstalled, 12504 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12505 final boolean applyUserRestrictions 12506 = (allUserHandles != null) && (perUserInstalled != null); 12507 PackageSetting disabledPs = null; 12508 // Confirm if the system package has been updated 12509 // An updated system app can be deleted. This will also have to restore 12510 // the system pkg from system partition 12511 // reader 12512 synchronized (mPackages) { 12513 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12514 } 12515 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12516 + " disabledPs=" + disabledPs); 12517 if (disabledPs == null) { 12518 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12519 return false; 12520 } else if (DEBUG_REMOVE) { 12521 Slog.d(TAG, "Deleting system pkg from data partition"); 12522 } 12523 if (DEBUG_REMOVE) { 12524 if (applyUserRestrictions) { 12525 Slog.d(TAG, "Remembering install states:"); 12526 for (int i = 0; i < allUserHandles.length; i++) { 12527 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12528 } 12529 } 12530 } 12531 // Delete the updated package 12532 outInfo.isRemovedPackageSystemUpdate = true; 12533 if (disabledPs.versionCode < newPs.versionCode) { 12534 // Delete data for downgrades 12535 flags &= ~PackageManager.DELETE_KEEP_DATA; 12536 } else { 12537 // Preserve data by setting flag 12538 flags |= PackageManager.DELETE_KEEP_DATA; 12539 } 12540 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12541 allUserHandles, perUserInstalled, outInfo, writeSettings); 12542 if (!ret) { 12543 return false; 12544 } 12545 // writer 12546 synchronized (mPackages) { 12547 // Reinstate the old system package 12548 mSettings.enableSystemPackageLPw(newPs.name); 12549 // Remove any native libraries from the upgraded package. 12550 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12551 } 12552 // Install the system package 12553 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12554 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12555 if (locationIsPrivileged(disabledPs.codePath)) { 12556 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12557 } 12558 12559 final PackageParser.Package newPkg; 12560 try { 12561 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12562 } catch (PackageManagerException e) { 12563 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12564 return false; 12565 } 12566 12567 // writer 12568 synchronized (mPackages) { 12569 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12570 updatePermissionsLPw(newPkg.packageName, newPkg, 12571 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12572 if (applyUserRestrictions) { 12573 if (DEBUG_REMOVE) { 12574 Slog.d(TAG, "Propagating install state across reinstall"); 12575 } 12576 for (int i = 0; i < allUserHandles.length; i++) { 12577 if (DEBUG_REMOVE) { 12578 Slog.d(TAG, " user " + allUserHandles[i] 12579 + " => " + perUserInstalled[i]); 12580 } 12581 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12582 } 12583 // Regardless of writeSettings we need to ensure that this restriction 12584 // state propagation is persisted 12585 mSettings.writeAllUsersPackageRestrictionsLPr(); 12586 } 12587 // can downgrade to reader here 12588 if (writeSettings) { 12589 mSettings.writeLPr(); 12590 } 12591 } 12592 return true; 12593 } 12594 12595 private boolean deleteInstalledPackageLI(PackageSetting ps, 12596 boolean deleteCodeAndResources, int flags, 12597 int[] allUserHandles, boolean[] perUserInstalled, 12598 PackageRemovedInfo outInfo, boolean writeSettings) { 12599 if (outInfo != null) { 12600 outInfo.uid = ps.appId; 12601 } 12602 12603 // Delete package data from internal structures and also remove data if flag is set 12604 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12605 12606 // Delete application code and resources 12607 if (deleteCodeAndResources && (outInfo != null)) { 12608 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12609 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12610 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12611 } 12612 return true; 12613 } 12614 12615 @Override 12616 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12617 int userId) { 12618 mContext.enforceCallingOrSelfPermission( 12619 android.Manifest.permission.DELETE_PACKAGES, null); 12620 synchronized (mPackages) { 12621 PackageSetting ps = mSettings.mPackages.get(packageName); 12622 if (ps == null) { 12623 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12624 return false; 12625 } 12626 if (!ps.getInstalled(userId)) { 12627 // Can't block uninstall for an app that is not installed or enabled. 12628 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12629 return false; 12630 } 12631 ps.setBlockUninstall(blockUninstall, userId); 12632 mSettings.writePackageRestrictionsLPr(userId); 12633 } 12634 return true; 12635 } 12636 12637 @Override 12638 public boolean getBlockUninstallForUser(String packageName, int userId) { 12639 synchronized (mPackages) { 12640 PackageSetting ps = mSettings.mPackages.get(packageName); 12641 if (ps == null) { 12642 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12643 return false; 12644 } 12645 return ps.getBlockUninstall(userId); 12646 } 12647 } 12648 12649 /* 12650 * This method handles package deletion in general 12651 */ 12652 private boolean deletePackageLI(String packageName, UserHandle user, 12653 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12654 int flags, PackageRemovedInfo outInfo, 12655 boolean writeSettings) { 12656 if (packageName == null) { 12657 Slog.w(TAG, "Attempt to delete null packageName."); 12658 return false; 12659 } 12660 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12661 PackageSetting ps; 12662 boolean dataOnly = false; 12663 int removeUser = -1; 12664 int appId = -1; 12665 synchronized (mPackages) { 12666 ps = mSettings.mPackages.get(packageName); 12667 if (ps == null) { 12668 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12669 return false; 12670 } 12671 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12672 && user.getIdentifier() != UserHandle.USER_ALL) { 12673 // The caller is asking that the package only be deleted for a single 12674 // user. To do this, we just mark its uninstalled state and delete 12675 // its data. If this is a system app, we only allow this to happen if 12676 // they have set the special DELETE_SYSTEM_APP which requests different 12677 // semantics than normal for uninstalling system apps. 12678 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12679 ps.setUserState(user.getIdentifier(), 12680 COMPONENT_ENABLED_STATE_DEFAULT, 12681 false, //installed 12682 true, //stopped 12683 true, //notLaunched 12684 false, //hidden 12685 null, null, null, 12686 false, // blockUninstall 12687 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12688 if (!isSystemApp(ps)) { 12689 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12690 // Other user still have this package installed, so all 12691 // we need to do is clear this user's data and save that 12692 // it is uninstalled. 12693 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12694 removeUser = user.getIdentifier(); 12695 appId = ps.appId; 12696 scheduleWritePackageRestrictionsLocked(removeUser); 12697 } else { 12698 // We need to set it back to 'installed' so the uninstall 12699 // broadcasts will be sent correctly. 12700 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12701 ps.setInstalled(true, user.getIdentifier()); 12702 } 12703 } else { 12704 // This is a system app, so we assume that the 12705 // other users still have this package installed, so all 12706 // we need to do is clear this user's data and save that 12707 // it is uninstalled. 12708 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12709 removeUser = user.getIdentifier(); 12710 appId = ps.appId; 12711 scheduleWritePackageRestrictionsLocked(removeUser); 12712 } 12713 } 12714 } 12715 12716 if (removeUser >= 0) { 12717 // From above, we determined that we are deleting this only 12718 // for a single user. Continue the work here. 12719 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12720 if (outInfo != null) { 12721 outInfo.removedPackage = packageName; 12722 outInfo.removedAppId = appId; 12723 outInfo.removedUsers = new int[] {removeUser}; 12724 } 12725 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12726 removeKeystoreDataIfNeeded(removeUser, appId); 12727 schedulePackageCleaning(packageName, removeUser, false); 12728 synchronized (mPackages) { 12729 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12730 scheduleWritePackageRestrictionsLocked(removeUser); 12731 } 12732 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12733 removeUser); 12734 } 12735 return true; 12736 } 12737 12738 if (dataOnly) { 12739 // Delete application data first 12740 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12741 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12742 return true; 12743 } 12744 12745 boolean ret = false; 12746 if (isSystemApp(ps)) { 12747 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12748 // When an updated system application is deleted we delete the existing resources as well and 12749 // fall back to existing code in system partition 12750 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12751 flags, outInfo, writeSettings); 12752 } else { 12753 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12754 // Kill application pre-emptively especially for apps on sd. 12755 killApplication(packageName, ps.appId, "uninstall pkg"); 12756 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12757 allUserHandles, perUserInstalled, 12758 outInfo, writeSettings); 12759 } 12760 12761 return ret; 12762 } 12763 12764 private final class ClearStorageConnection implements ServiceConnection { 12765 IMediaContainerService mContainerService; 12766 12767 @Override 12768 public void onServiceConnected(ComponentName name, IBinder service) { 12769 synchronized (this) { 12770 mContainerService = IMediaContainerService.Stub.asInterface(service); 12771 notifyAll(); 12772 } 12773 } 12774 12775 @Override 12776 public void onServiceDisconnected(ComponentName name) { 12777 } 12778 } 12779 12780 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12781 final boolean mounted; 12782 if (Environment.isExternalStorageEmulated()) { 12783 mounted = true; 12784 } else { 12785 final String status = Environment.getExternalStorageState(); 12786 12787 mounted = status.equals(Environment.MEDIA_MOUNTED) 12788 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12789 } 12790 12791 if (!mounted) { 12792 return; 12793 } 12794 12795 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12796 int[] users; 12797 if (userId == UserHandle.USER_ALL) { 12798 users = sUserManager.getUserIds(); 12799 } else { 12800 users = new int[] { userId }; 12801 } 12802 final ClearStorageConnection conn = new ClearStorageConnection(); 12803 if (mContext.bindServiceAsUser( 12804 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12805 try { 12806 for (int curUser : users) { 12807 long timeout = SystemClock.uptimeMillis() + 5000; 12808 synchronized (conn) { 12809 long now = SystemClock.uptimeMillis(); 12810 while (conn.mContainerService == null && now < timeout) { 12811 try { 12812 conn.wait(timeout - now); 12813 } catch (InterruptedException e) { 12814 } 12815 } 12816 } 12817 if (conn.mContainerService == null) { 12818 return; 12819 } 12820 12821 final UserEnvironment userEnv = new UserEnvironment(curUser); 12822 clearDirectory(conn.mContainerService, 12823 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12824 if (allData) { 12825 clearDirectory(conn.mContainerService, 12826 userEnv.buildExternalStorageAppDataDirs(packageName)); 12827 clearDirectory(conn.mContainerService, 12828 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12829 } 12830 } 12831 } finally { 12832 mContext.unbindService(conn); 12833 } 12834 } 12835 } 12836 12837 @Override 12838 public void clearApplicationUserData(final String packageName, 12839 final IPackageDataObserver observer, final int userId) { 12840 mContext.enforceCallingOrSelfPermission( 12841 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12842 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12843 // Queue up an async operation since the package deletion may take a little while. 12844 mHandler.post(new Runnable() { 12845 public void run() { 12846 mHandler.removeCallbacks(this); 12847 final boolean succeeded; 12848 synchronized (mInstallLock) { 12849 succeeded = clearApplicationUserDataLI(packageName, userId); 12850 } 12851 clearExternalStorageDataSync(packageName, userId, true); 12852 if (succeeded) { 12853 // invoke DeviceStorageMonitor's update method to clear any notifications 12854 DeviceStorageMonitorInternal 12855 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12856 if (dsm != null) { 12857 dsm.checkMemory(); 12858 } 12859 } 12860 if(observer != null) { 12861 try { 12862 observer.onRemoveCompleted(packageName, succeeded); 12863 } catch (RemoteException e) { 12864 Log.i(TAG, "Observer no longer exists."); 12865 } 12866 } //end if observer 12867 } //end run 12868 }); 12869 } 12870 12871 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12872 if (packageName == null) { 12873 Slog.w(TAG, "Attempt to delete null packageName."); 12874 return false; 12875 } 12876 12877 // Try finding details about the requested package 12878 PackageParser.Package pkg; 12879 synchronized (mPackages) { 12880 pkg = mPackages.get(packageName); 12881 if (pkg == null) { 12882 final PackageSetting ps = mSettings.mPackages.get(packageName); 12883 if (ps != null) { 12884 pkg = ps.pkg; 12885 } 12886 } 12887 12888 if (pkg == null) { 12889 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12890 return false; 12891 } 12892 12893 PackageSetting ps = (PackageSetting) pkg.mExtras; 12894 PermissionsState permissionsState = ps.getPermissionsState(); 12895 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12896 } 12897 12898 // Always delete data directories for package, even if we found no other 12899 // record of app. This helps users recover from UID mismatches without 12900 // resorting to a full data wipe. 12901 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12902 if (retCode < 0) { 12903 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12904 return false; 12905 } 12906 12907 final int appId = pkg.applicationInfo.uid; 12908 removeKeystoreDataIfNeeded(userId, appId); 12909 12910 // Create a native library symlink only if we have native libraries 12911 // and if the native libraries are 32 bit libraries. We do not provide 12912 // this symlink for 64 bit libraries. 12913 if (pkg.applicationInfo.primaryCpuAbi != null && 12914 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12915 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12916 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12917 nativeLibPath, userId) < 0) { 12918 Slog.w(TAG, "Failed linking native library dir"); 12919 return false; 12920 } 12921 } 12922 12923 return true; 12924 } 12925 12926 12927 /** 12928 * Revokes granted runtime permissions and clears resettable flags 12929 * which are flags that can be set by a user interaction. 12930 * 12931 * @param permissionsState The permission state to reset. 12932 * @param userId The device user for which to do a reset. 12933 */ 12934 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12935 PermissionsState permissionsState, int userId) { 12936 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12937 | PackageManager.FLAG_PERMISSION_USER_FIXED 12938 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12939 12940 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 12941 } 12942 12943 /** 12944 * Revokes granted runtime permissions and clears all flags. 12945 * 12946 * @param permissionsState The permission state to reset. 12947 * @param userId The device user for which to do a reset. 12948 */ 12949 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 12950 PermissionsState permissionsState, int userId) { 12951 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 12952 PackageManager.MASK_PERMISSION_FLAGS); 12953 } 12954 12955 /** 12956 * Revokes granted runtime permissions and clears certain flags. 12957 * 12958 * @param permissionsState The permission state to reset. 12959 * @param userId The device user for which to do a reset. 12960 * @param flags The flags that is going to be reset. 12961 */ 12962 private void revokeRuntimePermissionsAndClearFlagsLocked( 12963 PermissionsState permissionsState, int userId, int flags) { 12964 boolean needsWrite = false; 12965 12966 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12967 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12968 if (bp != null) { 12969 permissionsState.revokeRuntimePermission(bp, userId); 12970 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 12971 needsWrite = true; 12972 } 12973 } 12974 12975 // Ensure default permissions are never cleared. 12976 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 12977 12978 if (needsWrite) { 12979 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12980 } 12981 } 12982 12983 /** 12984 * Remove entries from the keystore daemon. Will only remove it if the 12985 * {@code appId} is valid. 12986 */ 12987 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12988 if (appId < 0) { 12989 return; 12990 } 12991 12992 final KeyStore keyStore = KeyStore.getInstance(); 12993 if (keyStore != null) { 12994 if (userId == UserHandle.USER_ALL) { 12995 for (final int individual : sUserManager.getUserIds()) { 12996 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12997 } 12998 } else { 12999 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13000 } 13001 } else { 13002 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13003 } 13004 } 13005 13006 @Override 13007 public void deleteApplicationCacheFiles(final String packageName, 13008 final IPackageDataObserver observer) { 13009 mContext.enforceCallingOrSelfPermission( 13010 android.Manifest.permission.DELETE_CACHE_FILES, null); 13011 // Queue up an async operation since the package deletion may take a little while. 13012 final int userId = UserHandle.getCallingUserId(); 13013 mHandler.post(new Runnable() { 13014 public void run() { 13015 mHandler.removeCallbacks(this); 13016 final boolean succeded; 13017 synchronized (mInstallLock) { 13018 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13019 } 13020 clearExternalStorageDataSync(packageName, userId, false); 13021 if (observer != null) { 13022 try { 13023 observer.onRemoveCompleted(packageName, succeded); 13024 } catch (RemoteException e) { 13025 Log.i(TAG, "Observer no longer exists."); 13026 } 13027 } //end if observer 13028 } //end run 13029 }); 13030 } 13031 13032 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13033 if (packageName == null) { 13034 Slog.w(TAG, "Attempt to delete null packageName."); 13035 return false; 13036 } 13037 PackageParser.Package p; 13038 synchronized (mPackages) { 13039 p = mPackages.get(packageName); 13040 } 13041 if (p == null) { 13042 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13043 return false; 13044 } 13045 final ApplicationInfo applicationInfo = p.applicationInfo; 13046 if (applicationInfo == null) { 13047 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13048 return false; 13049 } 13050 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13051 if (retCode < 0) { 13052 Slog.w(TAG, "Couldn't remove cache files for package: " 13053 + packageName + " u" + userId); 13054 return false; 13055 } 13056 return true; 13057 } 13058 13059 @Override 13060 public void getPackageSizeInfo(final String packageName, int userHandle, 13061 final IPackageStatsObserver observer) { 13062 mContext.enforceCallingOrSelfPermission( 13063 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13064 if (packageName == null) { 13065 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13066 } 13067 13068 PackageStats stats = new PackageStats(packageName, userHandle); 13069 13070 /* 13071 * Queue up an async operation since the package measurement may take a 13072 * little while. 13073 */ 13074 Message msg = mHandler.obtainMessage(INIT_COPY); 13075 msg.obj = new MeasureParams(stats, observer); 13076 mHandler.sendMessage(msg); 13077 } 13078 13079 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13080 PackageStats pStats) { 13081 if (packageName == null) { 13082 Slog.w(TAG, "Attempt to get size of null packageName."); 13083 return false; 13084 } 13085 PackageParser.Package p; 13086 boolean dataOnly = false; 13087 String libDirRoot = null; 13088 String asecPath = null; 13089 PackageSetting ps = null; 13090 synchronized (mPackages) { 13091 p = mPackages.get(packageName); 13092 ps = mSettings.mPackages.get(packageName); 13093 if(p == null) { 13094 dataOnly = true; 13095 if((ps == null) || (ps.pkg == null)) { 13096 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13097 return false; 13098 } 13099 p = ps.pkg; 13100 } 13101 if (ps != null) { 13102 libDirRoot = ps.legacyNativeLibraryPathString; 13103 } 13104 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13105 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13106 if (secureContainerId != null) { 13107 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13108 } 13109 } 13110 } 13111 String publicSrcDir = null; 13112 if(!dataOnly) { 13113 final ApplicationInfo applicationInfo = p.applicationInfo; 13114 if (applicationInfo == null) { 13115 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13116 return false; 13117 } 13118 if (p.isForwardLocked()) { 13119 publicSrcDir = applicationInfo.getBaseResourcePath(); 13120 } 13121 } 13122 // TODO: extend to measure size of split APKs 13123 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13124 // not just the first level. 13125 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13126 // just the primary. 13127 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13128 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13129 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13130 if (res < 0) { 13131 return false; 13132 } 13133 13134 // Fix-up for forward-locked applications in ASEC containers. 13135 if (!isExternal(p)) { 13136 pStats.codeSize += pStats.externalCodeSize; 13137 pStats.externalCodeSize = 0L; 13138 } 13139 13140 return true; 13141 } 13142 13143 13144 @Override 13145 public void addPackageToPreferred(String packageName) { 13146 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13147 } 13148 13149 @Override 13150 public void removePackageFromPreferred(String packageName) { 13151 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13152 } 13153 13154 @Override 13155 public List<PackageInfo> getPreferredPackages(int flags) { 13156 return new ArrayList<PackageInfo>(); 13157 } 13158 13159 private int getUidTargetSdkVersionLockedLPr(int uid) { 13160 Object obj = mSettings.getUserIdLPr(uid); 13161 if (obj instanceof SharedUserSetting) { 13162 final SharedUserSetting sus = (SharedUserSetting) obj; 13163 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13164 final Iterator<PackageSetting> it = sus.packages.iterator(); 13165 while (it.hasNext()) { 13166 final PackageSetting ps = it.next(); 13167 if (ps.pkg != null) { 13168 int v = ps.pkg.applicationInfo.targetSdkVersion; 13169 if (v < vers) vers = v; 13170 } 13171 } 13172 return vers; 13173 } else if (obj instanceof PackageSetting) { 13174 final PackageSetting ps = (PackageSetting) obj; 13175 if (ps.pkg != null) { 13176 return ps.pkg.applicationInfo.targetSdkVersion; 13177 } 13178 } 13179 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13180 } 13181 13182 @Override 13183 public void addPreferredActivity(IntentFilter filter, int match, 13184 ComponentName[] set, ComponentName activity, int userId) { 13185 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13186 "Adding preferred"); 13187 } 13188 13189 private void addPreferredActivityInternal(IntentFilter filter, int match, 13190 ComponentName[] set, ComponentName activity, boolean always, int userId, 13191 String opname) { 13192 // writer 13193 int callingUid = Binder.getCallingUid(); 13194 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13195 if (filter.countActions() == 0) { 13196 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13197 return; 13198 } 13199 synchronized (mPackages) { 13200 if (mContext.checkCallingOrSelfPermission( 13201 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13202 != PackageManager.PERMISSION_GRANTED) { 13203 if (getUidTargetSdkVersionLockedLPr(callingUid) 13204 < Build.VERSION_CODES.FROYO) { 13205 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13206 + callingUid); 13207 return; 13208 } 13209 mContext.enforceCallingOrSelfPermission( 13210 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13211 } 13212 13213 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13214 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13215 + userId + ":"); 13216 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13217 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13218 scheduleWritePackageRestrictionsLocked(userId); 13219 } 13220 } 13221 13222 @Override 13223 public void replacePreferredActivity(IntentFilter filter, int match, 13224 ComponentName[] set, ComponentName activity, int userId) { 13225 if (filter.countActions() != 1) { 13226 throw new IllegalArgumentException( 13227 "replacePreferredActivity expects filter to have only 1 action."); 13228 } 13229 if (filter.countDataAuthorities() != 0 13230 || filter.countDataPaths() != 0 13231 || filter.countDataSchemes() > 1 13232 || filter.countDataTypes() != 0) { 13233 throw new IllegalArgumentException( 13234 "replacePreferredActivity expects filter to have no data authorities, " + 13235 "paths, or types; and at most one scheme."); 13236 } 13237 13238 final int callingUid = Binder.getCallingUid(); 13239 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13240 synchronized (mPackages) { 13241 if (mContext.checkCallingOrSelfPermission( 13242 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13243 != PackageManager.PERMISSION_GRANTED) { 13244 if (getUidTargetSdkVersionLockedLPr(callingUid) 13245 < Build.VERSION_CODES.FROYO) { 13246 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13247 + Binder.getCallingUid()); 13248 return; 13249 } 13250 mContext.enforceCallingOrSelfPermission( 13251 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13252 } 13253 13254 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13255 if (pir != null) { 13256 // Get all of the existing entries that exactly match this filter. 13257 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13258 if (existing != null && existing.size() == 1) { 13259 PreferredActivity cur = existing.get(0); 13260 if (DEBUG_PREFERRED) { 13261 Slog.i(TAG, "Checking replace of preferred:"); 13262 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13263 if (!cur.mPref.mAlways) { 13264 Slog.i(TAG, " -- CUR; not mAlways!"); 13265 } else { 13266 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13267 Slog.i(TAG, " -- CUR: mSet=" 13268 + Arrays.toString(cur.mPref.mSetComponents)); 13269 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13270 Slog.i(TAG, " -- NEW: mMatch=" 13271 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13272 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13273 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13274 } 13275 } 13276 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13277 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13278 && cur.mPref.sameSet(set)) { 13279 // Setting the preferred activity to what it happens to be already 13280 if (DEBUG_PREFERRED) { 13281 Slog.i(TAG, "Replacing with same preferred activity " 13282 + cur.mPref.mShortComponent + " for user " 13283 + userId + ":"); 13284 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13285 } 13286 return; 13287 } 13288 } 13289 13290 if (existing != null) { 13291 if (DEBUG_PREFERRED) { 13292 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13293 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13294 } 13295 for (int i = 0; i < existing.size(); i++) { 13296 PreferredActivity pa = existing.get(i); 13297 if (DEBUG_PREFERRED) { 13298 Slog.i(TAG, "Removing existing preferred activity " 13299 + pa.mPref.mComponent + ":"); 13300 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13301 } 13302 pir.removeFilter(pa); 13303 } 13304 } 13305 } 13306 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13307 "Replacing preferred"); 13308 } 13309 } 13310 13311 @Override 13312 public void clearPackagePreferredActivities(String packageName) { 13313 final int uid = Binder.getCallingUid(); 13314 // writer 13315 synchronized (mPackages) { 13316 PackageParser.Package pkg = mPackages.get(packageName); 13317 if (pkg == null || pkg.applicationInfo.uid != uid) { 13318 if (mContext.checkCallingOrSelfPermission( 13319 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13320 != PackageManager.PERMISSION_GRANTED) { 13321 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13322 < Build.VERSION_CODES.FROYO) { 13323 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13324 + Binder.getCallingUid()); 13325 return; 13326 } 13327 mContext.enforceCallingOrSelfPermission( 13328 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13329 } 13330 } 13331 13332 int user = UserHandle.getCallingUserId(); 13333 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13334 scheduleWritePackageRestrictionsLocked(user); 13335 } 13336 } 13337 } 13338 13339 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13340 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13341 ArrayList<PreferredActivity> removed = null; 13342 boolean changed = false; 13343 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13344 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13345 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13346 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13347 continue; 13348 } 13349 Iterator<PreferredActivity> it = pir.filterIterator(); 13350 while (it.hasNext()) { 13351 PreferredActivity pa = it.next(); 13352 // Mark entry for removal only if it matches the package name 13353 // and the entry is of type "always". 13354 if (packageName == null || 13355 (pa.mPref.mComponent.getPackageName().equals(packageName) 13356 && pa.mPref.mAlways)) { 13357 if (removed == null) { 13358 removed = new ArrayList<PreferredActivity>(); 13359 } 13360 removed.add(pa); 13361 } 13362 } 13363 if (removed != null) { 13364 for (int j=0; j<removed.size(); j++) { 13365 PreferredActivity pa = removed.get(j); 13366 pir.removeFilter(pa); 13367 } 13368 changed = true; 13369 } 13370 } 13371 return changed; 13372 } 13373 13374 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13375 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13376 if (userId == UserHandle.USER_ALL) { 13377 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13378 sUserManager.getUserIds())) { 13379 for (int oneUserId : sUserManager.getUserIds()) { 13380 scheduleWritePackageRestrictionsLocked(oneUserId); 13381 } 13382 } 13383 } else { 13384 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13385 scheduleWritePackageRestrictionsLocked(userId); 13386 } 13387 } 13388 } 13389 13390 13391 void clearDefaultBrowserIfNeeded(String packageName) { 13392 for (int oneUserId : sUserManager.getUserIds()) { 13393 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13394 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13395 if (packageName.equals(defaultBrowserPackageName)) { 13396 setDefaultBrowserPackageName(null, oneUserId); 13397 } 13398 } 13399 } 13400 13401 @Override 13402 public void resetPreferredActivities(int userId) { 13403 /* TODO: Actually use userId. Why is it being passed in? */ 13404 mContext.enforceCallingOrSelfPermission( 13405 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13406 // writer 13407 synchronized (mPackages) { 13408 int user = UserHandle.getCallingUserId(); 13409 clearPackagePreferredActivitiesLPw(null, user); 13410 mSettings.readDefaultPreferredAppsLPw(this, user); 13411 scheduleWritePackageRestrictionsLocked(user); 13412 } 13413 } 13414 13415 @Override 13416 public int getPreferredActivities(List<IntentFilter> outFilters, 13417 List<ComponentName> outActivities, String packageName) { 13418 13419 int num = 0; 13420 final int userId = UserHandle.getCallingUserId(); 13421 // reader 13422 synchronized (mPackages) { 13423 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13424 if (pir != null) { 13425 final Iterator<PreferredActivity> it = pir.filterIterator(); 13426 while (it.hasNext()) { 13427 final PreferredActivity pa = it.next(); 13428 if (packageName == null 13429 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13430 && pa.mPref.mAlways)) { 13431 if (outFilters != null) { 13432 outFilters.add(new IntentFilter(pa)); 13433 } 13434 if (outActivities != null) { 13435 outActivities.add(pa.mPref.mComponent); 13436 } 13437 } 13438 } 13439 } 13440 } 13441 13442 return num; 13443 } 13444 13445 @Override 13446 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13447 int userId) { 13448 int callingUid = Binder.getCallingUid(); 13449 if (callingUid != Process.SYSTEM_UID) { 13450 throw new SecurityException( 13451 "addPersistentPreferredActivity can only be run by the system"); 13452 } 13453 if (filter.countActions() == 0) { 13454 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13455 return; 13456 } 13457 synchronized (mPackages) { 13458 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13459 " :"); 13460 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13461 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13462 new PersistentPreferredActivity(filter, activity)); 13463 scheduleWritePackageRestrictionsLocked(userId); 13464 } 13465 } 13466 13467 @Override 13468 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13469 int callingUid = Binder.getCallingUid(); 13470 if (callingUid != Process.SYSTEM_UID) { 13471 throw new SecurityException( 13472 "clearPackagePersistentPreferredActivities can only be run by the system"); 13473 } 13474 ArrayList<PersistentPreferredActivity> removed = null; 13475 boolean changed = false; 13476 synchronized (mPackages) { 13477 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13478 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13479 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13480 .valueAt(i); 13481 if (userId != thisUserId) { 13482 continue; 13483 } 13484 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13485 while (it.hasNext()) { 13486 PersistentPreferredActivity ppa = it.next(); 13487 // Mark entry for removal only if it matches the package name. 13488 if (ppa.mComponent.getPackageName().equals(packageName)) { 13489 if (removed == null) { 13490 removed = new ArrayList<PersistentPreferredActivity>(); 13491 } 13492 removed.add(ppa); 13493 } 13494 } 13495 if (removed != null) { 13496 for (int j=0; j<removed.size(); j++) { 13497 PersistentPreferredActivity ppa = removed.get(j); 13498 ppir.removeFilter(ppa); 13499 } 13500 changed = true; 13501 } 13502 } 13503 13504 if (changed) { 13505 scheduleWritePackageRestrictionsLocked(userId); 13506 } 13507 } 13508 } 13509 13510 /** 13511 * Common machinery for picking apart a restored XML blob and passing 13512 * it to a caller-supplied functor to be applied to the running system. 13513 */ 13514 private void restoreFromXml(XmlPullParser parser, int userId, 13515 String expectedStartTag, BlobXmlRestorer functor) 13516 throws IOException, XmlPullParserException { 13517 int type; 13518 while ((type = parser.next()) != XmlPullParser.START_TAG 13519 && type != XmlPullParser.END_DOCUMENT) { 13520 } 13521 if (type != XmlPullParser.START_TAG) { 13522 // oops didn't find a start tag?! 13523 if (DEBUG_BACKUP) { 13524 Slog.e(TAG, "Didn't find start tag during restore"); 13525 } 13526 return; 13527 } 13528 13529 // this is supposed to be TAG_PREFERRED_BACKUP 13530 if (!expectedStartTag.equals(parser.getName())) { 13531 if (DEBUG_BACKUP) { 13532 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13533 } 13534 return; 13535 } 13536 13537 // skip interfering stuff, then we're aligned with the backing implementation 13538 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13539 functor.apply(parser, userId); 13540 } 13541 13542 private interface BlobXmlRestorer { 13543 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13544 } 13545 13546 /** 13547 * Non-Binder method, support for the backup/restore mechanism: write the 13548 * full set of preferred activities in its canonical XML format. Returns the 13549 * XML output as a byte array, or null if there is none. 13550 */ 13551 @Override 13552 public byte[] getPreferredActivityBackup(int userId) { 13553 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13554 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13555 } 13556 13557 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13558 try { 13559 final XmlSerializer serializer = new FastXmlSerializer(); 13560 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13561 serializer.startDocument(null, true); 13562 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13563 13564 synchronized (mPackages) { 13565 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13566 } 13567 13568 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13569 serializer.endDocument(); 13570 serializer.flush(); 13571 } catch (Exception e) { 13572 if (DEBUG_BACKUP) { 13573 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13574 } 13575 return null; 13576 } 13577 13578 return dataStream.toByteArray(); 13579 } 13580 13581 @Override 13582 public void restorePreferredActivities(byte[] backup, int userId) { 13583 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13584 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13585 } 13586 13587 try { 13588 final XmlPullParser parser = Xml.newPullParser(); 13589 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13590 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13591 new BlobXmlRestorer() { 13592 @Override 13593 public void apply(XmlPullParser parser, int userId) 13594 throws XmlPullParserException, IOException { 13595 synchronized (mPackages) { 13596 mSettings.readPreferredActivitiesLPw(parser, userId); 13597 } 13598 } 13599 } ); 13600 } catch (Exception e) { 13601 if (DEBUG_BACKUP) { 13602 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13603 } 13604 } 13605 } 13606 13607 /** 13608 * Non-Binder method, support for the backup/restore mechanism: write the 13609 * default browser (etc) settings in its canonical XML format. Returns the default 13610 * browser XML representation as a byte array, or null if there is none. 13611 */ 13612 @Override 13613 public byte[] getDefaultAppsBackup(int userId) { 13614 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13615 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13616 } 13617 13618 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13619 try { 13620 final XmlSerializer serializer = new FastXmlSerializer(); 13621 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13622 serializer.startDocument(null, true); 13623 serializer.startTag(null, TAG_DEFAULT_APPS); 13624 13625 synchronized (mPackages) { 13626 mSettings.writeDefaultAppsLPr(serializer, userId); 13627 } 13628 13629 serializer.endTag(null, TAG_DEFAULT_APPS); 13630 serializer.endDocument(); 13631 serializer.flush(); 13632 } catch (Exception e) { 13633 if (DEBUG_BACKUP) { 13634 Slog.e(TAG, "Unable to write default apps for backup", e); 13635 } 13636 return null; 13637 } 13638 13639 return dataStream.toByteArray(); 13640 } 13641 13642 @Override 13643 public void restoreDefaultApps(byte[] backup, int userId) { 13644 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13645 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13646 } 13647 13648 try { 13649 final XmlPullParser parser = Xml.newPullParser(); 13650 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13651 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13652 new BlobXmlRestorer() { 13653 @Override 13654 public void apply(XmlPullParser parser, int userId) 13655 throws XmlPullParserException, IOException { 13656 synchronized (mPackages) { 13657 mSettings.readDefaultAppsLPw(parser, userId); 13658 } 13659 } 13660 } ); 13661 } catch (Exception e) { 13662 if (DEBUG_BACKUP) { 13663 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13664 } 13665 } 13666 } 13667 13668 @Override 13669 public byte[] getIntentFilterVerificationBackup(int userId) { 13670 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13671 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13672 } 13673 13674 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13675 try { 13676 final XmlSerializer serializer = new FastXmlSerializer(); 13677 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13678 serializer.startDocument(null, true); 13679 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13680 13681 synchronized (mPackages) { 13682 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13683 } 13684 13685 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13686 serializer.endDocument(); 13687 serializer.flush(); 13688 } catch (Exception e) { 13689 if (DEBUG_BACKUP) { 13690 Slog.e(TAG, "Unable to write default apps for backup", e); 13691 } 13692 return null; 13693 } 13694 13695 return dataStream.toByteArray(); 13696 } 13697 13698 @Override 13699 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13700 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13701 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13702 } 13703 13704 try { 13705 final XmlPullParser parser = Xml.newPullParser(); 13706 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13707 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13708 new BlobXmlRestorer() { 13709 @Override 13710 public void apply(XmlPullParser parser, int userId) 13711 throws XmlPullParserException, IOException { 13712 synchronized (mPackages) { 13713 mSettings.readAllDomainVerificationsLPr(parser, userId); 13714 mSettings.writeLPr(); 13715 } 13716 } 13717 } ); 13718 } catch (Exception e) { 13719 if (DEBUG_BACKUP) { 13720 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13721 } 13722 } 13723 } 13724 13725 @Override 13726 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13727 int sourceUserId, int targetUserId, int flags) { 13728 mContext.enforceCallingOrSelfPermission( 13729 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13730 int callingUid = Binder.getCallingUid(); 13731 enforceOwnerRights(ownerPackage, callingUid); 13732 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13733 if (intentFilter.countActions() == 0) { 13734 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13735 return; 13736 } 13737 synchronized (mPackages) { 13738 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13739 ownerPackage, targetUserId, flags); 13740 CrossProfileIntentResolver resolver = 13741 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13742 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13743 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13744 if (existing != null) { 13745 int size = existing.size(); 13746 for (int i = 0; i < size; i++) { 13747 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13748 return; 13749 } 13750 } 13751 } 13752 resolver.addFilter(newFilter); 13753 scheduleWritePackageRestrictionsLocked(sourceUserId); 13754 } 13755 } 13756 13757 @Override 13758 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13759 mContext.enforceCallingOrSelfPermission( 13760 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13761 int callingUid = Binder.getCallingUid(); 13762 enforceOwnerRights(ownerPackage, callingUid); 13763 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13764 synchronized (mPackages) { 13765 CrossProfileIntentResolver resolver = 13766 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13767 ArraySet<CrossProfileIntentFilter> set = 13768 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13769 for (CrossProfileIntentFilter filter : set) { 13770 if (filter.getOwnerPackage().equals(ownerPackage)) { 13771 resolver.removeFilter(filter); 13772 } 13773 } 13774 scheduleWritePackageRestrictionsLocked(sourceUserId); 13775 } 13776 } 13777 13778 // Enforcing that callingUid is owning pkg on userId 13779 private void enforceOwnerRights(String pkg, int callingUid) { 13780 // The system owns everything. 13781 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13782 return; 13783 } 13784 int callingUserId = UserHandle.getUserId(callingUid); 13785 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13786 if (pi == null) { 13787 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13788 + callingUserId); 13789 } 13790 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13791 throw new SecurityException("Calling uid " + callingUid 13792 + " does not own package " + pkg); 13793 } 13794 } 13795 13796 @Override 13797 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13798 Intent intent = new Intent(Intent.ACTION_MAIN); 13799 intent.addCategory(Intent.CATEGORY_HOME); 13800 13801 final int callingUserId = UserHandle.getCallingUserId(); 13802 List<ResolveInfo> list = queryIntentActivities(intent, null, 13803 PackageManager.GET_META_DATA, callingUserId); 13804 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13805 true, false, false, callingUserId); 13806 13807 allHomeCandidates.clear(); 13808 if (list != null) { 13809 for (ResolveInfo ri : list) { 13810 allHomeCandidates.add(ri); 13811 } 13812 } 13813 return (preferred == null || preferred.activityInfo == null) 13814 ? null 13815 : new ComponentName(preferred.activityInfo.packageName, 13816 preferred.activityInfo.name); 13817 } 13818 13819 @Override 13820 public void setApplicationEnabledSetting(String appPackageName, 13821 int newState, int flags, int userId, String callingPackage) { 13822 if (!sUserManager.exists(userId)) return; 13823 if (callingPackage == null) { 13824 callingPackage = Integer.toString(Binder.getCallingUid()); 13825 } 13826 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13827 } 13828 13829 @Override 13830 public void setComponentEnabledSetting(ComponentName componentName, 13831 int newState, int flags, int userId) { 13832 if (!sUserManager.exists(userId)) return; 13833 setEnabledSetting(componentName.getPackageName(), 13834 componentName.getClassName(), newState, flags, userId, null); 13835 } 13836 13837 private void setEnabledSetting(final String packageName, String className, int newState, 13838 final int flags, int userId, String callingPackage) { 13839 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13840 || newState == COMPONENT_ENABLED_STATE_ENABLED 13841 || newState == COMPONENT_ENABLED_STATE_DISABLED 13842 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13843 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13844 throw new IllegalArgumentException("Invalid new component state: " 13845 + newState); 13846 } 13847 PackageSetting pkgSetting; 13848 final int uid = Binder.getCallingUid(); 13849 final int permission = mContext.checkCallingOrSelfPermission( 13850 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13851 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13852 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13853 boolean sendNow = false; 13854 boolean isApp = (className == null); 13855 String componentName = isApp ? packageName : className; 13856 int packageUid = -1; 13857 ArrayList<String> components; 13858 13859 // writer 13860 synchronized (mPackages) { 13861 pkgSetting = mSettings.mPackages.get(packageName); 13862 if (pkgSetting == null) { 13863 if (className == null) { 13864 throw new IllegalArgumentException( 13865 "Unknown package: " + packageName); 13866 } 13867 throw new IllegalArgumentException( 13868 "Unknown component: " + packageName 13869 + "/" + className); 13870 } 13871 // Allow root and verify that userId is not being specified by a different user 13872 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13873 throw new SecurityException( 13874 "Permission Denial: attempt to change component state from pid=" 13875 + Binder.getCallingPid() 13876 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13877 } 13878 if (className == null) { 13879 // We're dealing with an application/package level state change 13880 if (pkgSetting.getEnabled(userId) == newState) { 13881 // Nothing to do 13882 return; 13883 } 13884 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13885 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13886 // Don't care about who enables an app. 13887 callingPackage = null; 13888 } 13889 pkgSetting.setEnabled(newState, userId, callingPackage); 13890 // pkgSetting.pkg.mSetEnabled = newState; 13891 } else { 13892 // We're dealing with a component level state change 13893 // First, verify that this is a valid class name. 13894 PackageParser.Package pkg = pkgSetting.pkg; 13895 if (pkg == null || !pkg.hasComponentClassName(className)) { 13896 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13897 throw new IllegalArgumentException("Component class " + className 13898 + " does not exist in " + packageName); 13899 } else { 13900 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13901 + className + " does not exist in " + packageName); 13902 } 13903 } 13904 switch (newState) { 13905 case COMPONENT_ENABLED_STATE_ENABLED: 13906 if (!pkgSetting.enableComponentLPw(className, userId)) { 13907 return; 13908 } 13909 break; 13910 case COMPONENT_ENABLED_STATE_DISABLED: 13911 if (!pkgSetting.disableComponentLPw(className, userId)) { 13912 return; 13913 } 13914 break; 13915 case COMPONENT_ENABLED_STATE_DEFAULT: 13916 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13917 return; 13918 } 13919 break; 13920 default: 13921 Slog.e(TAG, "Invalid new component state: " + newState); 13922 return; 13923 } 13924 } 13925 scheduleWritePackageRestrictionsLocked(userId); 13926 components = mPendingBroadcasts.get(userId, packageName); 13927 final boolean newPackage = components == null; 13928 if (newPackage) { 13929 components = new ArrayList<String>(); 13930 } 13931 if (!components.contains(componentName)) { 13932 components.add(componentName); 13933 } 13934 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13935 sendNow = true; 13936 // Purge entry from pending broadcast list if another one exists already 13937 // since we are sending one right away. 13938 mPendingBroadcasts.remove(userId, packageName); 13939 } else { 13940 if (newPackage) { 13941 mPendingBroadcasts.put(userId, packageName, components); 13942 } 13943 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13944 // Schedule a message 13945 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13946 } 13947 } 13948 } 13949 13950 long callingId = Binder.clearCallingIdentity(); 13951 try { 13952 if (sendNow) { 13953 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13954 sendPackageChangedBroadcast(packageName, 13955 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13956 } 13957 } finally { 13958 Binder.restoreCallingIdentity(callingId); 13959 } 13960 } 13961 13962 private void sendPackageChangedBroadcast(String packageName, 13963 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13964 if (DEBUG_INSTALL) 13965 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13966 + componentNames); 13967 Bundle extras = new Bundle(4); 13968 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13969 String nameList[] = new String[componentNames.size()]; 13970 componentNames.toArray(nameList); 13971 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13972 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13973 extras.putInt(Intent.EXTRA_UID, packageUid); 13974 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13975 new int[] {UserHandle.getUserId(packageUid)}); 13976 } 13977 13978 @Override 13979 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13980 if (!sUserManager.exists(userId)) return; 13981 final int uid = Binder.getCallingUid(); 13982 final int permission = mContext.checkCallingOrSelfPermission( 13983 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13984 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13985 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13986 // writer 13987 synchronized (mPackages) { 13988 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13989 allowedByPermission, uid, userId)) { 13990 scheduleWritePackageRestrictionsLocked(userId); 13991 } 13992 } 13993 } 13994 13995 @Override 13996 public String getInstallerPackageName(String packageName) { 13997 // reader 13998 synchronized (mPackages) { 13999 return mSettings.getInstallerPackageNameLPr(packageName); 14000 } 14001 } 14002 14003 @Override 14004 public int getApplicationEnabledSetting(String packageName, int userId) { 14005 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14006 int uid = Binder.getCallingUid(); 14007 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14008 // reader 14009 synchronized (mPackages) { 14010 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14011 } 14012 } 14013 14014 @Override 14015 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14016 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14017 int uid = Binder.getCallingUid(); 14018 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14019 // reader 14020 synchronized (mPackages) { 14021 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14022 } 14023 } 14024 14025 @Override 14026 public void enterSafeMode() { 14027 enforceSystemOrRoot("Only the system can request entering safe mode"); 14028 14029 if (!mSystemReady) { 14030 mSafeMode = true; 14031 } 14032 } 14033 14034 @Override 14035 public void systemReady() { 14036 mSystemReady = true; 14037 14038 // Read the compatibilty setting when the system is ready. 14039 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14040 mContext.getContentResolver(), 14041 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14042 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14043 if (DEBUG_SETTINGS) { 14044 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14045 } 14046 14047 synchronized (mPackages) { 14048 // Verify that all of the preferred activity components actually 14049 // exist. It is possible for applications to be updated and at 14050 // that point remove a previously declared activity component that 14051 // had been set as a preferred activity. We try to clean this up 14052 // the next time we encounter that preferred activity, but it is 14053 // possible for the user flow to never be able to return to that 14054 // situation so here we do a sanity check to make sure we haven't 14055 // left any junk around. 14056 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14057 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14058 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14059 removed.clear(); 14060 for (PreferredActivity pa : pir.filterSet()) { 14061 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14062 removed.add(pa); 14063 } 14064 } 14065 if (removed.size() > 0) { 14066 for (int r=0; r<removed.size(); r++) { 14067 PreferredActivity pa = removed.get(r); 14068 Slog.w(TAG, "Removing dangling preferred activity: " 14069 + pa.mPref.mComponent); 14070 pir.removeFilter(pa); 14071 } 14072 mSettings.writePackageRestrictionsLPr( 14073 mSettings.mPreferredActivities.keyAt(i)); 14074 } 14075 } 14076 } 14077 sUserManager.systemReady(); 14078 14079 // If we upgraded grant all default permissions before kicking off. 14080 if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) { 14081 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14082 for (int userId : UserManagerService.getInstance().getUserIds()) { 14083 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14084 } 14085 } 14086 14087 // Kick off any messages waiting for system ready 14088 if (mPostSystemReadyMessages != null) { 14089 for (Message msg : mPostSystemReadyMessages) { 14090 msg.sendToTarget(); 14091 } 14092 mPostSystemReadyMessages = null; 14093 } 14094 14095 // Watch for external volumes that come and go over time 14096 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14097 storage.registerListener(mStorageListener); 14098 14099 mInstallerService.systemReady(); 14100 mPackageDexOptimizer.systemReady(); 14101 } 14102 14103 @Override 14104 public boolean isSafeMode() { 14105 return mSafeMode; 14106 } 14107 14108 @Override 14109 public boolean hasSystemUidErrors() { 14110 return mHasSystemUidErrors; 14111 } 14112 14113 static String arrayToString(int[] array) { 14114 StringBuffer buf = new StringBuffer(128); 14115 buf.append('['); 14116 if (array != null) { 14117 for (int i=0; i<array.length; i++) { 14118 if (i > 0) buf.append(", "); 14119 buf.append(array[i]); 14120 } 14121 } 14122 buf.append(']'); 14123 return buf.toString(); 14124 } 14125 14126 static class DumpState { 14127 public static final int DUMP_LIBS = 1 << 0; 14128 public static final int DUMP_FEATURES = 1 << 1; 14129 public static final int DUMP_RESOLVERS = 1 << 2; 14130 public static final int DUMP_PERMISSIONS = 1 << 3; 14131 public static final int DUMP_PACKAGES = 1 << 4; 14132 public static final int DUMP_SHARED_USERS = 1 << 5; 14133 public static final int DUMP_MESSAGES = 1 << 6; 14134 public static final int DUMP_PROVIDERS = 1 << 7; 14135 public static final int DUMP_VERIFIERS = 1 << 8; 14136 public static final int DUMP_PREFERRED = 1 << 9; 14137 public static final int DUMP_PREFERRED_XML = 1 << 10; 14138 public static final int DUMP_KEYSETS = 1 << 11; 14139 public static final int DUMP_VERSION = 1 << 12; 14140 public static final int DUMP_INSTALLS = 1 << 13; 14141 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14142 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14143 14144 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14145 14146 private int mTypes; 14147 14148 private int mOptions; 14149 14150 private boolean mTitlePrinted; 14151 14152 private SharedUserSetting mSharedUser; 14153 14154 public boolean isDumping(int type) { 14155 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14156 return true; 14157 } 14158 14159 return (mTypes & type) != 0; 14160 } 14161 14162 public void setDump(int type) { 14163 mTypes |= type; 14164 } 14165 14166 public boolean isOptionEnabled(int option) { 14167 return (mOptions & option) != 0; 14168 } 14169 14170 public void setOptionEnabled(int option) { 14171 mOptions |= option; 14172 } 14173 14174 public boolean onTitlePrinted() { 14175 final boolean printed = mTitlePrinted; 14176 mTitlePrinted = true; 14177 return printed; 14178 } 14179 14180 public boolean getTitlePrinted() { 14181 return mTitlePrinted; 14182 } 14183 14184 public void setTitlePrinted(boolean enabled) { 14185 mTitlePrinted = enabled; 14186 } 14187 14188 public SharedUserSetting getSharedUser() { 14189 return mSharedUser; 14190 } 14191 14192 public void setSharedUser(SharedUserSetting user) { 14193 mSharedUser = user; 14194 } 14195 } 14196 14197 @Override 14198 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14199 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14200 != PackageManager.PERMISSION_GRANTED) { 14201 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14202 + Binder.getCallingPid() 14203 + ", uid=" + Binder.getCallingUid() 14204 + " without permission " 14205 + android.Manifest.permission.DUMP); 14206 return; 14207 } 14208 14209 DumpState dumpState = new DumpState(); 14210 boolean fullPreferred = false; 14211 boolean checkin = false; 14212 14213 String packageName = null; 14214 ArraySet<String> permissionNames = null; 14215 14216 int opti = 0; 14217 while (opti < args.length) { 14218 String opt = args[opti]; 14219 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14220 break; 14221 } 14222 opti++; 14223 14224 if ("-a".equals(opt)) { 14225 // Right now we only know how to print all. 14226 } else if ("-h".equals(opt)) { 14227 pw.println("Package manager dump options:"); 14228 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14229 pw.println(" --checkin: dump for a checkin"); 14230 pw.println(" -f: print details of intent filters"); 14231 pw.println(" -h: print this help"); 14232 pw.println(" cmd may be one of:"); 14233 pw.println(" l[ibraries]: list known shared libraries"); 14234 pw.println(" f[ibraries]: list device features"); 14235 pw.println(" k[eysets]: print known keysets"); 14236 pw.println(" r[esolvers]: dump intent resolvers"); 14237 pw.println(" perm[issions]: dump permissions"); 14238 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14239 pw.println(" pref[erred]: print preferred package settings"); 14240 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14241 pw.println(" prov[iders]: dump content providers"); 14242 pw.println(" p[ackages]: dump installed packages"); 14243 pw.println(" s[hared-users]: dump shared user IDs"); 14244 pw.println(" m[essages]: print collected runtime messages"); 14245 pw.println(" v[erifiers]: print package verifier info"); 14246 pw.println(" version: print database version info"); 14247 pw.println(" write: write current settings now"); 14248 pw.println(" <package.name>: info about given package"); 14249 pw.println(" installs: details about install sessions"); 14250 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14251 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14252 return; 14253 } else if ("--checkin".equals(opt)) { 14254 checkin = true; 14255 } else if ("-f".equals(opt)) { 14256 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14257 } else { 14258 pw.println("Unknown argument: " + opt + "; use -h for help"); 14259 } 14260 } 14261 14262 // Is the caller requesting to dump a particular piece of data? 14263 if (opti < args.length) { 14264 String cmd = args[opti]; 14265 opti++; 14266 // Is this a package name? 14267 if ("android".equals(cmd) || cmd.contains(".")) { 14268 packageName = cmd; 14269 // When dumping a single package, we always dump all of its 14270 // filter information since the amount of data will be reasonable. 14271 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14272 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14273 dumpState.setDump(DumpState.DUMP_LIBS); 14274 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14275 dumpState.setDump(DumpState.DUMP_FEATURES); 14276 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14277 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14278 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14279 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14280 } else if ("permission".equals(cmd)) { 14281 if (opti >= args.length) { 14282 pw.println("Error: permission requires permission name"); 14283 return; 14284 } 14285 permissionNames = new ArraySet<>(); 14286 while (opti < args.length) { 14287 permissionNames.add(args[opti]); 14288 opti++; 14289 } 14290 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14291 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14292 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14293 dumpState.setDump(DumpState.DUMP_PREFERRED); 14294 } else if ("preferred-xml".equals(cmd)) { 14295 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14296 if (opti < args.length && "--full".equals(args[opti])) { 14297 fullPreferred = true; 14298 opti++; 14299 } 14300 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14301 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14302 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14303 dumpState.setDump(DumpState.DUMP_PACKAGES); 14304 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14305 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14306 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14307 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14308 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14309 dumpState.setDump(DumpState.DUMP_MESSAGES); 14310 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14311 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14312 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14313 || "intent-filter-verifiers".equals(cmd)) { 14314 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14315 } else if ("version".equals(cmd)) { 14316 dumpState.setDump(DumpState.DUMP_VERSION); 14317 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14318 dumpState.setDump(DumpState.DUMP_KEYSETS); 14319 } else if ("installs".equals(cmd)) { 14320 dumpState.setDump(DumpState.DUMP_INSTALLS); 14321 } else if ("write".equals(cmd)) { 14322 synchronized (mPackages) { 14323 mSettings.writeLPr(); 14324 pw.println("Settings written."); 14325 return; 14326 } 14327 } 14328 } 14329 14330 if (checkin) { 14331 pw.println("vers,1"); 14332 } 14333 14334 // reader 14335 synchronized (mPackages) { 14336 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14337 if (!checkin) { 14338 if (dumpState.onTitlePrinted()) 14339 pw.println(); 14340 pw.println("Database versions:"); 14341 pw.print(" SDK Version:"); 14342 pw.print(" internal="); 14343 pw.print(mSettings.mInternalSdkPlatform); 14344 pw.print(" external="); 14345 pw.println(mSettings.mExternalSdkPlatform); 14346 pw.print(" DB Version:"); 14347 pw.print(" internal="); 14348 pw.print(mSettings.mInternalDatabaseVersion); 14349 pw.print(" external="); 14350 pw.println(mSettings.mExternalDatabaseVersion); 14351 } 14352 } 14353 14354 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14355 if (!checkin) { 14356 if (dumpState.onTitlePrinted()) 14357 pw.println(); 14358 pw.println("Verifiers:"); 14359 pw.print(" Required: "); 14360 pw.print(mRequiredVerifierPackage); 14361 pw.print(" (uid="); 14362 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14363 pw.println(")"); 14364 } else if (mRequiredVerifierPackage != null) { 14365 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14366 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14367 } 14368 } 14369 14370 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14371 packageName == null) { 14372 if (mIntentFilterVerifierComponent != null) { 14373 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14374 if (!checkin) { 14375 if (dumpState.onTitlePrinted()) 14376 pw.println(); 14377 pw.println("Intent Filter Verifier:"); 14378 pw.print(" Using: "); 14379 pw.print(verifierPackageName); 14380 pw.print(" (uid="); 14381 pw.print(getPackageUid(verifierPackageName, 0)); 14382 pw.println(")"); 14383 } else if (verifierPackageName != null) { 14384 pw.print("ifv,"); pw.print(verifierPackageName); 14385 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14386 } 14387 } else { 14388 pw.println(); 14389 pw.println("No Intent Filter Verifier available!"); 14390 } 14391 } 14392 14393 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14394 boolean printedHeader = false; 14395 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14396 while (it.hasNext()) { 14397 String name = it.next(); 14398 SharedLibraryEntry ent = mSharedLibraries.get(name); 14399 if (!checkin) { 14400 if (!printedHeader) { 14401 if (dumpState.onTitlePrinted()) 14402 pw.println(); 14403 pw.println("Libraries:"); 14404 printedHeader = true; 14405 } 14406 pw.print(" "); 14407 } else { 14408 pw.print("lib,"); 14409 } 14410 pw.print(name); 14411 if (!checkin) { 14412 pw.print(" -> "); 14413 } 14414 if (ent.path != null) { 14415 if (!checkin) { 14416 pw.print("(jar) "); 14417 pw.print(ent.path); 14418 } else { 14419 pw.print(",jar,"); 14420 pw.print(ent.path); 14421 } 14422 } else { 14423 if (!checkin) { 14424 pw.print("(apk) "); 14425 pw.print(ent.apk); 14426 } else { 14427 pw.print(",apk,"); 14428 pw.print(ent.apk); 14429 } 14430 } 14431 pw.println(); 14432 } 14433 } 14434 14435 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14436 if (dumpState.onTitlePrinted()) 14437 pw.println(); 14438 if (!checkin) { 14439 pw.println("Features:"); 14440 } 14441 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14442 while (it.hasNext()) { 14443 String name = it.next(); 14444 if (!checkin) { 14445 pw.print(" "); 14446 } else { 14447 pw.print("feat,"); 14448 } 14449 pw.println(name); 14450 } 14451 } 14452 14453 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14454 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14455 : "Activity Resolver Table:", " ", packageName, 14456 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14457 dumpState.setTitlePrinted(true); 14458 } 14459 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14460 : "Receiver Resolver Table:", " ", packageName, 14461 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14462 dumpState.setTitlePrinted(true); 14463 } 14464 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14465 : "Service Resolver Table:", " ", packageName, 14466 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14467 dumpState.setTitlePrinted(true); 14468 } 14469 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14470 : "Provider Resolver Table:", " ", packageName, 14471 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14472 dumpState.setTitlePrinted(true); 14473 } 14474 } 14475 14476 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14477 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14478 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14479 int user = mSettings.mPreferredActivities.keyAt(i); 14480 if (pir.dump(pw, 14481 dumpState.getTitlePrinted() 14482 ? "\nPreferred Activities User " + user + ":" 14483 : "Preferred Activities User " + user + ":", " ", 14484 packageName, true, false)) { 14485 dumpState.setTitlePrinted(true); 14486 } 14487 } 14488 } 14489 14490 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14491 pw.flush(); 14492 FileOutputStream fout = new FileOutputStream(fd); 14493 BufferedOutputStream str = new BufferedOutputStream(fout); 14494 XmlSerializer serializer = new FastXmlSerializer(); 14495 try { 14496 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14497 serializer.startDocument(null, true); 14498 serializer.setFeature( 14499 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14500 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14501 serializer.endDocument(); 14502 serializer.flush(); 14503 } catch (IllegalArgumentException e) { 14504 pw.println("Failed writing: " + e); 14505 } catch (IllegalStateException e) { 14506 pw.println("Failed writing: " + e); 14507 } catch (IOException e) { 14508 pw.println("Failed writing: " + e); 14509 } 14510 } 14511 14512 if (!checkin 14513 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14514 && packageName == null) { 14515 pw.println(); 14516 int count = mSettings.mPackages.size(); 14517 if (count == 0) { 14518 pw.println("No domain preferred apps!"); 14519 pw.println(); 14520 } else { 14521 final String prefix = " "; 14522 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14523 if (allPackageSettings.size() == 0) { 14524 pw.println("No domain preferred apps!"); 14525 pw.println(); 14526 } else { 14527 pw.println("Domain preferred apps status:"); 14528 pw.println(); 14529 count = 0; 14530 for (PackageSetting ps : allPackageSettings) { 14531 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14532 if (ivi == null || ivi.getPackageName() == null) continue; 14533 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14534 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14535 pw.println(prefix + "Status: " + ivi.getStatusString()); 14536 pw.println(); 14537 count++; 14538 } 14539 if (count == 0) { 14540 pw.println(prefix + "No domain preferred app status!"); 14541 pw.println(); 14542 } 14543 for (int userId : sUserManager.getUserIds()) { 14544 pw.println("Domain preferred apps for User " + userId + ":"); 14545 pw.println(); 14546 count = 0; 14547 for (PackageSetting ps : allPackageSettings) { 14548 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14549 if (ivi == null || ivi.getPackageName() == null) { 14550 continue; 14551 } 14552 final int status = ps.getDomainVerificationStatusForUser(userId); 14553 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14554 continue; 14555 } 14556 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14557 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14558 String statusStr = IntentFilterVerificationInfo. 14559 getStatusStringFromValue(status); 14560 pw.println(prefix + "Status: " + statusStr); 14561 pw.println(); 14562 count++; 14563 } 14564 if (count == 0) { 14565 pw.println(prefix + "No domain preferred apps!"); 14566 pw.println(); 14567 } 14568 } 14569 } 14570 } 14571 } 14572 14573 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14574 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14575 if (packageName == null && permissionNames == null) { 14576 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14577 if (iperm == 0) { 14578 if (dumpState.onTitlePrinted()) 14579 pw.println(); 14580 pw.println("AppOp Permissions:"); 14581 } 14582 pw.print(" AppOp Permission "); 14583 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14584 pw.println(":"); 14585 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14586 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14587 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14588 } 14589 } 14590 } 14591 } 14592 14593 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14594 boolean printedSomething = false; 14595 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14596 if (packageName != null && !packageName.equals(p.info.packageName)) { 14597 continue; 14598 } 14599 if (!printedSomething) { 14600 if (dumpState.onTitlePrinted()) 14601 pw.println(); 14602 pw.println("Registered ContentProviders:"); 14603 printedSomething = true; 14604 } 14605 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14606 pw.print(" "); pw.println(p.toString()); 14607 } 14608 printedSomething = false; 14609 for (Map.Entry<String, PackageParser.Provider> entry : 14610 mProvidersByAuthority.entrySet()) { 14611 PackageParser.Provider p = entry.getValue(); 14612 if (packageName != null && !packageName.equals(p.info.packageName)) { 14613 continue; 14614 } 14615 if (!printedSomething) { 14616 if (dumpState.onTitlePrinted()) 14617 pw.println(); 14618 pw.println("ContentProvider Authorities:"); 14619 printedSomething = true; 14620 } 14621 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14622 pw.print(" "); pw.println(p.toString()); 14623 if (p.info != null && p.info.applicationInfo != null) { 14624 final String appInfo = p.info.applicationInfo.toString(); 14625 pw.print(" applicationInfo="); pw.println(appInfo); 14626 } 14627 } 14628 } 14629 14630 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14631 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14632 } 14633 14634 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14635 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14636 } 14637 14638 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14639 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14640 } 14641 14642 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14643 // XXX should handle packageName != null by dumping only install data that 14644 // the given package is involved with. 14645 if (dumpState.onTitlePrinted()) pw.println(); 14646 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14647 } 14648 14649 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14650 if (dumpState.onTitlePrinted()) pw.println(); 14651 mSettings.dumpReadMessagesLPr(pw, dumpState); 14652 14653 pw.println(); 14654 pw.println("Package warning messages:"); 14655 BufferedReader in = null; 14656 String line = null; 14657 try { 14658 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14659 while ((line = in.readLine()) != null) { 14660 if (line.contains("ignored: updated version")) continue; 14661 pw.println(line); 14662 } 14663 } catch (IOException ignored) { 14664 } finally { 14665 IoUtils.closeQuietly(in); 14666 } 14667 } 14668 14669 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14670 BufferedReader in = null; 14671 String line = null; 14672 try { 14673 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14674 while ((line = in.readLine()) != null) { 14675 if (line.contains("ignored: updated version")) continue; 14676 pw.print("msg,"); 14677 pw.println(line); 14678 } 14679 } catch (IOException ignored) { 14680 } finally { 14681 IoUtils.closeQuietly(in); 14682 } 14683 } 14684 } 14685 } 14686 14687 // ------- apps on sdcard specific code ------- 14688 static final boolean DEBUG_SD_INSTALL = false; 14689 14690 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14691 14692 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14693 14694 private boolean mMediaMounted = false; 14695 14696 static String getEncryptKey() { 14697 try { 14698 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14699 SD_ENCRYPTION_KEYSTORE_NAME); 14700 if (sdEncKey == null) { 14701 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14702 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14703 if (sdEncKey == null) { 14704 Slog.e(TAG, "Failed to create encryption keys"); 14705 return null; 14706 } 14707 } 14708 return sdEncKey; 14709 } catch (NoSuchAlgorithmException nsae) { 14710 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14711 return null; 14712 } catch (IOException ioe) { 14713 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14714 return null; 14715 } 14716 } 14717 14718 /* 14719 * Update media status on PackageManager. 14720 */ 14721 @Override 14722 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14723 int callingUid = Binder.getCallingUid(); 14724 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14725 throw new SecurityException("Media status can only be updated by the system"); 14726 } 14727 // reader; this apparently protects mMediaMounted, but should probably 14728 // be a different lock in that case. 14729 synchronized (mPackages) { 14730 Log.i(TAG, "Updating external media status from " 14731 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14732 + (mediaStatus ? "mounted" : "unmounted")); 14733 if (DEBUG_SD_INSTALL) 14734 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14735 + ", mMediaMounted=" + mMediaMounted); 14736 if (mediaStatus == mMediaMounted) { 14737 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14738 : 0, -1); 14739 mHandler.sendMessage(msg); 14740 return; 14741 } 14742 mMediaMounted = mediaStatus; 14743 } 14744 // Queue up an async operation since the package installation may take a 14745 // little while. 14746 mHandler.post(new Runnable() { 14747 public void run() { 14748 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14749 } 14750 }); 14751 } 14752 14753 /** 14754 * Called by MountService when the initial ASECs to scan are available. 14755 * Should block until all the ASEC containers are finished being scanned. 14756 */ 14757 public void scanAvailableAsecs() { 14758 updateExternalMediaStatusInner(true, false, false); 14759 if (mShouldRestoreconData) { 14760 SELinuxMMAC.setRestoreconDone(); 14761 mShouldRestoreconData = false; 14762 } 14763 } 14764 14765 /* 14766 * Collect information of applications on external media, map them against 14767 * existing containers and update information based on current mount status. 14768 * Please note that we always have to report status if reportStatus has been 14769 * set to true especially when unloading packages. 14770 */ 14771 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14772 boolean externalStorage) { 14773 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14774 int[] uidArr = EmptyArray.INT; 14775 14776 final String[] list = PackageHelper.getSecureContainerList(); 14777 if (ArrayUtils.isEmpty(list)) { 14778 Log.i(TAG, "No secure containers found"); 14779 } else { 14780 // Process list of secure containers and categorize them 14781 // as active or stale based on their package internal state. 14782 14783 // reader 14784 synchronized (mPackages) { 14785 for (String cid : list) { 14786 // Leave stages untouched for now; installer service owns them 14787 if (PackageInstallerService.isStageName(cid)) continue; 14788 14789 if (DEBUG_SD_INSTALL) 14790 Log.i(TAG, "Processing container " + cid); 14791 String pkgName = getAsecPackageName(cid); 14792 if (pkgName == null) { 14793 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14794 continue; 14795 } 14796 if (DEBUG_SD_INSTALL) 14797 Log.i(TAG, "Looking for pkg : " + pkgName); 14798 14799 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14800 if (ps == null) { 14801 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14802 continue; 14803 } 14804 14805 /* 14806 * Skip packages that are not external if we're unmounting 14807 * external storage. 14808 */ 14809 if (externalStorage && !isMounted && !isExternal(ps)) { 14810 continue; 14811 } 14812 14813 final AsecInstallArgs args = new AsecInstallArgs(cid, 14814 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14815 // The package status is changed only if the code path 14816 // matches between settings and the container id. 14817 if (ps.codePathString != null 14818 && ps.codePathString.startsWith(args.getCodePath())) { 14819 if (DEBUG_SD_INSTALL) { 14820 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14821 + " at code path: " + ps.codePathString); 14822 } 14823 14824 // We do have a valid package installed on sdcard 14825 processCids.put(args, ps.codePathString); 14826 final int uid = ps.appId; 14827 if (uid != -1) { 14828 uidArr = ArrayUtils.appendInt(uidArr, uid); 14829 } 14830 } else { 14831 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14832 + ps.codePathString); 14833 } 14834 } 14835 } 14836 14837 Arrays.sort(uidArr); 14838 } 14839 14840 // Process packages with valid entries. 14841 if (isMounted) { 14842 if (DEBUG_SD_INSTALL) 14843 Log.i(TAG, "Loading packages"); 14844 loadMediaPackages(processCids, uidArr); 14845 startCleaningPackages(); 14846 mInstallerService.onSecureContainersAvailable(); 14847 } else { 14848 if (DEBUG_SD_INSTALL) 14849 Log.i(TAG, "Unloading packages"); 14850 unloadMediaPackages(processCids, uidArr, reportStatus); 14851 } 14852 } 14853 14854 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14855 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14856 final int size = infos.size(); 14857 final String[] packageNames = new String[size]; 14858 final int[] packageUids = new int[size]; 14859 for (int i = 0; i < size; i++) { 14860 final ApplicationInfo info = infos.get(i); 14861 packageNames[i] = info.packageName; 14862 packageUids[i] = info.uid; 14863 } 14864 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14865 finishedReceiver); 14866 } 14867 14868 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14869 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14870 sendResourcesChangedBroadcast(mediaStatus, replacing, 14871 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14872 } 14873 14874 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14875 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14876 int size = pkgList.length; 14877 if (size > 0) { 14878 // Send broadcasts here 14879 Bundle extras = new Bundle(); 14880 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14881 if (uidArr != null) { 14882 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14883 } 14884 if (replacing) { 14885 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14886 } 14887 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14888 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14889 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14890 } 14891 } 14892 14893 /* 14894 * Look at potentially valid container ids from processCids If package 14895 * information doesn't match the one on record or package scanning fails, 14896 * the cid is added to list of removeCids. We currently don't delete stale 14897 * containers. 14898 */ 14899 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14900 ArrayList<String> pkgList = new ArrayList<String>(); 14901 Set<AsecInstallArgs> keys = processCids.keySet(); 14902 14903 for (AsecInstallArgs args : keys) { 14904 String codePath = processCids.get(args); 14905 if (DEBUG_SD_INSTALL) 14906 Log.i(TAG, "Loading container : " + args.cid); 14907 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14908 try { 14909 // Make sure there are no container errors first. 14910 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14911 Slog.e(TAG, "Failed to mount cid : " + args.cid 14912 + " when installing from sdcard"); 14913 continue; 14914 } 14915 // Check code path here. 14916 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14917 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14918 + " does not match one in settings " + codePath); 14919 continue; 14920 } 14921 // Parse package 14922 int parseFlags = mDefParseFlags; 14923 if (args.isExternalAsec()) { 14924 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14925 } 14926 if (args.isFwdLocked()) { 14927 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14928 } 14929 14930 synchronized (mInstallLock) { 14931 PackageParser.Package pkg = null; 14932 try { 14933 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14934 } catch (PackageManagerException e) { 14935 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14936 } 14937 // Scan the package 14938 if (pkg != null) { 14939 /* 14940 * TODO why is the lock being held? doPostInstall is 14941 * called in other places without the lock. This needs 14942 * to be straightened out. 14943 */ 14944 // writer 14945 synchronized (mPackages) { 14946 retCode = PackageManager.INSTALL_SUCCEEDED; 14947 pkgList.add(pkg.packageName); 14948 // Post process args 14949 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14950 pkg.applicationInfo.uid); 14951 } 14952 } else { 14953 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14954 } 14955 } 14956 14957 } finally { 14958 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14959 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14960 } 14961 } 14962 } 14963 // writer 14964 synchronized (mPackages) { 14965 // If the platform SDK has changed since the last time we booted, 14966 // we need to re-grant app permission to catch any new ones that 14967 // appear. This is really a hack, and means that apps can in some 14968 // cases get permissions that the user didn't initially explicitly 14969 // allow... it would be nice to have some better way to handle 14970 // this situation. 14971 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14972 if (regrantPermissions) 14973 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14974 + mSdkVersion + "; regranting permissions for external storage"); 14975 mSettings.mExternalSdkPlatform = mSdkVersion; 14976 14977 // Make sure group IDs have been assigned, and any permission 14978 // changes in other apps are accounted for 14979 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14980 | (regrantPermissions 14981 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14982 : 0)); 14983 14984 mSettings.updateExternalDatabaseVersion(); 14985 14986 // can downgrade to reader 14987 // Persist settings 14988 mSettings.writeLPr(); 14989 } 14990 // Send a broadcast to let everyone know we are done processing 14991 if (pkgList.size() > 0) { 14992 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14993 } 14994 } 14995 14996 /* 14997 * Utility method to unload a list of specified containers 14998 */ 14999 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15000 // Just unmount all valid containers. 15001 for (AsecInstallArgs arg : cidArgs) { 15002 synchronized (mInstallLock) { 15003 arg.doPostDeleteLI(false); 15004 } 15005 } 15006 } 15007 15008 /* 15009 * Unload packages mounted on external media. This involves deleting package 15010 * data from internal structures, sending broadcasts about diabled packages, 15011 * gc'ing to free up references, unmounting all secure containers 15012 * corresponding to packages on external media, and posting a 15013 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15014 * that we always have to post this message if status has been requested no 15015 * matter what. 15016 */ 15017 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15018 final boolean reportStatus) { 15019 if (DEBUG_SD_INSTALL) 15020 Log.i(TAG, "unloading media packages"); 15021 ArrayList<String> pkgList = new ArrayList<String>(); 15022 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15023 final Set<AsecInstallArgs> keys = processCids.keySet(); 15024 for (AsecInstallArgs args : keys) { 15025 String pkgName = args.getPackageName(); 15026 if (DEBUG_SD_INSTALL) 15027 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15028 // Delete package internally 15029 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15030 synchronized (mInstallLock) { 15031 boolean res = deletePackageLI(pkgName, null, false, null, null, 15032 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15033 if (res) { 15034 pkgList.add(pkgName); 15035 } else { 15036 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15037 failedList.add(args); 15038 } 15039 } 15040 } 15041 15042 // reader 15043 synchronized (mPackages) { 15044 // We didn't update the settings after removing each package; 15045 // write them now for all packages. 15046 mSettings.writeLPr(); 15047 } 15048 15049 // We have to absolutely send UPDATED_MEDIA_STATUS only 15050 // after confirming that all the receivers processed the ordered 15051 // broadcast when packages get disabled, force a gc to clean things up. 15052 // and unload all the containers. 15053 if (pkgList.size() > 0) { 15054 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15055 new IIntentReceiver.Stub() { 15056 public void performReceive(Intent intent, int resultCode, String data, 15057 Bundle extras, boolean ordered, boolean sticky, 15058 int sendingUser) throws RemoteException { 15059 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15060 reportStatus ? 1 : 0, 1, keys); 15061 mHandler.sendMessage(msg); 15062 } 15063 }); 15064 } else { 15065 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15066 keys); 15067 mHandler.sendMessage(msg); 15068 } 15069 } 15070 15071 private void loadPrivatePackages(VolumeInfo vol) { 15072 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15073 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15074 synchronized (mInstallLock) { 15075 synchronized (mPackages) { 15076 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15077 for (PackageSetting ps : packages) { 15078 final PackageParser.Package pkg; 15079 try { 15080 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15081 loaded.add(pkg.applicationInfo); 15082 } catch (PackageManagerException e) { 15083 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15084 } 15085 } 15086 15087 // TODO: regrant any permissions that changed based since original install 15088 15089 mSettings.writeLPr(); 15090 } 15091 } 15092 15093 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15094 sendResourcesChangedBroadcast(true, false, loaded, null); 15095 } 15096 15097 private void unloadPrivatePackages(VolumeInfo vol) { 15098 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15099 synchronized (mInstallLock) { 15100 synchronized (mPackages) { 15101 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15102 for (PackageSetting ps : packages) { 15103 if (ps.pkg == null) continue; 15104 15105 final ApplicationInfo info = ps.pkg.applicationInfo; 15106 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15107 if (deletePackageLI(ps.name, null, false, null, null, 15108 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15109 unloaded.add(info); 15110 } else { 15111 Slog.w(TAG, "Failed to unload " + ps.codePath); 15112 } 15113 } 15114 15115 mSettings.writeLPr(); 15116 } 15117 } 15118 15119 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15120 sendResourcesChangedBroadcast(false, false, unloaded, null); 15121 } 15122 15123 private void unfreezePackage(String packageName) { 15124 synchronized (mPackages) { 15125 final PackageSetting ps = mSettings.mPackages.get(packageName); 15126 if (ps != null) { 15127 ps.frozen = false; 15128 } 15129 } 15130 } 15131 15132 @Override 15133 public int movePackage(final String packageName, final String volumeUuid) { 15134 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15135 15136 final int moveId = mNextMoveId.getAndIncrement(); 15137 try { 15138 movePackageInternal(packageName, volumeUuid, moveId); 15139 } catch (PackageManagerException e) { 15140 Slog.w(TAG, "Failed to move " + packageName, e); 15141 mMoveCallbacks.notifyStatusChanged(moveId, 15142 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15143 } 15144 return moveId; 15145 } 15146 15147 private void movePackageInternal(final String packageName, final String volumeUuid, 15148 final int moveId) throws PackageManagerException { 15149 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15150 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15151 final PackageManager pm = mContext.getPackageManager(); 15152 15153 final boolean currentAsec; 15154 final String currentVolumeUuid; 15155 final File codeFile; 15156 final String installerPackageName; 15157 final String packageAbiOverride; 15158 final int appId; 15159 final String seinfo; 15160 final String label; 15161 15162 // reader 15163 synchronized (mPackages) { 15164 final PackageParser.Package pkg = mPackages.get(packageName); 15165 final PackageSetting ps = mSettings.mPackages.get(packageName); 15166 if (pkg == null || ps == null) { 15167 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15168 } 15169 15170 if (pkg.applicationInfo.isSystemApp()) { 15171 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15172 "Cannot move system application"); 15173 } 15174 15175 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15176 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15177 "Package already moved to " + volumeUuid); 15178 } 15179 15180 final File probe = new File(pkg.codePath); 15181 final File probeOat = new File(probe, "oat"); 15182 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15183 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15184 "Move only supported for modern cluster style installs"); 15185 } 15186 15187 if (ps.frozen) { 15188 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15189 "Failed to move already frozen package"); 15190 } 15191 ps.frozen = true; 15192 15193 currentAsec = pkg.applicationInfo.isForwardLocked() 15194 || pkg.applicationInfo.isExternalAsec(); 15195 currentVolumeUuid = ps.volumeUuid; 15196 codeFile = new File(pkg.codePath); 15197 installerPackageName = ps.installerPackageName; 15198 packageAbiOverride = ps.cpuAbiOverrideString; 15199 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15200 seinfo = pkg.applicationInfo.seinfo; 15201 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15202 } 15203 15204 // Now that we're guarded by frozen state, kill app during move 15205 killApplication(packageName, appId, "move pkg"); 15206 15207 final Bundle extras = new Bundle(); 15208 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15209 extras.putString(Intent.EXTRA_TITLE, label); 15210 mMoveCallbacks.notifyCreated(moveId, extras); 15211 15212 int installFlags; 15213 final boolean moveCompleteApp; 15214 final File measurePath; 15215 15216 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15217 installFlags = INSTALL_INTERNAL; 15218 moveCompleteApp = !currentAsec; 15219 measurePath = Environment.getDataAppDirectory(volumeUuid); 15220 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15221 installFlags = INSTALL_EXTERNAL; 15222 moveCompleteApp = false; 15223 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15224 } else { 15225 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15226 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15227 || !volume.isMountedWritable()) { 15228 unfreezePackage(packageName); 15229 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15230 "Move location not mounted private volume"); 15231 } 15232 15233 Preconditions.checkState(!currentAsec); 15234 15235 installFlags = INSTALL_INTERNAL; 15236 moveCompleteApp = true; 15237 measurePath = Environment.getDataAppDirectory(volumeUuid); 15238 } 15239 15240 final PackageStats stats = new PackageStats(null, -1); 15241 synchronized (mInstaller) { 15242 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15243 unfreezePackage(packageName); 15244 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15245 "Failed to measure package size"); 15246 } 15247 } 15248 15249 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15250 + stats.dataSize); 15251 15252 final long startFreeBytes = measurePath.getFreeSpace(); 15253 final long sizeBytes; 15254 if (moveCompleteApp) { 15255 sizeBytes = stats.codeSize + stats.dataSize; 15256 } else { 15257 sizeBytes = stats.codeSize; 15258 } 15259 15260 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15261 unfreezePackage(packageName); 15262 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15263 "Not enough free space to move"); 15264 } 15265 15266 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15267 15268 final CountDownLatch installedLatch = new CountDownLatch(1); 15269 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15270 @Override 15271 public void onUserActionRequired(Intent intent) throws RemoteException { 15272 throw new IllegalStateException(); 15273 } 15274 15275 @Override 15276 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15277 Bundle extras) throws RemoteException { 15278 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15279 + PackageManager.installStatusToString(returnCode, msg)); 15280 15281 installedLatch.countDown(); 15282 15283 // Regardless of success or failure of the move operation, 15284 // always unfreeze the package 15285 unfreezePackage(packageName); 15286 15287 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15288 switch (status) { 15289 case PackageInstaller.STATUS_SUCCESS: 15290 mMoveCallbacks.notifyStatusChanged(moveId, 15291 PackageManager.MOVE_SUCCEEDED); 15292 break; 15293 case PackageInstaller.STATUS_FAILURE_STORAGE: 15294 mMoveCallbacks.notifyStatusChanged(moveId, 15295 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15296 break; 15297 default: 15298 mMoveCallbacks.notifyStatusChanged(moveId, 15299 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15300 break; 15301 } 15302 } 15303 }; 15304 15305 final MoveInfo move; 15306 if (moveCompleteApp) { 15307 // Kick off a thread to report progress estimates 15308 new Thread() { 15309 @Override 15310 public void run() { 15311 while (true) { 15312 try { 15313 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15314 break; 15315 } 15316 } catch (InterruptedException ignored) { 15317 } 15318 15319 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15320 final int progress = 10 + (int) MathUtils.constrain( 15321 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15322 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15323 } 15324 } 15325 }.start(); 15326 15327 final String dataAppName = codeFile.getName(); 15328 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15329 dataAppName, appId, seinfo); 15330 } else { 15331 move = null; 15332 } 15333 15334 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15335 15336 final Message msg = mHandler.obtainMessage(INIT_COPY); 15337 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15338 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15339 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15340 mHandler.sendMessage(msg); 15341 } 15342 15343 @Override 15344 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15345 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15346 15347 final int realMoveId = mNextMoveId.getAndIncrement(); 15348 final Bundle extras = new Bundle(); 15349 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15350 mMoveCallbacks.notifyCreated(realMoveId, extras); 15351 15352 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15353 @Override 15354 public void onCreated(int moveId, Bundle extras) { 15355 // Ignored 15356 } 15357 15358 @Override 15359 public void onStatusChanged(int moveId, int status, long estMillis) { 15360 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15361 } 15362 }; 15363 15364 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15365 storage.setPrimaryStorageUuid(volumeUuid, callback); 15366 return realMoveId; 15367 } 15368 15369 @Override 15370 public int getMoveStatus(int moveId) { 15371 mContext.enforceCallingOrSelfPermission( 15372 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15373 return mMoveCallbacks.mLastStatus.get(moveId); 15374 } 15375 15376 @Override 15377 public void registerMoveCallback(IPackageMoveObserver callback) { 15378 mContext.enforceCallingOrSelfPermission( 15379 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15380 mMoveCallbacks.register(callback); 15381 } 15382 15383 @Override 15384 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15385 mContext.enforceCallingOrSelfPermission( 15386 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15387 mMoveCallbacks.unregister(callback); 15388 } 15389 15390 @Override 15391 public boolean setInstallLocation(int loc) { 15392 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15393 null); 15394 if (getInstallLocation() == loc) { 15395 return true; 15396 } 15397 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15398 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15399 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15400 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15401 return true; 15402 } 15403 return false; 15404 } 15405 15406 @Override 15407 public int getInstallLocation() { 15408 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15409 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15410 PackageHelper.APP_INSTALL_AUTO); 15411 } 15412 15413 /** Called by UserManagerService */ 15414 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15415 mDirtyUsers.remove(userHandle); 15416 mSettings.removeUserLPw(userHandle); 15417 mPendingBroadcasts.remove(userHandle); 15418 if (mInstaller != null) { 15419 // Technically, we shouldn't be doing this with the package lock 15420 // held. However, this is very rare, and there is already so much 15421 // other disk I/O going on, that we'll let it slide for now. 15422 final StorageManager storage = StorageManager.from(mContext); 15423 final List<VolumeInfo> vols = storage.getVolumes(); 15424 for (VolumeInfo vol : vols) { 15425 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15426 final String volumeUuid = vol.getFsUuid(); 15427 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15428 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15429 } 15430 } 15431 } 15432 mUserNeedsBadging.delete(userHandle); 15433 removeUnusedPackagesLILPw(userManager, userHandle); 15434 } 15435 15436 /** 15437 * We're removing userHandle and would like to remove any downloaded packages 15438 * that are no longer in use by any other user. 15439 * @param userHandle the user being removed 15440 */ 15441 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15442 final boolean DEBUG_CLEAN_APKS = false; 15443 int [] users = userManager.getUserIdsLPr(); 15444 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15445 while (psit.hasNext()) { 15446 PackageSetting ps = psit.next(); 15447 if (ps.pkg == null) { 15448 continue; 15449 } 15450 final String packageName = ps.pkg.packageName; 15451 // Skip over if system app 15452 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15453 continue; 15454 } 15455 if (DEBUG_CLEAN_APKS) { 15456 Slog.i(TAG, "Checking package " + packageName); 15457 } 15458 boolean keep = false; 15459 for (int i = 0; i < users.length; i++) { 15460 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15461 keep = true; 15462 if (DEBUG_CLEAN_APKS) { 15463 Slog.i(TAG, " Keeping package " + packageName + " for user " 15464 + users[i]); 15465 } 15466 break; 15467 } 15468 } 15469 if (!keep) { 15470 if (DEBUG_CLEAN_APKS) { 15471 Slog.i(TAG, " Removing package " + packageName); 15472 } 15473 mHandler.post(new Runnable() { 15474 public void run() { 15475 deletePackageX(packageName, userHandle, 0); 15476 } //end run 15477 }); 15478 } 15479 } 15480 } 15481 15482 /** Called by UserManagerService */ 15483 void createNewUserLILPw(int userHandle, File path) { 15484 if (mInstaller != null) { 15485 mInstaller.createUserConfig(userHandle); 15486 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15487 } 15488 } 15489 15490 void newUserCreatedLILPw(final int userHandle) { 15491 // We cannot grant the default permissions with a lock held as 15492 // we query providers from other components for default handlers 15493 // such as enabled IMEs, etc. 15494 mHandler.post(new Runnable() { 15495 @Override 15496 public void run() { 15497 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15498 } 15499 }); 15500 } 15501 15502 @Override 15503 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15504 mContext.enforceCallingOrSelfPermission( 15505 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15506 "Only package verification agents can read the verifier device identity"); 15507 15508 synchronized (mPackages) { 15509 return mSettings.getVerifierDeviceIdentityLPw(); 15510 } 15511 } 15512 15513 @Override 15514 public void setPermissionEnforced(String permission, boolean enforced) { 15515 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15516 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15517 synchronized (mPackages) { 15518 if (mSettings.mReadExternalStorageEnforced == null 15519 || mSettings.mReadExternalStorageEnforced != enforced) { 15520 mSettings.mReadExternalStorageEnforced = enforced; 15521 mSettings.writeLPr(); 15522 } 15523 } 15524 // kill any non-foreground processes so we restart them and 15525 // grant/revoke the GID. 15526 final IActivityManager am = ActivityManagerNative.getDefault(); 15527 if (am != null) { 15528 final long token = Binder.clearCallingIdentity(); 15529 try { 15530 am.killProcessesBelowForeground("setPermissionEnforcement"); 15531 } catch (RemoteException e) { 15532 } finally { 15533 Binder.restoreCallingIdentity(token); 15534 } 15535 } 15536 } else { 15537 throw new IllegalArgumentException("No selective enforcement for " + permission); 15538 } 15539 } 15540 15541 @Override 15542 @Deprecated 15543 public boolean isPermissionEnforced(String permission) { 15544 return true; 15545 } 15546 15547 @Override 15548 public boolean isStorageLow() { 15549 final long token = Binder.clearCallingIdentity(); 15550 try { 15551 final DeviceStorageMonitorInternal 15552 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15553 if (dsm != null) { 15554 return dsm.isMemoryLow(); 15555 } else { 15556 return false; 15557 } 15558 } finally { 15559 Binder.restoreCallingIdentity(token); 15560 } 15561 } 15562 15563 @Override 15564 public IPackageInstaller getPackageInstaller() { 15565 return mInstallerService; 15566 } 15567 15568 private boolean userNeedsBadging(int userId) { 15569 int index = mUserNeedsBadging.indexOfKey(userId); 15570 if (index < 0) { 15571 final UserInfo userInfo; 15572 final long token = Binder.clearCallingIdentity(); 15573 try { 15574 userInfo = sUserManager.getUserInfo(userId); 15575 } finally { 15576 Binder.restoreCallingIdentity(token); 15577 } 15578 final boolean b; 15579 if (userInfo != null && userInfo.isManagedProfile()) { 15580 b = true; 15581 } else { 15582 b = false; 15583 } 15584 mUserNeedsBadging.put(userId, b); 15585 return b; 15586 } 15587 return mUserNeedsBadging.valueAt(index); 15588 } 15589 15590 @Override 15591 public KeySet getKeySetByAlias(String packageName, String alias) { 15592 if (packageName == null || alias == null) { 15593 return null; 15594 } 15595 synchronized(mPackages) { 15596 final PackageParser.Package pkg = mPackages.get(packageName); 15597 if (pkg == null) { 15598 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15599 throw new IllegalArgumentException("Unknown package: " + packageName); 15600 } 15601 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15602 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15603 } 15604 } 15605 15606 @Override 15607 public KeySet getSigningKeySet(String packageName) { 15608 if (packageName == null) { 15609 return null; 15610 } 15611 synchronized(mPackages) { 15612 final PackageParser.Package pkg = mPackages.get(packageName); 15613 if (pkg == null) { 15614 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15615 throw new IllegalArgumentException("Unknown package: " + packageName); 15616 } 15617 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15618 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15619 throw new SecurityException("May not access signing KeySet of other apps."); 15620 } 15621 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15622 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15623 } 15624 } 15625 15626 @Override 15627 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15628 if (packageName == null || ks == null) { 15629 return false; 15630 } 15631 synchronized(mPackages) { 15632 final PackageParser.Package pkg = mPackages.get(packageName); 15633 if (pkg == null) { 15634 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15635 throw new IllegalArgumentException("Unknown package: " + packageName); 15636 } 15637 IBinder ksh = ks.getToken(); 15638 if (ksh instanceof KeySetHandle) { 15639 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15640 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15641 } 15642 return false; 15643 } 15644 } 15645 15646 @Override 15647 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15648 if (packageName == null || ks == null) { 15649 return false; 15650 } 15651 synchronized(mPackages) { 15652 final PackageParser.Package pkg = mPackages.get(packageName); 15653 if (pkg == null) { 15654 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15655 throw new IllegalArgumentException("Unknown package: " + packageName); 15656 } 15657 IBinder ksh = ks.getToken(); 15658 if (ksh instanceof KeySetHandle) { 15659 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15660 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15661 } 15662 return false; 15663 } 15664 } 15665 15666 public void getUsageStatsIfNoPackageUsageInfo() { 15667 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15668 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15669 if (usm == null) { 15670 throw new IllegalStateException("UsageStatsManager must be initialized"); 15671 } 15672 long now = System.currentTimeMillis(); 15673 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15674 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15675 String packageName = entry.getKey(); 15676 PackageParser.Package pkg = mPackages.get(packageName); 15677 if (pkg == null) { 15678 continue; 15679 } 15680 UsageStats usage = entry.getValue(); 15681 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15682 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15683 } 15684 } 15685 } 15686 15687 /** 15688 * Check and throw if the given before/after packages would be considered a 15689 * downgrade. 15690 */ 15691 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15692 throws PackageManagerException { 15693 if (after.versionCode < before.mVersionCode) { 15694 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15695 "Update version code " + after.versionCode + " is older than current " 15696 + before.mVersionCode); 15697 } else if (after.versionCode == before.mVersionCode) { 15698 if (after.baseRevisionCode < before.baseRevisionCode) { 15699 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15700 "Update base revision code " + after.baseRevisionCode 15701 + " is older than current " + before.baseRevisionCode); 15702 } 15703 15704 if (!ArrayUtils.isEmpty(after.splitNames)) { 15705 for (int i = 0; i < after.splitNames.length; i++) { 15706 final String splitName = after.splitNames[i]; 15707 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15708 if (j != -1) { 15709 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15710 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15711 "Update split " + splitName + " revision code " 15712 + after.splitRevisionCodes[i] + " is older than current " 15713 + before.splitRevisionCodes[j]); 15714 } 15715 } 15716 } 15717 } 15718 } 15719 } 15720 15721 private static class MoveCallbacks extends Handler { 15722 private static final int MSG_CREATED = 1; 15723 private static final int MSG_STATUS_CHANGED = 2; 15724 15725 private final RemoteCallbackList<IPackageMoveObserver> 15726 mCallbacks = new RemoteCallbackList<>(); 15727 15728 private final SparseIntArray mLastStatus = new SparseIntArray(); 15729 15730 public MoveCallbacks(Looper looper) { 15731 super(looper); 15732 } 15733 15734 public void register(IPackageMoveObserver callback) { 15735 mCallbacks.register(callback); 15736 } 15737 15738 public void unregister(IPackageMoveObserver callback) { 15739 mCallbacks.unregister(callback); 15740 } 15741 15742 @Override 15743 public void handleMessage(Message msg) { 15744 final SomeArgs args = (SomeArgs) msg.obj; 15745 final int n = mCallbacks.beginBroadcast(); 15746 for (int i = 0; i < n; i++) { 15747 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15748 try { 15749 invokeCallback(callback, msg.what, args); 15750 } catch (RemoteException ignored) { 15751 } 15752 } 15753 mCallbacks.finishBroadcast(); 15754 args.recycle(); 15755 } 15756 15757 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15758 throws RemoteException { 15759 switch (what) { 15760 case MSG_CREATED: { 15761 callback.onCreated(args.argi1, (Bundle) args.arg2); 15762 break; 15763 } 15764 case MSG_STATUS_CHANGED: { 15765 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15766 break; 15767 } 15768 } 15769 } 15770 15771 private void notifyCreated(int moveId, Bundle extras) { 15772 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15773 15774 final SomeArgs args = SomeArgs.obtain(); 15775 args.argi1 = moveId; 15776 args.arg2 = extras; 15777 obtainMessage(MSG_CREATED, args).sendToTarget(); 15778 } 15779 15780 private void notifyStatusChanged(int moveId, int status) { 15781 notifyStatusChanged(moveId, status, -1); 15782 } 15783 15784 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15785 Slog.v(TAG, "Move " + moveId + " status " + status); 15786 15787 final SomeArgs args = SomeArgs.obtain(); 15788 args.argi1 = moveId; 15789 args.argi2 = status; 15790 args.arg3 = estMillis; 15791 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15792 15793 synchronized (mLastStatus) { 15794 mLastStatus.put(moveId, status); 15795 } 15796 } 15797 } 15798 15799 private final class OnPermissionChangeListeners extends Handler { 15800 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15801 15802 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15803 new RemoteCallbackList<>(); 15804 15805 public OnPermissionChangeListeners(Looper looper) { 15806 super(looper); 15807 } 15808 15809 @Override 15810 public void handleMessage(Message msg) { 15811 switch (msg.what) { 15812 case MSG_ON_PERMISSIONS_CHANGED: { 15813 final int uid = msg.arg1; 15814 handleOnPermissionsChanged(uid); 15815 } break; 15816 } 15817 } 15818 15819 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15820 mPermissionListeners.register(listener); 15821 15822 } 15823 15824 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15825 mPermissionListeners.unregister(listener); 15826 } 15827 15828 public void onPermissionsChanged(int uid) { 15829 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15830 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15831 } 15832 } 15833 15834 private void handleOnPermissionsChanged(int uid) { 15835 final int count = mPermissionListeners.beginBroadcast(); 15836 try { 15837 for (int i = 0; i < count; i++) { 15838 IOnPermissionsChangeListener callback = mPermissionListeners 15839 .getBroadcastItem(i); 15840 try { 15841 callback.onPermissionsChanged(uid); 15842 } catch (RemoteException e) { 15843 Log.e(TAG, "Permission listener is dead", e); 15844 } 15845 } 15846 } finally { 15847 mPermissionListeners.finishBroadcast(); 15848 } 15849 } 15850 } 15851 15852 private class PackageManagerInternalImpl extends PackageManagerInternal { 15853 @Override 15854 public void setLocationPackagesProvider(PackagesProvider provider) { 15855 synchronized (mPackages) { 15856 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15857 } 15858 } 15859 15860 @Override 15861 public void setImePackagesProvider(PackagesProvider provider) { 15862 synchronized (mPackages) { 15863 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15864 } 15865 } 15866 15867 @Override 15868 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15869 synchronized (mPackages) { 15870 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15871 } 15872 } 15873 } 15874 15875 @Override 15876 public void grantDefaultPermissions(final int userId) { 15877 enforceSystemOrPhoneCaller("grantDefaultPermissions"); 15878 long token = Binder.clearCallingIdentity(); 15879 try { 15880 // We cannot grant the default permissions with a lock held as 15881 // we query providers from other components for default handlers 15882 // such as enabled IMEs, etc. 15883 mHandler.post(new Runnable() { 15884 @Override 15885 public void run() { 15886 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15887 } 15888 }); 15889 } finally { 15890 Binder.restoreCallingIdentity(token); 15891 } 15892 } 15893 15894 @Override 15895 public void setCarrierAppPackagesProvider(final IPackagesProvider provider) { 15896 enforceSystemOrPhoneCaller("setCarrierAppPackagesProvider"); 15897 long token = Binder.clearCallingIdentity(); 15898 try { 15899 PackageManagerInternal.PackagesProvider wrapper = 15900 new PackageManagerInternal.PackagesProvider() { 15901 @Override 15902 public String[] getPackages(int userId) { 15903 try { 15904 return provider.getPackages(userId); 15905 } catch (RemoteException e) { 15906 return null; 15907 } 15908 } 15909 }; 15910 synchronized (mPackages) { 15911 mDefaultPermissionPolicy.setCarrierAppPackagesProviderLPw(wrapper); 15912 } 15913 } finally { 15914 Binder.restoreCallingIdentity(token); 15915 } 15916 } 15917 15918 private static void enforceSystemOrPhoneCaller(String tag) { 15919 int callingUid = Binder.getCallingUid(); 15920 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 15921 throw new SecurityException( 15922 "Cannot call " + tag + " from UID " + callingUid); 15923 } 15924 } 15925} 15926