PackageManagerService.java revision 32e80d7588720bdc9f8a3e961ac4566d7c80b2b9
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 28import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 29import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 30import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 37import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 38import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 39import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 40import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 45import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 47import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 48import static android.content.pm.PackageManager.INSTALL_INTERNAL; 49import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 53import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 54import static android.content.pm.PackageManager.MATCH_ALL; 55import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 56import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 57import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 58import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 59import static android.content.pm.PackageManager.PERMISSION_GRANTED; 60import static android.content.pm.PackageParser.isApkFile; 61import static android.os.Process.PACKAGE_INFO_GID; 62import static android.os.Process.SYSTEM_UID; 63import static android.system.OsConstants.O_CREAT; 64import static android.system.OsConstants.O_RDWR; 65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 66import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 67import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 68import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 69import static com.android.internal.util.ArrayUtils.appendInt; 70import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 72import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 73import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 74import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 75 76import android.Manifest; 77import android.app.ActivityManager; 78import android.app.ActivityManagerNative; 79import android.app.AppGlobals; 80import android.app.IActivityManager; 81import android.app.admin.IDevicePolicyManager; 82import android.app.backup.IBackupManager; 83import android.app.usage.UsageStats; 84import android.app.usage.UsageStatsManager; 85import android.content.BroadcastReceiver; 86import android.content.ComponentName; 87import android.content.Context; 88import android.content.IIntentReceiver; 89import android.content.Intent; 90import android.content.IntentFilter; 91import android.content.IntentSender; 92import android.content.IntentSender.SendIntentException; 93import android.content.ServiceConnection; 94import android.content.pm.ActivityInfo; 95import android.content.pm.ApplicationInfo; 96import android.content.pm.FeatureInfo; 97import android.content.pm.IOnPermissionsChangeListener; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 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.annotations.GuardedBy; 196import com.android.internal.app.IMediaContainerService; 197import com.android.internal.app.ResolverActivity; 198import com.android.internal.content.NativeLibraryHelper; 199import com.android.internal.content.PackageHelper; 200import com.android.internal.os.IParcelFileDescriptorFactory; 201import com.android.internal.os.SomeArgs; 202import com.android.internal.os.Zygote; 203import com.android.internal.util.ArrayUtils; 204import com.android.internal.util.FastPrintWriter; 205import com.android.internal.util.FastXmlSerializer; 206import com.android.internal.util.IndentingPrintWriter; 207import com.android.internal.util.Preconditions; 208import com.android.server.EventLogTags; 209import com.android.server.FgThread; 210import com.android.server.IntentResolver; 211import com.android.server.LocalServices; 212import com.android.server.ServiceThread; 213import com.android.server.SystemConfig; 214import com.android.server.Watchdog; 215import com.android.server.pm.PermissionsState.PermissionState; 216import com.android.server.pm.Settings.DatabaseVersion; 217import com.android.server.storage.DeviceStorageMonitorInternal; 218 219import org.xmlpull.v1.XmlPullParser; 220import org.xmlpull.v1.XmlPullParserException; 221import org.xmlpull.v1.XmlSerializer; 222 223import java.io.BufferedInputStream; 224import java.io.BufferedOutputStream; 225import java.io.BufferedReader; 226import java.io.ByteArrayInputStream; 227import java.io.ByteArrayOutputStream; 228import java.io.File; 229import java.io.FileDescriptor; 230import java.io.FileNotFoundException; 231import java.io.FileOutputStream; 232import java.io.FileReader; 233import java.io.FilenameFilter; 234import java.io.IOException; 235import java.io.InputStream; 236import java.io.PrintWriter; 237import java.nio.charset.StandardCharsets; 238import java.security.NoSuchAlgorithmException; 239import java.security.PublicKey; 240import java.security.cert.CertificateEncodingException; 241import java.security.cert.CertificateException; 242import java.text.SimpleDateFormat; 243import java.util.ArrayList; 244import java.util.Arrays; 245import java.util.Collection; 246import java.util.Collections; 247import java.util.Comparator; 248import java.util.Date; 249import java.util.Iterator; 250import java.util.List; 251import java.util.Map; 252import java.util.Objects; 253import java.util.Set; 254import java.util.concurrent.CountDownLatch; 255import java.util.concurrent.TimeUnit; 256import java.util.concurrent.atomic.AtomicBoolean; 257import java.util.concurrent.atomic.AtomicInteger; 258import java.util.concurrent.atomic.AtomicLong; 259 260/** 261 * Keep track of all those .apks everywhere. 262 * 263 * This is very central to the platform's security; please run the unit 264 * tests whenever making modifications here: 265 * 266mmm frameworks/base/tests/AndroidTests 267adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 268adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 269 * 270 * {@hide} 271 */ 272public class PackageManagerService extends IPackageManager.Stub { 273 static final String TAG = "PackageManager"; 274 static final boolean DEBUG_SETTINGS = false; 275 static final boolean DEBUG_PREFERRED = false; 276 static final boolean DEBUG_UPGRADE = false; 277 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 278 private static final boolean DEBUG_BACKUP = true; 279 private static final boolean DEBUG_INSTALL = false; 280 private static final boolean DEBUG_REMOVE = false; 281 private static final boolean DEBUG_BROADCASTS = false; 282 private static final boolean DEBUG_SHOW_INFO = false; 283 private static final boolean DEBUG_PACKAGE_INFO = false; 284 private static final boolean DEBUG_INTENT_MATCHING = false; 285 private static final boolean DEBUG_PACKAGE_SCANNING = false; 286 private static final boolean DEBUG_VERIFY = false; 287 private static final boolean DEBUG_DEXOPT = false; 288 private static final boolean DEBUG_ABI_SELECTION = false; 289 290 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 291 292 private static final int RADIO_UID = Process.PHONE_UID; 293 private static final int LOG_UID = Process.LOG_UID; 294 private static final int NFC_UID = Process.NFC_UID; 295 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 296 private static final int SHELL_UID = Process.SHELL_UID; 297 298 // Cap the size of permission trees that 3rd party apps can define 299 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 300 301 // Suffix used during package installation when copying/moving 302 // package apks to install directory. 303 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 304 305 static final int SCAN_NO_DEX = 1<<1; 306 static final int SCAN_FORCE_DEX = 1<<2; 307 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 308 static final int SCAN_NEW_INSTALL = 1<<4; 309 static final int SCAN_NO_PATHS = 1<<5; 310 static final int SCAN_UPDATE_TIME = 1<<6; 311 static final int SCAN_DEFER_DEX = 1<<7; 312 static final int SCAN_BOOTING = 1<<8; 313 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 314 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 315 static final int SCAN_REQUIRE_KNOWN = 1<<12; 316 static final int SCAN_MOVE = 1<<13; 317 static final int SCAN_INITIAL = 1<<14; 318 319 static final int REMOVE_CHATTY = 1<<16; 320 321 private static final int[] EMPTY_INT_ARRAY = new int[0]; 322 323 /** 324 * Timeout (in milliseconds) after which the watchdog should declare that 325 * our handler thread is wedged. The usual default for such things is one 326 * minute but we sometimes do very lengthy I/O operations on this thread, 327 * such as installing multi-gigabyte applications, so ours needs to be longer. 328 */ 329 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 330 331 /** 332 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 333 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 334 * settings entry if available, otherwise we use the hardcoded default. If it's been 335 * more than this long since the last fstrim, we force one during the boot sequence. 336 * 337 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 338 * one gets run at the next available charging+idle time. This final mandatory 339 * no-fstrim check kicks in only of the other scheduling criteria is never met. 340 */ 341 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 342 343 /** 344 * Whether verification is enabled by default. 345 */ 346 private static final boolean DEFAULT_VERIFY_ENABLE = true; 347 348 /** 349 * The default maximum time to wait for the verification agent to return in 350 * milliseconds. 351 */ 352 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 353 354 /** 355 * The default response for package verification timeout. 356 * 357 * This can be either PackageManager.VERIFICATION_ALLOW or 358 * PackageManager.VERIFICATION_REJECT. 359 */ 360 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 361 362 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 363 364 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 365 DEFAULT_CONTAINER_PACKAGE, 366 "com.android.defcontainer.DefaultContainerService"); 367 368 private static final String KILL_APP_REASON_GIDS_CHANGED = 369 "permission grant or revoke changed gids"; 370 371 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 372 "permissions revoked"; 373 374 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 375 376 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 377 378 /** Permission grant: not grant the permission. */ 379 private static final int GRANT_DENIED = 1; 380 381 /** Permission grant: grant the permission as an install permission. */ 382 private static final int GRANT_INSTALL = 2; 383 384 /** Permission grant: grant the permission as an install permission for a legacy app. */ 385 private static final int GRANT_INSTALL_LEGACY = 3; 386 387 /** Permission grant: grant the permission as a runtime one. */ 388 private static final int GRANT_RUNTIME = 4; 389 390 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 391 private static final int GRANT_UPGRADE = 5; 392 393 /** Canonical intent used to identify what counts as a "web browser" app */ 394 private static final Intent sBrowserIntent; 395 static { 396 sBrowserIntent = new Intent(); 397 sBrowserIntent.setAction(Intent.ACTION_VIEW); 398 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 399 sBrowserIntent.setData(Uri.parse("http:")); 400 } 401 402 final ServiceThread mHandlerThread; 403 404 final PackageHandler mHandler; 405 406 /** 407 * Messages for {@link #mHandler} that need to wait for system ready before 408 * being dispatched. 409 */ 410 private ArrayList<Message> mPostSystemReadyMessages; 411 412 final int mSdkVersion = Build.VERSION.SDK_INT; 413 414 final Context mContext; 415 final boolean mFactoryTest; 416 final boolean mOnlyCore; 417 final boolean mLazyDexOpt; 418 final long mDexOptLRUThresholdInMills; 419 final DisplayMetrics mMetrics; 420 final int mDefParseFlags; 421 final String[] mSeparateProcesses; 422 final boolean mIsUpgrade; 423 424 // This is where all application persistent data goes. 425 final File mAppDataDir; 426 427 // This is where all application persistent data goes for secondary users. 428 final File mUserAppDataDir; 429 430 /** The location for ASEC container files on internal storage. */ 431 final String mAsecInternalPath; 432 433 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 434 // LOCK HELD. Can be called with mInstallLock held. 435 @GuardedBy("mInstallLock") 436 final Installer mInstaller; 437 438 /** Directory where installed third-party apps stored */ 439 final File mAppInstallDir; 440 441 /** 442 * Directory to which applications installed internally have their 443 * 32 bit native libraries copied. 444 */ 445 private File mAppLib32InstallDir; 446 447 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 448 // apps. 449 final File mDrmAppPrivateInstallDir; 450 451 // ---------------------------------------------------------------- 452 453 // Lock for state used when installing and doing other long running 454 // operations. Methods that must be called with this lock held have 455 // the suffix "LI". 456 final Object mInstallLock = new Object(); 457 458 // ---------------------------------------------------------------- 459 460 // Keys are String (package name), values are Package. This also serves 461 // as the lock for the global state. Methods that must be called with 462 // this lock held have the prefix "LP". 463 @GuardedBy("mPackages") 464 final ArrayMap<String, PackageParser.Package> mPackages = 465 new ArrayMap<String, PackageParser.Package>(); 466 467 // Tracks available target package names -> overlay package paths. 468 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 469 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 470 471 final Settings mSettings; 472 boolean mRestoredSettings; 473 474 // System configuration read by SystemConfig. 475 final int[] mGlobalGids; 476 final SparseArray<ArraySet<String>> mSystemPermissions; 477 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 478 479 // If mac_permissions.xml was found for seinfo labeling. 480 boolean mFoundPolicyFile; 481 482 // If a recursive restorecon of /data/data/<pkg> is needed. 483 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 484 485 public static final class SharedLibraryEntry { 486 public final String path; 487 public final String apk; 488 489 SharedLibraryEntry(String _path, String _apk) { 490 path = _path; 491 apk = _apk; 492 } 493 } 494 495 // Currently known shared libraries. 496 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 497 new ArrayMap<String, SharedLibraryEntry>(); 498 499 // All available activities, for your resolving pleasure. 500 final ActivityIntentResolver mActivities = 501 new ActivityIntentResolver(); 502 503 // All available receivers, for your resolving pleasure. 504 final ActivityIntentResolver mReceivers = 505 new ActivityIntentResolver(); 506 507 // All available services, for your resolving pleasure. 508 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 509 510 // All available providers, for your resolving pleasure. 511 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 512 513 // Mapping from provider base names (first directory in content URI codePath) 514 // to the provider information. 515 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 516 new ArrayMap<String, PackageParser.Provider>(); 517 518 // Mapping from instrumentation class names to info about them. 519 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 520 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 521 522 // Mapping from permission names to info about them. 523 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 524 new ArrayMap<String, PackageParser.PermissionGroup>(); 525 526 // Packages whose data we have transfered into another package, thus 527 // should no longer exist. 528 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 529 530 // Broadcast actions that are only available to the system. 531 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 532 533 /** List of packages waiting for verification. */ 534 final SparseArray<PackageVerificationState> mPendingVerification 535 = new SparseArray<PackageVerificationState>(); 536 537 /** Set of packages associated with each app op permission. */ 538 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 539 540 final PackageInstallerService mInstallerService; 541 542 private final PackageDexOptimizer mPackageDexOptimizer; 543 544 private AtomicInteger mNextMoveId = new AtomicInteger(); 545 private final MoveCallbacks mMoveCallbacks; 546 547 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 548 549 // Cache of users who need badging. 550 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 551 552 /** Token for keys in mPendingVerification. */ 553 private int mPendingVerificationToken = 0; 554 555 volatile boolean mSystemReady; 556 volatile boolean mSafeMode; 557 volatile boolean mHasSystemUidErrors; 558 559 ApplicationInfo mAndroidApplication; 560 final ActivityInfo mResolveActivity = new ActivityInfo(); 561 final ResolveInfo mResolveInfo = new ResolveInfo(); 562 ComponentName mResolveComponentName; 563 PackageParser.Package mPlatformPackage; 564 ComponentName mCustomResolverComponentName; 565 566 boolean mResolverReplaced = false; 567 568 private final ComponentName mIntentFilterVerifierComponent; 569 private int mIntentFilterVerificationToken = 0; 570 571 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 572 = new SparseArray<IntentFilterVerificationState>(); 573 574 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 575 new DefaultPermissionGrantPolicy(this); 576 577 private static class IFVerificationParams { 578 PackageParser.Package pkg; 579 boolean replacing; 580 int userId; 581 int verifierUid; 582 583 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 584 int _userId, int _verifierUid) { 585 pkg = _pkg; 586 replacing = _replacing; 587 userId = _userId; 588 replacing = _replacing; 589 verifierUid = _verifierUid; 590 } 591 } 592 593 private interface IntentFilterVerifier<T extends IntentFilter> { 594 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 595 T filter, String packageName); 596 void startVerifications(int userId); 597 void receiveVerificationResponse(int verificationId); 598 } 599 600 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 601 private Context mContext; 602 private ComponentName mIntentFilterVerifierComponent; 603 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 604 605 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 606 mContext = context; 607 mIntentFilterVerifierComponent = verifierComponent; 608 } 609 610 private String getDefaultScheme() { 611 return IntentFilter.SCHEME_HTTPS; 612 } 613 614 @Override 615 public void startVerifications(int userId) { 616 // Launch verifications requests 617 int count = mCurrentIntentFilterVerifications.size(); 618 for (int n=0; n<count; n++) { 619 int verificationId = mCurrentIntentFilterVerifications.get(n); 620 final IntentFilterVerificationState ivs = 621 mIntentFilterVerificationStates.get(verificationId); 622 623 String packageName = ivs.getPackageName(); 624 625 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 626 final int filterCount = filters.size(); 627 ArraySet<String> domainsSet = new ArraySet<>(); 628 for (int m=0; m<filterCount; m++) { 629 PackageParser.ActivityIntentInfo filter = filters.get(m); 630 domainsSet.addAll(filter.getHostsList()); 631 } 632 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 633 synchronized (mPackages) { 634 if (mSettings.createIntentFilterVerificationIfNeededLPw( 635 packageName, domainsList) != null) { 636 scheduleWriteSettingsLocked(); 637 } 638 } 639 sendVerificationRequest(userId, verificationId, ivs); 640 } 641 mCurrentIntentFilterVerifications.clear(); 642 } 643 644 private void sendVerificationRequest(int userId, int verificationId, 645 IntentFilterVerificationState ivs) { 646 647 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 648 verificationIntent.putExtra( 649 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 650 verificationId); 651 verificationIntent.putExtra( 652 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 653 getDefaultScheme()); 654 verificationIntent.putExtra( 655 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 656 ivs.getHostsString()); 657 verificationIntent.putExtra( 658 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 659 ivs.getPackageName()); 660 verificationIntent.setComponent(mIntentFilterVerifierComponent); 661 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 662 663 UserHandle user = new UserHandle(userId); 664 mContext.sendBroadcastAsUser(verificationIntent, user); 665 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 666 "Sending IntentFilter verification broadcast"); 667 } 668 669 public void receiveVerificationResponse(int verificationId) { 670 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 671 672 final boolean verified = ivs.isVerified(); 673 674 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 675 final int count = filters.size(); 676 if (DEBUG_DOMAIN_VERIFICATION) { 677 Slog.i(TAG, "Received verification response " + verificationId 678 + " for " + count + " filters, verified=" + verified); 679 } 680 for (int n=0; n<count; n++) { 681 PackageParser.ActivityIntentInfo filter = filters.get(n); 682 filter.setVerified(verified); 683 684 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 685 + " verified with result:" + verified + " and hosts:" 686 + ivs.getHostsString()); 687 } 688 689 mIntentFilterVerificationStates.remove(verificationId); 690 691 final String packageName = ivs.getPackageName(); 692 IntentFilterVerificationInfo ivi = null; 693 694 synchronized (mPackages) { 695 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 696 } 697 if (ivi == null) { 698 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 699 + verificationId + " packageName:" + packageName); 700 return; 701 } 702 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 703 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 704 705 synchronized (mPackages) { 706 if (verified) { 707 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 708 } else { 709 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 710 } 711 scheduleWriteSettingsLocked(); 712 713 final int userId = ivs.getUserId(); 714 if (userId != UserHandle.USER_ALL) { 715 final int userStatus = 716 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 717 718 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 719 boolean needUpdate = false; 720 721 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 722 // already been set by the User thru the Disambiguation dialog 723 switch (userStatus) { 724 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 725 if (verified) { 726 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 727 } else { 728 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 729 } 730 needUpdate = true; 731 break; 732 733 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 734 if (verified) { 735 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 736 needUpdate = true; 737 } 738 break; 739 740 default: 741 // Nothing to do 742 } 743 744 if (needUpdate) { 745 mSettings.updateIntentFilterVerificationStatusLPw( 746 packageName, updatedStatus, userId); 747 scheduleWritePackageRestrictionsLocked(userId); 748 } 749 } 750 } 751 } 752 753 @Override 754 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 755 ActivityIntentInfo filter, String packageName) { 756 if (!hasValidDomains(filter)) { 757 return false; 758 } 759 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 760 if (ivs == null) { 761 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 762 packageName); 763 } 764 if (DEBUG_DOMAIN_VERIFICATION) { 765 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 766 } 767 ivs.addFilter(filter); 768 return true; 769 } 770 771 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 772 int userId, int verificationId, String packageName) { 773 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 774 verifierUid, userId, packageName); 775 ivs.setPendingState(); 776 synchronized (mPackages) { 777 mIntentFilterVerificationStates.append(verificationId, ivs); 778 mCurrentIntentFilterVerifications.add(verificationId); 779 } 780 return ivs; 781 } 782 } 783 784 private static boolean hasValidDomains(ActivityIntentInfo filter) { 785 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 786 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 787 if (!hasHTTPorHTTPS) { 788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 789 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 790 return false; 791 } 792 return true; 793 } 794 795 private IntentFilterVerifier mIntentFilterVerifier; 796 797 // Set of pending broadcasts for aggregating enable/disable of components. 798 static class PendingPackageBroadcasts { 799 // for each user id, a map of <package name -> components within that package> 800 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 801 802 public PendingPackageBroadcasts() { 803 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 804 } 805 806 public ArrayList<String> get(int userId, String packageName) { 807 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 808 return packages.get(packageName); 809 } 810 811 public void put(int userId, String packageName, ArrayList<String> components) { 812 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 813 packages.put(packageName, components); 814 } 815 816 public void remove(int userId, String packageName) { 817 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 818 if (packages != null) { 819 packages.remove(packageName); 820 } 821 } 822 823 public void remove(int userId) { 824 mUidMap.remove(userId); 825 } 826 827 public int userIdCount() { 828 return mUidMap.size(); 829 } 830 831 public int userIdAt(int n) { 832 return mUidMap.keyAt(n); 833 } 834 835 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 836 return mUidMap.get(userId); 837 } 838 839 public int size() { 840 // total number of pending broadcast entries across all userIds 841 int num = 0; 842 for (int i = 0; i< mUidMap.size(); i++) { 843 num += mUidMap.valueAt(i).size(); 844 } 845 return num; 846 } 847 848 public void clear() { 849 mUidMap.clear(); 850 } 851 852 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 853 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 854 if (map == null) { 855 map = new ArrayMap<String, ArrayList<String>>(); 856 mUidMap.put(userId, map); 857 } 858 return map; 859 } 860 } 861 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 862 863 // Service Connection to remote media container service to copy 864 // package uri's from external media onto secure containers 865 // or internal storage. 866 private IMediaContainerService mContainerService = null; 867 868 static final int SEND_PENDING_BROADCAST = 1; 869 static final int MCS_BOUND = 3; 870 static final int END_COPY = 4; 871 static final int INIT_COPY = 5; 872 static final int MCS_UNBIND = 6; 873 static final int START_CLEANING_PACKAGE = 7; 874 static final int FIND_INSTALL_LOC = 8; 875 static final int POST_INSTALL = 9; 876 static final int MCS_RECONNECT = 10; 877 static final int MCS_GIVE_UP = 11; 878 static final int UPDATED_MEDIA_STATUS = 12; 879 static final int WRITE_SETTINGS = 13; 880 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 881 static final int PACKAGE_VERIFIED = 15; 882 static final int CHECK_PENDING_VERIFICATION = 16; 883 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 884 static final int INTENT_FILTER_VERIFIED = 18; 885 886 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 887 888 // Delay time in millisecs 889 static final int BROADCAST_DELAY = 10 * 1000; 890 891 static UserManagerService sUserManager; 892 893 // Stores a list of users whose package restrictions file needs to be updated 894 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 895 896 final private DefaultContainerConnection mDefContainerConn = 897 new DefaultContainerConnection(); 898 class DefaultContainerConnection implements ServiceConnection { 899 public void onServiceConnected(ComponentName name, IBinder service) { 900 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 901 IMediaContainerService imcs = 902 IMediaContainerService.Stub.asInterface(service); 903 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 904 } 905 906 public void onServiceDisconnected(ComponentName name) { 907 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 908 } 909 } 910 911 // Recordkeeping of restore-after-install operations that are currently in flight 912 // between the Package Manager and the Backup Manager 913 class PostInstallData { 914 public InstallArgs args; 915 public PackageInstalledInfo res; 916 917 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 918 args = _a; 919 res = _r; 920 } 921 } 922 923 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 924 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 925 926 // XML tags for backup/restore of various bits of state 927 private static final String TAG_PREFERRED_BACKUP = "pa"; 928 private static final String TAG_DEFAULT_APPS = "da"; 929 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 930 931 private final String mRequiredVerifierPackage; 932 933 private final PackageUsage mPackageUsage = new PackageUsage(); 934 935 private class PackageUsage { 936 private static final int WRITE_INTERVAL 937 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 938 939 private final Object mFileLock = new Object(); 940 private final AtomicLong mLastWritten = new AtomicLong(0); 941 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 942 943 private boolean mIsHistoricalPackageUsageAvailable = true; 944 945 boolean isHistoricalPackageUsageAvailable() { 946 return mIsHistoricalPackageUsageAvailable; 947 } 948 949 void write(boolean force) { 950 if (force) { 951 writeInternal(); 952 return; 953 } 954 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 955 && !DEBUG_DEXOPT) { 956 return; 957 } 958 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 959 new Thread("PackageUsage_DiskWriter") { 960 @Override 961 public void run() { 962 try { 963 writeInternal(); 964 } finally { 965 mBackgroundWriteRunning.set(false); 966 } 967 } 968 }.start(); 969 } 970 } 971 972 private void writeInternal() { 973 synchronized (mPackages) { 974 synchronized (mFileLock) { 975 AtomicFile file = getFile(); 976 FileOutputStream f = null; 977 try { 978 f = file.startWrite(); 979 BufferedOutputStream out = new BufferedOutputStream(f); 980 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 981 StringBuilder sb = new StringBuilder(); 982 for (PackageParser.Package pkg : mPackages.values()) { 983 if (pkg.mLastPackageUsageTimeInMills == 0) { 984 continue; 985 } 986 sb.setLength(0); 987 sb.append(pkg.packageName); 988 sb.append(' '); 989 sb.append((long)pkg.mLastPackageUsageTimeInMills); 990 sb.append('\n'); 991 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 992 } 993 out.flush(); 994 file.finishWrite(f); 995 } catch (IOException e) { 996 if (f != null) { 997 file.failWrite(f); 998 } 999 Log.e(TAG, "Failed to write package usage times", e); 1000 } 1001 } 1002 } 1003 mLastWritten.set(SystemClock.elapsedRealtime()); 1004 } 1005 1006 void readLP() { 1007 synchronized (mFileLock) { 1008 AtomicFile file = getFile(); 1009 BufferedInputStream in = null; 1010 try { 1011 in = new BufferedInputStream(file.openRead()); 1012 StringBuffer sb = new StringBuffer(); 1013 while (true) { 1014 String packageName = readToken(in, sb, ' '); 1015 if (packageName == null) { 1016 break; 1017 } 1018 String timeInMillisString = readToken(in, sb, '\n'); 1019 if (timeInMillisString == null) { 1020 throw new IOException("Failed to find last usage time for package " 1021 + packageName); 1022 } 1023 PackageParser.Package pkg = mPackages.get(packageName); 1024 if (pkg == null) { 1025 continue; 1026 } 1027 long timeInMillis; 1028 try { 1029 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1030 } catch (NumberFormatException e) { 1031 throw new IOException("Failed to parse " + timeInMillisString 1032 + " as a long.", e); 1033 } 1034 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1035 } 1036 } catch (FileNotFoundException expected) { 1037 mIsHistoricalPackageUsageAvailable = false; 1038 } catch (IOException e) { 1039 Log.w(TAG, "Failed to read package usage times", e); 1040 } finally { 1041 IoUtils.closeQuietly(in); 1042 } 1043 } 1044 mLastWritten.set(SystemClock.elapsedRealtime()); 1045 } 1046 1047 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1048 throws IOException { 1049 sb.setLength(0); 1050 while (true) { 1051 int ch = in.read(); 1052 if (ch == -1) { 1053 if (sb.length() == 0) { 1054 return null; 1055 } 1056 throw new IOException("Unexpected EOF"); 1057 } 1058 if (ch == endOfToken) { 1059 return sb.toString(); 1060 } 1061 sb.append((char)ch); 1062 } 1063 } 1064 1065 private AtomicFile getFile() { 1066 File dataDir = Environment.getDataDirectory(); 1067 File systemDir = new File(dataDir, "system"); 1068 File fname = new File(systemDir, "package-usage.list"); 1069 return new AtomicFile(fname); 1070 } 1071 } 1072 1073 class PackageHandler extends Handler { 1074 private boolean mBound = false; 1075 final ArrayList<HandlerParams> mPendingInstalls = 1076 new ArrayList<HandlerParams>(); 1077 1078 private boolean connectToService() { 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1080 " DefaultContainerService"); 1081 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1082 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1083 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1084 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1085 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1086 mBound = true; 1087 return true; 1088 } 1089 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1090 return false; 1091 } 1092 1093 private void disconnectService() { 1094 mContainerService = null; 1095 mBound = false; 1096 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1097 mContext.unbindService(mDefContainerConn); 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1099 } 1100 1101 PackageHandler(Looper looper) { 1102 super(looper); 1103 } 1104 1105 public void handleMessage(Message msg) { 1106 try { 1107 doHandleMessage(msg); 1108 } finally { 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1110 } 1111 } 1112 1113 void doHandleMessage(Message msg) { 1114 switch (msg.what) { 1115 case INIT_COPY: { 1116 HandlerParams params = (HandlerParams) msg.obj; 1117 int idx = mPendingInstalls.size(); 1118 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1119 // If a bind was already initiated we dont really 1120 // need to do anything. The pending install 1121 // will be processed later on. 1122 if (!mBound) { 1123 // If this is the only one pending we might 1124 // have to bind to the service again. 1125 if (!connectToService()) { 1126 Slog.e(TAG, "Failed to bind to media container service"); 1127 params.serviceError(); 1128 return; 1129 } else { 1130 // Once we bind to the service, the first 1131 // pending request will be processed. 1132 mPendingInstalls.add(idx, params); 1133 } 1134 } else { 1135 mPendingInstalls.add(idx, params); 1136 // Already bound to the service. Just make 1137 // sure we trigger off processing the first request. 1138 if (idx == 0) { 1139 mHandler.sendEmptyMessage(MCS_BOUND); 1140 } 1141 } 1142 break; 1143 } 1144 case MCS_BOUND: { 1145 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1146 if (msg.obj != null) { 1147 mContainerService = (IMediaContainerService) msg.obj; 1148 } 1149 if (mContainerService == null) { 1150 if (!mBound) { 1151 // Something seriously wrong since we are not bound and we are not 1152 // waiting for connection. Bail out. 1153 Slog.e(TAG, "Cannot bind to media container service"); 1154 for (HandlerParams params : mPendingInstalls) { 1155 // Indicate service bind error 1156 params.serviceError(); 1157 } 1158 mPendingInstalls.clear(); 1159 } else { 1160 Slog.w(TAG, "Waiting to connect to media container service"); 1161 } 1162 } else if (mPendingInstalls.size() > 0) { 1163 HandlerParams params = mPendingInstalls.get(0); 1164 if (params != null) { 1165 if (params.startCopy()) { 1166 // We are done... look for more work or to 1167 // go idle. 1168 if (DEBUG_SD_INSTALL) Log.i(TAG, 1169 "Checking for more work or unbind..."); 1170 // Delete pending install 1171 if (mPendingInstalls.size() > 0) { 1172 mPendingInstalls.remove(0); 1173 } 1174 if (mPendingInstalls.size() == 0) { 1175 if (mBound) { 1176 if (DEBUG_SD_INSTALL) Log.i(TAG, 1177 "Posting delayed MCS_UNBIND"); 1178 removeMessages(MCS_UNBIND); 1179 Message ubmsg = obtainMessage(MCS_UNBIND); 1180 // Unbind after a little delay, to avoid 1181 // continual thrashing. 1182 sendMessageDelayed(ubmsg, 10000); 1183 } 1184 } else { 1185 // There are more pending requests in queue. 1186 // Just post MCS_BOUND message to trigger processing 1187 // of next pending install. 1188 if (DEBUG_SD_INSTALL) Log.i(TAG, 1189 "Posting MCS_BOUND for next work"); 1190 mHandler.sendEmptyMessage(MCS_BOUND); 1191 } 1192 } 1193 } 1194 } else { 1195 // Should never happen ideally. 1196 Slog.w(TAG, "Empty queue"); 1197 } 1198 break; 1199 } 1200 case MCS_RECONNECT: { 1201 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1202 if (mPendingInstalls.size() > 0) { 1203 if (mBound) { 1204 disconnectService(); 1205 } 1206 if (!connectToService()) { 1207 Slog.e(TAG, "Failed to bind to media container service"); 1208 for (HandlerParams params : mPendingInstalls) { 1209 // Indicate service bind error 1210 params.serviceError(); 1211 } 1212 mPendingInstalls.clear(); 1213 } 1214 } 1215 break; 1216 } 1217 case MCS_UNBIND: { 1218 // If there is no actual work left, then time to unbind. 1219 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1220 1221 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1222 if (mBound) { 1223 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1224 1225 disconnectService(); 1226 } 1227 } else if (mPendingInstalls.size() > 0) { 1228 // There are more pending requests in queue. 1229 // Just post MCS_BOUND message to trigger processing 1230 // of next pending install. 1231 mHandler.sendEmptyMessage(MCS_BOUND); 1232 } 1233 1234 break; 1235 } 1236 case MCS_GIVE_UP: { 1237 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1238 mPendingInstalls.remove(0); 1239 break; 1240 } 1241 case SEND_PENDING_BROADCAST: { 1242 String packages[]; 1243 ArrayList<String> components[]; 1244 int size = 0; 1245 int uids[]; 1246 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1247 synchronized (mPackages) { 1248 if (mPendingBroadcasts == null) { 1249 return; 1250 } 1251 size = mPendingBroadcasts.size(); 1252 if (size <= 0) { 1253 // Nothing to be done. Just return 1254 return; 1255 } 1256 packages = new String[size]; 1257 components = new ArrayList[size]; 1258 uids = new int[size]; 1259 int i = 0; // filling out the above arrays 1260 1261 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1262 int packageUserId = mPendingBroadcasts.userIdAt(n); 1263 Iterator<Map.Entry<String, ArrayList<String>>> it 1264 = mPendingBroadcasts.packagesForUserId(packageUserId) 1265 .entrySet().iterator(); 1266 while (it.hasNext() && i < size) { 1267 Map.Entry<String, ArrayList<String>> ent = it.next(); 1268 packages[i] = ent.getKey(); 1269 components[i] = ent.getValue(); 1270 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1271 uids[i] = (ps != null) 1272 ? UserHandle.getUid(packageUserId, ps.appId) 1273 : -1; 1274 i++; 1275 } 1276 } 1277 size = i; 1278 mPendingBroadcasts.clear(); 1279 } 1280 // Send broadcasts 1281 for (int i = 0; i < size; i++) { 1282 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1283 } 1284 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1285 break; 1286 } 1287 case START_CLEANING_PACKAGE: { 1288 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1289 final String packageName = (String)msg.obj; 1290 final int userId = msg.arg1; 1291 final boolean andCode = msg.arg2 != 0; 1292 synchronized (mPackages) { 1293 if (userId == UserHandle.USER_ALL) { 1294 int[] users = sUserManager.getUserIds(); 1295 for (int user : users) { 1296 mSettings.addPackageToCleanLPw( 1297 new PackageCleanItem(user, packageName, andCode)); 1298 } 1299 } else { 1300 mSettings.addPackageToCleanLPw( 1301 new PackageCleanItem(userId, packageName, andCode)); 1302 } 1303 } 1304 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1305 startCleaningPackages(); 1306 } break; 1307 case POST_INSTALL: { 1308 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1309 PostInstallData data = mRunningInstalls.get(msg.arg1); 1310 mRunningInstalls.delete(msg.arg1); 1311 boolean deleteOld = false; 1312 1313 if (data != null) { 1314 InstallArgs args = data.args; 1315 PackageInstalledInfo res = data.res; 1316 final String packageName = res.pkg.applicationInfo.packageName; 1317 1318 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1319 res.removedInfo.sendBroadcast(false, true, false); 1320 Bundle extras = new Bundle(1); 1321 extras.putInt(Intent.EXTRA_UID, res.uid); 1322 1323 // Now that we successfully installed the package, grant runtime 1324 // permissions if requested before broadcasting the install. 1325 if ((args.installFlags 1326 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1327 grantRequestedRuntimePermissions(res.pkg, 1328 args.user.getIdentifier()); 1329 } 1330 1331 // Determine the set of users who are adding this 1332 // package for the first time vs. those who are seeing 1333 // an update. 1334 int[] firstUsers; 1335 int[] updateUsers = new int[0]; 1336 if (res.origUsers == null || res.origUsers.length == 0) { 1337 firstUsers = res.newUsers; 1338 } else { 1339 firstUsers = new int[0]; 1340 for (int i=0; i<res.newUsers.length; i++) { 1341 int user = res.newUsers[i]; 1342 boolean isNew = true; 1343 for (int j=0; j<res.origUsers.length; j++) { 1344 if (res.origUsers[j] == user) { 1345 isNew = false; 1346 break; 1347 } 1348 } 1349 if (isNew) { 1350 int[] newFirst = new int[firstUsers.length+1]; 1351 System.arraycopy(firstUsers, 0, newFirst, 0, 1352 firstUsers.length); 1353 newFirst[firstUsers.length] = user; 1354 firstUsers = newFirst; 1355 } else { 1356 int[] newUpdate = new int[updateUsers.length+1]; 1357 System.arraycopy(updateUsers, 0, newUpdate, 0, 1358 updateUsers.length); 1359 newUpdate[updateUsers.length] = user; 1360 updateUsers = newUpdate; 1361 } 1362 } 1363 } 1364 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1365 packageName, extras, null, null, firstUsers); 1366 final boolean update = res.removedInfo.removedPackage != null; 1367 if (update) { 1368 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1369 } 1370 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1371 packageName, extras, null, null, updateUsers); 1372 if (update) { 1373 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1374 packageName, extras, null, null, updateUsers); 1375 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1376 null, null, packageName, null, updateUsers); 1377 1378 // treat asec-hosted packages like removable media on upgrade 1379 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1380 if (DEBUG_INSTALL) { 1381 Slog.i(TAG, "upgrading pkg " + res.pkg 1382 + " is ASEC-hosted -> AVAILABLE"); 1383 } 1384 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1385 ArrayList<String> pkgList = new ArrayList<String>(1); 1386 pkgList.add(packageName); 1387 sendResourcesChangedBroadcast(true, true, 1388 pkgList,uidArray, null); 1389 } 1390 } 1391 if (res.removedInfo.args != null) { 1392 // Remove the replaced package's older resources safely now 1393 deleteOld = true; 1394 } 1395 1396 // If this app is a browser and it's newly-installed for some 1397 // users, clear any default-browser state in those users 1398 if (firstUsers.length > 0) { 1399 // the app's nature doesn't depend on the user, so we can just 1400 // check its browser nature in any user and generalize. 1401 if (packageIsBrowser(packageName, firstUsers[0])) { 1402 synchronized (mPackages) { 1403 for (int userId : firstUsers) { 1404 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1405 } 1406 } 1407 } 1408 } 1409 // Log current value of "unknown sources" setting 1410 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1411 getUnknownSourcesSettings()); 1412 } 1413 // Force a gc to clear up things 1414 Runtime.getRuntime().gc(); 1415 // We delete after a gc for applications on sdcard. 1416 if (deleteOld) { 1417 synchronized (mInstallLock) { 1418 res.removedInfo.args.doPostDeleteLI(true); 1419 } 1420 } 1421 if (args.observer != null) { 1422 try { 1423 Bundle extras = extrasForInstallResult(res); 1424 args.observer.onPackageInstalled(res.name, res.returnCode, 1425 res.returnMsg, extras); 1426 } catch (RemoteException e) { 1427 Slog.i(TAG, "Observer no longer exists."); 1428 } 1429 } 1430 } else { 1431 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1432 } 1433 } break; 1434 case UPDATED_MEDIA_STATUS: { 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1436 boolean reportStatus = msg.arg1 == 1; 1437 boolean doGc = msg.arg2 == 1; 1438 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1439 if (doGc) { 1440 // Force a gc to clear up stale containers. 1441 Runtime.getRuntime().gc(); 1442 } 1443 if (msg.obj != null) { 1444 @SuppressWarnings("unchecked") 1445 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1446 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1447 // Unload containers 1448 unloadAllContainers(args); 1449 } 1450 if (reportStatus) { 1451 try { 1452 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1453 PackageHelper.getMountService().finishMediaUpdate(); 1454 } catch (RemoteException e) { 1455 Log.e(TAG, "MountService not running?"); 1456 } 1457 } 1458 } break; 1459 case WRITE_SETTINGS: { 1460 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1461 synchronized (mPackages) { 1462 removeMessages(WRITE_SETTINGS); 1463 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1464 mSettings.writeLPr(); 1465 mDirtyUsers.clear(); 1466 } 1467 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1468 } break; 1469 case WRITE_PACKAGE_RESTRICTIONS: { 1470 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1471 synchronized (mPackages) { 1472 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1473 for (int userId : mDirtyUsers) { 1474 mSettings.writePackageRestrictionsLPr(userId); 1475 } 1476 mDirtyUsers.clear(); 1477 } 1478 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1479 } break; 1480 case CHECK_PENDING_VERIFICATION: { 1481 final int verificationId = msg.arg1; 1482 final PackageVerificationState state = mPendingVerification.get(verificationId); 1483 1484 if ((state != null) && !state.timeoutExtended()) { 1485 final InstallArgs args = state.getInstallArgs(); 1486 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1487 1488 Slog.i(TAG, "Verification timed out for " + originUri); 1489 mPendingVerification.remove(verificationId); 1490 1491 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1492 1493 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1494 Slog.i(TAG, "Continuing with installation of " + originUri); 1495 state.setVerifierResponse(Binder.getCallingUid(), 1496 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1497 broadcastPackageVerified(verificationId, originUri, 1498 PackageManager.VERIFICATION_ALLOW, 1499 state.getInstallArgs().getUser()); 1500 try { 1501 ret = args.copyApk(mContainerService, true); 1502 } catch (RemoteException e) { 1503 Slog.e(TAG, "Could not contact the ContainerService"); 1504 } 1505 } else { 1506 broadcastPackageVerified(verificationId, originUri, 1507 PackageManager.VERIFICATION_REJECT, 1508 state.getInstallArgs().getUser()); 1509 } 1510 1511 processPendingInstall(args, ret); 1512 mHandler.sendEmptyMessage(MCS_UNBIND); 1513 } 1514 break; 1515 } 1516 case PACKAGE_VERIFIED: { 1517 final int verificationId = msg.arg1; 1518 1519 final PackageVerificationState state = mPendingVerification.get(verificationId); 1520 if (state == null) { 1521 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1522 break; 1523 } 1524 1525 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1526 1527 state.setVerifierResponse(response.callerUid, response.code); 1528 1529 if (state.isVerificationComplete()) { 1530 mPendingVerification.remove(verificationId); 1531 1532 final InstallArgs args = state.getInstallArgs(); 1533 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1534 1535 int ret; 1536 if (state.isInstallAllowed()) { 1537 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1538 broadcastPackageVerified(verificationId, originUri, 1539 response.code, state.getInstallArgs().getUser()); 1540 try { 1541 ret = args.copyApk(mContainerService, true); 1542 } catch (RemoteException e) { 1543 Slog.e(TAG, "Could not contact the ContainerService"); 1544 } 1545 } else { 1546 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1547 } 1548 1549 processPendingInstall(args, ret); 1550 1551 mHandler.sendEmptyMessage(MCS_UNBIND); 1552 } 1553 1554 break; 1555 } 1556 case START_INTENT_FILTER_VERIFICATIONS: { 1557 IFVerificationParams params = (IFVerificationParams) msg.obj; 1558 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1559 params.replacing, params.pkg); 1560 break; 1561 } 1562 case INTENT_FILTER_VERIFIED: { 1563 final int verificationId = msg.arg1; 1564 1565 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1566 verificationId); 1567 if (state == null) { 1568 Slog.w(TAG, "Invalid IntentFilter verification token " 1569 + verificationId + " received"); 1570 break; 1571 } 1572 1573 final int userId = state.getUserId(); 1574 1575 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1576 "Processing IntentFilter verification with token:" 1577 + verificationId + " and userId:" + userId); 1578 1579 final IntentFilterVerificationResponse response = 1580 (IntentFilterVerificationResponse) msg.obj; 1581 1582 state.setVerifierResponse(response.callerUid, response.code); 1583 1584 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1585 "IntentFilter verification with token:" + verificationId 1586 + " and userId:" + userId 1587 + " is settings verifier response with response code:" 1588 + response.code); 1589 1590 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1591 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1592 + response.getFailedDomainsString()); 1593 } 1594 1595 if (state.isVerificationComplete()) { 1596 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1597 } else { 1598 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1599 "IntentFilter verification with token:" + verificationId 1600 + " was not said to be complete"); 1601 } 1602 1603 break; 1604 } 1605 } 1606 } 1607 } 1608 1609 private StorageEventListener mStorageListener = new StorageEventListener() { 1610 @Override 1611 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1612 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1613 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1614 final String volumeUuid = vol.getFsUuid(); 1615 1616 // Clean up any users or apps that were removed or recreated 1617 // while this volume was missing 1618 reconcileUsers(volumeUuid); 1619 reconcileApps(volumeUuid); 1620 1621 // Clean up any install sessions that expired or were 1622 // cancelled while this volume was missing 1623 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1624 1625 loadPrivatePackages(vol); 1626 1627 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1628 unloadPrivatePackages(vol); 1629 } 1630 } 1631 1632 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1633 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1634 updateExternalMediaStatus(true, false); 1635 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1636 updateExternalMediaStatus(false, false); 1637 } 1638 } 1639 } 1640 1641 @Override 1642 public void onVolumeForgotten(String fsUuid) { 1643 // Remove any apps installed on the forgotten volume 1644 synchronized (mPackages) { 1645 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1646 for (PackageSetting ps : packages) { 1647 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1648 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1649 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1650 } 1651 1652 mSettings.writeLPr(); 1653 } 1654 } 1655 }; 1656 1657 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1658 if (userId >= UserHandle.USER_OWNER) { 1659 grantRequestedRuntimePermissionsForUser(pkg, userId); 1660 } else if (userId == UserHandle.USER_ALL) { 1661 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1662 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1663 } 1664 } 1665 1666 // We could have touched GID membership, so flush out packages.list 1667 synchronized (mPackages) { 1668 mSettings.writePackageListLPr(); 1669 } 1670 } 1671 1672 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1673 SettingBase sb = (SettingBase) pkg.mExtras; 1674 if (sb == null) { 1675 return; 1676 } 1677 1678 PermissionsState permissionsState = sb.getPermissionsState(); 1679 1680 for (String permission : pkg.requestedPermissions) { 1681 BasePermission bp = mSettings.mPermissions.get(permission); 1682 if (bp != null && bp.isRuntime()) { 1683 permissionsState.grantRuntimePermission(bp, userId); 1684 } 1685 } 1686 } 1687 1688 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1689 Bundle extras = null; 1690 switch (res.returnCode) { 1691 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1692 extras = new Bundle(); 1693 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1694 res.origPermission); 1695 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1696 res.origPackage); 1697 break; 1698 } 1699 case PackageManager.INSTALL_SUCCEEDED: { 1700 extras = new Bundle(); 1701 extras.putBoolean(Intent.EXTRA_REPLACING, 1702 res.removedInfo != null && res.removedInfo.removedPackage != null); 1703 break; 1704 } 1705 } 1706 return extras; 1707 } 1708 1709 void scheduleWriteSettingsLocked() { 1710 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1711 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1712 } 1713 } 1714 1715 void scheduleWritePackageRestrictionsLocked(int userId) { 1716 if (!sUserManager.exists(userId)) return; 1717 mDirtyUsers.add(userId); 1718 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1719 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1720 } 1721 } 1722 1723 public static PackageManagerService main(Context context, Installer installer, 1724 boolean factoryTest, boolean onlyCore) { 1725 PackageManagerService m = new PackageManagerService(context, installer, 1726 factoryTest, onlyCore); 1727 ServiceManager.addService("package", m); 1728 return m; 1729 } 1730 1731 static String[] splitString(String str, char sep) { 1732 int count = 1; 1733 int i = 0; 1734 while ((i=str.indexOf(sep, i)) >= 0) { 1735 count++; 1736 i++; 1737 } 1738 1739 String[] res = new String[count]; 1740 i=0; 1741 count = 0; 1742 int lastI=0; 1743 while ((i=str.indexOf(sep, i)) >= 0) { 1744 res[count] = str.substring(lastI, i); 1745 count++; 1746 i++; 1747 lastI = i; 1748 } 1749 res[count] = str.substring(lastI, str.length()); 1750 return res; 1751 } 1752 1753 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1754 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1755 Context.DISPLAY_SERVICE); 1756 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1757 } 1758 1759 public PackageManagerService(Context context, Installer installer, 1760 boolean factoryTest, boolean onlyCore) { 1761 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1762 SystemClock.uptimeMillis()); 1763 1764 if (mSdkVersion <= 0) { 1765 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1766 } 1767 1768 mContext = context; 1769 mFactoryTest = factoryTest; 1770 mOnlyCore = onlyCore; 1771 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1772 mMetrics = new DisplayMetrics(); 1773 mSettings = new Settings(mPackages); 1774 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1775 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1776 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1777 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1778 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1779 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1780 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1781 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1782 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1783 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1784 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1785 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1786 1787 // TODO: add a property to control this? 1788 long dexOptLRUThresholdInMinutes; 1789 if (mLazyDexOpt) { 1790 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1791 } else { 1792 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1793 } 1794 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1795 1796 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1797 if (separateProcesses != null && separateProcesses.length() > 0) { 1798 if ("*".equals(separateProcesses)) { 1799 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1800 mSeparateProcesses = null; 1801 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1802 } else { 1803 mDefParseFlags = 0; 1804 mSeparateProcesses = separateProcesses.split(","); 1805 Slog.w(TAG, "Running with debug.separate_processes: " 1806 + separateProcesses); 1807 } 1808 } else { 1809 mDefParseFlags = 0; 1810 mSeparateProcesses = null; 1811 } 1812 1813 mInstaller = installer; 1814 mPackageDexOptimizer = new PackageDexOptimizer(this); 1815 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1816 1817 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1818 FgThread.get().getLooper()); 1819 1820 getDefaultDisplayMetrics(context, mMetrics); 1821 1822 SystemConfig systemConfig = SystemConfig.getInstance(); 1823 mGlobalGids = systemConfig.getGlobalGids(); 1824 mSystemPermissions = systemConfig.getSystemPermissions(); 1825 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1826 1827 synchronized (mInstallLock) { 1828 // writer 1829 synchronized (mPackages) { 1830 mHandlerThread = new ServiceThread(TAG, 1831 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1832 mHandlerThread.start(); 1833 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1834 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1835 1836 File dataDir = Environment.getDataDirectory(); 1837 mAppDataDir = new File(dataDir, "data"); 1838 mAppInstallDir = new File(dataDir, "app"); 1839 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1840 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1841 mUserAppDataDir = new File(dataDir, "user"); 1842 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1843 1844 sUserManager = new UserManagerService(context, this, 1845 mInstallLock, mPackages); 1846 1847 // Propagate permission configuration in to package manager. 1848 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1849 = systemConfig.getPermissions(); 1850 for (int i=0; i<permConfig.size(); i++) { 1851 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1852 BasePermission bp = mSettings.mPermissions.get(perm.name); 1853 if (bp == null) { 1854 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1855 mSettings.mPermissions.put(perm.name, bp); 1856 } 1857 if (perm.gids != null) { 1858 bp.setGids(perm.gids, perm.perUser); 1859 } 1860 } 1861 1862 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1863 for (int i=0; i<libConfig.size(); i++) { 1864 mSharedLibraries.put(libConfig.keyAt(i), 1865 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1866 } 1867 1868 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1869 1870 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1871 mSdkVersion, mOnlyCore); 1872 1873 String customResolverActivity = Resources.getSystem().getString( 1874 R.string.config_customResolverActivity); 1875 if (TextUtils.isEmpty(customResolverActivity)) { 1876 customResolverActivity = null; 1877 } else { 1878 mCustomResolverComponentName = ComponentName.unflattenFromString( 1879 customResolverActivity); 1880 } 1881 1882 long startTime = SystemClock.uptimeMillis(); 1883 1884 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1885 startTime); 1886 1887 // Set flag to monitor and not change apk file paths when 1888 // scanning install directories. 1889 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1890 1891 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1892 1893 /** 1894 * Add everything in the in the boot class path to the 1895 * list of process files because dexopt will have been run 1896 * if necessary during zygote startup. 1897 */ 1898 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1899 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1900 1901 if (bootClassPath != null) { 1902 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1903 for (String element : bootClassPathElements) { 1904 alreadyDexOpted.add(element); 1905 } 1906 } else { 1907 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1908 } 1909 1910 if (systemServerClassPath != null) { 1911 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1912 for (String element : systemServerClassPathElements) { 1913 alreadyDexOpted.add(element); 1914 } 1915 } else { 1916 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1917 } 1918 1919 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1920 final String[] dexCodeInstructionSets = 1921 getDexCodeInstructionSets( 1922 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1923 1924 /** 1925 * Ensure all external libraries have had dexopt run on them. 1926 */ 1927 if (mSharedLibraries.size() > 0) { 1928 // NOTE: For now, we're compiling these system "shared libraries" 1929 // (and framework jars) into all available architectures. It's possible 1930 // to compile them only when we come across an app that uses them (there's 1931 // already logic for that in scanPackageLI) but that adds some complexity. 1932 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1933 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1934 final String lib = libEntry.path; 1935 if (lib == null) { 1936 continue; 1937 } 1938 1939 try { 1940 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1941 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1942 alreadyDexOpted.add(lib); 1943 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1944 } 1945 } catch (FileNotFoundException e) { 1946 Slog.w(TAG, "Library not found: " + lib); 1947 } catch (IOException e) { 1948 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1949 + e.getMessage()); 1950 } 1951 } 1952 } 1953 } 1954 1955 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1956 1957 // Gross hack for now: we know this file doesn't contain any 1958 // code, so don't dexopt it to avoid the resulting log spew. 1959 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1960 1961 // Gross hack for now: we know this file is only part of 1962 // the boot class path for art, so don't dexopt it to 1963 // avoid the resulting log spew. 1964 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1965 1966 /** 1967 * There are a number of commands implemented in Java, which 1968 * we currently need to do the dexopt on so that they can be 1969 * run from a non-root shell. 1970 */ 1971 String[] frameworkFiles = frameworkDir.list(); 1972 if (frameworkFiles != null) { 1973 // TODO: We could compile these only for the most preferred ABI. We should 1974 // first double check that the dex files for these commands are not referenced 1975 // by other system apps. 1976 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1977 for (int i=0; i<frameworkFiles.length; i++) { 1978 File libPath = new File(frameworkDir, frameworkFiles[i]); 1979 String path = libPath.getPath(); 1980 // Skip the file if we already did it. 1981 if (alreadyDexOpted.contains(path)) { 1982 continue; 1983 } 1984 // Skip the file if it is not a type we want to dexopt. 1985 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1986 continue; 1987 } 1988 try { 1989 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1990 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1991 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1992 } 1993 } catch (FileNotFoundException e) { 1994 Slog.w(TAG, "Jar not found: " + path); 1995 } catch (IOException e) { 1996 Slog.w(TAG, "Exception reading jar: " + path, e); 1997 } 1998 } 1999 } 2000 } 2001 2002 // Collect vendor overlay packages. 2003 // (Do this before scanning any apps.) 2004 // For security and version matching reason, only consider 2005 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2006 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2007 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2008 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2009 2010 // Find base frameworks (resource packages without code). 2011 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2012 | PackageParser.PARSE_IS_SYSTEM_DIR 2013 | PackageParser.PARSE_IS_PRIVILEGED, 2014 scanFlags | SCAN_NO_DEX, 0); 2015 2016 // Collected privileged system packages. 2017 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2018 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2019 | PackageParser.PARSE_IS_SYSTEM_DIR 2020 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2021 2022 // Collect ordinary system packages. 2023 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2024 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2025 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2026 2027 // Collect all vendor packages. 2028 File vendorAppDir = new File("/vendor/app"); 2029 try { 2030 vendorAppDir = vendorAppDir.getCanonicalFile(); 2031 } catch (IOException e) { 2032 // failed to look up canonical path, continue with original one 2033 } 2034 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2035 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2036 2037 // Collect all OEM packages. 2038 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2039 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2040 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2041 2042 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2043 mInstaller.moveFiles(); 2044 2045 // Prune any system packages that no longer exist. 2046 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2047 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2048 if (!mOnlyCore) { 2049 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2050 while (psit.hasNext()) { 2051 PackageSetting ps = psit.next(); 2052 2053 /* 2054 * If this is not a system app, it can't be a 2055 * disable system app. 2056 */ 2057 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2058 continue; 2059 } 2060 2061 /* 2062 * If the package is scanned, it's not erased. 2063 */ 2064 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2065 if (scannedPkg != null) { 2066 /* 2067 * If the system app is both scanned and in the 2068 * disabled packages list, then it must have been 2069 * added via OTA. Remove it from the currently 2070 * scanned package so the previously user-installed 2071 * application can be scanned. 2072 */ 2073 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2074 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2075 + ps.name + "; removing system app. Last known codePath=" 2076 + ps.codePathString + ", installStatus=" + ps.installStatus 2077 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2078 + scannedPkg.mVersionCode); 2079 removePackageLI(ps, true); 2080 expectingBetter.put(ps.name, ps.codePath); 2081 } 2082 2083 continue; 2084 } 2085 2086 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2087 psit.remove(); 2088 logCriticalInfo(Log.WARN, "System package " + ps.name 2089 + " no longer exists; wiping its data"); 2090 removeDataDirsLI(null, ps.name); 2091 } else { 2092 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2093 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2094 possiblyDeletedUpdatedSystemApps.add(ps.name); 2095 } 2096 } 2097 } 2098 } 2099 2100 //look for any incomplete package installations 2101 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2102 //clean up list 2103 for(int i = 0; i < deletePkgsList.size(); i++) { 2104 //clean up here 2105 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2106 } 2107 //delete tmp files 2108 deleteTempPackageFiles(); 2109 2110 // Remove any shared userIDs that have no associated packages 2111 mSettings.pruneSharedUsersLPw(); 2112 2113 if (!mOnlyCore) { 2114 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2115 SystemClock.uptimeMillis()); 2116 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2117 2118 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2119 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2120 2121 /** 2122 * Remove disable package settings for any updated system 2123 * apps that were removed via an OTA. If they're not a 2124 * previously-updated app, remove them completely. 2125 * Otherwise, just revoke their system-level permissions. 2126 */ 2127 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2128 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2129 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2130 2131 String msg; 2132 if (deletedPkg == null) { 2133 msg = "Updated system package " + deletedAppName 2134 + " no longer exists; wiping its data"; 2135 removeDataDirsLI(null, deletedAppName); 2136 } else { 2137 msg = "Updated system app + " + deletedAppName 2138 + " no longer present; removing system privileges for " 2139 + deletedAppName; 2140 2141 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2142 2143 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2144 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2145 } 2146 logCriticalInfo(Log.WARN, msg); 2147 } 2148 2149 /** 2150 * Make sure all system apps that we expected to appear on 2151 * the userdata partition actually showed up. If they never 2152 * appeared, crawl back and revive the system version. 2153 */ 2154 for (int i = 0; i < expectingBetter.size(); i++) { 2155 final String packageName = expectingBetter.keyAt(i); 2156 if (!mPackages.containsKey(packageName)) { 2157 final File scanFile = expectingBetter.valueAt(i); 2158 2159 logCriticalInfo(Log.WARN, "Expected better " + packageName 2160 + " but never showed up; reverting to system"); 2161 2162 final int reparseFlags; 2163 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2164 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2165 | PackageParser.PARSE_IS_SYSTEM_DIR 2166 | PackageParser.PARSE_IS_PRIVILEGED; 2167 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2168 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2169 | PackageParser.PARSE_IS_SYSTEM_DIR; 2170 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2171 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2172 | PackageParser.PARSE_IS_SYSTEM_DIR; 2173 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2174 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2175 | PackageParser.PARSE_IS_SYSTEM_DIR; 2176 } else { 2177 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2178 continue; 2179 } 2180 2181 mSettings.enableSystemPackageLPw(packageName); 2182 2183 try { 2184 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2185 } catch (PackageManagerException e) { 2186 Slog.e(TAG, "Failed to parse original system package: " 2187 + e.getMessage()); 2188 } 2189 } 2190 } 2191 } 2192 2193 // Now that we know all of the shared libraries, update all clients to have 2194 // the correct library paths. 2195 updateAllSharedLibrariesLPw(); 2196 2197 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2198 // NOTE: We ignore potential failures here during a system scan (like 2199 // the rest of the commands above) because there's precious little we 2200 // can do about it. A settings error is reported, though. 2201 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2202 false /* force dexopt */, false /* defer dexopt */); 2203 } 2204 2205 // Now that we know all the packages we are keeping, 2206 // read and update their last usage times. 2207 mPackageUsage.readLP(); 2208 2209 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2210 SystemClock.uptimeMillis()); 2211 Slog.i(TAG, "Time to scan packages: " 2212 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2213 + " seconds"); 2214 2215 // If the platform SDK has changed since the last time we booted, 2216 // we need to re-grant app permission to catch any new ones that 2217 // appear. This is really a hack, and means that apps can in some 2218 // cases get permissions that the user didn't initially explicitly 2219 // allow... it would be nice to have some better way to handle 2220 // this situation. 2221 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2222 != mSdkVersion; 2223 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2224 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2225 + "; regranting permissions for internal storage"); 2226 mSettings.mInternalSdkPlatform = mSdkVersion; 2227 2228 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2229 | (regrantPermissions 2230 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2231 : 0)); 2232 2233 // If this is the first boot, and it is a normal boot, then 2234 // we need to initialize the default preferred apps. 2235 if (!mRestoredSettings && !onlyCore) { 2236 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2237 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2238 } 2239 2240 // If this is first boot after an OTA, and a normal boot, then 2241 // we need to clear code cache directories. 2242 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2243 if (mIsUpgrade && !onlyCore) { 2244 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2245 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2246 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2247 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2248 } 2249 mSettings.mFingerprint = Build.FINGERPRINT; 2250 } 2251 2252 primeDomainVerificationsLPw(); 2253 checkDefaultBrowser(); 2254 2255 // All the changes are done during package scanning. 2256 mSettings.updateInternalDatabaseVersion(); 2257 2258 // can downgrade to reader 2259 mSettings.writeLPr(); 2260 2261 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2262 SystemClock.uptimeMillis()); 2263 2264 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2265 2266 mInstallerService = new PackageInstallerService(context, this); 2267 2268 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2269 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2270 mIntentFilterVerifierComponent); 2271 2272 } // synchronized (mPackages) 2273 } // synchronized (mInstallLock) 2274 2275 // Now after opening every single application zip, make sure they 2276 // are all flushed. Not really needed, but keeps things nice and 2277 // tidy. 2278 Runtime.getRuntime().gc(); 2279 2280 // Expose private service for system components to use. 2281 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2282 } 2283 2284 @Override 2285 public boolean isFirstBoot() { 2286 return !mRestoredSettings; 2287 } 2288 2289 @Override 2290 public boolean isOnlyCoreApps() { 2291 return mOnlyCore; 2292 } 2293 2294 @Override 2295 public boolean isUpgrade() { 2296 return mIsUpgrade; 2297 } 2298 2299 private String getRequiredVerifierLPr() { 2300 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2301 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2302 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2303 2304 String requiredVerifier = null; 2305 2306 final int N = receivers.size(); 2307 for (int i = 0; i < N; i++) { 2308 final ResolveInfo info = receivers.get(i); 2309 2310 if (info.activityInfo == null) { 2311 continue; 2312 } 2313 2314 final String packageName = info.activityInfo.packageName; 2315 2316 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2317 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2318 continue; 2319 } 2320 2321 if (requiredVerifier != null) { 2322 throw new RuntimeException("There can be only one required verifier"); 2323 } 2324 2325 requiredVerifier = packageName; 2326 } 2327 2328 return requiredVerifier; 2329 } 2330 2331 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2332 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2333 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2334 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2335 2336 ComponentName verifierComponentName = null; 2337 2338 int priority = -1000; 2339 final int N = receivers.size(); 2340 for (int i = 0; i < N; i++) { 2341 final ResolveInfo info = receivers.get(i); 2342 2343 if (info.activityInfo == null) { 2344 continue; 2345 } 2346 2347 final String packageName = info.activityInfo.packageName; 2348 2349 final PackageSetting ps = mSettings.mPackages.get(packageName); 2350 if (ps == null) { 2351 continue; 2352 } 2353 2354 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2355 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2356 continue; 2357 } 2358 2359 // Select the IntentFilterVerifier with the highest priority 2360 if (priority < info.priority) { 2361 priority = info.priority; 2362 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2363 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2364 + verifierComponentName + " with priority: " + info.priority); 2365 } 2366 } 2367 2368 return verifierComponentName; 2369 } 2370 2371 private void primeDomainVerificationsLPw() { 2372 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2373 boolean updated = false; 2374 ArraySet<String> allHostsSet = new ArraySet<>(); 2375 for (PackageParser.Package pkg : mPackages.values()) { 2376 final String packageName = pkg.packageName; 2377 if (!hasDomainURLs(pkg)) { 2378 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2379 "package with no domain URLs: " + packageName); 2380 continue; 2381 } 2382 if (!pkg.isSystemApp()) { 2383 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2384 "No priming domain verifications for a non system package : " + 2385 packageName); 2386 continue; 2387 } 2388 for (PackageParser.Activity a : pkg.activities) { 2389 for (ActivityIntentInfo filter : a.intents) { 2390 if (hasValidDomains(filter)) { 2391 allHostsSet.addAll(filter.getHostsList()); 2392 } 2393 } 2394 } 2395 if (allHostsSet.size() == 0) { 2396 allHostsSet.add("*"); 2397 } 2398 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2399 IntentFilterVerificationInfo ivi = 2400 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2401 if (ivi != null) { 2402 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2403 "Priming domain verifications for package: " + packageName + 2404 " with hosts:" + ivi.getDomainsString()); 2405 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2406 updated = true; 2407 } 2408 else { 2409 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2410 "No priming domain verifications for package: " + packageName); 2411 } 2412 allHostsSet.clear(); 2413 } 2414 if (updated) { 2415 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2416 "Will need to write primed domain verifications"); 2417 } 2418 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2419 } 2420 2421 private void applyFactoryDefaultBrowserLPw(int userId) { 2422 // The default browser app's package name is stored in a string resource, 2423 // with a product-specific overlay used for vendor customization. 2424 String browserPkg = mContext.getResources().getString( 2425 com.android.internal.R.string.default_browser); 2426 if (browserPkg != null) { 2427 // non-empty string => required to be a known package 2428 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2429 if (ps == null) { 2430 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2431 browserPkg = null; 2432 } else { 2433 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2434 } 2435 } 2436 2437 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2438 // default. If there's more than one, just leave everything alone. 2439 if (browserPkg == null) { 2440 calculateDefaultBrowserLPw(userId); 2441 } 2442 } 2443 2444 private void calculateDefaultBrowserLPw(int userId) { 2445 List<String> allBrowsers = resolveAllBrowserApps(userId); 2446 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2447 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2448 } 2449 2450 private List<String> resolveAllBrowserApps(int userId) { 2451 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2452 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2453 PackageManager.MATCH_ALL, userId); 2454 2455 final int count = list.size(); 2456 List<String> result = new ArrayList<String>(count); 2457 for (int i=0; i<count; i++) { 2458 ResolveInfo info = list.get(i); 2459 if (info.activityInfo == null 2460 || !info.handleAllWebDataURI 2461 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2462 || result.contains(info.activityInfo.packageName)) { 2463 continue; 2464 } 2465 result.add(info.activityInfo.packageName); 2466 } 2467 2468 return result; 2469 } 2470 2471 private boolean packageIsBrowser(String packageName, int userId) { 2472 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2473 PackageManager.MATCH_ALL, userId); 2474 final int N = list.size(); 2475 for (int i = 0; i < N; i++) { 2476 ResolveInfo info = list.get(i); 2477 if (packageName.equals(info.activityInfo.packageName)) { 2478 return true; 2479 } 2480 } 2481 return false; 2482 } 2483 2484 private void checkDefaultBrowser() { 2485 final int myUserId = UserHandle.myUserId(); 2486 final String packageName = getDefaultBrowserPackageName(myUserId); 2487 if (packageName != null) { 2488 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2489 if (info == null) { 2490 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2491 synchronized (mPackages) { 2492 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2493 } 2494 } 2495 } 2496 } 2497 2498 @Override 2499 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2500 throws RemoteException { 2501 try { 2502 return super.onTransact(code, data, reply, flags); 2503 } catch (RuntimeException e) { 2504 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2505 Slog.wtf(TAG, "Package Manager Crash", e); 2506 } 2507 throw e; 2508 } 2509 } 2510 2511 void cleanupInstallFailedPackage(PackageSetting ps) { 2512 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2513 2514 removeDataDirsLI(ps.volumeUuid, ps.name); 2515 if (ps.codePath != null) { 2516 if (ps.codePath.isDirectory()) { 2517 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2518 } else { 2519 ps.codePath.delete(); 2520 } 2521 } 2522 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2523 if (ps.resourcePath.isDirectory()) { 2524 FileUtils.deleteContents(ps.resourcePath); 2525 } 2526 ps.resourcePath.delete(); 2527 } 2528 mSettings.removePackageLPw(ps.name); 2529 } 2530 2531 static int[] appendInts(int[] cur, int[] add) { 2532 if (add == null) return cur; 2533 if (cur == null) return add; 2534 final int N = add.length; 2535 for (int i=0; i<N; i++) { 2536 cur = appendInt(cur, add[i]); 2537 } 2538 return cur; 2539 } 2540 2541 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2542 if (!sUserManager.exists(userId)) return null; 2543 final PackageSetting ps = (PackageSetting) p.mExtras; 2544 if (ps == null) { 2545 return null; 2546 } 2547 2548 final PermissionsState permissionsState = ps.getPermissionsState(); 2549 2550 final int[] gids = permissionsState.computeGids(userId); 2551 final Set<String> permissions = permissionsState.getPermissions(userId); 2552 final PackageUserState state = ps.readUserState(userId); 2553 2554 return PackageParser.generatePackageInfo(p, gids, flags, 2555 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2556 } 2557 2558 @Override 2559 public boolean isPackageFrozen(String packageName) { 2560 synchronized (mPackages) { 2561 final PackageSetting ps = mSettings.mPackages.get(packageName); 2562 if (ps != null) { 2563 return ps.frozen; 2564 } 2565 } 2566 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2567 return true; 2568 } 2569 2570 @Override 2571 public boolean isPackageAvailable(String packageName, int userId) { 2572 if (!sUserManager.exists(userId)) return false; 2573 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2574 synchronized (mPackages) { 2575 PackageParser.Package p = mPackages.get(packageName); 2576 if (p != null) { 2577 final PackageSetting ps = (PackageSetting) p.mExtras; 2578 if (ps != null) { 2579 final PackageUserState state = ps.readUserState(userId); 2580 if (state != null) { 2581 return PackageParser.isAvailable(state); 2582 } 2583 } 2584 } 2585 } 2586 return false; 2587 } 2588 2589 @Override 2590 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2591 if (!sUserManager.exists(userId)) return null; 2592 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2593 // reader 2594 synchronized (mPackages) { 2595 PackageParser.Package p = mPackages.get(packageName); 2596 if (DEBUG_PACKAGE_INFO) 2597 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2598 if (p != null) { 2599 return generatePackageInfo(p, flags, userId); 2600 } 2601 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2602 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2603 } 2604 } 2605 return null; 2606 } 2607 2608 @Override 2609 public String[] currentToCanonicalPackageNames(String[] names) { 2610 String[] out = new String[names.length]; 2611 // reader 2612 synchronized (mPackages) { 2613 for (int i=names.length-1; i>=0; i--) { 2614 PackageSetting ps = mSettings.mPackages.get(names[i]); 2615 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2616 } 2617 } 2618 return out; 2619 } 2620 2621 @Override 2622 public String[] canonicalToCurrentPackageNames(String[] names) { 2623 String[] out = new String[names.length]; 2624 // reader 2625 synchronized (mPackages) { 2626 for (int i=names.length-1; i>=0; i--) { 2627 String cur = mSettings.mRenamedPackages.get(names[i]); 2628 out[i] = cur != null ? cur : names[i]; 2629 } 2630 } 2631 return out; 2632 } 2633 2634 @Override 2635 public int getPackageUid(String packageName, int userId) { 2636 if (!sUserManager.exists(userId)) return -1; 2637 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2638 2639 // reader 2640 synchronized (mPackages) { 2641 PackageParser.Package p = mPackages.get(packageName); 2642 if(p != null) { 2643 return UserHandle.getUid(userId, p.applicationInfo.uid); 2644 } 2645 PackageSetting ps = mSettings.mPackages.get(packageName); 2646 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2647 return -1; 2648 } 2649 p = ps.pkg; 2650 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2651 } 2652 } 2653 2654 @Override 2655 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2656 if (!sUserManager.exists(userId)) { 2657 return null; 2658 } 2659 2660 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2661 "getPackageGids"); 2662 2663 // reader 2664 synchronized (mPackages) { 2665 PackageParser.Package p = mPackages.get(packageName); 2666 if (DEBUG_PACKAGE_INFO) { 2667 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2668 } 2669 if (p != null) { 2670 PackageSetting ps = (PackageSetting) p.mExtras; 2671 return ps.getPermissionsState().computeGids(userId); 2672 } 2673 } 2674 2675 return null; 2676 } 2677 2678 @Override 2679 public int getMountExternalMode(int uid) { 2680 if (Process.isIsolated(uid)) { 2681 return Zygote.MOUNT_EXTERNAL_NONE; 2682 } else { 2683 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2684 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2685 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2686 return Zygote.MOUNT_EXTERNAL_WRITE; 2687 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2688 return Zygote.MOUNT_EXTERNAL_READ; 2689 } else { 2690 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2691 } 2692 } 2693 } 2694 2695 static PermissionInfo generatePermissionInfo( 2696 BasePermission bp, int flags) { 2697 if (bp.perm != null) { 2698 return PackageParser.generatePermissionInfo(bp.perm, flags); 2699 } 2700 PermissionInfo pi = new PermissionInfo(); 2701 pi.name = bp.name; 2702 pi.packageName = bp.sourcePackage; 2703 pi.nonLocalizedLabel = bp.name; 2704 pi.protectionLevel = bp.protectionLevel; 2705 return pi; 2706 } 2707 2708 @Override 2709 public PermissionInfo getPermissionInfo(String name, int flags) { 2710 // reader 2711 synchronized (mPackages) { 2712 final BasePermission p = mSettings.mPermissions.get(name); 2713 if (p != null) { 2714 return generatePermissionInfo(p, flags); 2715 } 2716 return null; 2717 } 2718 } 2719 2720 @Override 2721 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2722 // reader 2723 synchronized (mPackages) { 2724 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2725 for (BasePermission p : mSettings.mPermissions.values()) { 2726 if (group == null) { 2727 if (p.perm == null || p.perm.info.group == null) { 2728 out.add(generatePermissionInfo(p, flags)); 2729 } 2730 } else { 2731 if (p.perm != null && group.equals(p.perm.info.group)) { 2732 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2733 } 2734 } 2735 } 2736 2737 if (out.size() > 0) { 2738 return out; 2739 } 2740 return mPermissionGroups.containsKey(group) ? out : null; 2741 } 2742 } 2743 2744 @Override 2745 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2746 // reader 2747 synchronized (mPackages) { 2748 return PackageParser.generatePermissionGroupInfo( 2749 mPermissionGroups.get(name), flags); 2750 } 2751 } 2752 2753 @Override 2754 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2755 // reader 2756 synchronized (mPackages) { 2757 final int N = mPermissionGroups.size(); 2758 ArrayList<PermissionGroupInfo> out 2759 = new ArrayList<PermissionGroupInfo>(N); 2760 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2761 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2762 } 2763 return out; 2764 } 2765 } 2766 2767 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2768 int userId) { 2769 if (!sUserManager.exists(userId)) return null; 2770 PackageSetting ps = mSettings.mPackages.get(packageName); 2771 if (ps != null) { 2772 if (ps.pkg == null) { 2773 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2774 flags, userId); 2775 if (pInfo != null) { 2776 return pInfo.applicationInfo; 2777 } 2778 return null; 2779 } 2780 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2781 ps.readUserState(userId), userId); 2782 } 2783 return null; 2784 } 2785 2786 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2787 int userId) { 2788 if (!sUserManager.exists(userId)) return null; 2789 PackageSetting ps = mSettings.mPackages.get(packageName); 2790 if (ps != null) { 2791 PackageParser.Package pkg = ps.pkg; 2792 if (pkg == null) { 2793 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2794 return null; 2795 } 2796 // Only data remains, so we aren't worried about code paths 2797 pkg = new PackageParser.Package(packageName); 2798 pkg.applicationInfo.packageName = packageName; 2799 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2800 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2801 pkg.applicationInfo.dataDir = Environment 2802 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2803 .getAbsolutePath(); 2804 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2805 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2806 } 2807 return generatePackageInfo(pkg, flags, userId); 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2814 if (!sUserManager.exists(userId)) return null; 2815 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2816 // writer 2817 synchronized (mPackages) { 2818 PackageParser.Package p = mPackages.get(packageName); 2819 if (DEBUG_PACKAGE_INFO) Log.v( 2820 TAG, "getApplicationInfo " + packageName 2821 + ": " + p); 2822 if (p != null) { 2823 PackageSetting ps = mSettings.mPackages.get(packageName); 2824 if (ps == null) return null; 2825 // Note: isEnabledLP() does not apply here - always return info 2826 return PackageParser.generateApplicationInfo( 2827 p, flags, ps.readUserState(userId), userId); 2828 } 2829 if ("android".equals(packageName)||"system".equals(packageName)) { 2830 return mAndroidApplication; 2831 } 2832 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2833 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2834 } 2835 } 2836 return null; 2837 } 2838 2839 @Override 2840 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2841 final IPackageDataObserver observer) { 2842 mContext.enforceCallingOrSelfPermission( 2843 android.Manifest.permission.CLEAR_APP_CACHE, null); 2844 // Queue up an async operation since clearing cache may take a little while. 2845 mHandler.post(new Runnable() { 2846 public void run() { 2847 mHandler.removeCallbacks(this); 2848 int retCode = -1; 2849 synchronized (mInstallLock) { 2850 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2851 if (retCode < 0) { 2852 Slog.w(TAG, "Couldn't clear application caches"); 2853 } 2854 } 2855 if (observer != null) { 2856 try { 2857 observer.onRemoveCompleted(null, (retCode >= 0)); 2858 } catch (RemoteException e) { 2859 Slog.w(TAG, "RemoveException when invoking call back"); 2860 } 2861 } 2862 } 2863 }); 2864 } 2865 2866 @Override 2867 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2868 final IntentSender pi) { 2869 mContext.enforceCallingOrSelfPermission( 2870 android.Manifest.permission.CLEAR_APP_CACHE, null); 2871 // Queue up an async operation since clearing cache may take a little while. 2872 mHandler.post(new Runnable() { 2873 public void run() { 2874 mHandler.removeCallbacks(this); 2875 int retCode = -1; 2876 synchronized (mInstallLock) { 2877 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2878 if (retCode < 0) { 2879 Slog.w(TAG, "Couldn't clear application caches"); 2880 } 2881 } 2882 if(pi != null) { 2883 try { 2884 // Callback via pending intent 2885 int code = (retCode >= 0) ? 1 : 0; 2886 pi.sendIntent(null, code, null, 2887 null, null); 2888 } catch (SendIntentException e1) { 2889 Slog.i(TAG, "Failed to send pending intent"); 2890 } 2891 } 2892 } 2893 }); 2894 } 2895 2896 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2897 synchronized (mInstallLock) { 2898 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2899 throw new IOException("Failed to free enough space"); 2900 } 2901 } 2902 } 2903 2904 @Override 2905 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2906 if (!sUserManager.exists(userId)) return null; 2907 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2908 synchronized (mPackages) { 2909 PackageParser.Activity a = mActivities.mActivities.get(component); 2910 2911 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2912 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2913 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2914 if (ps == null) return null; 2915 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2916 userId); 2917 } 2918 if (mResolveComponentName.equals(component)) { 2919 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2920 new PackageUserState(), userId); 2921 } 2922 } 2923 return null; 2924 } 2925 2926 @Override 2927 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2928 String resolvedType) { 2929 synchronized (mPackages) { 2930 PackageParser.Activity a = mActivities.mActivities.get(component); 2931 if (a == null) { 2932 return false; 2933 } 2934 for (int i=0; i<a.intents.size(); i++) { 2935 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2936 intent.getData(), intent.getCategories(), TAG) >= 0) { 2937 return true; 2938 } 2939 } 2940 return false; 2941 } 2942 } 2943 2944 @Override 2945 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2946 if (!sUserManager.exists(userId)) return null; 2947 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2948 synchronized (mPackages) { 2949 PackageParser.Activity a = mReceivers.mActivities.get(component); 2950 if (DEBUG_PACKAGE_INFO) Log.v( 2951 TAG, "getReceiverInfo " + component + ": " + a); 2952 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2953 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2954 if (ps == null) return null; 2955 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2956 userId); 2957 } 2958 } 2959 return null; 2960 } 2961 2962 @Override 2963 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2964 if (!sUserManager.exists(userId)) return null; 2965 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2966 synchronized (mPackages) { 2967 PackageParser.Service s = mServices.mServices.get(component); 2968 if (DEBUG_PACKAGE_INFO) Log.v( 2969 TAG, "getServiceInfo " + component + ": " + s); 2970 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2971 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2972 if (ps == null) return null; 2973 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2974 userId); 2975 } 2976 } 2977 return null; 2978 } 2979 2980 @Override 2981 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2982 if (!sUserManager.exists(userId)) return null; 2983 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2984 synchronized (mPackages) { 2985 PackageParser.Provider p = mProviders.mProviders.get(component); 2986 if (DEBUG_PACKAGE_INFO) Log.v( 2987 TAG, "getProviderInfo " + component + ": " + p); 2988 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2989 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2990 if (ps == null) return null; 2991 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2992 userId); 2993 } 2994 } 2995 return null; 2996 } 2997 2998 @Override 2999 public String[] getSystemSharedLibraryNames() { 3000 Set<String> libSet; 3001 synchronized (mPackages) { 3002 libSet = mSharedLibraries.keySet(); 3003 int size = libSet.size(); 3004 if (size > 0) { 3005 String[] libs = new String[size]; 3006 libSet.toArray(libs); 3007 return libs; 3008 } 3009 } 3010 return null; 3011 } 3012 3013 /** 3014 * @hide 3015 */ 3016 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3017 synchronized (mPackages) { 3018 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3019 if (lib != null && lib.apk != null) { 3020 return mPackages.get(lib.apk); 3021 } 3022 } 3023 return null; 3024 } 3025 3026 @Override 3027 public FeatureInfo[] getSystemAvailableFeatures() { 3028 Collection<FeatureInfo> featSet; 3029 synchronized (mPackages) { 3030 featSet = mAvailableFeatures.values(); 3031 int size = featSet.size(); 3032 if (size > 0) { 3033 FeatureInfo[] features = new FeatureInfo[size+1]; 3034 featSet.toArray(features); 3035 FeatureInfo fi = new FeatureInfo(); 3036 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3037 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3038 features[size] = fi; 3039 return features; 3040 } 3041 } 3042 return null; 3043 } 3044 3045 @Override 3046 public boolean hasSystemFeature(String name) { 3047 synchronized (mPackages) { 3048 return mAvailableFeatures.containsKey(name); 3049 } 3050 } 3051 3052 private void checkValidCaller(int uid, int userId) { 3053 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3054 return; 3055 3056 throw new SecurityException("Caller uid=" + uid 3057 + " is not privileged to communicate with user=" + userId); 3058 } 3059 3060 @Override 3061 public int checkPermission(String permName, String pkgName, int userId) { 3062 if (!sUserManager.exists(userId)) { 3063 return PackageManager.PERMISSION_DENIED; 3064 } 3065 3066 synchronized (mPackages) { 3067 final PackageParser.Package p = mPackages.get(pkgName); 3068 if (p != null && p.mExtras != null) { 3069 final PackageSetting ps = (PackageSetting) p.mExtras; 3070 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3071 return PackageManager.PERMISSION_GRANTED; 3072 } 3073 } 3074 } 3075 3076 return PackageManager.PERMISSION_DENIED; 3077 } 3078 3079 @Override 3080 public int checkUidPermission(String permName, int uid) { 3081 final int userId = UserHandle.getUserId(uid); 3082 3083 if (!sUserManager.exists(userId)) { 3084 return PackageManager.PERMISSION_DENIED; 3085 } 3086 3087 synchronized (mPackages) { 3088 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3089 if (obj != null) { 3090 final SettingBase ps = (SettingBase) obj; 3091 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3092 return PackageManager.PERMISSION_GRANTED; 3093 } 3094 } else { 3095 ArraySet<String> perms = mSystemPermissions.get(uid); 3096 if (perms != null && perms.contains(permName)) { 3097 return PackageManager.PERMISSION_GRANTED; 3098 } 3099 } 3100 } 3101 3102 return PackageManager.PERMISSION_DENIED; 3103 } 3104 3105 /** 3106 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3107 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3108 * @param checkShell TODO(yamasani): 3109 * @param message the message to log on security exception 3110 */ 3111 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3112 boolean checkShell, String message) { 3113 if (userId < 0) { 3114 throw new IllegalArgumentException("Invalid userId " + userId); 3115 } 3116 if (checkShell) { 3117 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3118 } 3119 if (userId == UserHandle.getUserId(callingUid)) return; 3120 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3121 if (requireFullPermission) { 3122 mContext.enforceCallingOrSelfPermission( 3123 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3124 } else { 3125 try { 3126 mContext.enforceCallingOrSelfPermission( 3127 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3128 } catch (SecurityException se) { 3129 mContext.enforceCallingOrSelfPermission( 3130 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3131 } 3132 } 3133 } 3134 } 3135 3136 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3137 if (callingUid == Process.SHELL_UID) { 3138 if (userHandle >= 0 3139 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3140 throw new SecurityException("Shell does not have permission to access user " 3141 + userHandle); 3142 } else if (userHandle < 0) { 3143 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3144 + Debug.getCallers(3)); 3145 } 3146 } 3147 } 3148 3149 private BasePermission findPermissionTreeLP(String permName) { 3150 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3151 if (permName.startsWith(bp.name) && 3152 permName.length() > bp.name.length() && 3153 permName.charAt(bp.name.length()) == '.') { 3154 return bp; 3155 } 3156 } 3157 return null; 3158 } 3159 3160 private BasePermission checkPermissionTreeLP(String permName) { 3161 if (permName != null) { 3162 BasePermission bp = findPermissionTreeLP(permName); 3163 if (bp != null) { 3164 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3165 return bp; 3166 } 3167 throw new SecurityException("Calling uid " 3168 + Binder.getCallingUid() 3169 + " is not allowed to add to permission tree " 3170 + bp.name + " owned by uid " + bp.uid); 3171 } 3172 } 3173 throw new SecurityException("No permission tree found for " + permName); 3174 } 3175 3176 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3177 if (s1 == null) { 3178 return s2 == null; 3179 } 3180 if (s2 == null) { 3181 return false; 3182 } 3183 if (s1.getClass() != s2.getClass()) { 3184 return false; 3185 } 3186 return s1.equals(s2); 3187 } 3188 3189 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3190 if (pi1.icon != pi2.icon) return false; 3191 if (pi1.logo != pi2.logo) return false; 3192 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3193 if (!compareStrings(pi1.name, pi2.name)) return false; 3194 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3195 // We'll take care of setting this one. 3196 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3197 // These are not currently stored in settings. 3198 //if (!compareStrings(pi1.group, pi2.group)) return false; 3199 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3200 //if (pi1.labelRes != pi2.labelRes) return false; 3201 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3202 return true; 3203 } 3204 3205 int permissionInfoFootprint(PermissionInfo info) { 3206 int size = info.name.length(); 3207 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3208 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3209 return size; 3210 } 3211 3212 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3213 int size = 0; 3214 for (BasePermission perm : mSettings.mPermissions.values()) { 3215 if (perm.uid == tree.uid) { 3216 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3217 } 3218 } 3219 return size; 3220 } 3221 3222 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3223 // We calculate the max size of permissions defined by this uid and throw 3224 // if that plus the size of 'info' would exceed our stated maximum. 3225 if (tree.uid != Process.SYSTEM_UID) { 3226 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3227 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3228 throw new SecurityException("Permission tree size cap exceeded"); 3229 } 3230 } 3231 } 3232 3233 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3234 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3235 throw new SecurityException("Label must be specified in permission"); 3236 } 3237 BasePermission tree = checkPermissionTreeLP(info.name); 3238 BasePermission bp = mSettings.mPermissions.get(info.name); 3239 boolean added = bp == null; 3240 boolean changed = true; 3241 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3242 if (added) { 3243 enforcePermissionCapLocked(info, tree); 3244 bp = new BasePermission(info.name, tree.sourcePackage, 3245 BasePermission.TYPE_DYNAMIC); 3246 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3247 throw new SecurityException( 3248 "Not allowed to modify non-dynamic permission " 3249 + info.name); 3250 } else { 3251 if (bp.protectionLevel == fixedLevel 3252 && bp.perm.owner.equals(tree.perm.owner) 3253 && bp.uid == tree.uid 3254 && comparePermissionInfos(bp.perm.info, info)) { 3255 changed = false; 3256 } 3257 } 3258 bp.protectionLevel = fixedLevel; 3259 info = new PermissionInfo(info); 3260 info.protectionLevel = fixedLevel; 3261 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3262 bp.perm.info.packageName = tree.perm.info.packageName; 3263 bp.uid = tree.uid; 3264 if (added) { 3265 mSettings.mPermissions.put(info.name, bp); 3266 } 3267 if (changed) { 3268 if (!async) { 3269 mSettings.writeLPr(); 3270 } else { 3271 scheduleWriteSettingsLocked(); 3272 } 3273 } 3274 return added; 3275 } 3276 3277 @Override 3278 public boolean addPermission(PermissionInfo info) { 3279 synchronized (mPackages) { 3280 return addPermissionLocked(info, false); 3281 } 3282 } 3283 3284 @Override 3285 public boolean addPermissionAsync(PermissionInfo info) { 3286 synchronized (mPackages) { 3287 return addPermissionLocked(info, true); 3288 } 3289 } 3290 3291 @Override 3292 public void removePermission(String name) { 3293 synchronized (mPackages) { 3294 checkPermissionTreeLP(name); 3295 BasePermission bp = mSettings.mPermissions.get(name); 3296 if (bp != null) { 3297 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3298 throw new SecurityException( 3299 "Not allowed to modify non-dynamic permission " 3300 + name); 3301 } 3302 mSettings.mPermissions.remove(name); 3303 mSettings.writeLPr(); 3304 } 3305 } 3306 } 3307 3308 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3309 BasePermission bp) { 3310 int index = pkg.requestedPermissions.indexOf(bp.name); 3311 if (index == -1) { 3312 throw new SecurityException("Package " + pkg.packageName 3313 + " has not requested permission " + bp.name); 3314 } 3315 if (!bp.isRuntime()) { 3316 throw new SecurityException("Permission " + bp.name 3317 + " is not a changeable permission type"); 3318 } 3319 } 3320 3321 @Override 3322 public void grantRuntimePermission(String packageName, String name, final int userId) { 3323 if (!sUserManager.exists(userId)) { 3324 Log.e(TAG, "No such user:" + userId); 3325 return; 3326 } 3327 3328 mContext.enforceCallingOrSelfPermission( 3329 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3330 "grantRuntimePermission"); 3331 3332 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3333 "grantRuntimePermission"); 3334 3335 final int uid; 3336 final SettingBase sb; 3337 3338 synchronized (mPackages) { 3339 final PackageParser.Package pkg = mPackages.get(packageName); 3340 if (pkg == null) { 3341 throw new IllegalArgumentException("Unknown package: " + packageName); 3342 } 3343 3344 final BasePermission bp = mSettings.mPermissions.get(name); 3345 if (bp == null) { 3346 throw new IllegalArgumentException("Unknown permission: " + name); 3347 } 3348 3349 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3350 3351 uid = pkg.applicationInfo.uid; 3352 sb = (SettingBase) pkg.mExtras; 3353 if (sb == null) { 3354 throw new IllegalArgumentException("Unknown package: " + packageName); 3355 } 3356 3357 final PermissionsState permissionsState = sb.getPermissionsState(); 3358 3359 final int flags = permissionsState.getPermissionFlags(name, userId); 3360 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3361 throw new SecurityException("Cannot grant system fixed permission: " 3362 + name + " for package: " + packageName); 3363 } 3364 3365 final int result = permissionsState.grantRuntimePermission(bp, userId); 3366 switch (result) { 3367 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3368 return; 3369 } 3370 3371 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3372 mHandler.post(new Runnable() { 3373 @Override 3374 public void run() { 3375 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3376 } 3377 }); 3378 } break; 3379 } 3380 3381 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3382 3383 // Not critical if that is lost - app has to request again. 3384 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3385 } 3386 3387 if (READ_EXTERNAL_STORAGE.equals(name) 3388 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3389 final long token = Binder.clearCallingIdentity(); 3390 try { 3391 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3392 storage.remountUid(uid); 3393 } finally { 3394 Binder.restoreCallingIdentity(token); 3395 } 3396 } 3397 } 3398 3399 @Override 3400 public void revokeRuntimePermission(String packageName, String name, int userId) { 3401 if (!sUserManager.exists(userId)) { 3402 Log.e(TAG, "No such user:" + userId); 3403 return; 3404 } 3405 3406 mContext.enforceCallingOrSelfPermission( 3407 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3408 "revokeRuntimePermission"); 3409 3410 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3411 "revokeRuntimePermission"); 3412 3413 final SettingBase sb; 3414 3415 synchronized (mPackages) { 3416 final PackageParser.Package pkg = mPackages.get(packageName); 3417 if (pkg == null) { 3418 throw new IllegalArgumentException("Unknown package: " + packageName); 3419 } 3420 3421 final BasePermission bp = mSettings.mPermissions.get(name); 3422 if (bp == null) { 3423 throw new IllegalArgumentException("Unknown permission: " + name); 3424 } 3425 3426 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3427 3428 sb = (SettingBase) pkg.mExtras; 3429 if (sb == null) { 3430 throw new IllegalArgumentException("Unknown package: " + packageName); 3431 } 3432 3433 final PermissionsState permissionsState = sb.getPermissionsState(); 3434 3435 final int flags = permissionsState.getPermissionFlags(name, userId); 3436 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3437 throw new SecurityException("Cannot revoke system fixed permission: " 3438 + name + " for package: " + packageName); 3439 } 3440 3441 if (permissionsState.revokeRuntimePermission(bp, userId) == 3442 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3443 return; 3444 } 3445 3446 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3447 3448 // Critical, after this call app should never have the permission. 3449 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3450 } 3451 3452 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3453 } 3454 3455 @Override 3456 public void resetRuntimePermissions() { 3457 mContext.enforceCallingOrSelfPermission( 3458 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3459 "revokeRuntimePermission"); 3460 3461 int callingUid = Binder.getCallingUid(); 3462 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3463 mContext.enforceCallingOrSelfPermission( 3464 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3465 "resetRuntimePermissions"); 3466 } 3467 3468 final int[] userIds; 3469 3470 synchronized (mPackages) { 3471 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3472 final int userCount = UserManagerService.getInstance().getUserIds().length; 3473 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3474 } 3475 3476 for (int userId : userIds) { 3477 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3478 } 3479 } 3480 3481 @Override 3482 public int getPermissionFlags(String name, String packageName, int userId) { 3483 if (!sUserManager.exists(userId)) { 3484 return 0; 3485 } 3486 3487 mContext.enforceCallingOrSelfPermission( 3488 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3489 "getPermissionFlags"); 3490 3491 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3492 "getPermissionFlags"); 3493 3494 synchronized (mPackages) { 3495 final PackageParser.Package pkg = mPackages.get(packageName); 3496 if (pkg == null) { 3497 throw new IllegalArgumentException("Unknown package: " + packageName); 3498 } 3499 3500 final BasePermission bp = mSettings.mPermissions.get(name); 3501 if (bp == null) { 3502 throw new IllegalArgumentException("Unknown permission: " + name); 3503 } 3504 3505 SettingBase sb = (SettingBase) pkg.mExtras; 3506 if (sb == null) { 3507 throw new IllegalArgumentException("Unknown package: " + packageName); 3508 } 3509 3510 PermissionsState permissionsState = sb.getPermissionsState(); 3511 return permissionsState.getPermissionFlags(name, userId); 3512 } 3513 } 3514 3515 @Override 3516 public void updatePermissionFlags(String name, String packageName, int flagMask, 3517 int flagValues, int userId) { 3518 if (!sUserManager.exists(userId)) { 3519 return; 3520 } 3521 3522 mContext.enforceCallingOrSelfPermission( 3523 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3524 "updatePermissionFlags"); 3525 3526 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3527 "updatePermissionFlags"); 3528 3529 // Only the system can change system fixed flags. 3530 if (getCallingUid() != Process.SYSTEM_UID) { 3531 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3532 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3533 } 3534 3535 synchronized (mPackages) { 3536 final PackageParser.Package pkg = mPackages.get(packageName); 3537 if (pkg == null) { 3538 throw new IllegalArgumentException("Unknown package: " + packageName); 3539 } 3540 3541 final BasePermission bp = mSettings.mPermissions.get(name); 3542 if (bp == null) { 3543 throw new IllegalArgumentException("Unknown permission: " + name); 3544 } 3545 3546 SettingBase sb = (SettingBase) pkg.mExtras; 3547 if (sb == null) { 3548 throw new IllegalArgumentException("Unknown package: " + packageName); 3549 } 3550 3551 PermissionsState permissionsState = sb.getPermissionsState(); 3552 3553 // Only the package manager can change flags for system component permissions. 3554 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3555 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3556 return; 3557 } 3558 3559 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3560 3561 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3562 // Install and runtime permissions are stored in different places, 3563 // so figure out what permission changed and persist the change. 3564 if (permissionsState.getInstallPermissionState(name) != null) { 3565 scheduleWriteSettingsLocked(); 3566 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3567 || hadState) { 3568 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3569 } 3570 } 3571 } 3572 } 3573 3574 /** 3575 * Update the permission flags for all packages and runtime permissions of a user in order 3576 * to allow device or profile owner to remove POLICY_FIXED. 3577 */ 3578 @Override 3579 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3580 if (!sUserManager.exists(userId)) { 3581 return; 3582 } 3583 3584 mContext.enforceCallingOrSelfPermission( 3585 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3586 "updatePermissionFlagsForAllApps"); 3587 3588 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3589 "updatePermissionFlagsForAllApps"); 3590 3591 // Only the system can change system fixed flags. 3592 if (getCallingUid() != Process.SYSTEM_UID) { 3593 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3594 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3595 } 3596 3597 synchronized (mPackages) { 3598 boolean changed = false; 3599 final int packageCount = mPackages.size(); 3600 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3601 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3602 SettingBase sb = (SettingBase) pkg.mExtras; 3603 if (sb == null) { 3604 continue; 3605 } 3606 PermissionsState permissionsState = sb.getPermissionsState(); 3607 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3608 userId, flagMask, flagValues); 3609 } 3610 if (changed) { 3611 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3612 } 3613 } 3614 } 3615 3616 @Override 3617 public boolean shouldShowRequestPermissionRationale(String permissionName, 3618 String packageName, int userId) { 3619 if (UserHandle.getCallingUserId() != userId) { 3620 mContext.enforceCallingPermission( 3621 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3622 "canShowRequestPermissionRationale for user " + userId); 3623 } 3624 3625 final int uid = getPackageUid(packageName, userId); 3626 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3627 return false; 3628 } 3629 3630 if (checkPermission(permissionName, packageName, userId) 3631 == PackageManager.PERMISSION_GRANTED) { 3632 return false; 3633 } 3634 3635 final int flags; 3636 3637 final long identity = Binder.clearCallingIdentity(); 3638 try { 3639 flags = getPermissionFlags(permissionName, 3640 packageName, userId); 3641 } finally { 3642 Binder.restoreCallingIdentity(identity); 3643 } 3644 3645 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3646 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3647 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3648 3649 if ((flags & fixedFlags) != 0) { 3650 return false; 3651 } 3652 3653 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3654 } 3655 3656 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3657 BasePermission bp = mSettings.mPermissions.get(permission); 3658 if (bp == null) { 3659 throw new SecurityException("Missing " + permission + " permission"); 3660 } 3661 3662 SettingBase sb = (SettingBase) pkg.mExtras; 3663 PermissionsState permissionsState = sb.getPermissionsState(); 3664 3665 if (permissionsState.grantInstallPermission(bp) != 3666 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3667 scheduleWriteSettingsLocked(); 3668 } 3669 } 3670 3671 @Override 3672 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3673 mContext.enforceCallingOrSelfPermission( 3674 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3675 "addOnPermissionsChangeListener"); 3676 3677 synchronized (mPackages) { 3678 mOnPermissionChangeListeners.addListenerLocked(listener); 3679 } 3680 } 3681 3682 @Override 3683 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3684 synchronized (mPackages) { 3685 mOnPermissionChangeListeners.removeListenerLocked(listener); 3686 } 3687 } 3688 3689 @Override 3690 public boolean isProtectedBroadcast(String actionName) { 3691 synchronized (mPackages) { 3692 return mProtectedBroadcasts.contains(actionName); 3693 } 3694 } 3695 3696 @Override 3697 public int checkSignatures(String pkg1, String pkg2) { 3698 synchronized (mPackages) { 3699 final PackageParser.Package p1 = mPackages.get(pkg1); 3700 final PackageParser.Package p2 = mPackages.get(pkg2); 3701 if (p1 == null || p1.mExtras == null 3702 || p2 == null || p2.mExtras == null) { 3703 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3704 } 3705 return compareSignatures(p1.mSignatures, p2.mSignatures); 3706 } 3707 } 3708 3709 @Override 3710 public int checkUidSignatures(int uid1, int uid2) { 3711 // Map to base uids. 3712 uid1 = UserHandle.getAppId(uid1); 3713 uid2 = UserHandle.getAppId(uid2); 3714 // reader 3715 synchronized (mPackages) { 3716 Signature[] s1; 3717 Signature[] s2; 3718 Object obj = mSettings.getUserIdLPr(uid1); 3719 if (obj != null) { 3720 if (obj instanceof SharedUserSetting) { 3721 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3722 } else if (obj instanceof PackageSetting) { 3723 s1 = ((PackageSetting)obj).signatures.mSignatures; 3724 } else { 3725 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3726 } 3727 } else { 3728 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3729 } 3730 obj = mSettings.getUserIdLPr(uid2); 3731 if (obj != null) { 3732 if (obj instanceof SharedUserSetting) { 3733 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3734 } else if (obj instanceof PackageSetting) { 3735 s2 = ((PackageSetting)obj).signatures.mSignatures; 3736 } else { 3737 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3738 } 3739 } else { 3740 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3741 } 3742 return compareSignatures(s1, s2); 3743 } 3744 } 3745 3746 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3747 final long identity = Binder.clearCallingIdentity(); 3748 try { 3749 if (sb instanceof SharedUserSetting) { 3750 SharedUserSetting sus = (SharedUserSetting) sb; 3751 final int packageCount = sus.packages.size(); 3752 for (int i = 0; i < packageCount; i++) { 3753 PackageSetting susPs = sus.packages.valueAt(i); 3754 if (userId == UserHandle.USER_ALL) { 3755 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3756 } else { 3757 final int uid = UserHandle.getUid(userId, susPs.appId); 3758 killUid(uid, reason); 3759 } 3760 } 3761 } else if (sb instanceof PackageSetting) { 3762 PackageSetting ps = (PackageSetting) sb; 3763 if (userId == UserHandle.USER_ALL) { 3764 killApplication(ps.pkg.packageName, ps.appId, reason); 3765 } else { 3766 final int uid = UserHandle.getUid(userId, ps.appId); 3767 killUid(uid, reason); 3768 } 3769 } 3770 } finally { 3771 Binder.restoreCallingIdentity(identity); 3772 } 3773 } 3774 3775 private static void killUid(int uid, String reason) { 3776 IActivityManager am = ActivityManagerNative.getDefault(); 3777 if (am != null) { 3778 try { 3779 am.killUid(uid, reason); 3780 } catch (RemoteException e) { 3781 /* ignore - same process */ 3782 } 3783 } 3784 } 3785 3786 /** 3787 * Compares two sets of signatures. Returns: 3788 * <br /> 3789 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3790 * <br /> 3791 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3792 * <br /> 3793 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3794 * <br /> 3795 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3796 * <br /> 3797 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3798 */ 3799 static int compareSignatures(Signature[] s1, Signature[] s2) { 3800 if (s1 == null) { 3801 return s2 == null 3802 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3803 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3804 } 3805 3806 if (s2 == null) { 3807 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3808 } 3809 3810 if (s1.length != s2.length) { 3811 return PackageManager.SIGNATURE_NO_MATCH; 3812 } 3813 3814 // Since both signature sets are of size 1, we can compare without HashSets. 3815 if (s1.length == 1) { 3816 return s1[0].equals(s2[0]) ? 3817 PackageManager.SIGNATURE_MATCH : 3818 PackageManager.SIGNATURE_NO_MATCH; 3819 } 3820 3821 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3822 for (Signature sig : s1) { 3823 set1.add(sig); 3824 } 3825 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3826 for (Signature sig : s2) { 3827 set2.add(sig); 3828 } 3829 // Make sure s2 contains all signatures in s1. 3830 if (set1.equals(set2)) { 3831 return PackageManager.SIGNATURE_MATCH; 3832 } 3833 return PackageManager.SIGNATURE_NO_MATCH; 3834 } 3835 3836 /** 3837 * If the database version for this type of package (internal storage or 3838 * external storage) is less than the version where package signatures 3839 * were updated, return true. 3840 */ 3841 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3842 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3843 DatabaseVersion.SIGNATURE_END_ENTITY)) 3844 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3845 DatabaseVersion.SIGNATURE_END_ENTITY)); 3846 } 3847 3848 /** 3849 * Used for backward compatibility to make sure any packages with 3850 * certificate chains get upgraded to the new style. {@code existingSigs} 3851 * will be in the old format (since they were stored on disk from before the 3852 * system upgrade) and {@code scannedSigs} will be in the newer format. 3853 */ 3854 private int compareSignaturesCompat(PackageSignatures existingSigs, 3855 PackageParser.Package scannedPkg) { 3856 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3857 return PackageManager.SIGNATURE_NO_MATCH; 3858 } 3859 3860 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3861 for (Signature sig : existingSigs.mSignatures) { 3862 existingSet.add(sig); 3863 } 3864 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3865 for (Signature sig : scannedPkg.mSignatures) { 3866 try { 3867 Signature[] chainSignatures = sig.getChainSignatures(); 3868 for (Signature chainSig : chainSignatures) { 3869 scannedCompatSet.add(chainSig); 3870 } 3871 } catch (CertificateEncodingException e) { 3872 scannedCompatSet.add(sig); 3873 } 3874 } 3875 /* 3876 * Make sure the expanded scanned set contains all signatures in the 3877 * existing one. 3878 */ 3879 if (scannedCompatSet.equals(existingSet)) { 3880 // Migrate the old signatures to the new scheme. 3881 existingSigs.assignSignatures(scannedPkg.mSignatures); 3882 // The new KeySets will be re-added later in the scanning process. 3883 synchronized (mPackages) { 3884 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3885 } 3886 return PackageManager.SIGNATURE_MATCH; 3887 } 3888 return PackageManager.SIGNATURE_NO_MATCH; 3889 } 3890 3891 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3892 if (isExternal(scannedPkg)) { 3893 return mSettings.isExternalDatabaseVersionOlderThan( 3894 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3895 } else { 3896 return mSettings.isInternalDatabaseVersionOlderThan( 3897 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3898 } 3899 } 3900 3901 private int compareSignaturesRecover(PackageSignatures existingSigs, 3902 PackageParser.Package scannedPkg) { 3903 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3904 return PackageManager.SIGNATURE_NO_MATCH; 3905 } 3906 3907 String msg = null; 3908 try { 3909 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3910 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3911 + scannedPkg.packageName); 3912 return PackageManager.SIGNATURE_MATCH; 3913 } 3914 } catch (CertificateException e) { 3915 msg = e.getMessage(); 3916 } 3917 3918 logCriticalInfo(Log.INFO, 3919 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3920 return PackageManager.SIGNATURE_NO_MATCH; 3921 } 3922 3923 @Override 3924 public String[] getPackagesForUid(int uid) { 3925 uid = UserHandle.getAppId(uid); 3926 // reader 3927 synchronized (mPackages) { 3928 Object obj = mSettings.getUserIdLPr(uid); 3929 if (obj instanceof SharedUserSetting) { 3930 final SharedUserSetting sus = (SharedUserSetting) obj; 3931 final int N = sus.packages.size(); 3932 final String[] res = new String[N]; 3933 final Iterator<PackageSetting> it = sus.packages.iterator(); 3934 int i = 0; 3935 while (it.hasNext()) { 3936 res[i++] = it.next().name; 3937 } 3938 return res; 3939 } else if (obj instanceof PackageSetting) { 3940 final PackageSetting ps = (PackageSetting) obj; 3941 return new String[] { ps.name }; 3942 } 3943 } 3944 return null; 3945 } 3946 3947 @Override 3948 public String getNameForUid(int uid) { 3949 // reader 3950 synchronized (mPackages) { 3951 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3952 if (obj instanceof SharedUserSetting) { 3953 final SharedUserSetting sus = (SharedUserSetting) obj; 3954 return sus.name + ":" + sus.userId; 3955 } else if (obj instanceof PackageSetting) { 3956 final PackageSetting ps = (PackageSetting) obj; 3957 return ps.name; 3958 } 3959 } 3960 return null; 3961 } 3962 3963 @Override 3964 public int getUidForSharedUser(String sharedUserName) { 3965 if(sharedUserName == null) { 3966 return -1; 3967 } 3968 // reader 3969 synchronized (mPackages) { 3970 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3971 if (suid == null) { 3972 return -1; 3973 } 3974 return suid.userId; 3975 } 3976 } 3977 3978 @Override 3979 public int getFlagsForUid(int uid) { 3980 synchronized (mPackages) { 3981 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3982 if (obj instanceof SharedUserSetting) { 3983 final SharedUserSetting sus = (SharedUserSetting) obj; 3984 return sus.pkgFlags; 3985 } else if (obj instanceof PackageSetting) { 3986 final PackageSetting ps = (PackageSetting) obj; 3987 return ps.pkgFlags; 3988 } 3989 } 3990 return 0; 3991 } 3992 3993 @Override 3994 public int getPrivateFlagsForUid(int uid) { 3995 synchronized (mPackages) { 3996 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3997 if (obj instanceof SharedUserSetting) { 3998 final SharedUserSetting sus = (SharedUserSetting) obj; 3999 return sus.pkgPrivateFlags; 4000 } else if (obj instanceof PackageSetting) { 4001 final PackageSetting ps = (PackageSetting) obj; 4002 return ps.pkgPrivateFlags; 4003 } 4004 } 4005 return 0; 4006 } 4007 4008 @Override 4009 public boolean isUidPrivileged(int uid) { 4010 uid = UserHandle.getAppId(uid); 4011 // reader 4012 synchronized (mPackages) { 4013 Object obj = mSettings.getUserIdLPr(uid); 4014 if (obj instanceof SharedUserSetting) { 4015 final SharedUserSetting sus = (SharedUserSetting) obj; 4016 final Iterator<PackageSetting> it = sus.packages.iterator(); 4017 while (it.hasNext()) { 4018 if (it.next().isPrivileged()) { 4019 return true; 4020 } 4021 } 4022 } else if (obj instanceof PackageSetting) { 4023 final PackageSetting ps = (PackageSetting) obj; 4024 return ps.isPrivileged(); 4025 } 4026 } 4027 return false; 4028 } 4029 4030 @Override 4031 public String[] getAppOpPermissionPackages(String permissionName) { 4032 synchronized (mPackages) { 4033 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4034 if (pkgs == null) { 4035 return null; 4036 } 4037 return pkgs.toArray(new String[pkgs.size()]); 4038 } 4039 } 4040 4041 @Override 4042 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4043 int flags, int userId) { 4044 if (!sUserManager.exists(userId)) return null; 4045 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4046 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4047 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4048 } 4049 4050 @Override 4051 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4052 IntentFilter filter, int match, ComponentName activity) { 4053 final int userId = UserHandle.getCallingUserId(); 4054 if (DEBUG_PREFERRED) { 4055 Log.v(TAG, "setLastChosenActivity intent=" + intent 4056 + " resolvedType=" + resolvedType 4057 + " flags=" + flags 4058 + " filter=" + filter 4059 + " match=" + match 4060 + " activity=" + activity); 4061 filter.dump(new PrintStreamPrinter(System.out), " "); 4062 } 4063 intent.setComponent(null); 4064 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4065 // Find any earlier preferred or last chosen entries and nuke them 4066 findPreferredActivity(intent, resolvedType, 4067 flags, query, 0, false, true, false, userId); 4068 // Add the new activity as the last chosen for this filter 4069 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4070 "Setting last chosen"); 4071 } 4072 4073 @Override 4074 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4075 final int userId = UserHandle.getCallingUserId(); 4076 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4077 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4078 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4079 false, false, false, userId); 4080 } 4081 4082 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4083 int flags, List<ResolveInfo> query, int userId) { 4084 if (query != null) { 4085 final int N = query.size(); 4086 if (N == 1) { 4087 return query.get(0); 4088 } else if (N > 1) { 4089 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4090 // If there is more than one activity with the same priority, 4091 // then let the user decide between them. 4092 ResolveInfo r0 = query.get(0); 4093 ResolveInfo r1 = query.get(1); 4094 if (DEBUG_INTENT_MATCHING || debug) { 4095 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4096 + r1.activityInfo.name + "=" + r1.priority); 4097 } 4098 // If the first activity has a higher priority, or a different 4099 // default, then it is always desireable to pick it. 4100 if (r0.priority != r1.priority 4101 || r0.preferredOrder != r1.preferredOrder 4102 || r0.isDefault != r1.isDefault) { 4103 return query.get(0); 4104 } 4105 // If we have saved a preference for a preferred activity for 4106 // this Intent, use that. 4107 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4108 flags, query, r0.priority, true, false, debug, userId); 4109 if (ri != null) { 4110 return ri; 4111 } 4112 if (userId != 0) { 4113 ri = new ResolveInfo(mResolveInfo); 4114 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4115 ri.activityInfo.applicationInfo = new ApplicationInfo( 4116 ri.activityInfo.applicationInfo); 4117 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4118 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4119 return ri; 4120 } 4121 return mResolveInfo; 4122 } 4123 } 4124 return null; 4125 } 4126 4127 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4128 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4129 final int N = query.size(); 4130 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4131 .get(userId); 4132 // Get the list of persistent preferred activities that handle the intent 4133 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4134 List<PersistentPreferredActivity> pprefs = ppir != null 4135 ? ppir.queryIntent(intent, resolvedType, 4136 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4137 : null; 4138 if (pprefs != null && pprefs.size() > 0) { 4139 final int M = pprefs.size(); 4140 for (int i=0; i<M; i++) { 4141 final PersistentPreferredActivity ppa = pprefs.get(i); 4142 if (DEBUG_PREFERRED || debug) { 4143 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4144 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4145 + "\n component=" + ppa.mComponent); 4146 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4147 } 4148 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4149 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4150 if (DEBUG_PREFERRED || debug) { 4151 Slog.v(TAG, "Found persistent preferred activity:"); 4152 if (ai != null) { 4153 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4154 } else { 4155 Slog.v(TAG, " null"); 4156 } 4157 } 4158 if (ai == null) { 4159 // This previously registered persistent preferred activity 4160 // component is no longer known. Ignore it and do NOT remove it. 4161 continue; 4162 } 4163 for (int j=0; j<N; j++) { 4164 final ResolveInfo ri = query.get(j); 4165 if (!ri.activityInfo.applicationInfo.packageName 4166 .equals(ai.applicationInfo.packageName)) { 4167 continue; 4168 } 4169 if (!ri.activityInfo.name.equals(ai.name)) { 4170 continue; 4171 } 4172 // Found a persistent preference that can handle the intent. 4173 if (DEBUG_PREFERRED || debug) { 4174 Slog.v(TAG, "Returning persistent preferred activity: " + 4175 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4176 } 4177 return ri; 4178 } 4179 } 4180 } 4181 return null; 4182 } 4183 4184 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4185 List<ResolveInfo> query, int priority, boolean always, 4186 boolean removeMatches, boolean debug, int userId) { 4187 if (!sUserManager.exists(userId)) return null; 4188 // writer 4189 synchronized (mPackages) { 4190 if (intent.getSelector() != null) { 4191 intent = intent.getSelector(); 4192 } 4193 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4194 4195 // Try to find a matching persistent preferred activity. 4196 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4197 debug, userId); 4198 4199 // If a persistent preferred activity matched, use it. 4200 if (pri != null) { 4201 return pri; 4202 } 4203 4204 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4205 // Get the list of preferred activities that handle the intent 4206 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4207 List<PreferredActivity> prefs = pir != null 4208 ? pir.queryIntent(intent, resolvedType, 4209 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4210 : null; 4211 if (prefs != null && prefs.size() > 0) { 4212 boolean changed = false; 4213 try { 4214 // First figure out how good the original match set is. 4215 // We will only allow preferred activities that came 4216 // from the same match quality. 4217 int match = 0; 4218 4219 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4220 4221 final int N = query.size(); 4222 for (int j=0; j<N; j++) { 4223 final ResolveInfo ri = query.get(j); 4224 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4225 + ": 0x" + Integer.toHexString(match)); 4226 if (ri.match > match) { 4227 match = ri.match; 4228 } 4229 } 4230 4231 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4232 + Integer.toHexString(match)); 4233 4234 match &= IntentFilter.MATCH_CATEGORY_MASK; 4235 final int M = prefs.size(); 4236 for (int i=0; i<M; i++) { 4237 final PreferredActivity pa = prefs.get(i); 4238 if (DEBUG_PREFERRED || debug) { 4239 Slog.v(TAG, "Checking PreferredActivity ds=" 4240 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4241 + "\n component=" + pa.mPref.mComponent); 4242 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4243 } 4244 if (pa.mPref.mMatch != match) { 4245 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4246 + Integer.toHexString(pa.mPref.mMatch)); 4247 continue; 4248 } 4249 // If it's not an "always" type preferred activity and that's what we're 4250 // looking for, skip it. 4251 if (always && !pa.mPref.mAlways) { 4252 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4253 continue; 4254 } 4255 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4256 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4257 if (DEBUG_PREFERRED || debug) { 4258 Slog.v(TAG, "Found preferred activity:"); 4259 if (ai != null) { 4260 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4261 } else { 4262 Slog.v(TAG, " null"); 4263 } 4264 } 4265 if (ai == null) { 4266 // This previously registered preferred activity 4267 // component is no longer known. Most likely an update 4268 // to the app was installed and in the new version this 4269 // component no longer exists. Clean it up by removing 4270 // it from the preferred activities list, and skip it. 4271 Slog.w(TAG, "Removing dangling preferred activity: " 4272 + pa.mPref.mComponent); 4273 pir.removeFilter(pa); 4274 changed = true; 4275 continue; 4276 } 4277 for (int j=0; j<N; j++) { 4278 final ResolveInfo ri = query.get(j); 4279 if (!ri.activityInfo.applicationInfo.packageName 4280 .equals(ai.applicationInfo.packageName)) { 4281 continue; 4282 } 4283 if (!ri.activityInfo.name.equals(ai.name)) { 4284 continue; 4285 } 4286 4287 if (removeMatches) { 4288 pir.removeFilter(pa); 4289 changed = true; 4290 if (DEBUG_PREFERRED) { 4291 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4292 } 4293 break; 4294 } 4295 4296 // Okay we found a previously set preferred or last chosen app. 4297 // If the result set is different from when this 4298 // was created, we need to clear it and re-ask the 4299 // user their preference, if we're looking for an "always" type entry. 4300 if (always && !pa.mPref.sameSet(query)) { 4301 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4302 + intent + " type " + resolvedType); 4303 if (DEBUG_PREFERRED) { 4304 Slog.v(TAG, "Removing preferred activity since set changed " 4305 + pa.mPref.mComponent); 4306 } 4307 pir.removeFilter(pa); 4308 // Re-add the filter as a "last chosen" entry (!always) 4309 PreferredActivity lastChosen = new PreferredActivity( 4310 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4311 pir.addFilter(lastChosen); 4312 changed = true; 4313 return null; 4314 } 4315 4316 // Yay! Either the set matched or we're looking for the last chosen 4317 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4318 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4319 return ri; 4320 } 4321 } 4322 } finally { 4323 if (changed) { 4324 if (DEBUG_PREFERRED) { 4325 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4326 } 4327 scheduleWritePackageRestrictionsLocked(userId); 4328 } 4329 } 4330 } 4331 } 4332 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4333 return null; 4334 } 4335 4336 /* 4337 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4338 */ 4339 @Override 4340 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4341 int targetUserId) { 4342 mContext.enforceCallingOrSelfPermission( 4343 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4344 List<CrossProfileIntentFilter> matches = 4345 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4346 if (matches != null) { 4347 int size = matches.size(); 4348 for (int i = 0; i < size; i++) { 4349 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4350 } 4351 } 4352 if (hasWebURI(intent)) { 4353 // cross-profile app linking works only towards the parent. 4354 final UserInfo parent = getProfileParent(sourceUserId); 4355 synchronized(mPackages) { 4356 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4357 parent.id) != null; 4358 } 4359 } 4360 return false; 4361 } 4362 4363 private UserInfo getProfileParent(int userId) { 4364 final long identity = Binder.clearCallingIdentity(); 4365 try { 4366 return sUserManager.getProfileParent(userId); 4367 } finally { 4368 Binder.restoreCallingIdentity(identity); 4369 } 4370 } 4371 4372 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4373 String resolvedType, int userId) { 4374 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4375 if (resolver != null) { 4376 return resolver.queryIntent(intent, resolvedType, false, userId); 4377 } 4378 return null; 4379 } 4380 4381 @Override 4382 public List<ResolveInfo> queryIntentActivities(Intent intent, 4383 String resolvedType, int flags, int userId) { 4384 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4385 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4386 ComponentName comp = intent.getComponent(); 4387 if (comp == null) { 4388 if (intent.getSelector() != null) { 4389 intent = intent.getSelector(); 4390 comp = intent.getComponent(); 4391 } 4392 } 4393 4394 if (comp != null) { 4395 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4396 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4397 if (ai != null) { 4398 final ResolveInfo ri = new ResolveInfo(); 4399 ri.activityInfo = ai; 4400 list.add(ri); 4401 } 4402 return list; 4403 } 4404 4405 // reader 4406 synchronized (mPackages) { 4407 final String pkgName = intent.getPackage(); 4408 if (pkgName == null) { 4409 List<CrossProfileIntentFilter> matchingFilters = 4410 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4411 // Check for results that need to skip the current profile. 4412 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4413 resolvedType, flags, userId); 4414 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4415 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4416 result.add(xpResolveInfo); 4417 return filterIfNotPrimaryUser(result, userId); 4418 } 4419 4420 // Check for results in the current profile. 4421 List<ResolveInfo> result = mActivities.queryIntent( 4422 intent, resolvedType, flags, userId); 4423 4424 // Check for cross profile results. 4425 xpResolveInfo = queryCrossProfileIntents( 4426 matchingFilters, intent, resolvedType, flags, userId); 4427 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4428 result.add(xpResolveInfo); 4429 Collections.sort(result, mResolvePrioritySorter); 4430 } 4431 result = filterIfNotPrimaryUser(result, userId); 4432 if (hasWebURI(intent)) { 4433 CrossProfileDomainInfo xpDomainInfo = null; 4434 final UserInfo parent = getProfileParent(userId); 4435 if (parent != null) { 4436 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4437 flags, userId, parent.id); 4438 } 4439 if (xpDomainInfo != null) { 4440 if (xpResolveInfo != null) { 4441 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4442 // in the result. 4443 result.remove(xpResolveInfo); 4444 } 4445 if (result.size() == 0) { 4446 result.add(xpDomainInfo.resolveInfo); 4447 return result; 4448 } 4449 } else if (result.size() <= 1) { 4450 return result; 4451 } 4452 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4453 xpDomainInfo); 4454 Collections.sort(result, mResolvePrioritySorter); 4455 } 4456 return result; 4457 } 4458 final PackageParser.Package pkg = mPackages.get(pkgName); 4459 if (pkg != null) { 4460 return filterIfNotPrimaryUser( 4461 mActivities.queryIntentForPackage( 4462 intent, resolvedType, flags, pkg.activities, userId), 4463 userId); 4464 } 4465 return new ArrayList<ResolveInfo>(); 4466 } 4467 } 4468 4469 private static class CrossProfileDomainInfo { 4470 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4471 ResolveInfo resolveInfo; 4472 /* Best domain verification status of the activities found in the other profile */ 4473 int bestDomainVerificationStatus; 4474 } 4475 4476 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4477 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4478 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4479 sourceUserId)) { 4480 return null; 4481 } 4482 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4483 resolvedType, flags, parentUserId); 4484 4485 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4486 return null; 4487 } 4488 CrossProfileDomainInfo result = null; 4489 int size = resultTargetUser.size(); 4490 for (int i = 0; i < size; i++) { 4491 ResolveInfo riTargetUser = resultTargetUser.get(i); 4492 // Intent filter verification is only for filters that specify a host. So don't return 4493 // those that handle all web uris. 4494 if (riTargetUser.handleAllWebDataURI) { 4495 continue; 4496 } 4497 String packageName = riTargetUser.activityInfo.packageName; 4498 PackageSetting ps = mSettings.mPackages.get(packageName); 4499 if (ps == null) { 4500 continue; 4501 } 4502 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4503 if (result == null) { 4504 result = new CrossProfileDomainInfo(); 4505 result.resolveInfo = 4506 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4507 result.bestDomainVerificationStatus = status; 4508 } else { 4509 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4510 result.bestDomainVerificationStatus); 4511 } 4512 } 4513 return result; 4514 } 4515 4516 /** 4517 * Verification statuses are ordered from the worse to the best, except for 4518 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4519 */ 4520 private int bestDomainVerificationStatus(int status1, int status2) { 4521 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4522 return status2; 4523 } 4524 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4525 return status1; 4526 } 4527 return (int) MathUtils.max(status1, status2); 4528 } 4529 4530 private boolean isUserEnabled(int userId) { 4531 long callingId = Binder.clearCallingIdentity(); 4532 try { 4533 UserInfo userInfo = sUserManager.getUserInfo(userId); 4534 return userInfo != null && userInfo.isEnabled(); 4535 } finally { 4536 Binder.restoreCallingIdentity(callingId); 4537 } 4538 } 4539 4540 /** 4541 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4542 * 4543 * @return filtered list 4544 */ 4545 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4546 if (userId == UserHandle.USER_OWNER) { 4547 return resolveInfos; 4548 } 4549 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4550 ResolveInfo info = resolveInfos.get(i); 4551 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4552 resolveInfos.remove(i); 4553 } 4554 } 4555 return resolveInfos; 4556 } 4557 4558 private static boolean hasWebURI(Intent intent) { 4559 if (intent.getData() == null) { 4560 return false; 4561 } 4562 final String scheme = intent.getScheme(); 4563 if (TextUtils.isEmpty(scheme)) { 4564 return false; 4565 } 4566 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4567 } 4568 4569 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4570 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4571 if (DEBUG_PREFERRED) { 4572 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4573 candidates.size()); 4574 } 4575 4576 final int userId = UserHandle.getCallingUserId(); 4577 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4578 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4579 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4580 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4581 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4582 4583 synchronized (mPackages) { 4584 final int count = candidates.size(); 4585 // First, try to use the domain preferred app. Partition the candidates into four lists: 4586 // one for the final results, one for the "do not use ever", one for "undefined status" 4587 // and finally one for "Browser App type". 4588 for (int n=0; n<count; n++) { 4589 ResolveInfo info = candidates.get(n); 4590 String packageName = info.activityInfo.packageName; 4591 PackageSetting ps = mSettings.mPackages.get(packageName); 4592 if (ps != null) { 4593 // Add to the special match all list (Browser use case) 4594 if (info.handleAllWebDataURI) { 4595 matchAllList.add(info); 4596 continue; 4597 } 4598 // Try to get the status from User settings first 4599 int status = getDomainVerificationStatusLPr(ps, userId); 4600 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4601 alwaysList.add(info); 4602 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4603 neverList.add(info); 4604 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4605 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4606 undefinedList.add(info); 4607 } 4608 } 4609 } 4610 // First try to add the "always" resolution for the current user if there is any 4611 if (alwaysList.size() > 0) { 4612 result.addAll(alwaysList); 4613 // if there is an "always" for the parent user, add it. 4614 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4615 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4616 result.add(xpDomainInfo.resolveInfo); 4617 } else { 4618 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4619 result.addAll(undefinedList); 4620 if (xpDomainInfo != null && ( 4621 xpDomainInfo.bestDomainVerificationStatus 4622 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4623 || xpDomainInfo.bestDomainVerificationStatus 4624 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4625 result.add(xpDomainInfo.resolveInfo); 4626 } 4627 // Also add Browsers (all of them or only the default one) 4628 if ((flags & MATCH_ALL) != 0) { 4629 result.addAll(matchAllList); 4630 } else { 4631 // Try to add the Default Browser if we can 4632 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4633 UserHandle.myUserId()); 4634 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4635 boolean defaultBrowserFound = false; 4636 final int browserCount = matchAllList.size(); 4637 for (int n=0; n<browserCount; n++) { 4638 ResolveInfo browser = matchAllList.get(n); 4639 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4640 result.add(browser); 4641 defaultBrowserFound = true; 4642 break; 4643 } 4644 } 4645 if (!defaultBrowserFound) { 4646 result.addAll(matchAllList); 4647 } 4648 } else { 4649 result.addAll(matchAllList); 4650 } 4651 } 4652 4653 // If there is nothing selected, add all candidates and remove the ones that the User 4654 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4655 if (result.size() == 0) { 4656 result.addAll(candidates); 4657 result.removeAll(neverList); 4658 } 4659 } 4660 } 4661 if (DEBUG_PREFERRED) { 4662 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4663 result.size()); 4664 } 4665 return result; 4666 } 4667 4668 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4669 int status = ps.getDomainVerificationStatusForUser(userId); 4670 // if none available, get the master status 4671 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4672 if (ps.getIntentFilterVerificationInfo() != null) { 4673 status = ps.getIntentFilterVerificationInfo().getStatus(); 4674 } 4675 } 4676 return status; 4677 } 4678 4679 private ResolveInfo querySkipCurrentProfileIntents( 4680 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4681 int flags, int sourceUserId) { 4682 if (matchingFilters != null) { 4683 int size = matchingFilters.size(); 4684 for (int i = 0; i < size; i ++) { 4685 CrossProfileIntentFilter filter = matchingFilters.get(i); 4686 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4687 // Checking if there are activities in the target user that can handle the 4688 // intent. 4689 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4690 flags, sourceUserId); 4691 if (resolveInfo != null) { 4692 return resolveInfo; 4693 } 4694 } 4695 } 4696 } 4697 return null; 4698 } 4699 4700 // Return matching ResolveInfo if any for skip current profile intent filters. 4701 private ResolveInfo queryCrossProfileIntents( 4702 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4703 int flags, int sourceUserId) { 4704 if (matchingFilters != null) { 4705 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4706 // match the same intent. For performance reasons, it is better not to 4707 // run queryIntent twice for the same userId 4708 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4709 int size = matchingFilters.size(); 4710 for (int i = 0; i < size; i++) { 4711 CrossProfileIntentFilter filter = matchingFilters.get(i); 4712 int targetUserId = filter.getTargetUserId(); 4713 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4714 && !alreadyTriedUserIds.get(targetUserId)) { 4715 // Checking if there are activities in the target user that can handle the 4716 // intent. 4717 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4718 flags, sourceUserId); 4719 if (resolveInfo != null) return resolveInfo; 4720 alreadyTriedUserIds.put(targetUserId, true); 4721 } 4722 } 4723 } 4724 return null; 4725 } 4726 4727 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4728 String resolvedType, int flags, int sourceUserId) { 4729 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4730 resolvedType, flags, filter.getTargetUserId()); 4731 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4732 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4733 } 4734 return null; 4735 } 4736 4737 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4738 int sourceUserId, int targetUserId) { 4739 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4740 String className; 4741 if (targetUserId == UserHandle.USER_OWNER) { 4742 className = FORWARD_INTENT_TO_USER_OWNER; 4743 } else { 4744 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4745 } 4746 ComponentName forwardingActivityComponentName = new ComponentName( 4747 mAndroidApplication.packageName, className); 4748 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4749 sourceUserId); 4750 if (targetUserId == UserHandle.USER_OWNER) { 4751 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4752 forwardingResolveInfo.noResourceId = true; 4753 } 4754 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4755 forwardingResolveInfo.priority = 0; 4756 forwardingResolveInfo.preferredOrder = 0; 4757 forwardingResolveInfo.match = 0; 4758 forwardingResolveInfo.isDefault = true; 4759 forwardingResolveInfo.filter = filter; 4760 forwardingResolveInfo.targetUserId = targetUserId; 4761 return forwardingResolveInfo; 4762 } 4763 4764 @Override 4765 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4766 Intent[] specifics, String[] specificTypes, Intent intent, 4767 String resolvedType, int flags, int userId) { 4768 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4769 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4770 false, "query intent activity options"); 4771 final String resultsAction = intent.getAction(); 4772 4773 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4774 | PackageManager.GET_RESOLVED_FILTER, userId); 4775 4776 if (DEBUG_INTENT_MATCHING) { 4777 Log.v(TAG, "Query " + intent + ": " + results); 4778 } 4779 4780 int specificsPos = 0; 4781 int N; 4782 4783 // todo: note that the algorithm used here is O(N^2). This 4784 // isn't a problem in our current environment, but if we start running 4785 // into situations where we have more than 5 or 10 matches then this 4786 // should probably be changed to something smarter... 4787 4788 // First we go through and resolve each of the specific items 4789 // that were supplied, taking care of removing any corresponding 4790 // duplicate items in the generic resolve list. 4791 if (specifics != null) { 4792 for (int i=0; i<specifics.length; i++) { 4793 final Intent sintent = specifics[i]; 4794 if (sintent == null) { 4795 continue; 4796 } 4797 4798 if (DEBUG_INTENT_MATCHING) { 4799 Log.v(TAG, "Specific #" + i + ": " + sintent); 4800 } 4801 4802 String action = sintent.getAction(); 4803 if (resultsAction != null && resultsAction.equals(action)) { 4804 // If this action was explicitly requested, then don't 4805 // remove things that have it. 4806 action = null; 4807 } 4808 4809 ResolveInfo ri = null; 4810 ActivityInfo ai = null; 4811 4812 ComponentName comp = sintent.getComponent(); 4813 if (comp == null) { 4814 ri = resolveIntent( 4815 sintent, 4816 specificTypes != null ? specificTypes[i] : null, 4817 flags, userId); 4818 if (ri == null) { 4819 continue; 4820 } 4821 if (ri == mResolveInfo) { 4822 // ACK! Must do something better with this. 4823 } 4824 ai = ri.activityInfo; 4825 comp = new ComponentName(ai.applicationInfo.packageName, 4826 ai.name); 4827 } else { 4828 ai = getActivityInfo(comp, flags, userId); 4829 if (ai == null) { 4830 continue; 4831 } 4832 } 4833 4834 // Look for any generic query activities that are duplicates 4835 // of this specific one, and remove them from the results. 4836 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4837 N = results.size(); 4838 int j; 4839 for (j=specificsPos; j<N; j++) { 4840 ResolveInfo sri = results.get(j); 4841 if ((sri.activityInfo.name.equals(comp.getClassName()) 4842 && sri.activityInfo.applicationInfo.packageName.equals( 4843 comp.getPackageName())) 4844 || (action != null && sri.filter.matchAction(action))) { 4845 results.remove(j); 4846 if (DEBUG_INTENT_MATCHING) Log.v( 4847 TAG, "Removing duplicate item from " + j 4848 + " due to specific " + specificsPos); 4849 if (ri == null) { 4850 ri = sri; 4851 } 4852 j--; 4853 N--; 4854 } 4855 } 4856 4857 // Add this specific item to its proper place. 4858 if (ri == null) { 4859 ri = new ResolveInfo(); 4860 ri.activityInfo = ai; 4861 } 4862 results.add(specificsPos, ri); 4863 ri.specificIndex = i; 4864 specificsPos++; 4865 } 4866 } 4867 4868 // Now we go through the remaining generic results and remove any 4869 // duplicate actions that are found here. 4870 N = results.size(); 4871 for (int i=specificsPos; i<N-1; i++) { 4872 final ResolveInfo rii = results.get(i); 4873 if (rii.filter == null) { 4874 continue; 4875 } 4876 4877 // Iterate over all of the actions of this result's intent 4878 // filter... typically this should be just one. 4879 final Iterator<String> it = rii.filter.actionsIterator(); 4880 if (it == null) { 4881 continue; 4882 } 4883 while (it.hasNext()) { 4884 final String action = it.next(); 4885 if (resultsAction != null && resultsAction.equals(action)) { 4886 // If this action was explicitly requested, then don't 4887 // remove things that have it. 4888 continue; 4889 } 4890 for (int j=i+1; j<N; j++) { 4891 final ResolveInfo rij = results.get(j); 4892 if (rij.filter != null && rij.filter.hasAction(action)) { 4893 results.remove(j); 4894 if (DEBUG_INTENT_MATCHING) Log.v( 4895 TAG, "Removing duplicate item from " + j 4896 + " due to action " + action + " at " + i); 4897 j--; 4898 N--; 4899 } 4900 } 4901 } 4902 4903 // If the caller didn't request filter information, drop it now 4904 // so we don't have to marshall/unmarshall it. 4905 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4906 rii.filter = null; 4907 } 4908 } 4909 4910 // Filter out the caller activity if so requested. 4911 if (caller != null) { 4912 N = results.size(); 4913 for (int i=0; i<N; i++) { 4914 ActivityInfo ainfo = results.get(i).activityInfo; 4915 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4916 && caller.getClassName().equals(ainfo.name)) { 4917 results.remove(i); 4918 break; 4919 } 4920 } 4921 } 4922 4923 // If the caller didn't request filter information, 4924 // drop them now so we don't have to 4925 // marshall/unmarshall it. 4926 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4927 N = results.size(); 4928 for (int i=0; i<N; i++) { 4929 results.get(i).filter = null; 4930 } 4931 } 4932 4933 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4934 return results; 4935 } 4936 4937 @Override 4938 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4939 int userId) { 4940 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4941 ComponentName comp = intent.getComponent(); 4942 if (comp == null) { 4943 if (intent.getSelector() != null) { 4944 intent = intent.getSelector(); 4945 comp = intent.getComponent(); 4946 } 4947 } 4948 if (comp != null) { 4949 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4950 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4951 if (ai != null) { 4952 ResolveInfo ri = new ResolveInfo(); 4953 ri.activityInfo = ai; 4954 list.add(ri); 4955 } 4956 return list; 4957 } 4958 4959 // reader 4960 synchronized (mPackages) { 4961 String pkgName = intent.getPackage(); 4962 if (pkgName == null) { 4963 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4964 } 4965 final PackageParser.Package pkg = mPackages.get(pkgName); 4966 if (pkg != null) { 4967 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4968 userId); 4969 } 4970 return null; 4971 } 4972 } 4973 4974 @Override 4975 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4976 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4977 if (!sUserManager.exists(userId)) return null; 4978 if (query != null) { 4979 if (query.size() >= 1) { 4980 // If there is more than one service with the same priority, 4981 // just arbitrarily pick the first one. 4982 return query.get(0); 4983 } 4984 } 4985 return null; 4986 } 4987 4988 @Override 4989 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4990 int userId) { 4991 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4992 ComponentName comp = intent.getComponent(); 4993 if (comp == null) { 4994 if (intent.getSelector() != null) { 4995 intent = intent.getSelector(); 4996 comp = intent.getComponent(); 4997 } 4998 } 4999 if (comp != null) { 5000 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5001 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5002 if (si != null) { 5003 final ResolveInfo ri = new ResolveInfo(); 5004 ri.serviceInfo = si; 5005 list.add(ri); 5006 } 5007 return list; 5008 } 5009 5010 // reader 5011 synchronized (mPackages) { 5012 String pkgName = intent.getPackage(); 5013 if (pkgName == null) { 5014 return mServices.queryIntent(intent, resolvedType, flags, userId); 5015 } 5016 final PackageParser.Package pkg = mPackages.get(pkgName); 5017 if (pkg != null) { 5018 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5019 userId); 5020 } 5021 return null; 5022 } 5023 } 5024 5025 @Override 5026 public List<ResolveInfo> queryIntentContentProviders( 5027 Intent intent, String resolvedType, int flags, int userId) { 5028 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5029 ComponentName comp = intent.getComponent(); 5030 if (comp == null) { 5031 if (intent.getSelector() != null) { 5032 intent = intent.getSelector(); 5033 comp = intent.getComponent(); 5034 } 5035 } 5036 if (comp != null) { 5037 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5038 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5039 if (pi != null) { 5040 final ResolveInfo ri = new ResolveInfo(); 5041 ri.providerInfo = pi; 5042 list.add(ri); 5043 } 5044 return list; 5045 } 5046 5047 // reader 5048 synchronized (mPackages) { 5049 String pkgName = intent.getPackage(); 5050 if (pkgName == null) { 5051 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5052 } 5053 final PackageParser.Package pkg = mPackages.get(pkgName); 5054 if (pkg != null) { 5055 return mProviders.queryIntentForPackage( 5056 intent, resolvedType, flags, pkg.providers, userId); 5057 } 5058 return null; 5059 } 5060 } 5061 5062 @Override 5063 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5064 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5065 5066 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5067 5068 // writer 5069 synchronized (mPackages) { 5070 ArrayList<PackageInfo> list; 5071 if (listUninstalled) { 5072 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5073 for (PackageSetting ps : mSettings.mPackages.values()) { 5074 PackageInfo pi; 5075 if (ps.pkg != null) { 5076 pi = generatePackageInfo(ps.pkg, flags, userId); 5077 } else { 5078 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5079 } 5080 if (pi != null) { 5081 list.add(pi); 5082 } 5083 } 5084 } else { 5085 list = new ArrayList<PackageInfo>(mPackages.size()); 5086 for (PackageParser.Package p : mPackages.values()) { 5087 PackageInfo pi = generatePackageInfo(p, flags, userId); 5088 if (pi != null) { 5089 list.add(pi); 5090 } 5091 } 5092 } 5093 5094 return new ParceledListSlice<PackageInfo>(list); 5095 } 5096 } 5097 5098 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5099 String[] permissions, boolean[] tmp, int flags, int userId) { 5100 int numMatch = 0; 5101 final PermissionsState permissionsState = ps.getPermissionsState(); 5102 for (int i=0; i<permissions.length; i++) { 5103 final String permission = permissions[i]; 5104 if (permissionsState.hasPermission(permission, userId)) { 5105 tmp[i] = true; 5106 numMatch++; 5107 } else { 5108 tmp[i] = false; 5109 } 5110 } 5111 if (numMatch == 0) { 5112 return; 5113 } 5114 PackageInfo pi; 5115 if (ps.pkg != null) { 5116 pi = generatePackageInfo(ps.pkg, flags, userId); 5117 } else { 5118 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5119 } 5120 // The above might return null in cases of uninstalled apps or install-state 5121 // skew across users/profiles. 5122 if (pi != null) { 5123 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5124 if (numMatch == permissions.length) { 5125 pi.requestedPermissions = permissions; 5126 } else { 5127 pi.requestedPermissions = new String[numMatch]; 5128 numMatch = 0; 5129 for (int i=0; i<permissions.length; i++) { 5130 if (tmp[i]) { 5131 pi.requestedPermissions[numMatch] = permissions[i]; 5132 numMatch++; 5133 } 5134 } 5135 } 5136 } 5137 list.add(pi); 5138 } 5139 } 5140 5141 @Override 5142 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5143 String[] permissions, int flags, int userId) { 5144 if (!sUserManager.exists(userId)) return null; 5145 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5146 5147 // writer 5148 synchronized (mPackages) { 5149 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5150 boolean[] tmpBools = new boolean[permissions.length]; 5151 if (listUninstalled) { 5152 for (PackageSetting ps : mSettings.mPackages.values()) { 5153 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5154 } 5155 } else { 5156 for (PackageParser.Package pkg : mPackages.values()) { 5157 PackageSetting ps = (PackageSetting)pkg.mExtras; 5158 if (ps != null) { 5159 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5160 userId); 5161 } 5162 } 5163 } 5164 5165 return new ParceledListSlice<PackageInfo>(list); 5166 } 5167 } 5168 5169 @Override 5170 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5171 if (!sUserManager.exists(userId)) return null; 5172 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5173 5174 // writer 5175 synchronized (mPackages) { 5176 ArrayList<ApplicationInfo> list; 5177 if (listUninstalled) { 5178 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5179 for (PackageSetting ps : mSettings.mPackages.values()) { 5180 ApplicationInfo ai; 5181 if (ps.pkg != null) { 5182 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5183 ps.readUserState(userId), userId); 5184 } else { 5185 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5186 } 5187 if (ai != null) { 5188 list.add(ai); 5189 } 5190 } 5191 } else { 5192 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5193 for (PackageParser.Package p : mPackages.values()) { 5194 if (p.mExtras != null) { 5195 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5196 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5197 if (ai != null) { 5198 list.add(ai); 5199 } 5200 } 5201 } 5202 } 5203 5204 return new ParceledListSlice<ApplicationInfo>(list); 5205 } 5206 } 5207 5208 public List<ApplicationInfo> getPersistentApplications(int flags) { 5209 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5210 5211 // reader 5212 synchronized (mPackages) { 5213 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5214 final int userId = UserHandle.getCallingUserId(); 5215 while (i.hasNext()) { 5216 final PackageParser.Package p = i.next(); 5217 if (p.applicationInfo != null 5218 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5219 && (!mSafeMode || isSystemApp(p))) { 5220 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5221 if (ps != null) { 5222 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5223 ps.readUserState(userId), userId); 5224 if (ai != null) { 5225 finalList.add(ai); 5226 } 5227 } 5228 } 5229 } 5230 } 5231 5232 return finalList; 5233 } 5234 5235 @Override 5236 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5237 if (!sUserManager.exists(userId)) return null; 5238 // reader 5239 synchronized (mPackages) { 5240 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5241 PackageSetting ps = provider != null 5242 ? mSettings.mPackages.get(provider.owner.packageName) 5243 : null; 5244 return ps != null 5245 && mSettings.isEnabledLPr(provider.info, flags, userId) 5246 && (!mSafeMode || (provider.info.applicationInfo.flags 5247 &ApplicationInfo.FLAG_SYSTEM) != 0) 5248 ? PackageParser.generateProviderInfo(provider, flags, 5249 ps.readUserState(userId), userId) 5250 : null; 5251 } 5252 } 5253 5254 /** 5255 * @deprecated 5256 */ 5257 @Deprecated 5258 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5259 // reader 5260 synchronized (mPackages) { 5261 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5262 .entrySet().iterator(); 5263 final int userId = UserHandle.getCallingUserId(); 5264 while (i.hasNext()) { 5265 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5266 PackageParser.Provider p = entry.getValue(); 5267 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5268 5269 if (ps != null && p.syncable 5270 && (!mSafeMode || (p.info.applicationInfo.flags 5271 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5272 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5273 ps.readUserState(userId), userId); 5274 if (info != null) { 5275 outNames.add(entry.getKey()); 5276 outInfo.add(info); 5277 } 5278 } 5279 } 5280 } 5281 } 5282 5283 @Override 5284 public List<ProviderInfo> queryContentProviders(String processName, 5285 int uid, int flags) { 5286 ArrayList<ProviderInfo> finalList = null; 5287 // reader 5288 synchronized (mPackages) { 5289 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5290 final int userId = processName != null ? 5291 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5292 while (i.hasNext()) { 5293 final PackageParser.Provider p = i.next(); 5294 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5295 if (ps != null && p.info.authority != null 5296 && (processName == null 5297 || (p.info.processName.equals(processName) 5298 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5299 && mSettings.isEnabledLPr(p.info, flags, userId) 5300 && (!mSafeMode 5301 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5302 if (finalList == null) { 5303 finalList = new ArrayList<ProviderInfo>(3); 5304 } 5305 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5306 ps.readUserState(userId), userId); 5307 if (info != null) { 5308 finalList.add(info); 5309 } 5310 } 5311 } 5312 } 5313 5314 if (finalList != null) { 5315 Collections.sort(finalList, mProviderInitOrderSorter); 5316 } 5317 5318 return finalList; 5319 } 5320 5321 @Override 5322 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5323 int flags) { 5324 // reader 5325 synchronized (mPackages) { 5326 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5327 return PackageParser.generateInstrumentationInfo(i, flags); 5328 } 5329 } 5330 5331 @Override 5332 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5333 int flags) { 5334 ArrayList<InstrumentationInfo> finalList = 5335 new ArrayList<InstrumentationInfo>(); 5336 5337 // reader 5338 synchronized (mPackages) { 5339 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5340 while (i.hasNext()) { 5341 final PackageParser.Instrumentation p = i.next(); 5342 if (targetPackage == null 5343 || targetPackage.equals(p.info.targetPackage)) { 5344 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5345 flags); 5346 if (ii != null) { 5347 finalList.add(ii); 5348 } 5349 } 5350 } 5351 } 5352 5353 return finalList; 5354 } 5355 5356 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5357 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5358 if (overlays == null) { 5359 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5360 return; 5361 } 5362 for (PackageParser.Package opkg : overlays.values()) { 5363 // Not much to do if idmap fails: we already logged the error 5364 // and we certainly don't want to abort installation of pkg simply 5365 // because an overlay didn't fit properly. For these reasons, 5366 // ignore the return value of createIdmapForPackagePairLI. 5367 createIdmapForPackagePairLI(pkg, opkg); 5368 } 5369 } 5370 5371 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5372 PackageParser.Package opkg) { 5373 if (!opkg.mTrustedOverlay) { 5374 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5375 opkg.baseCodePath + ": overlay not trusted"); 5376 return false; 5377 } 5378 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5379 if (overlaySet == null) { 5380 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5381 opkg.baseCodePath + " but target package has no known overlays"); 5382 return false; 5383 } 5384 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5385 // TODO: generate idmap for split APKs 5386 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5387 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5388 + opkg.baseCodePath); 5389 return false; 5390 } 5391 PackageParser.Package[] overlayArray = 5392 overlaySet.values().toArray(new PackageParser.Package[0]); 5393 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5394 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5395 return p1.mOverlayPriority - p2.mOverlayPriority; 5396 } 5397 }; 5398 Arrays.sort(overlayArray, cmp); 5399 5400 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5401 int i = 0; 5402 for (PackageParser.Package p : overlayArray) { 5403 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5404 } 5405 return true; 5406 } 5407 5408 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5409 final File[] files = dir.listFiles(); 5410 if (ArrayUtils.isEmpty(files)) { 5411 Log.d(TAG, "No files in app dir " + dir); 5412 return; 5413 } 5414 5415 if (DEBUG_PACKAGE_SCANNING) { 5416 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5417 + " flags=0x" + Integer.toHexString(parseFlags)); 5418 } 5419 5420 for (File file : files) { 5421 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5422 && !PackageInstallerService.isStageName(file.getName()); 5423 if (!isPackage) { 5424 // Ignore entries which are not packages 5425 continue; 5426 } 5427 try { 5428 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5429 scanFlags, currentTime, null); 5430 } catch (PackageManagerException e) { 5431 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5432 5433 // Delete invalid userdata apps 5434 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5435 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5436 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5437 if (file.isDirectory()) { 5438 mInstaller.rmPackageDir(file.getAbsolutePath()); 5439 } else { 5440 file.delete(); 5441 } 5442 } 5443 } 5444 } 5445 } 5446 5447 private static File getSettingsProblemFile() { 5448 File dataDir = Environment.getDataDirectory(); 5449 File systemDir = new File(dataDir, "system"); 5450 File fname = new File(systemDir, "uiderrors.txt"); 5451 return fname; 5452 } 5453 5454 static void reportSettingsProblem(int priority, String msg) { 5455 logCriticalInfo(priority, msg); 5456 } 5457 5458 static void logCriticalInfo(int priority, String msg) { 5459 Slog.println(priority, TAG, msg); 5460 EventLogTags.writePmCriticalInfo(msg); 5461 try { 5462 File fname = getSettingsProblemFile(); 5463 FileOutputStream out = new FileOutputStream(fname, true); 5464 PrintWriter pw = new FastPrintWriter(out); 5465 SimpleDateFormat formatter = new SimpleDateFormat(); 5466 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5467 pw.println(dateString + ": " + msg); 5468 pw.close(); 5469 FileUtils.setPermissions( 5470 fname.toString(), 5471 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5472 -1, -1); 5473 } catch (java.io.IOException e) { 5474 } 5475 } 5476 5477 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5478 PackageParser.Package pkg, File srcFile, int parseFlags) 5479 throws PackageManagerException { 5480 if (ps != null 5481 && ps.codePath.equals(srcFile) 5482 && ps.timeStamp == srcFile.lastModified() 5483 && !isCompatSignatureUpdateNeeded(pkg) 5484 && !isRecoverSignatureUpdateNeeded(pkg)) { 5485 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5486 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5487 ArraySet<PublicKey> signingKs; 5488 synchronized (mPackages) { 5489 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5490 } 5491 if (ps.signatures.mSignatures != null 5492 && ps.signatures.mSignatures.length != 0 5493 && signingKs != null) { 5494 // Optimization: reuse the existing cached certificates 5495 // if the package appears to be unchanged. 5496 pkg.mSignatures = ps.signatures.mSignatures; 5497 pkg.mSigningKeys = signingKs; 5498 return; 5499 } 5500 5501 Slog.w(TAG, "PackageSetting for " + ps.name 5502 + " is missing signatures. Collecting certs again to recover them."); 5503 } else { 5504 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5505 } 5506 5507 try { 5508 pp.collectCertificates(pkg, parseFlags); 5509 pp.collectManifestDigest(pkg); 5510 } catch (PackageParserException e) { 5511 throw PackageManagerException.from(e); 5512 } 5513 } 5514 5515 /* 5516 * Scan a package and return the newly parsed package. 5517 * Returns null in case of errors and the error code is stored in mLastScanError 5518 */ 5519 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5520 long currentTime, UserHandle user) throws PackageManagerException { 5521 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5522 parseFlags |= mDefParseFlags; 5523 PackageParser pp = new PackageParser(); 5524 pp.setSeparateProcesses(mSeparateProcesses); 5525 pp.setOnlyCoreApps(mOnlyCore); 5526 pp.setDisplayMetrics(mMetrics); 5527 5528 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5529 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5530 } 5531 5532 final PackageParser.Package pkg; 5533 try { 5534 pkg = pp.parsePackage(scanFile, parseFlags); 5535 } catch (PackageParserException e) { 5536 throw PackageManagerException.from(e); 5537 } 5538 5539 PackageSetting ps = null; 5540 PackageSetting updatedPkg; 5541 // reader 5542 synchronized (mPackages) { 5543 // Look to see if we already know about this package. 5544 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5545 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5546 // This package has been renamed to its original name. Let's 5547 // use that. 5548 ps = mSettings.peekPackageLPr(oldName); 5549 } 5550 // If there was no original package, see one for the real package name. 5551 if (ps == null) { 5552 ps = mSettings.peekPackageLPr(pkg.packageName); 5553 } 5554 // Check to see if this package could be hiding/updating a system 5555 // package. Must look for it either under the original or real 5556 // package name depending on our state. 5557 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5558 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5559 } 5560 boolean updatedPkgBetter = false; 5561 // First check if this is a system package that may involve an update 5562 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5563 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5564 // it needs to drop FLAG_PRIVILEGED. 5565 if (locationIsPrivileged(scanFile)) { 5566 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5567 } else { 5568 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5569 } 5570 5571 if (ps != null && !ps.codePath.equals(scanFile)) { 5572 // The path has changed from what was last scanned... check the 5573 // version of the new path against what we have stored to determine 5574 // what to do. 5575 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5576 if (pkg.mVersionCode <= ps.versionCode) { 5577 // The system package has been updated and the code path does not match 5578 // Ignore entry. Skip it. 5579 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5580 + " ignored: updated version " + ps.versionCode 5581 + " better than this " + pkg.mVersionCode); 5582 if (!updatedPkg.codePath.equals(scanFile)) { 5583 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5584 + ps.name + " changing from " + updatedPkg.codePathString 5585 + " to " + scanFile); 5586 updatedPkg.codePath = scanFile; 5587 updatedPkg.codePathString = scanFile.toString(); 5588 updatedPkg.resourcePath = scanFile; 5589 updatedPkg.resourcePathString = scanFile.toString(); 5590 } 5591 updatedPkg.pkg = pkg; 5592 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5593 } else { 5594 // The current app on the system partition is better than 5595 // what we have updated to on the data partition; switch 5596 // back to the system partition version. 5597 // At this point, its safely assumed that package installation for 5598 // apps in system partition will go through. If not there won't be a working 5599 // version of the app 5600 // writer 5601 synchronized (mPackages) { 5602 // Just remove the loaded entries from package lists. 5603 mPackages.remove(ps.name); 5604 } 5605 5606 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5607 + " reverting from " + ps.codePathString 5608 + ": new version " + pkg.mVersionCode 5609 + " better than installed " + ps.versionCode); 5610 5611 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5612 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5613 synchronized (mInstallLock) { 5614 args.cleanUpResourcesLI(); 5615 } 5616 synchronized (mPackages) { 5617 mSettings.enableSystemPackageLPw(ps.name); 5618 } 5619 updatedPkgBetter = true; 5620 } 5621 } 5622 } 5623 5624 if (updatedPkg != null) { 5625 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5626 // initially 5627 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5628 5629 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5630 // flag set initially 5631 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5632 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5633 } 5634 } 5635 5636 // Verify certificates against what was last scanned 5637 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5638 5639 /* 5640 * A new system app appeared, but we already had a non-system one of the 5641 * same name installed earlier. 5642 */ 5643 boolean shouldHideSystemApp = false; 5644 if (updatedPkg == null && ps != null 5645 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5646 /* 5647 * Check to make sure the signatures match first. If they don't, 5648 * wipe the installed application and its data. 5649 */ 5650 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5651 != PackageManager.SIGNATURE_MATCH) { 5652 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5653 + " signatures don't match existing userdata copy; removing"); 5654 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5655 ps = null; 5656 } else { 5657 /* 5658 * If the newly-added system app is an older version than the 5659 * already installed version, hide it. It will be scanned later 5660 * and re-added like an update. 5661 */ 5662 if (pkg.mVersionCode <= ps.versionCode) { 5663 shouldHideSystemApp = true; 5664 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5665 + " but new version " + pkg.mVersionCode + " better than installed " 5666 + ps.versionCode + "; hiding system"); 5667 } else { 5668 /* 5669 * The newly found system app is a newer version that the 5670 * one previously installed. Simply remove the 5671 * already-installed application and replace it with our own 5672 * while keeping the application data. 5673 */ 5674 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5675 + " reverting from " + ps.codePathString + ": new version " 5676 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5677 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5678 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5679 synchronized (mInstallLock) { 5680 args.cleanUpResourcesLI(); 5681 } 5682 } 5683 } 5684 } 5685 5686 // The apk is forward locked (not public) if its code and resources 5687 // are kept in different files. (except for app in either system or 5688 // vendor path). 5689 // TODO grab this value from PackageSettings 5690 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5691 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5692 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5693 } 5694 } 5695 5696 // TODO: extend to support forward-locked splits 5697 String resourcePath = null; 5698 String baseResourcePath = null; 5699 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5700 if (ps != null && ps.resourcePathString != null) { 5701 resourcePath = ps.resourcePathString; 5702 baseResourcePath = ps.resourcePathString; 5703 } else { 5704 // Should not happen at all. Just log an error. 5705 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5706 } 5707 } else { 5708 resourcePath = pkg.codePath; 5709 baseResourcePath = pkg.baseCodePath; 5710 } 5711 5712 // Set application objects path explicitly. 5713 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5714 pkg.applicationInfo.setCodePath(pkg.codePath); 5715 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5716 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5717 pkg.applicationInfo.setResourcePath(resourcePath); 5718 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5719 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5720 5721 // Note that we invoke the following method only if we are about to unpack an application 5722 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5723 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5724 5725 /* 5726 * If the system app should be overridden by a previously installed 5727 * data, hide the system app now and let the /data/app scan pick it up 5728 * again. 5729 */ 5730 if (shouldHideSystemApp) { 5731 synchronized (mPackages) { 5732 /* 5733 * We have to grant systems permissions before we hide, because 5734 * grantPermissions will assume the package update is trying to 5735 * expand its permissions. 5736 */ 5737 grantPermissionsLPw(pkg, true, pkg.packageName); 5738 mSettings.disableSystemPackageLPw(pkg.packageName); 5739 } 5740 } 5741 5742 return scannedPkg; 5743 } 5744 5745 private static String fixProcessName(String defProcessName, 5746 String processName, int uid) { 5747 if (processName == null) { 5748 return defProcessName; 5749 } 5750 return processName; 5751 } 5752 5753 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5754 throws PackageManagerException { 5755 if (pkgSetting.signatures.mSignatures != null) { 5756 // Already existing package. Make sure signatures match 5757 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5758 == PackageManager.SIGNATURE_MATCH; 5759 if (!match) { 5760 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5761 == PackageManager.SIGNATURE_MATCH; 5762 } 5763 if (!match) { 5764 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5765 == PackageManager.SIGNATURE_MATCH; 5766 } 5767 if (!match) { 5768 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5769 + pkg.packageName + " signatures do not match the " 5770 + "previously installed version; ignoring!"); 5771 } 5772 } 5773 5774 // Check for shared user signatures 5775 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5776 // Already existing package. Make sure signatures match 5777 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5778 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5779 if (!match) { 5780 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5781 == PackageManager.SIGNATURE_MATCH; 5782 } 5783 if (!match) { 5784 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5785 == PackageManager.SIGNATURE_MATCH; 5786 } 5787 if (!match) { 5788 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5789 "Package " + pkg.packageName 5790 + " has no signatures that match those in shared user " 5791 + pkgSetting.sharedUser.name + "; ignoring!"); 5792 } 5793 } 5794 } 5795 5796 /** 5797 * Enforces that only the system UID or root's UID can call a method exposed 5798 * via Binder. 5799 * 5800 * @param message used as message if SecurityException is thrown 5801 * @throws SecurityException if the caller is not system or root 5802 */ 5803 private static final void enforceSystemOrRoot(String message) { 5804 final int uid = Binder.getCallingUid(); 5805 if (uid != Process.SYSTEM_UID && uid != 0) { 5806 throw new SecurityException(message); 5807 } 5808 } 5809 5810 @Override 5811 public void performBootDexOpt() { 5812 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5813 5814 // Before everything else, see whether we need to fstrim. 5815 try { 5816 IMountService ms = PackageHelper.getMountService(); 5817 if (ms != null) { 5818 final boolean isUpgrade = isUpgrade(); 5819 boolean doTrim = isUpgrade; 5820 if (doTrim) { 5821 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5822 } else { 5823 final long interval = android.provider.Settings.Global.getLong( 5824 mContext.getContentResolver(), 5825 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5826 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5827 if (interval > 0) { 5828 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5829 if (timeSinceLast > interval) { 5830 doTrim = true; 5831 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5832 + "; running immediately"); 5833 } 5834 } 5835 } 5836 if (doTrim) { 5837 if (!isFirstBoot()) { 5838 try { 5839 ActivityManagerNative.getDefault().showBootMessage( 5840 mContext.getResources().getString( 5841 R.string.android_upgrading_fstrim), true); 5842 } catch (RemoteException e) { 5843 } 5844 } 5845 ms.runMaintenance(); 5846 } 5847 } else { 5848 Slog.e(TAG, "Mount service unavailable!"); 5849 } 5850 } catch (RemoteException e) { 5851 // Can't happen; MountService is local 5852 } 5853 5854 final ArraySet<PackageParser.Package> pkgs; 5855 synchronized (mPackages) { 5856 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5857 } 5858 5859 if (pkgs != null) { 5860 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5861 // in case the device runs out of space. 5862 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5863 // Give priority to core apps. 5864 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5865 PackageParser.Package pkg = it.next(); 5866 if (pkg.coreApp) { 5867 if (DEBUG_DEXOPT) { 5868 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5869 } 5870 sortedPkgs.add(pkg); 5871 it.remove(); 5872 } 5873 } 5874 // Give priority to system apps that listen for pre boot complete. 5875 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5876 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5877 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5878 PackageParser.Package pkg = it.next(); 5879 if (pkgNames.contains(pkg.packageName)) { 5880 if (DEBUG_DEXOPT) { 5881 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5882 } 5883 sortedPkgs.add(pkg); 5884 it.remove(); 5885 } 5886 } 5887 // Give priority to system apps. 5888 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5889 PackageParser.Package pkg = it.next(); 5890 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5891 if (DEBUG_DEXOPT) { 5892 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5893 } 5894 sortedPkgs.add(pkg); 5895 it.remove(); 5896 } 5897 } 5898 // Give priority to updated system apps. 5899 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5900 PackageParser.Package pkg = it.next(); 5901 if (pkg.isUpdatedSystemApp()) { 5902 if (DEBUG_DEXOPT) { 5903 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5904 } 5905 sortedPkgs.add(pkg); 5906 it.remove(); 5907 } 5908 } 5909 // Give priority to apps that listen for boot complete. 5910 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5911 pkgNames = getPackageNamesForIntent(intent); 5912 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5913 PackageParser.Package pkg = it.next(); 5914 if (pkgNames.contains(pkg.packageName)) { 5915 if (DEBUG_DEXOPT) { 5916 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5917 } 5918 sortedPkgs.add(pkg); 5919 it.remove(); 5920 } 5921 } 5922 // Filter out packages that aren't recently used. 5923 filterRecentlyUsedApps(pkgs); 5924 // Add all remaining apps. 5925 for (PackageParser.Package pkg : pkgs) { 5926 if (DEBUG_DEXOPT) { 5927 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5928 } 5929 sortedPkgs.add(pkg); 5930 } 5931 5932 // If we want to be lazy, filter everything that wasn't recently used. 5933 if (mLazyDexOpt) { 5934 filterRecentlyUsedApps(sortedPkgs); 5935 } 5936 5937 int i = 0; 5938 int total = sortedPkgs.size(); 5939 File dataDir = Environment.getDataDirectory(); 5940 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5941 if (lowThreshold == 0) { 5942 throw new IllegalStateException("Invalid low memory threshold"); 5943 } 5944 for (PackageParser.Package pkg : sortedPkgs) { 5945 long usableSpace = dataDir.getUsableSpace(); 5946 if (usableSpace < lowThreshold) { 5947 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5948 break; 5949 } 5950 performBootDexOpt(pkg, ++i, total); 5951 } 5952 } 5953 } 5954 5955 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5956 // Filter out packages that aren't recently used. 5957 // 5958 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5959 // should do a full dexopt. 5960 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5961 int total = pkgs.size(); 5962 int skipped = 0; 5963 long now = System.currentTimeMillis(); 5964 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5965 PackageParser.Package pkg = i.next(); 5966 long then = pkg.mLastPackageUsageTimeInMills; 5967 if (then + mDexOptLRUThresholdInMills < now) { 5968 if (DEBUG_DEXOPT) { 5969 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5970 ((then == 0) ? "never" : new Date(then))); 5971 } 5972 i.remove(); 5973 skipped++; 5974 } 5975 } 5976 if (DEBUG_DEXOPT) { 5977 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5978 } 5979 } 5980 } 5981 5982 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5983 List<ResolveInfo> ris = null; 5984 try { 5985 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5986 intent, null, 0, UserHandle.USER_OWNER); 5987 } catch (RemoteException e) { 5988 } 5989 ArraySet<String> pkgNames = new ArraySet<String>(); 5990 if (ris != null) { 5991 for (ResolveInfo ri : ris) { 5992 pkgNames.add(ri.activityInfo.packageName); 5993 } 5994 } 5995 return pkgNames; 5996 } 5997 5998 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5999 if (DEBUG_DEXOPT) { 6000 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6001 } 6002 if (!isFirstBoot()) { 6003 try { 6004 ActivityManagerNative.getDefault().showBootMessage( 6005 mContext.getResources().getString(R.string.android_upgrading_apk, 6006 curr, total), true); 6007 } catch (RemoteException e) { 6008 } 6009 } 6010 PackageParser.Package p = pkg; 6011 synchronized (mInstallLock) { 6012 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6013 false /* force dex */, false /* defer */, true /* include dependencies */); 6014 } 6015 } 6016 6017 @Override 6018 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6019 return performDexOpt(packageName, instructionSet, false); 6020 } 6021 6022 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6023 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6024 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6025 if (!dexopt && !updateUsage) { 6026 // We aren't going to dexopt or update usage, so bail early. 6027 return false; 6028 } 6029 PackageParser.Package p; 6030 final String targetInstructionSet; 6031 synchronized (mPackages) { 6032 p = mPackages.get(packageName); 6033 if (p == null) { 6034 return false; 6035 } 6036 if (updateUsage) { 6037 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6038 } 6039 mPackageUsage.write(false); 6040 if (!dexopt) { 6041 // We aren't going to dexopt, so bail early. 6042 return false; 6043 } 6044 6045 targetInstructionSet = instructionSet != null ? instructionSet : 6046 getPrimaryInstructionSet(p.applicationInfo); 6047 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6048 return false; 6049 } 6050 } 6051 6052 synchronized (mInstallLock) { 6053 final String[] instructionSets = new String[] { targetInstructionSet }; 6054 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6055 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6056 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6057 } 6058 } 6059 6060 public ArraySet<String> getPackagesThatNeedDexOpt() { 6061 ArraySet<String> pkgs = null; 6062 synchronized (mPackages) { 6063 for (PackageParser.Package p : mPackages.values()) { 6064 if (DEBUG_DEXOPT) { 6065 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6066 } 6067 if (!p.mDexOptPerformed.isEmpty()) { 6068 continue; 6069 } 6070 if (pkgs == null) { 6071 pkgs = new ArraySet<String>(); 6072 } 6073 pkgs.add(p.packageName); 6074 } 6075 } 6076 return pkgs; 6077 } 6078 6079 public void shutdown() { 6080 mPackageUsage.write(true); 6081 } 6082 6083 @Override 6084 public void forceDexOpt(String packageName) { 6085 enforceSystemOrRoot("forceDexOpt"); 6086 6087 PackageParser.Package pkg; 6088 synchronized (mPackages) { 6089 pkg = mPackages.get(packageName); 6090 if (pkg == null) { 6091 throw new IllegalArgumentException("Missing package: " + packageName); 6092 } 6093 } 6094 6095 synchronized (mInstallLock) { 6096 final String[] instructionSets = new String[] { 6097 getPrimaryInstructionSet(pkg.applicationInfo) }; 6098 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6099 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6100 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6101 throw new IllegalStateException("Failed to dexopt: " + res); 6102 } 6103 } 6104 } 6105 6106 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6107 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6108 Slog.w(TAG, "Unable to update from " + oldPkg.name 6109 + " to " + newPkg.packageName 6110 + ": old package not in system partition"); 6111 return false; 6112 } else if (mPackages.get(oldPkg.name) != null) { 6113 Slog.w(TAG, "Unable to update from " + oldPkg.name 6114 + " to " + newPkg.packageName 6115 + ": old package still exists"); 6116 return false; 6117 } 6118 return true; 6119 } 6120 6121 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6122 int[] users = sUserManager.getUserIds(); 6123 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6124 if (res < 0) { 6125 return res; 6126 } 6127 for (int user : users) { 6128 if (user != 0) { 6129 res = mInstaller.createUserData(volumeUuid, packageName, 6130 UserHandle.getUid(user, uid), user, seinfo); 6131 if (res < 0) { 6132 return res; 6133 } 6134 } 6135 } 6136 return res; 6137 } 6138 6139 private int removeDataDirsLI(String volumeUuid, String packageName) { 6140 int[] users = sUserManager.getUserIds(); 6141 int res = 0; 6142 for (int user : users) { 6143 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6144 if (resInner < 0) { 6145 res = resInner; 6146 } 6147 } 6148 6149 return res; 6150 } 6151 6152 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6153 int[] users = sUserManager.getUserIds(); 6154 int res = 0; 6155 for (int user : users) { 6156 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6157 if (resInner < 0) { 6158 res = resInner; 6159 } 6160 } 6161 return res; 6162 } 6163 6164 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6165 PackageParser.Package changingLib) { 6166 if (file.path != null) { 6167 usesLibraryFiles.add(file.path); 6168 return; 6169 } 6170 PackageParser.Package p = mPackages.get(file.apk); 6171 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6172 // If we are doing this while in the middle of updating a library apk, 6173 // then we need to make sure to use that new apk for determining the 6174 // dependencies here. (We haven't yet finished committing the new apk 6175 // to the package manager state.) 6176 if (p == null || p.packageName.equals(changingLib.packageName)) { 6177 p = changingLib; 6178 } 6179 } 6180 if (p != null) { 6181 usesLibraryFiles.addAll(p.getAllCodePaths()); 6182 } 6183 } 6184 6185 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6186 PackageParser.Package changingLib) throws PackageManagerException { 6187 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6188 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6189 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6190 for (int i=0; i<N; i++) { 6191 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6192 if (file == null) { 6193 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6194 "Package " + pkg.packageName + " requires unavailable shared library " 6195 + pkg.usesLibraries.get(i) + "; failing!"); 6196 } 6197 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6198 } 6199 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6200 for (int i=0; i<N; i++) { 6201 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6202 if (file == null) { 6203 Slog.w(TAG, "Package " + pkg.packageName 6204 + " desires unavailable shared library " 6205 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6206 } else { 6207 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6208 } 6209 } 6210 N = usesLibraryFiles.size(); 6211 if (N > 0) { 6212 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6213 } else { 6214 pkg.usesLibraryFiles = null; 6215 } 6216 } 6217 } 6218 6219 private static boolean hasString(List<String> list, List<String> which) { 6220 if (list == null) { 6221 return false; 6222 } 6223 for (int i=list.size()-1; i>=0; i--) { 6224 for (int j=which.size()-1; j>=0; j--) { 6225 if (which.get(j).equals(list.get(i))) { 6226 return true; 6227 } 6228 } 6229 } 6230 return false; 6231 } 6232 6233 private void updateAllSharedLibrariesLPw() { 6234 for (PackageParser.Package pkg : mPackages.values()) { 6235 try { 6236 updateSharedLibrariesLPw(pkg, null); 6237 } catch (PackageManagerException e) { 6238 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6239 } 6240 } 6241 } 6242 6243 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6244 PackageParser.Package changingPkg) { 6245 ArrayList<PackageParser.Package> res = null; 6246 for (PackageParser.Package pkg : mPackages.values()) { 6247 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6248 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6249 if (res == null) { 6250 res = new ArrayList<PackageParser.Package>(); 6251 } 6252 res.add(pkg); 6253 try { 6254 updateSharedLibrariesLPw(pkg, changingPkg); 6255 } catch (PackageManagerException e) { 6256 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6257 } 6258 } 6259 } 6260 return res; 6261 } 6262 6263 /** 6264 * Derive the value of the {@code cpuAbiOverride} based on the provided 6265 * value and an optional stored value from the package settings. 6266 */ 6267 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6268 String cpuAbiOverride = null; 6269 6270 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6271 cpuAbiOverride = null; 6272 } else if (abiOverride != null) { 6273 cpuAbiOverride = abiOverride; 6274 } else if (settings != null) { 6275 cpuAbiOverride = settings.cpuAbiOverrideString; 6276 } 6277 6278 return cpuAbiOverride; 6279 } 6280 6281 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6282 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6283 boolean success = false; 6284 try { 6285 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6286 currentTime, user); 6287 success = true; 6288 return res; 6289 } finally { 6290 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6291 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6292 } 6293 } 6294 } 6295 6296 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6297 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6298 final File scanFile = new File(pkg.codePath); 6299 if (pkg.applicationInfo.getCodePath() == null || 6300 pkg.applicationInfo.getResourcePath() == null) { 6301 // Bail out. The resource and code paths haven't been set. 6302 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6303 "Code and resource paths haven't been set correctly"); 6304 } 6305 6306 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6307 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6308 } else { 6309 // Only allow system apps to be flagged as core apps. 6310 pkg.coreApp = false; 6311 } 6312 6313 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6314 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6315 } 6316 6317 if (mCustomResolverComponentName != null && 6318 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6319 setUpCustomResolverActivity(pkg); 6320 } 6321 6322 if (pkg.packageName.equals("android")) { 6323 synchronized (mPackages) { 6324 if (mAndroidApplication != null) { 6325 Slog.w(TAG, "*************************************************"); 6326 Slog.w(TAG, "Core android package being redefined. Skipping."); 6327 Slog.w(TAG, " file=" + scanFile); 6328 Slog.w(TAG, "*************************************************"); 6329 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6330 "Core android package being redefined. Skipping."); 6331 } 6332 6333 // Set up information for our fall-back user intent resolution activity. 6334 mPlatformPackage = pkg; 6335 pkg.mVersionCode = mSdkVersion; 6336 mAndroidApplication = pkg.applicationInfo; 6337 6338 if (!mResolverReplaced) { 6339 mResolveActivity.applicationInfo = mAndroidApplication; 6340 mResolveActivity.name = ResolverActivity.class.getName(); 6341 mResolveActivity.packageName = mAndroidApplication.packageName; 6342 mResolveActivity.processName = "system:ui"; 6343 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6344 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6345 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6346 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6347 mResolveActivity.exported = true; 6348 mResolveActivity.enabled = true; 6349 mResolveInfo.activityInfo = mResolveActivity; 6350 mResolveInfo.priority = 0; 6351 mResolveInfo.preferredOrder = 0; 6352 mResolveInfo.match = 0; 6353 mResolveComponentName = new ComponentName( 6354 mAndroidApplication.packageName, mResolveActivity.name); 6355 } 6356 } 6357 } 6358 6359 if (DEBUG_PACKAGE_SCANNING) { 6360 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6361 Log.d(TAG, "Scanning package " + pkg.packageName); 6362 } 6363 6364 if (mPackages.containsKey(pkg.packageName) 6365 || mSharedLibraries.containsKey(pkg.packageName)) { 6366 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6367 "Application package " + pkg.packageName 6368 + " already installed. Skipping duplicate."); 6369 } 6370 6371 // If we're only installing presumed-existing packages, require that the 6372 // scanned APK is both already known and at the path previously established 6373 // for it. Previously unknown packages we pick up normally, but if we have an 6374 // a priori expectation about this package's install presence, enforce it. 6375 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6376 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6377 if (known != null) { 6378 if (DEBUG_PACKAGE_SCANNING) { 6379 Log.d(TAG, "Examining " + pkg.codePath 6380 + " and requiring known paths " + known.codePathString 6381 + " & " + known.resourcePathString); 6382 } 6383 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6384 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6385 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6386 "Application package " + pkg.packageName 6387 + " found at " + pkg.applicationInfo.getCodePath() 6388 + " but expected at " + known.codePathString + "; ignoring."); 6389 } 6390 } 6391 } 6392 6393 // Initialize package source and resource directories 6394 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6395 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6396 6397 SharedUserSetting suid = null; 6398 PackageSetting pkgSetting = null; 6399 6400 if (!isSystemApp(pkg)) { 6401 // Only system apps can use these features. 6402 pkg.mOriginalPackages = null; 6403 pkg.mRealPackage = null; 6404 pkg.mAdoptPermissions = null; 6405 } 6406 6407 // writer 6408 synchronized (mPackages) { 6409 if (pkg.mSharedUserId != null) { 6410 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6411 if (suid == null) { 6412 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6413 "Creating application package " + pkg.packageName 6414 + " for shared user failed"); 6415 } 6416 if (DEBUG_PACKAGE_SCANNING) { 6417 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6418 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6419 + "): packages=" + suid.packages); 6420 } 6421 } 6422 6423 // Check if we are renaming from an original package name. 6424 PackageSetting origPackage = null; 6425 String realName = null; 6426 if (pkg.mOriginalPackages != null) { 6427 // This package may need to be renamed to a previously 6428 // installed name. Let's check on that... 6429 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6430 if (pkg.mOriginalPackages.contains(renamed)) { 6431 // This package had originally been installed as the 6432 // original name, and we have already taken care of 6433 // transitioning to the new one. Just update the new 6434 // one to continue using the old name. 6435 realName = pkg.mRealPackage; 6436 if (!pkg.packageName.equals(renamed)) { 6437 // Callers into this function may have already taken 6438 // care of renaming the package; only do it here if 6439 // it is not already done. 6440 pkg.setPackageName(renamed); 6441 } 6442 6443 } else { 6444 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6445 if ((origPackage = mSettings.peekPackageLPr( 6446 pkg.mOriginalPackages.get(i))) != null) { 6447 // We do have the package already installed under its 6448 // original name... should we use it? 6449 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6450 // New package is not compatible with original. 6451 origPackage = null; 6452 continue; 6453 } else if (origPackage.sharedUser != null) { 6454 // Make sure uid is compatible between packages. 6455 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6456 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6457 + " to " + pkg.packageName + ": old uid " 6458 + origPackage.sharedUser.name 6459 + " differs from " + pkg.mSharedUserId); 6460 origPackage = null; 6461 continue; 6462 } 6463 } else { 6464 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6465 + pkg.packageName + " to old name " + origPackage.name); 6466 } 6467 break; 6468 } 6469 } 6470 } 6471 } 6472 6473 if (mTransferedPackages.contains(pkg.packageName)) { 6474 Slog.w(TAG, "Package " + pkg.packageName 6475 + " was transferred to another, but its .apk remains"); 6476 } 6477 6478 // Just create the setting, don't add it yet. For already existing packages 6479 // the PkgSetting exists already and doesn't have to be created. 6480 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6481 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6482 pkg.applicationInfo.primaryCpuAbi, 6483 pkg.applicationInfo.secondaryCpuAbi, 6484 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6485 user, false); 6486 if (pkgSetting == null) { 6487 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6488 "Creating application package " + pkg.packageName + " failed"); 6489 } 6490 6491 if (pkgSetting.origPackage != null) { 6492 // If we are first transitioning from an original package, 6493 // fix up the new package's name now. We need to do this after 6494 // looking up the package under its new name, so getPackageLP 6495 // can take care of fiddling things correctly. 6496 pkg.setPackageName(origPackage.name); 6497 6498 // File a report about this. 6499 String msg = "New package " + pkgSetting.realName 6500 + " renamed to replace old package " + pkgSetting.name; 6501 reportSettingsProblem(Log.WARN, msg); 6502 6503 // Make a note of it. 6504 mTransferedPackages.add(origPackage.name); 6505 6506 // No longer need to retain this. 6507 pkgSetting.origPackage = null; 6508 } 6509 6510 if (realName != null) { 6511 // Make a note of it. 6512 mTransferedPackages.add(pkg.packageName); 6513 } 6514 6515 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6516 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6517 } 6518 6519 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6520 // Check all shared libraries and map to their actual file path. 6521 // We only do this here for apps not on a system dir, because those 6522 // are the only ones that can fail an install due to this. We 6523 // will take care of the system apps by updating all of their 6524 // library paths after the scan is done. 6525 updateSharedLibrariesLPw(pkg, null); 6526 } 6527 6528 if (mFoundPolicyFile) { 6529 SELinuxMMAC.assignSeinfoValue(pkg); 6530 } 6531 6532 pkg.applicationInfo.uid = pkgSetting.appId; 6533 pkg.mExtras = pkgSetting; 6534 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6535 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6536 // We just determined the app is signed correctly, so bring 6537 // over the latest parsed certs. 6538 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6539 } else { 6540 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6541 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6542 "Package " + pkg.packageName + " upgrade keys do not match the " 6543 + "previously installed version"); 6544 } else { 6545 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6546 String msg = "System package " + pkg.packageName 6547 + " signature changed; retaining data."; 6548 reportSettingsProblem(Log.WARN, msg); 6549 } 6550 } 6551 } else { 6552 try { 6553 verifySignaturesLP(pkgSetting, pkg); 6554 // We just determined the app is signed correctly, so bring 6555 // over the latest parsed certs. 6556 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6557 } catch (PackageManagerException e) { 6558 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6559 throw e; 6560 } 6561 // The signature has changed, but this package is in the system 6562 // image... let's recover! 6563 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6564 // However... if this package is part of a shared user, but it 6565 // doesn't match the signature of the shared user, let's fail. 6566 // What this means is that you can't change the signatures 6567 // associated with an overall shared user, which doesn't seem all 6568 // that unreasonable. 6569 if (pkgSetting.sharedUser != null) { 6570 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6571 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6572 throw new PackageManagerException( 6573 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6574 "Signature mismatch for shared user : " 6575 + pkgSetting.sharedUser); 6576 } 6577 } 6578 // File a report about this. 6579 String msg = "System package " + pkg.packageName 6580 + " signature changed; retaining data."; 6581 reportSettingsProblem(Log.WARN, msg); 6582 } 6583 } 6584 // Verify that this new package doesn't have any content providers 6585 // that conflict with existing packages. Only do this if the 6586 // package isn't already installed, since we don't want to break 6587 // things that are installed. 6588 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6589 final int N = pkg.providers.size(); 6590 int i; 6591 for (i=0; i<N; i++) { 6592 PackageParser.Provider p = pkg.providers.get(i); 6593 if (p.info.authority != null) { 6594 String names[] = p.info.authority.split(";"); 6595 for (int j = 0; j < names.length; j++) { 6596 if (mProvidersByAuthority.containsKey(names[j])) { 6597 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6598 final String otherPackageName = 6599 ((other != null && other.getComponentName() != null) ? 6600 other.getComponentName().getPackageName() : "?"); 6601 throw new PackageManagerException( 6602 INSTALL_FAILED_CONFLICTING_PROVIDER, 6603 "Can't install because provider name " + names[j] 6604 + " (in package " + pkg.applicationInfo.packageName 6605 + ") is already used by " + otherPackageName); 6606 } 6607 } 6608 } 6609 } 6610 } 6611 6612 if (pkg.mAdoptPermissions != null) { 6613 // This package wants to adopt ownership of permissions from 6614 // another package. 6615 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6616 final String origName = pkg.mAdoptPermissions.get(i); 6617 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6618 if (orig != null) { 6619 if (verifyPackageUpdateLPr(orig, pkg)) { 6620 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6621 + pkg.packageName); 6622 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6623 } 6624 } 6625 } 6626 } 6627 } 6628 6629 final String pkgName = pkg.packageName; 6630 6631 final long scanFileTime = scanFile.lastModified(); 6632 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6633 pkg.applicationInfo.processName = fixProcessName( 6634 pkg.applicationInfo.packageName, 6635 pkg.applicationInfo.processName, 6636 pkg.applicationInfo.uid); 6637 6638 File dataPath; 6639 if (mPlatformPackage == pkg) { 6640 // The system package is special. 6641 dataPath = new File(Environment.getDataDirectory(), "system"); 6642 6643 pkg.applicationInfo.dataDir = dataPath.getPath(); 6644 6645 } else { 6646 // This is a normal package, need to make its data directory. 6647 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6648 UserHandle.USER_OWNER, pkg.packageName); 6649 6650 boolean uidError = false; 6651 if (dataPath.exists()) { 6652 int currentUid = 0; 6653 try { 6654 StructStat stat = Os.stat(dataPath.getPath()); 6655 currentUid = stat.st_uid; 6656 } catch (ErrnoException e) { 6657 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6658 } 6659 6660 // If we have mismatched owners for the data path, we have a problem. 6661 if (currentUid != pkg.applicationInfo.uid) { 6662 boolean recovered = false; 6663 if (currentUid == 0) { 6664 // The directory somehow became owned by root. Wow. 6665 // This is probably because the system was stopped while 6666 // installd was in the middle of messing with its libs 6667 // directory. Ask installd to fix that. 6668 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6669 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6670 if (ret >= 0) { 6671 recovered = true; 6672 String msg = "Package " + pkg.packageName 6673 + " unexpectedly changed to uid 0; recovered to " + 6674 + pkg.applicationInfo.uid; 6675 reportSettingsProblem(Log.WARN, msg); 6676 } 6677 } 6678 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6679 || (scanFlags&SCAN_BOOTING) != 0)) { 6680 // If this is a system app, we can at least delete its 6681 // current data so the application will still work. 6682 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6683 if (ret >= 0) { 6684 // TODO: Kill the processes first 6685 // Old data gone! 6686 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6687 ? "System package " : "Third party package "; 6688 String msg = prefix + pkg.packageName 6689 + " has changed from uid: " 6690 + currentUid + " to " 6691 + pkg.applicationInfo.uid + "; old data erased"; 6692 reportSettingsProblem(Log.WARN, msg); 6693 recovered = true; 6694 6695 // And now re-install the app. 6696 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6697 pkg.applicationInfo.seinfo); 6698 if (ret == -1) { 6699 // Ack should not happen! 6700 msg = prefix + pkg.packageName 6701 + " could not have data directory re-created after delete."; 6702 reportSettingsProblem(Log.WARN, msg); 6703 throw new PackageManagerException( 6704 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6705 } 6706 } 6707 if (!recovered) { 6708 mHasSystemUidErrors = true; 6709 } 6710 } else if (!recovered) { 6711 // If we allow this install to proceed, we will be broken. 6712 // Abort, abort! 6713 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6714 "scanPackageLI"); 6715 } 6716 if (!recovered) { 6717 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6718 + pkg.applicationInfo.uid + "/fs_" 6719 + currentUid; 6720 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6721 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6722 String msg = "Package " + pkg.packageName 6723 + " has mismatched uid: " 6724 + currentUid + " on disk, " 6725 + pkg.applicationInfo.uid + " in settings"; 6726 // writer 6727 synchronized (mPackages) { 6728 mSettings.mReadMessages.append(msg); 6729 mSettings.mReadMessages.append('\n'); 6730 uidError = true; 6731 if (!pkgSetting.uidError) { 6732 reportSettingsProblem(Log.ERROR, msg); 6733 } 6734 } 6735 } 6736 } 6737 pkg.applicationInfo.dataDir = dataPath.getPath(); 6738 if (mShouldRestoreconData) { 6739 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6740 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6741 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6742 } 6743 } else { 6744 if (DEBUG_PACKAGE_SCANNING) { 6745 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6746 Log.v(TAG, "Want this data dir: " + dataPath); 6747 } 6748 //invoke installer to do the actual installation 6749 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6750 pkg.applicationInfo.seinfo); 6751 if (ret < 0) { 6752 // Error from installer 6753 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6754 "Unable to create data dirs [errorCode=" + ret + "]"); 6755 } 6756 6757 if (dataPath.exists()) { 6758 pkg.applicationInfo.dataDir = dataPath.getPath(); 6759 } else { 6760 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6761 pkg.applicationInfo.dataDir = null; 6762 } 6763 } 6764 6765 pkgSetting.uidError = uidError; 6766 } 6767 6768 final String path = scanFile.getPath(); 6769 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6770 6771 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6772 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6773 6774 // Some system apps still use directory structure for native libraries 6775 // in which case we might end up not detecting abi solely based on apk 6776 // structure. Try to detect abi based on directory structure. 6777 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6778 pkg.applicationInfo.primaryCpuAbi == null) { 6779 setBundledAppAbisAndRoots(pkg, pkgSetting); 6780 setNativeLibraryPaths(pkg); 6781 } 6782 6783 } else { 6784 if ((scanFlags & SCAN_MOVE) != 0) { 6785 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6786 // but we already have this packages package info in the PackageSetting. We just 6787 // use that and derive the native library path based on the new codepath. 6788 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6789 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6790 } 6791 6792 // Set native library paths again. For moves, the path will be updated based on the 6793 // ABIs we've determined above. For non-moves, the path will be updated based on the 6794 // ABIs we determined during compilation, but the path will depend on the final 6795 // package path (after the rename away from the stage path). 6796 setNativeLibraryPaths(pkg); 6797 } 6798 6799 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6800 final int[] userIds = sUserManager.getUserIds(); 6801 synchronized (mInstallLock) { 6802 // Make sure all user data directories are ready to roll; we're okay 6803 // if they already exist 6804 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6805 for (int userId : userIds) { 6806 if (userId != 0) { 6807 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6808 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6809 pkg.applicationInfo.seinfo); 6810 } 6811 } 6812 } 6813 6814 // Create a native library symlink only if we have native libraries 6815 // and if the native libraries are 32 bit libraries. We do not provide 6816 // this symlink for 64 bit libraries. 6817 if (pkg.applicationInfo.primaryCpuAbi != null && 6818 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6819 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6820 for (int userId : userIds) { 6821 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6822 nativeLibPath, userId) < 0) { 6823 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6824 "Failed linking native library dir (user=" + userId + ")"); 6825 } 6826 } 6827 } 6828 } 6829 6830 // This is a special case for the "system" package, where the ABI is 6831 // dictated by the zygote configuration (and init.rc). We should keep track 6832 // of this ABI so that we can deal with "normal" applications that run under 6833 // the same UID correctly. 6834 if (mPlatformPackage == pkg) { 6835 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6836 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6837 } 6838 6839 // If there's a mismatch between the abi-override in the package setting 6840 // and the abiOverride specified for the install. Warn about this because we 6841 // would've already compiled the app without taking the package setting into 6842 // account. 6843 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6844 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6845 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6846 " for package: " + pkg.packageName); 6847 } 6848 } 6849 6850 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6851 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6852 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6853 6854 // Copy the derived override back to the parsed package, so that we can 6855 // update the package settings accordingly. 6856 pkg.cpuAbiOverride = cpuAbiOverride; 6857 6858 if (DEBUG_ABI_SELECTION) { 6859 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6860 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6861 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6862 } 6863 6864 // Push the derived path down into PackageSettings so we know what to 6865 // clean up at uninstall time. 6866 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6867 6868 if (DEBUG_ABI_SELECTION) { 6869 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6870 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6871 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6872 } 6873 6874 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6875 // We don't do this here during boot because we can do it all 6876 // at once after scanning all existing packages. 6877 // 6878 // We also do this *before* we perform dexopt on this package, so that 6879 // we can avoid redundant dexopts, and also to make sure we've got the 6880 // code and package path correct. 6881 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6882 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6883 } 6884 6885 if ((scanFlags & SCAN_NO_DEX) == 0) { 6886 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6887 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6888 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6889 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6890 } 6891 } 6892 if (mFactoryTest && pkg.requestedPermissions.contains( 6893 android.Manifest.permission.FACTORY_TEST)) { 6894 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6895 } 6896 6897 ArrayList<PackageParser.Package> clientLibPkgs = null; 6898 6899 // writer 6900 synchronized (mPackages) { 6901 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6902 // Only system apps can add new shared libraries. 6903 if (pkg.libraryNames != null) { 6904 for (int i=0; i<pkg.libraryNames.size(); i++) { 6905 String name = pkg.libraryNames.get(i); 6906 boolean allowed = false; 6907 if (pkg.isUpdatedSystemApp()) { 6908 // New library entries can only be added through the 6909 // system image. This is important to get rid of a lot 6910 // of nasty edge cases: for example if we allowed a non- 6911 // system update of the app to add a library, then uninstalling 6912 // the update would make the library go away, and assumptions 6913 // we made such as through app install filtering would now 6914 // have allowed apps on the device which aren't compatible 6915 // with it. Better to just have the restriction here, be 6916 // conservative, and create many fewer cases that can negatively 6917 // impact the user experience. 6918 final PackageSetting sysPs = mSettings 6919 .getDisabledSystemPkgLPr(pkg.packageName); 6920 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6921 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6922 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6923 allowed = true; 6924 allowed = true; 6925 break; 6926 } 6927 } 6928 } 6929 } else { 6930 allowed = true; 6931 } 6932 if (allowed) { 6933 if (!mSharedLibraries.containsKey(name)) { 6934 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6935 } else if (!name.equals(pkg.packageName)) { 6936 Slog.w(TAG, "Package " + pkg.packageName + " library " 6937 + name + " already exists; skipping"); 6938 } 6939 } else { 6940 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6941 + name + " that is not declared on system image; skipping"); 6942 } 6943 } 6944 if ((scanFlags&SCAN_BOOTING) == 0) { 6945 // If we are not booting, we need to update any applications 6946 // that are clients of our shared library. If we are booting, 6947 // this will all be done once the scan is complete. 6948 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6949 } 6950 } 6951 } 6952 } 6953 6954 // We also need to dexopt any apps that are dependent on this library. Note that 6955 // if these fail, we should abort the install since installing the library will 6956 // result in some apps being broken. 6957 if (clientLibPkgs != null) { 6958 if ((scanFlags & SCAN_NO_DEX) == 0) { 6959 for (int i = 0; i < clientLibPkgs.size(); i++) { 6960 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6961 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6962 null /* instruction sets */, forceDex, 6963 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6964 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6965 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6966 "scanPackageLI failed to dexopt clientLibPkgs"); 6967 } 6968 } 6969 } 6970 } 6971 6972 // Also need to kill any apps that are dependent on the library. 6973 if (clientLibPkgs != null) { 6974 for (int i=0; i<clientLibPkgs.size(); i++) { 6975 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6976 killApplication(clientPkg.applicationInfo.packageName, 6977 clientPkg.applicationInfo.uid, "update lib"); 6978 } 6979 } 6980 6981 // Make sure we're not adding any bogus keyset info 6982 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6983 ksms.assertScannedPackageValid(pkg); 6984 6985 // writer 6986 synchronized (mPackages) { 6987 // We don't expect installation to fail beyond this point 6988 6989 // Add the new setting to mSettings 6990 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6991 // Add the new setting to mPackages 6992 mPackages.put(pkg.applicationInfo.packageName, pkg); 6993 // Make sure we don't accidentally delete its data. 6994 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6995 while (iter.hasNext()) { 6996 PackageCleanItem item = iter.next(); 6997 if (pkgName.equals(item.packageName)) { 6998 iter.remove(); 6999 } 7000 } 7001 7002 // Take care of first install / last update times. 7003 if (currentTime != 0) { 7004 if (pkgSetting.firstInstallTime == 0) { 7005 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7006 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7007 pkgSetting.lastUpdateTime = currentTime; 7008 } 7009 } else if (pkgSetting.firstInstallTime == 0) { 7010 // We need *something*. Take time time stamp of the file. 7011 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7012 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7013 if (scanFileTime != pkgSetting.timeStamp) { 7014 // A package on the system image has changed; consider this 7015 // to be an update. 7016 pkgSetting.lastUpdateTime = scanFileTime; 7017 } 7018 } 7019 7020 // Add the package's KeySets to the global KeySetManagerService 7021 ksms.addScannedPackageLPw(pkg); 7022 7023 int N = pkg.providers.size(); 7024 StringBuilder r = null; 7025 int i; 7026 for (i=0; i<N; i++) { 7027 PackageParser.Provider p = pkg.providers.get(i); 7028 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7029 p.info.processName, pkg.applicationInfo.uid); 7030 mProviders.addProvider(p); 7031 p.syncable = p.info.isSyncable; 7032 if (p.info.authority != null) { 7033 String names[] = p.info.authority.split(";"); 7034 p.info.authority = null; 7035 for (int j = 0; j < names.length; j++) { 7036 if (j == 1 && p.syncable) { 7037 // We only want the first authority for a provider to possibly be 7038 // syncable, so if we already added this provider using a different 7039 // authority clear the syncable flag. We copy the provider before 7040 // changing it because the mProviders object contains a reference 7041 // to a provider that we don't want to change. 7042 // Only do this for the second authority since the resulting provider 7043 // object can be the same for all future authorities for this provider. 7044 p = new PackageParser.Provider(p); 7045 p.syncable = false; 7046 } 7047 if (!mProvidersByAuthority.containsKey(names[j])) { 7048 mProvidersByAuthority.put(names[j], p); 7049 if (p.info.authority == null) { 7050 p.info.authority = names[j]; 7051 } else { 7052 p.info.authority = p.info.authority + ";" + names[j]; 7053 } 7054 if (DEBUG_PACKAGE_SCANNING) { 7055 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7056 Log.d(TAG, "Registered content provider: " + names[j] 7057 + ", className = " + p.info.name + ", isSyncable = " 7058 + p.info.isSyncable); 7059 } 7060 } else { 7061 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7062 Slog.w(TAG, "Skipping provider name " + names[j] + 7063 " (in package " + pkg.applicationInfo.packageName + 7064 "): name already used by " 7065 + ((other != null && other.getComponentName() != null) 7066 ? other.getComponentName().getPackageName() : "?")); 7067 } 7068 } 7069 } 7070 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7071 if (r == null) { 7072 r = new StringBuilder(256); 7073 } else { 7074 r.append(' '); 7075 } 7076 r.append(p.info.name); 7077 } 7078 } 7079 if (r != null) { 7080 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7081 } 7082 7083 N = pkg.services.size(); 7084 r = null; 7085 for (i=0; i<N; i++) { 7086 PackageParser.Service s = pkg.services.get(i); 7087 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7088 s.info.processName, pkg.applicationInfo.uid); 7089 mServices.addService(s); 7090 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7091 if (r == null) { 7092 r = new StringBuilder(256); 7093 } else { 7094 r.append(' '); 7095 } 7096 r.append(s.info.name); 7097 } 7098 } 7099 if (r != null) { 7100 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7101 } 7102 7103 N = pkg.receivers.size(); 7104 r = null; 7105 for (i=0; i<N; i++) { 7106 PackageParser.Activity a = pkg.receivers.get(i); 7107 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7108 a.info.processName, pkg.applicationInfo.uid); 7109 mReceivers.addActivity(a, "receiver"); 7110 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7111 if (r == null) { 7112 r = new StringBuilder(256); 7113 } else { 7114 r.append(' '); 7115 } 7116 r.append(a.info.name); 7117 } 7118 } 7119 if (r != null) { 7120 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7121 } 7122 7123 N = pkg.activities.size(); 7124 r = null; 7125 for (i=0; i<N; i++) { 7126 PackageParser.Activity a = pkg.activities.get(i); 7127 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7128 a.info.processName, pkg.applicationInfo.uid); 7129 mActivities.addActivity(a, "activity"); 7130 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7131 if (r == null) { 7132 r = new StringBuilder(256); 7133 } else { 7134 r.append(' '); 7135 } 7136 r.append(a.info.name); 7137 } 7138 } 7139 if (r != null) { 7140 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7141 } 7142 7143 N = pkg.permissionGroups.size(); 7144 r = null; 7145 for (i=0; i<N; i++) { 7146 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7147 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7148 if (cur == null) { 7149 mPermissionGroups.put(pg.info.name, pg); 7150 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7151 if (r == null) { 7152 r = new StringBuilder(256); 7153 } else { 7154 r.append(' '); 7155 } 7156 r.append(pg.info.name); 7157 } 7158 } else { 7159 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7160 + pg.info.packageName + " ignored: original from " 7161 + cur.info.packageName); 7162 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7163 if (r == null) { 7164 r = new StringBuilder(256); 7165 } else { 7166 r.append(' '); 7167 } 7168 r.append("DUP:"); 7169 r.append(pg.info.name); 7170 } 7171 } 7172 } 7173 if (r != null) { 7174 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7175 } 7176 7177 N = pkg.permissions.size(); 7178 r = null; 7179 for (i=0; i<N; i++) { 7180 PackageParser.Permission p = pkg.permissions.get(i); 7181 7182 // Now that permission groups have a special meaning, we ignore permission 7183 // groups for legacy apps to prevent unexpected behavior. In particular, 7184 // permissions for one app being granted to someone just becuase they happen 7185 // to be in a group defined by another app (before this had no implications). 7186 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7187 p.group = mPermissionGroups.get(p.info.group); 7188 // Warn for a permission in an unknown group. 7189 if (p.info.group != null && p.group == null) { 7190 Slog.w(TAG, "Permission " + p.info.name + " from package " 7191 + p.info.packageName + " in an unknown group " + p.info.group); 7192 } 7193 } 7194 7195 ArrayMap<String, BasePermission> permissionMap = 7196 p.tree ? mSettings.mPermissionTrees 7197 : mSettings.mPermissions; 7198 BasePermission bp = permissionMap.get(p.info.name); 7199 7200 // Allow system apps to redefine non-system permissions 7201 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7202 final boolean currentOwnerIsSystem = (bp.perm != null 7203 && isSystemApp(bp.perm.owner)); 7204 if (isSystemApp(p.owner)) { 7205 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7206 // It's a built-in permission and no owner, take ownership now 7207 bp.packageSetting = pkgSetting; 7208 bp.perm = p; 7209 bp.uid = pkg.applicationInfo.uid; 7210 bp.sourcePackage = p.info.packageName; 7211 } else if (!currentOwnerIsSystem) { 7212 String msg = "New decl " + p.owner + " of permission " 7213 + p.info.name + " is system; overriding " + bp.sourcePackage; 7214 reportSettingsProblem(Log.WARN, msg); 7215 bp = null; 7216 } 7217 } 7218 } 7219 7220 if (bp == null) { 7221 bp = new BasePermission(p.info.name, p.info.packageName, 7222 BasePermission.TYPE_NORMAL); 7223 permissionMap.put(p.info.name, bp); 7224 } 7225 7226 if (bp.perm == null) { 7227 if (bp.sourcePackage == null 7228 || bp.sourcePackage.equals(p.info.packageName)) { 7229 BasePermission tree = findPermissionTreeLP(p.info.name); 7230 if (tree == null 7231 || tree.sourcePackage.equals(p.info.packageName)) { 7232 bp.packageSetting = pkgSetting; 7233 bp.perm = p; 7234 bp.uid = pkg.applicationInfo.uid; 7235 bp.sourcePackage = p.info.packageName; 7236 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7237 if (r == null) { 7238 r = new StringBuilder(256); 7239 } else { 7240 r.append(' '); 7241 } 7242 r.append(p.info.name); 7243 } 7244 } else { 7245 Slog.w(TAG, "Permission " + p.info.name + " from package " 7246 + p.info.packageName + " ignored: base tree " 7247 + tree.name + " is from package " 7248 + tree.sourcePackage); 7249 } 7250 } else { 7251 Slog.w(TAG, "Permission " + p.info.name + " from package " 7252 + p.info.packageName + " ignored: original from " 7253 + bp.sourcePackage); 7254 } 7255 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7256 if (r == null) { 7257 r = new StringBuilder(256); 7258 } else { 7259 r.append(' '); 7260 } 7261 r.append("DUP:"); 7262 r.append(p.info.name); 7263 } 7264 if (bp.perm == p) { 7265 bp.protectionLevel = p.info.protectionLevel; 7266 } 7267 } 7268 7269 if (r != null) { 7270 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7271 } 7272 7273 N = pkg.instrumentation.size(); 7274 r = null; 7275 for (i=0; i<N; i++) { 7276 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7277 a.info.packageName = pkg.applicationInfo.packageName; 7278 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7279 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7280 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7281 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7282 a.info.dataDir = pkg.applicationInfo.dataDir; 7283 7284 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7285 // need other information about the application, like the ABI and what not ? 7286 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7287 mInstrumentation.put(a.getComponentName(), a); 7288 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7289 if (r == null) { 7290 r = new StringBuilder(256); 7291 } else { 7292 r.append(' '); 7293 } 7294 r.append(a.info.name); 7295 } 7296 } 7297 if (r != null) { 7298 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7299 } 7300 7301 if (pkg.protectedBroadcasts != null) { 7302 N = pkg.protectedBroadcasts.size(); 7303 for (i=0; i<N; i++) { 7304 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7305 } 7306 } 7307 7308 pkgSetting.setTimeStamp(scanFileTime); 7309 7310 // Create idmap files for pairs of (packages, overlay packages). 7311 // Note: "android", ie framework-res.apk, is handled by native layers. 7312 if (pkg.mOverlayTarget != null) { 7313 // This is an overlay package. 7314 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7315 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7316 mOverlays.put(pkg.mOverlayTarget, 7317 new ArrayMap<String, PackageParser.Package>()); 7318 } 7319 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7320 map.put(pkg.packageName, pkg); 7321 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7322 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7323 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7324 "scanPackageLI failed to createIdmap"); 7325 } 7326 } 7327 } else if (mOverlays.containsKey(pkg.packageName) && 7328 !pkg.packageName.equals("android")) { 7329 // This is a regular package, with one or more known overlay packages. 7330 createIdmapsForPackageLI(pkg); 7331 } 7332 } 7333 7334 return pkg; 7335 } 7336 7337 /** 7338 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7339 * is derived purely on the basis of the contents of {@code scanFile} and 7340 * {@code cpuAbiOverride}. 7341 * 7342 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7343 */ 7344 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7345 String cpuAbiOverride, boolean extractLibs) 7346 throws PackageManagerException { 7347 // TODO: We can probably be smarter about this stuff. For installed apps, 7348 // we can calculate this information at install time once and for all. For 7349 // system apps, we can probably assume that this information doesn't change 7350 // after the first boot scan. As things stand, we do lots of unnecessary work. 7351 7352 // Give ourselves some initial paths; we'll come back for another 7353 // pass once we've determined ABI below. 7354 setNativeLibraryPaths(pkg); 7355 7356 // We would never need to extract libs for forward-locked and external packages, 7357 // since the container service will do it for us. We shouldn't attempt to 7358 // extract libs from system app when it was not updated. 7359 if (pkg.isForwardLocked() || isExternal(pkg) || 7360 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7361 extractLibs = false; 7362 } 7363 7364 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7365 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7366 7367 NativeLibraryHelper.Handle handle = null; 7368 try { 7369 handle = NativeLibraryHelper.Handle.create(scanFile); 7370 // TODO(multiArch): This can be null for apps that didn't go through the 7371 // usual installation process. We can calculate it again, like we 7372 // do during install time. 7373 // 7374 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7375 // unnecessary. 7376 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7377 7378 // Null out the abis so that they can be recalculated. 7379 pkg.applicationInfo.primaryCpuAbi = null; 7380 pkg.applicationInfo.secondaryCpuAbi = null; 7381 if (isMultiArch(pkg.applicationInfo)) { 7382 // Warn if we've set an abiOverride for multi-lib packages.. 7383 // By definition, we need to copy both 32 and 64 bit libraries for 7384 // such packages. 7385 if (pkg.cpuAbiOverride != null 7386 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7387 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7388 } 7389 7390 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7391 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7392 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7393 if (extractLibs) { 7394 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7395 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7396 useIsaSpecificSubdirs); 7397 } else { 7398 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7399 } 7400 } 7401 7402 maybeThrowExceptionForMultiArchCopy( 7403 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7404 7405 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7406 if (extractLibs) { 7407 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7408 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7409 useIsaSpecificSubdirs); 7410 } else { 7411 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7412 } 7413 } 7414 7415 maybeThrowExceptionForMultiArchCopy( 7416 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7417 7418 if (abi64 >= 0) { 7419 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7420 } 7421 7422 if (abi32 >= 0) { 7423 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7424 if (abi64 >= 0) { 7425 pkg.applicationInfo.secondaryCpuAbi = abi; 7426 } else { 7427 pkg.applicationInfo.primaryCpuAbi = abi; 7428 } 7429 } 7430 } else { 7431 String[] abiList = (cpuAbiOverride != null) ? 7432 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7433 7434 // Enable gross and lame hacks for apps that are built with old 7435 // SDK tools. We must scan their APKs for renderscript bitcode and 7436 // not launch them if it's present. Don't bother checking on devices 7437 // that don't have 64 bit support. 7438 boolean needsRenderScriptOverride = false; 7439 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7440 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7441 abiList = Build.SUPPORTED_32_BIT_ABIS; 7442 needsRenderScriptOverride = true; 7443 } 7444 7445 final int copyRet; 7446 if (extractLibs) { 7447 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7448 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7449 } else { 7450 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7451 } 7452 7453 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7454 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7455 "Error unpackaging native libs for app, errorCode=" + copyRet); 7456 } 7457 7458 if (copyRet >= 0) { 7459 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7460 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7461 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7462 } else if (needsRenderScriptOverride) { 7463 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7464 } 7465 } 7466 } catch (IOException ioe) { 7467 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7468 } finally { 7469 IoUtils.closeQuietly(handle); 7470 } 7471 7472 // Now that we've calculated the ABIs and determined if it's an internal app, 7473 // we will go ahead and populate the nativeLibraryPath. 7474 setNativeLibraryPaths(pkg); 7475 } 7476 7477 /** 7478 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7479 * i.e, so that all packages can be run inside a single process if required. 7480 * 7481 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7482 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7483 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7484 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7485 * updating a package that belongs to a shared user. 7486 * 7487 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7488 * adds unnecessary complexity. 7489 */ 7490 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7491 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7492 String requiredInstructionSet = null; 7493 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7494 requiredInstructionSet = VMRuntime.getInstructionSet( 7495 scannedPackage.applicationInfo.primaryCpuAbi); 7496 } 7497 7498 PackageSetting requirer = null; 7499 for (PackageSetting ps : packagesForUser) { 7500 // If packagesForUser contains scannedPackage, we skip it. This will happen 7501 // when scannedPackage is an update of an existing package. Without this check, 7502 // we will never be able to change the ABI of any package belonging to a shared 7503 // user, even if it's compatible with other packages. 7504 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7505 if (ps.primaryCpuAbiString == null) { 7506 continue; 7507 } 7508 7509 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7510 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7511 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7512 // this but there's not much we can do. 7513 String errorMessage = "Instruction set mismatch, " 7514 + ((requirer == null) ? "[caller]" : requirer) 7515 + " requires " + requiredInstructionSet + " whereas " + ps 7516 + " requires " + instructionSet; 7517 Slog.w(TAG, errorMessage); 7518 } 7519 7520 if (requiredInstructionSet == null) { 7521 requiredInstructionSet = instructionSet; 7522 requirer = ps; 7523 } 7524 } 7525 } 7526 7527 if (requiredInstructionSet != null) { 7528 String adjustedAbi; 7529 if (requirer != null) { 7530 // requirer != null implies that either scannedPackage was null or that scannedPackage 7531 // did not require an ABI, in which case we have to adjust scannedPackage to match 7532 // the ABI of the set (which is the same as requirer's ABI) 7533 adjustedAbi = requirer.primaryCpuAbiString; 7534 if (scannedPackage != null) { 7535 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7536 } 7537 } else { 7538 // requirer == null implies that we're updating all ABIs in the set to 7539 // match scannedPackage. 7540 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7541 } 7542 7543 for (PackageSetting ps : packagesForUser) { 7544 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7545 if (ps.primaryCpuAbiString != null) { 7546 continue; 7547 } 7548 7549 ps.primaryCpuAbiString = adjustedAbi; 7550 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7551 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7552 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7553 7554 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7555 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7556 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7557 ps.primaryCpuAbiString = null; 7558 ps.pkg.applicationInfo.primaryCpuAbi = null; 7559 return; 7560 } else { 7561 mInstaller.rmdex(ps.codePathString, 7562 getDexCodeInstructionSet(getPreferredInstructionSet())); 7563 } 7564 } 7565 } 7566 } 7567 } 7568 } 7569 7570 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7571 synchronized (mPackages) { 7572 mResolverReplaced = true; 7573 // Set up information for custom user intent resolution activity. 7574 mResolveActivity.applicationInfo = pkg.applicationInfo; 7575 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7576 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7577 mResolveActivity.processName = pkg.applicationInfo.packageName; 7578 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7579 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7580 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7581 mResolveActivity.theme = 0; 7582 mResolveActivity.exported = true; 7583 mResolveActivity.enabled = true; 7584 mResolveInfo.activityInfo = mResolveActivity; 7585 mResolveInfo.priority = 0; 7586 mResolveInfo.preferredOrder = 0; 7587 mResolveInfo.match = 0; 7588 mResolveComponentName = mCustomResolverComponentName; 7589 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7590 mResolveComponentName); 7591 } 7592 } 7593 7594 private static String calculateBundledApkRoot(final String codePathString) { 7595 final File codePath = new File(codePathString); 7596 final File codeRoot; 7597 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7598 codeRoot = Environment.getRootDirectory(); 7599 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7600 codeRoot = Environment.getOemDirectory(); 7601 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7602 codeRoot = Environment.getVendorDirectory(); 7603 } else { 7604 // Unrecognized code path; take its top real segment as the apk root: 7605 // e.g. /something/app/blah.apk => /something 7606 try { 7607 File f = codePath.getCanonicalFile(); 7608 File parent = f.getParentFile(); // non-null because codePath is a file 7609 File tmp; 7610 while ((tmp = parent.getParentFile()) != null) { 7611 f = parent; 7612 parent = tmp; 7613 } 7614 codeRoot = f; 7615 Slog.w(TAG, "Unrecognized code path " 7616 + codePath + " - using " + codeRoot); 7617 } catch (IOException e) { 7618 // Can't canonicalize the code path -- shenanigans? 7619 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7620 return Environment.getRootDirectory().getPath(); 7621 } 7622 } 7623 return codeRoot.getPath(); 7624 } 7625 7626 /** 7627 * Derive and set the location of native libraries for the given package, 7628 * which varies depending on where and how the package was installed. 7629 */ 7630 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7631 final ApplicationInfo info = pkg.applicationInfo; 7632 final String codePath = pkg.codePath; 7633 final File codeFile = new File(codePath); 7634 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7635 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7636 7637 info.nativeLibraryRootDir = null; 7638 info.nativeLibraryRootRequiresIsa = false; 7639 info.nativeLibraryDir = null; 7640 info.secondaryNativeLibraryDir = null; 7641 7642 if (isApkFile(codeFile)) { 7643 // Monolithic install 7644 if (bundledApp) { 7645 // If "/system/lib64/apkname" exists, assume that is the per-package 7646 // native library directory to use; otherwise use "/system/lib/apkname". 7647 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7648 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7649 getPrimaryInstructionSet(info)); 7650 7651 // This is a bundled system app so choose the path based on the ABI. 7652 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7653 // is just the default path. 7654 final String apkName = deriveCodePathName(codePath); 7655 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7656 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7657 apkName).getAbsolutePath(); 7658 7659 if (info.secondaryCpuAbi != null) { 7660 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7661 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7662 secondaryLibDir, apkName).getAbsolutePath(); 7663 } 7664 } else if (asecApp) { 7665 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7666 .getAbsolutePath(); 7667 } else { 7668 final String apkName = deriveCodePathName(codePath); 7669 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7670 .getAbsolutePath(); 7671 } 7672 7673 info.nativeLibraryRootRequiresIsa = false; 7674 info.nativeLibraryDir = info.nativeLibraryRootDir; 7675 } else { 7676 // Cluster install 7677 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7678 info.nativeLibraryRootRequiresIsa = true; 7679 7680 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7681 getPrimaryInstructionSet(info)).getAbsolutePath(); 7682 7683 if (info.secondaryCpuAbi != null) { 7684 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7685 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7686 } 7687 } 7688 } 7689 7690 /** 7691 * Calculate the abis and roots for a bundled app. These can uniquely 7692 * be determined from the contents of the system partition, i.e whether 7693 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7694 * of this information, and instead assume that the system was built 7695 * sensibly. 7696 */ 7697 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7698 PackageSetting pkgSetting) { 7699 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7700 7701 // If "/system/lib64/apkname" exists, assume that is the per-package 7702 // native library directory to use; otherwise use "/system/lib/apkname". 7703 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7704 setBundledAppAbi(pkg, apkRoot, apkName); 7705 // pkgSetting might be null during rescan following uninstall of updates 7706 // to a bundled app, so accommodate that possibility. The settings in 7707 // that case will be established later from the parsed package. 7708 // 7709 // If the settings aren't null, sync them up with what we've just derived. 7710 // note that apkRoot isn't stored in the package settings. 7711 if (pkgSetting != null) { 7712 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7713 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7714 } 7715 } 7716 7717 /** 7718 * Deduces the ABI of a bundled app and sets the relevant fields on the 7719 * parsed pkg object. 7720 * 7721 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7722 * under which system libraries are installed. 7723 * @param apkName the name of the installed package. 7724 */ 7725 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7726 final File codeFile = new File(pkg.codePath); 7727 7728 final boolean has64BitLibs; 7729 final boolean has32BitLibs; 7730 if (isApkFile(codeFile)) { 7731 // Monolithic install 7732 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7733 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7734 } else { 7735 // Cluster install 7736 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7737 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7738 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7739 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7740 has64BitLibs = (new File(rootDir, isa)).exists(); 7741 } else { 7742 has64BitLibs = false; 7743 } 7744 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7745 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7746 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7747 has32BitLibs = (new File(rootDir, isa)).exists(); 7748 } else { 7749 has32BitLibs = false; 7750 } 7751 } 7752 7753 if (has64BitLibs && !has32BitLibs) { 7754 // The package has 64 bit libs, but not 32 bit libs. Its primary 7755 // ABI should be 64 bit. We can safely assume here that the bundled 7756 // native libraries correspond to the most preferred ABI in the list. 7757 7758 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7759 pkg.applicationInfo.secondaryCpuAbi = null; 7760 } else if (has32BitLibs && !has64BitLibs) { 7761 // The package has 32 bit libs but not 64 bit libs. Its primary 7762 // ABI should be 32 bit. 7763 7764 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7765 pkg.applicationInfo.secondaryCpuAbi = null; 7766 } else if (has32BitLibs && has64BitLibs) { 7767 // The application has both 64 and 32 bit bundled libraries. We check 7768 // here that the app declares multiArch support, and warn if it doesn't. 7769 // 7770 // We will be lenient here and record both ABIs. The primary will be the 7771 // ABI that's higher on the list, i.e, a device that's configured to prefer 7772 // 64 bit apps will see a 64 bit primary ABI, 7773 7774 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7775 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7776 } 7777 7778 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7779 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7780 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7781 } else { 7782 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7783 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7784 } 7785 } else { 7786 pkg.applicationInfo.primaryCpuAbi = null; 7787 pkg.applicationInfo.secondaryCpuAbi = null; 7788 } 7789 } 7790 7791 private void killApplication(String pkgName, int appId, String reason) { 7792 // Request the ActivityManager to kill the process(only for existing packages) 7793 // so that we do not end up in a confused state while the user is still using the older 7794 // version of the application while the new one gets installed. 7795 IActivityManager am = ActivityManagerNative.getDefault(); 7796 if (am != null) { 7797 try { 7798 am.killApplicationWithAppId(pkgName, appId, reason); 7799 } catch (RemoteException e) { 7800 } 7801 } 7802 } 7803 7804 void removePackageLI(PackageSetting ps, boolean chatty) { 7805 if (DEBUG_INSTALL) { 7806 if (chatty) 7807 Log.d(TAG, "Removing package " + ps.name); 7808 } 7809 7810 // writer 7811 synchronized (mPackages) { 7812 mPackages.remove(ps.name); 7813 final PackageParser.Package pkg = ps.pkg; 7814 if (pkg != null) { 7815 cleanPackageDataStructuresLILPw(pkg, chatty); 7816 } 7817 } 7818 } 7819 7820 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7821 if (DEBUG_INSTALL) { 7822 if (chatty) 7823 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7824 } 7825 7826 // writer 7827 synchronized (mPackages) { 7828 mPackages.remove(pkg.applicationInfo.packageName); 7829 cleanPackageDataStructuresLILPw(pkg, chatty); 7830 } 7831 } 7832 7833 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7834 int N = pkg.providers.size(); 7835 StringBuilder r = null; 7836 int i; 7837 for (i=0; i<N; i++) { 7838 PackageParser.Provider p = pkg.providers.get(i); 7839 mProviders.removeProvider(p); 7840 if (p.info.authority == null) { 7841 7842 /* There was another ContentProvider with this authority when 7843 * this app was installed so this authority is null, 7844 * Ignore it as we don't have to unregister the provider. 7845 */ 7846 continue; 7847 } 7848 String names[] = p.info.authority.split(";"); 7849 for (int j = 0; j < names.length; j++) { 7850 if (mProvidersByAuthority.get(names[j]) == p) { 7851 mProvidersByAuthority.remove(names[j]); 7852 if (DEBUG_REMOVE) { 7853 if (chatty) 7854 Log.d(TAG, "Unregistered content provider: " + names[j] 7855 + ", className = " + p.info.name + ", isSyncable = " 7856 + p.info.isSyncable); 7857 } 7858 } 7859 } 7860 if (DEBUG_REMOVE && chatty) { 7861 if (r == null) { 7862 r = new StringBuilder(256); 7863 } else { 7864 r.append(' '); 7865 } 7866 r.append(p.info.name); 7867 } 7868 } 7869 if (r != null) { 7870 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7871 } 7872 7873 N = pkg.services.size(); 7874 r = null; 7875 for (i=0; i<N; i++) { 7876 PackageParser.Service s = pkg.services.get(i); 7877 mServices.removeService(s); 7878 if (chatty) { 7879 if (r == null) { 7880 r = new StringBuilder(256); 7881 } else { 7882 r.append(' '); 7883 } 7884 r.append(s.info.name); 7885 } 7886 } 7887 if (r != null) { 7888 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7889 } 7890 7891 N = pkg.receivers.size(); 7892 r = null; 7893 for (i=0; i<N; i++) { 7894 PackageParser.Activity a = pkg.receivers.get(i); 7895 mReceivers.removeActivity(a, "receiver"); 7896 if (DEBUG_REMOVE && chatty) { 7897 if (r == null) { 7898 r = new StringBuilder(256); 7899 } else { 7900 r.append(' '); 7901 } 7902 r.append(a.info.name); 7903 } 7904 } 7905 if (r != null) { 7906 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7907 } 7908 7909 N = pkg.activities.size(); 7910 r = null; 7911 for (i=0; i<N; i++) { 7912 PackageParser.Activity a = pkg.activities.get(i); 7913 mActivities.removeActivity(a, "activity"); 7914 if (DEBUG_REMOVE && chatty) { 7915 if (r == null) { 7916 r = new StringBuilder(256); 7917 } else { 7918 r.append(' '); 7919 } 7920 r.append(a.info.name); 7921 } 7922 } 7923 if (r != null) { 7924 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7925 } 7926 7927 N = pkg.permissions.size(); 7928 r = null; 7929 for (i=0; i<N; i++) { 7930 PackageParser.Permission p = pkg.permissions.get(i); 7931 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7932 if (bp == null) { 7933 bp = mSettings.mPermissionTrees.get(p.info.name); 7934 } 7935 if (bp != null && bp.perm == p) { 7936 bp.perm = null; 7937 if (DEBUG_REMOVE && chatty) { 7938 if (r == null) { 7939 r = new StringBuilder(256); 7940 } else { 7941 r.append(' '); 7942 } 7943 r.append(p.info.name); 7944 } 7945 } 7946 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7947 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7948 if (appOpPerms != null) { 7949 appOpPerms.remove(pkg.packageName); 7950 } 7951 } 7952 } 7953 if (r != null) { 7954 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7955 } 7956 7957 N = pkg.requestedPermissions.size(); 7958 r = null; 7959 for (i=0; i<N; i++) { 7960 String perm = pkg.requestedPermissions.get(i); 7961 BasePermission bp = mSettings.mPermissions.get(perm); 7962 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7963 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7964 if (appOpPerms != null) { 7965 appOpPerms.remove(pkg.packageName); 7966 if (appOpPerms.isEmpty()) { 7967 mAppOpPermissionPackages.remove(perm); 7968 } 7969 } 7970 } 7971 } 7972 if (r != null) { 7973 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7974 } 7975 7976 N = pkg.instrumentation.size(); 7977 r = null; 7978 for (i=0; i<N; i++) { 7979 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7980 mInstrumentation.remove(a.getComponentName()); 7981 if (DEBUG_REMOVE && chatty) { 7982 if (r == null) { 7983 r = new StringBuilder(256); 7984 } else { 7985 r.append(' '); 7986 } 7987 r.append(a.info.name); 7988 } 7989 } 7990 if (r != null) { 7991 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7992 } 7993 7994 r = null; 7995 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7996 // Only system apps can hold shared libraries. 7997 if (pkg.libraryNames != null) { 7998 for (i=0; i<pkg.libraryNames.size(); i++) { 7999 String name = pkg.libraryNames.get(i); 8000 SharedLibraryEntry cur = mSharedLibraries.get(name); 8001 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8002 mSharedLibraries.remove(name); 8003 if (DEBUG_REMOVE && chatty) { 8004 if (r == null) { 8005 r = new StringBuilder(256); 8006 } else { 8007 r.append(' '); 8008 } 8009 r.append(name); 8010 } 8011 } 8012 } 8013 } 8014 } 8015 if (r != null) { 8016 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8017 } 8018 } 8019 8020 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8021 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8022 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8023 return true; 8024 } 8025 } 8026 return false; 8027 } 8028 8029 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8030 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8031 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8032 8033 private void updatePermissionsLPw(String changingPkg, 8034 PackageParser.Package pkgInfo, int flags) { 8035 // Make sure there are no dangling permission trees. 8036 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8037 while (it.hasNext()) { 8038 final BasePermission bp = it.next(); 8039 if (bp.packageSetting == null) { 8040 // We may not yet have parsed the package, so just see if 8041 // we still know about its settings. 8042 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8043 } 8044 if (bp.packageSetting == null) { 8045 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8046 + " from package " + bp.sourcePackage); 8047 it.remove(); 8048 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8049 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8050 Slog.i(TAG, "Removing old permission tree: " + bp.name 8051 + " from package " + bp.sourcePackage); 8052 flags |= UPDATE_PERMISSIONS_ALL; 8053 it.remove(); 8054 } 8055 } 8056 } 8057 8058 // Make sure all dynamic permissions have been assigned to a package, 8059 // and make sure there are no dangling permissions. 8060 it = mSettings.mPermissions.values().iterator(); 8061 while (it.hasNext()) { 8062 final BasePermission bp = it.next(); 8063 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8064 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8065 + bp.name + " pkg=" + bp.sourcePackage 8066 + " info=" + bp.pendingInfo); 8067 if (bp.packageSetting == null && bp.pendingInfo != null) { 8068 final BasePermission tree = findPermissionTreeLP(bp.name); 8069 if (tree != null && tree.perm != null) { 8070 bp.packageSetting = tree.packageSetting; 8071 bp.perm = new PackageParser.Permission(tree.perm.owner, 8072 new PermissionInfo(bp.pendingInfo)); 8073 bp.perm.info.packageName = tree.perm.info.packageName; 8074 bp.perm.info.name = bp.name; 8075 bp.uid = tree.uid; 8076 } 8077 } 8078 } 8079 if (bp.packageSetting == null) { 8080 // We may not yet have parsed the package, so just see if 8081 // we still know about its settings. 8082 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8083 } 8084 if (bp.packageSetting == null) { 8085 Slog.w(TAG, "Removing dangling permission: " + bp.name 8086 + " from package " + bp.sourcePackage); 8087 it.remove(); 8088 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8089 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8090 Slog.i(TAG, "Removing old permission: " + bp.name 8091 + " from package " + bp.sourcePackage); 8092 flags |= UPDATE_PERMISSIONS_ALL; 8093 it.remove(); 8094 } 8095 } 8096 } 8097 8098 // Now update the permissions for all packages, in particular 8099 // replace the granted permissions of the system packages. 8100 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8101 for (PackageParser.Package pkg : mPackages.values()) { 8102 if (pkg != pkgInfo) { 8103 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8104 changingPkg); 8105 } 8106 } 8107 } 8108 8109 if (pkgInfo != null) { 8110 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8111 } 8112 } 8113 8114 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8115 String packageOfInterest) { 8116 // IMPORTANT: There are two types of permissions: install and runtime. 8117 // Install time permissions are granted when the app is installed to 8118 // all device users and users added in the future. Runtime permissions 8119 // are granted at runtime explicitly to specific users. Normal and signature 8120 // protected permissions are install time permissions. Dangerous permissions 8121 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8122 // otherwise they are runtime permissions. This function does not manage 8123 // runtime permissions except for the case an app targeting Lollipop MR1 8124 // being upgraded to target a newer SDK, in which case dangerous permissions 8125 // are transformed from install time to runtime ones. 8126 8127 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8128 if (ps == null) { 8129 return; 8130 } 8131 8132 PermissionsState permissionsState = ps.getPermissionsState(); 8133 PermissionsState origPermissions = permissionsState; 8134 8135 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8136 8137 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8138 8139 boolean changedInstallPermission = false; 8140 8141 if (replace) { 8142 ps.installPermissionsFixed = false; 8143 if (!ps.isSharedUser()) { 8144 origPermissions = new PermissionsState(permissionsState); 8145 permissionsState.reset(); 8146 } 8147 } 8148 8149 permissionsState.setGlobalGids(mGlobalGids); 8150 8151 final int N = pkg.requestedPermissions.size(); 8152 for (int i=0; i<N; i++) { 8153 final String name = pkg.requestedPermissions.get(i); 8154 final BasePermission bp = mSettings.mPermissions.get(name); 8155 8156 if (DEBUG_INSTALL) { 8157 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8158 } 8159 8160 if (bp == null || bp.packageSetting == null) { 8161 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8162 Slog.w(TAG, "Unknown permission " + name 8163 + " in package " + pkg.packageName); 8164 } 8165 continue; 8166 } 8167 8168 final String perm = bp.name; 8169 boolean allowedSig = false; 8170 int grant = GRANT_DENIED; 8171 8172 // Keep track of app op permissions. 8173 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8174 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8175 if (pkgs == null) { 8176 pkgs = new ArraySet<>(); 8177 mAppOpPermissionPackages.put(bp.name, pkgs); 8178 } 8179 pkgs.add(pkg.packageName); 8180 } 8181 8182 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8183 switch (level) { 8184 case PermissionInfo.PROTECTION_NORMAL: { 8185 // For all apps normal permissions are install time ones. 8186 grant = GRANT_INSTALL; 8187 } break; 8188 8189 case PermissionInfo.PROTECTION_DANGEROUS: { 8190 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8191 // For legacy apps dangerous permissions are install time ones. 8192 grant = GRANT_INSTALL_LEGACY; 8193 } else if (origPermissions.hasInstallPermission(bp.name)) { 8194 // For legacy apps that became modern, install becomes runtime. 8195 grant = GRANT_UPGRADE; 8196 } else { 8197 // For modern apps keep runtime permissions unchanged. 8198 grant = GRANT_RUNTIME; 8199 } 8200 } break; 8201 8202 case PermissionInfo.PROTECTION_SIGNATURE: { 8203 // For all apps signature permissions are install time ones. 8204 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8205 if (allowedSig) { 8206 grant = GRANT_INSTALL; 8207 } 8208 } break; 8209 } 8210 8211 if (DEBUG_INSTALL) { 8212 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8213 } 8214 8215 if (grant != GRANT_DENIED) { 8216 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8217 // If this is an existing, non-system package, then 8218 // we can't add any new permissions to it. 8219 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8220 // Except... if this is a permission that was added 8221 // to the platform (note: need to only do this when 8222 // updating the platform). 8223 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8224 grant = GRANT_DENIED; 8225 } 8226 } 8227 } 8228 8229 switch (grant) { 8230 case GRANT_INSTALL: { 8231 // Revoke this as runtime permission to handle the case of 8232 // a runtime permission being downgraded to an install one. 8233 for (int userId : UserManagerService.getInstance().getUserIds()) { 8234 if (origPermissions.getRuntimePermissionState( 8235 bp.name, userId) != null) { 8236 // Revoke the runtime permission and clear the flags. 8237 origPermissions.revokeRuntimePermission(bp, userId); 8238 origPermissions.updatePermissionFlags(bp, userId, 8239 PackageManager.MASK_PERMISSION_FLAGS, 0); 8240 // If we revoked a permission permission, we have to write. 8241 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8242 changedRuntimePermissionUserIds, userId); 8243 } 8244 } 8245 // Grant an install permission. 8246 if (permissionsState.grantInstallPermission(bp) != 8247 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8248 changedInstallPermission = true; 8249 } 8250 } break; 8251 8252 case GRANT_INSTALL_LEGACY: { 8253 // Grant an install permission. 8254 if (permissionsState.grantInstallPermission(bp) != 8255 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8256 changedInstallPermission = true; 8257 } 8258 } break; 8259 8260 case GRANT_RUNTIME: { 8261 // Grant previously granted runtime permissions. 8262 for (int userId : UserManagerService.getInstance().getUserIds()) { 8263 PermissionState permissionState = origPermissions 8264 .getRuntimePermissionState(bp.name, userId); 8265 final int flags = permissionState != null 8266 ? permissionState.getFlags() : 0; 8267 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8268 if (permissionsState.grantRuntimePermission(bp, userId) == 8269 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8270 // If we cannot put the permission as it was, we have to write. 8271 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8272 changedRuntimePermissionUserIds, userId); 8273 } 8274 } 8275 // Propagate the permission flags. 8276 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8277 } 8278 } break; 8279 8280 case GRANT_UPGRADE: { 8281 // Grant runtime permissions for a previously held install permission. 8282 PermissionState permissionState = origPermissions 8283 .getInstallPermissionState(bp.name); 8284 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8285 8286 if (origPermissions.revokeInstallPermission(bp) 8287 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8288 // We will be transferring the permission flags, so clear them. 8289 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8290 PackageManager.MASK_PERMISSION_FLAGS, 0); 8291 changedInstallPermission = true; 8292 } 8293 8294 // If the permission is not to be promoted to runtime we ignore it and 8295 // also its other flags as they are not applicable to install permissions. 8296 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8297 for (int userId : currentUserIds) { 8298 if (permissionsState.grantRuntimePermission(bp, userId) != 8299 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8300 // Transfer the permission flags. 8301 permissionsState.updatePermissionFlags(bp, userId, 8302 flags, flags); 8303 // If we granted the permission, we have to write. 8304 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8305 changedRuntimePermissionUserIds, userId); 8306 } 8307 } 8308 } 8309 } break; 8310 8311 default: { 8312 if (packageOfInterest == null 8313 || packageOfInterest.equals(pkg.packageName)) { 8314 Slog.w(TAG, "Not granting permission " + perm 8315 + " to package " + pkg.packageName 8316 + " because it was previously installed without"); 8317 } 8318 } break; 8319 } 8320 } else { 8321 if (permissionsState.revokeInstallPermission(bp) != 8322 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8323 // Also drop the permission flags. 8324 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8325 PackageManager.MASK_PERMISSION_FLAGS, 0); 8326 changedInstallPermission = true; 8327 Slog.i(TAG, "Un-granting permission " + perm 8328 + " from package " + pkg.packageName 8329 + " (protectionLevel=" + bp.protectionLevel 8330 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8331 + ")"); 8332 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8333 // Don't print warning for app op permissions, since it is fine for them 8334 // not to be granted, there is a UI for the user to decide. 8335 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8336 Slog.w(TAG, "Not granting permission " + perm 8337 + " to package " + pkg.packageName 8338 + " (protectionLevel=" + bp.protectionLevel 8339 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8340 + ")"); 8341 } 8342 } 8343 } 8344 } 8345 8346 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8347 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8348 // This is the first that we have heard about this package, so the 8349 // permissions we have now selected are fixed until explicitly 8350 // changed. 8351 ps.installPermissionsFixed = true; 8352 } 8353 8354 // Persist the runtime permissions state for users with changes. 8355 for (int userId : changedRuntimePermissionUserIds) { 8356 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8357 } 8358 } 8359 8360 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8361 boolean allowed = false; 8362 final int NP = PackageParser.NEW_PERMISSIONS.length; 8363 for (int ip=0; ip<NP; ip++) { 8364 final PackageParser.NewPermissionInfo npi 8365 = PackageParser.NEW_PERMISSIONS[ip]; 8366 if (npi.name.equals(perm) 8367 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8368 allowed = true; 8369 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8370 + pkg.packageName); 8371 break; 8372 } 8373 } 8374 return allowed; 8375 } 8376 8377 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8378 BasePermission bp, PermissionsState origPermissions) { 8379 boolean allowed; 8380 allowed = (compareSignatures( 8381 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8382 == PackageManager.SIGNATURE_MATCH) 8383 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8384 == PackageManager.SIGNATURE_MATCH); 8385 if (!allowed && (bp.protectionLevel 8386 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8387 if (isSystemApp(pkg)) { 8388 // For updated system applications, a system permission 8389 // is granted only if it had been defined by the original application. 8390 if (pkg.isUpdatedSystemApp()) { 8391 final PackageSetting sysPs = mSettings 8392 .getDisabledSystemPkgLPr(pkg.packageName); 8393 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8394 // If the original was granted this permission, we take 8395 // that grant decision as read and propagate it to the 8396 // update. 8397 if (sysPs.isPrivileged()) { 8398 allowed = true; 8399 } 8400 } else { 8401 // The system apk may have been updated with an older 8402 // version of the one on the data partition, but which 8403 // granted a new system permission that it didn't have 8404 // before. In this case we do want to allow the app to 8405 // now get the new permission if the ancestral apk is 8406 // privileged to get it. 8407 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8408 for (int j=0; 8409 j<sysPs.pkg.requestedPermissions.size(); j++) { 8410 if (perm.equals( 8411 sysPs.pkg.requestedPermissions.get(j))) { 8412 allowed = true; 8413 break; 8414 } 8415 } 8416 } 8417 } 8418 } else { 8419 allowed = isPrivilegedApp(pkg); 8420 } 8421 } 8422 } 8423 if (!allowed && (bp.protectionLevel 8424 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8425 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8426 // If this was a previously normal/dangerous permission that got moved 8427 // to a system permission as part of the runtime permission redesign, then 8428 // we still want to blindly grant it to old apps. 8429 allowed = true; 8430 } 8431 if (!allowed && (bp.protectionLevel 8432 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8433 // For development permissions, a development permission 8434 // is granted only if it was already granted. 8435 allowed = origPermissions.hasInstallPermission(perm); 8436 } 8437 return allowed; 8438 } 8439 8440 final class ActivityIntentResolver 8441 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8442 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8443 boolean defaultOnly, int userId) { 8444 if (!sUserManager.exists(userId)) return null; 8445 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8446 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8447 } 8448 8449 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8450 int userId) { 8451 if (!sUserManager.exists(userId)) return null; 8452 mFlags = flags; 8453 return super.queryIntent(intent, resolvedType, 8454 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8455 } 8456 8457 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8458 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8459 if (!sUserManager.exists(userId)) return null; 8460 if (packageActivities == null) { 8461 return null; 8462 } 8463 mFlags = flags; 8464 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8465 final int N = packageActivities.size(); 8466 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8467 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8468 8469 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8470 for (int i = 0; i < N; ++i) { 8471 intentFilters = packageActivities.get(i).intents; 8472 if (intentFilters != null && intentFilters.size() > 0) { 8473 PackageParser.ActivityIntentInfo[] array = 8474 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8475 intentFilters.toArray(array); 8476 listCut.add(array); 8477 } 8478 } 8479 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8480 } 8481 8482 public final void addActivity(PackageParser.Activity a, String type) { 8483 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8484 mActivities.put(a.getComponentName(), a); 8485 if (DEBUG_SHOW_INFO) 8486 Log.v( 8487 TAG, " " + type + " " + 8488 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8489 if (DEBUG_SHOW_INFO) 8490 Log.v(TAG, " Class=" + a.info.name); 8491 final int NI = a.intents.size(); 8492 for (int j=0; j<NI; j++) { 8493 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8494 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8495 intent.setPriority(0); 8496 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8497 + a.className + " with priority > 0, forcing to 0"); 8498 } 8499 if (DEBUG_SHOW_INFO) { 8500 Log.v(TAG, " IntentFilter:"); 8501 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8502 } 8503 if (!intent.debugCheck()) { 8504 Log.w(TAG, "==> For Activity " + a.info.name); 8505 } 8506 addFilter(intent); 8507 } 8508 } 8509 8510 public final void removeActivity(PackageParser.Activity a, String type) { 8511 mActivities.remove(a.getComponentName()); 8512 if (DEBUG_SHOW_INFO) { 8513 Log.v(TAG, " " + type + " " 8514 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8515 : a.info.name) + ":"); 8516 Log.v(TAG, " Class=" + a.info.name); 8517 } 8518 final int NI = a.intents.size(); 8519 for (int j=0; j<NI; j++) { 8520 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8521 if (DEBUG_SHOW_INFO) { 8522 Log.v(TAG, " IntentFilter:"); 8523 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8524 } 8525 removeFilter(intent); 8526 } 8527 } 8528 8529 @Override 8530 protected boolean allowFilterResult( 8531 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8532 ActivityInfo filterAi = filter.activity.info; 8533 for (int i=dest.size()-1; i>=0; i--) { 8534 ActivityInfo destAi = dest.get(i).activityInfo; 8535 if (destAi.name == filterAi.name 8536 && destAi.packageName == filterAi.packageName) { 8537 return false; 8538 } 8539 } 8540 return true; 8541 } 8542 8543 @Override 8544 protected ActivityIntentInfo[] newArray(int size) { 8545 return new ActivityIntentInfo[size]; 8546 } 8547 8548 @Override 8549 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8550 if (!sUserManager.exists(userId)) return true; 8551 PackageParser.Package p = filter.activity.owner; 8552 if (p != null) { 8553 PackageSetting ps = (PackageSetting)p.mExtras; 8554 if (ps != null) { 8555 // System apps are never considered stopped for purposes of 8556 // filtering, because there may be no way for the user to 8557 // actually re-launch them. 8558 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8559 && ps.getStopped(userId); 8560 } 8561 } 8562 return false; 8563 } 8564 8565 @Override 8566 protected boolean isPackageForFilter(String packageName, 8567 PackageParser.ActivityIntentInfo info) { 8568 return packageName.equals(info.activity.owner.packageName); 8569 } 8570 8571 @Override 8572 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8573 int match, int userId) { 8574 if (!sUserManager.exists(userId)) return null; 8575 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8576 return null; 8577 } 8578 final PackageParser.Activity activity = info.activity; 8579 if (mSafeMode && (activity.info.applicationInfo.flags 8580 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8581 return null; 8582 } 8583 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8584 if (ps == null) { 8585 return null; 8586 } 8587 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8588 ps.readUserState(userId), userId); 8589 if (ai == null) { 8590 return null; 8591 } 8592 final ResolveInfo res = new ResolveInfo(); 8593 res.activityInfo = ai; 8594 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8595 res.filter = info; 8596 } 8597 if (info != null) { 8598 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8599 } 8600 res.priority = info.getPriority(); 8601 res.preferredOrder = activity.owner.mPreferredOrder; 8602 //System.out.println("Result: " + res.activityInfo.className + 8603 // " = " + res.priority); 8604 res.match = match; 8605 res.isDefault = info.hasDefault; 8606 res.labelRes = info.labelRes; 8607 res.nonLocalizedLabel = info.nonLocalizedLabel; 8608 if (userNeedsBadging(userId)) { 8609 res.noResourceId = true; 8610 } else { 8611 res.icon = info.icon; 8612 } 8613 res.iconResourceId = info.icon; 8614 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8615 return res; 8616 } 8617 8618 @Override 8619 protected void sortResults(List<ResolveInfo> results) { 8620 Collections.sort(results, mResolvePrioritySorter); 8621 } 8622 8623 @Override 8624 protected void dumpFilter(PrintWriter out, String prefix, 8625 PackageParser.ActivityIntentInfo filter) { 8626 out.print(prefix); out.print( 8627 Integer.toHexString(System.identityHashCode(filter.activity))); 8628 out.print(' '); 8629 filter.activity.printComponentShortName(out); 8630 out.print(" filter "); 8631 out.println(Integer.toHexString(System.identityHashCode(filter))); 8632 } 8633 8634 @Override 8635 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8636 return filter.activity; 8637 } 8638 8639 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8640 PackageParser.Activity activity = (PackageParser.Activity)label; 8641 out.print(prefix); out.print( 8642 Integer.toHexString(System.identityHashCode(activity))); 8643 out.print(' '); 8644 activity.printComponentShortName(out); 8645 if (count > 1) { 8646 out.print(" ("); out.print(count); out.print(" filters)"); 8647 } 8648 out.println(); 8649 } 8650 8651// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8652// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8653// final List<ResolveInfo> retList = Lists.newArrayList(); 8654// while (i.hasNext()) { 8655// final ResolveInfo resolveInfo = i.next(); 8656// if (isEnabledLP(resolveInfo.activityInfo)) { 8657// retList.add(resolveInfo); 8658// } 8659// } 8660// return retList; 8661// } 8662 8663 // Keys are String (activity class name), values are Activity. 8664 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8665 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8666 private int mFlags; 8667 } 8668 8669 private final class ServiceIntentResolver 8670 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8671 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8672 boolean defaultOnly, int userId) { 8673 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8674 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8675 } 8676 8677 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8678 int userId) { 8679 if (!sUserManager.exists(userId)) return null; 8680 mFlags = flags; 8681 return super.queryIntent(intent, resolvedType, 8682 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8683 } 8684 8685 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8686 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8687 if (!sUserManager.exists(userId)) return null; 8688 if (packageServices == null) { 8689 return null; 8690 } 8691 mFlags = flags; 8692 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8693 final int N = packageServices.size(); 8694 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8695 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8696 8697 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8698 for (int i = 0; i < N; ++i) { 8699 intentFilters = packageServices.get(i).intents; 8700 if (intentFilters != null && intentFilters.size() > 0) { 8701 PackageParser.ServiceIntentInfo[] array = 8702 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8703 intentFilters.toArray(array); 8704 listCut.add(array); 8705 } 8706 } 8707 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8708 } 8709 8710 public final void addService(PackageParser.Service s) { 8711 mServices.put(s.getComponentName(), s); 8712 if (DEBUG_SHOW_INFO) { 8713 Log.v(TAG, " " 8714 + (s.info.nonLocalizedLabel != null 8715 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8716 Log.v(TAG, " Class=" + s.info.name); 8717 } 8718 final int NI = s.intents.size(); 8719 int j; 8720 for (j=0; j<NI; j++) { 8721 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8722 if (DEBUG_SHOW_INFO) { 8723 Log.v(TAG, " IntentFilter:"); 8724 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8725 } 8726 if (!intent.debugCheck()) { 8727 Log.w(TAG, "==> For Service " + s.info.name); 8728 } 8729 addFilter(intent); 8730 } 8731 } 8732 8733 public final void removeService(PackageParser.Service s) { 8734 mServices.remove(s.getComponentName()); 8735 if (DEBUG_SHOW_INFO) { 8736 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8737 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8738 Log.v(TAG, " Class=" + s.info.name); 8739 } 8740 final int NI = s.intents.size(); 8741 int j; 8742 for (j=0; j<NI; j++) { 8743 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8744 if (DEBUG_SHOW_INFO) { 8745 Log.v(TAG, " IntentFilter:"); 8746 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8747 } 8748 removeFilter(intent); 8749 } 8750 } 8751 8752 @Override 8753 protected boolean allowFilterResult( 8754 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8755 ServiceInfo filterSi = filter.service.info; 8756 for (int i=dest.size()-1; i>=0; i--) { 8757 ServiceInfo destAi = dest.get(i).serviceInfo; 8758 if (destAi.name == filterSi.name 8759 && destAi.packageName == filterSi.packageName) { 8760 return false; 8761 } 8762 } 8763 return true; 8764 } 8765 8766 @Override 8767 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8768 return new PackageParser.ServiceIntentInfo[size]; 8769 } 8770 8771 @Override 8772 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8773 if (!sUserManager.exists(userId)) return true; 8774 PackageParser.Package p = filter.service.owner; 8775 if (p != null) { 8776 PackageSetting ps = (PackageSetting)p.mExtras; 8777 if (ps != null) { 8778 // System apps are never considered stopped for purposes of 8779 // filtering, because there may be no way for the user to 8780 // actually re-launch them. 8781 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8782 && ps.getStopped(userId); 8783 } 8784 } 8785 return false; 8786 } 8787 8788 @Override 8789 protected boolean isPackageForFilter(String packageName, 8790 PackageParser.ServiceIntentInfo info) { 8791 return packageName.equals(info.service.owner.packageName); 8792 } 8793 8794 @Override 8795 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8796 int match, int userId) { 8797 if (!sUserManager.exists(userId)) return null; 8798 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8799 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8800 return null; 8801 } 8802 final PackageParser.Service service = info.service; 8803 if (mSafeMode && (service.info.applicationInfo.flags 8804 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8805 return null; 8806 } 8807 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8808 if (ps == null) { 8809 return null; 8810 } 8811 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8812 ps.readUserState(userId), userId); 8813 if (si == null) { 8814 return null; 8815 } 8816 final ResolveInfo res = new ResolveInfo(); 8817 res.serviceInfo = si; 8818 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8819 res.filter = filter; 8820 } 8821 res.priority = info.getPriority(); 8822 res.preferredOrder = service.owner.mPreferredOrder; 8823 res.match = match; 8824 res.isDefault = info.hasDefault; 8825 res.labelRes = info.labelRes; 8826 res.nonLocalizedLabel = info.nonLocalizedLabel; 8827 res.icon = info.icon; 8828 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8829 return res; 8830 } 8831 8832 @Override 8833 protected void sortResults(List<ResolveInfo> results) { 8834 Collections.sort(results, mResolvePrioritySorter); 8835 } 8836 8837 @Override 8838 protected void dumpFilter(PrintWriter out, String prefix, 8839 PackageParser.ServiceIntentInfo filter) { 8840 out.print(prefix); out.print( 8841 Integer.toHexString(System.identityHashCode(filter.service))); 8842 out.print(' '); 8843 filter.service.printComponentShortName(out); 8844 out.print(" filter "); 8845 out.println(Integer.toHexString(System.identityHashCode(filter))); 8846 } 8847 8848 @Override 8849 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8850 return filter.service; 8851 } 8852 8853 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8854 PackageParser.Service service = (PackageParser.Service)label; 8855 out.print(prefix); out.print( 8856 Integer.toHexString(System.identityHashCode(service))); 8857 out.print(' '); 8858 service.printComponentShortName(out); 8859 if (count > 1) { 8860 out.print(" ("); out.print(count); out.print(" filters)"); 8861 } 8862 out.println(); 8863 } 8864 8865// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8866// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8867// final List<ResolveInfo> retList = Lists.newArrayList(); 8868// while (i.hasNext()) { 8869// final ResolveInfo resolveInfo = (ResolveInfo) i; 8870// if (isEnabledLP(resolveInfo.serviceInfo)) { 8871// retList.add(resolveInfo); 8872// } 8873// } 8874// return retList; 8875// } 8876 8877 // Keys are String (activity class name), values are Activity. 8878 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8879 = new ArrayMap<ComponentName, PackageParser.Service>(); 8880 private int mFlags; 8881 }; 8882 8883 private final class ProviderIntentResolver 8884 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8885 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8886 boolean defaultOnly, int userId) { 8887 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8888 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8889 } 8890 8891 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8892 int userId) { 8893 if (!sUserManager.exists(userId)) 8894 return null; 8895 mFlags = flags; 8896 return super.queryIntent(intent, resolvedType, 8897 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8898 } 8899 8900 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8901 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8902 if (!sUserManager.exists(userId)) 8903 return null; 8904 if (packageProviders == null) { 8905 return null; 8906 } 8907 mFlags = flags; 8908 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8909 final int N = packageProviders.size(); 8910 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8911 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8912 8913 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8914 for (int i = 0; i < N; ++i) { 8915 intentFilters = packageProviders.get(i).intents; 8916 if (intentFilters != null && intentFilters.size() > 0) { 8917 PackageParser.ProviderIntentInfo[] array = 8918 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8919 intentFilters.toArray(array); 8920 listCut.add(array); 8921 } 8922 } 8923 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8924 } 8925 8926 public final void addProvider(PackageParser.Provider p) { 8927 if (mProviders.containsKey(p.getComponentName())) { 8928 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8929 return; 8930 } 8931 8932 mProviders.put(p.getComponentName(), p); 8933 if (DEBUG_SHOW_INFO) { 8934 Log.v(TAG, " " 8935 + (p.info.nonLocalizedLabel != null 8936 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8937 Log.v(TAG, " Class=" + p.info.name); 8938 } 8939 final int NI = p.intents.size(); 8940 int j; 8941 for (j = 0; j < NI; j++) { 8942 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8943 if (DEBUG_SHOW_INFO) { 8944 Log.v(TAG, " IntentFilter:"); 8945 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8946 } 8947 if (!intent.debugCheck()) { 8948 Log.w(TAG, "==> For Provider " + p.info.name); 8949 } 8950 addFilter(intent); 8951 } 8952 } 8953 8954 public final void removeProvider(PackageParser.Provider p) { 8955 mProviders.remove(p.getComponentName()); 8956 if (DEBUG_SHOW_INFO) { 8957 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8958 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8959 Log.v(TAG, " Class=" + p.info.name); 8960 } 8961 final int NI = p.intents.size(); 8962 int j; 8963 for (j = 0; j < NI; j++) { 8964 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8965 if (DEBUG_SHOW_INFO) { 8966 Log.v(TAG, " IntentFilter:"); 8967 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8968 } 8969 removeFilter(intent); 8970 } 8971 } 8972 8973 @Override 8974 protected boolean allowFilterResult( 8975 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8976 ProviderInfo filterPi = filter.provider.info; 8977 for (int i = dest.size() - 1; i >= 0; i--) { 8978 ProviderInfo destPi = dest.get(i).providerInfo; 8979 if (destPi.name == filterPi.name 8980 && destPi.packageName == filterPi.packageName) { 8981 return false; 8982 } 8983 } 8984 return true; 8985 } 8986 8987 @Override 8988 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8989 return new PackageParser.ProviderIntentInfo[size]; 8990 } 8991 8992 @Override 8993 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8994 if (!sUserManager.exists(userId)) 8995 return true; 8996 PackageParser.Package p = filter.provider.owner; 8997 if (p != null) { 8998 PackageSetting ps = (PackageSetting) p.mExtras; 8999 if (ps != null) { 9000 // System apps are never considered stopped for purposes of 9001 // filtering, because there may be no way for the user to 9002 // actually re-launch them. 9003 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9004 && ps.getStopped(userId); 9005 } 9006 } 9007 return false; 9008 } 9009 9010 @Override 9011 protected boolean isPackageForFilter(String packageName, 9012 PackageParser.ProviderIntentInfo info) { 9013 return packageName.equals(info.provider.owner.packageName); 9014 } 9015 9016 @Override 9017 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9018 int match, int userId) { 9019 if (!sUserManager.exists(userId)) 9020 return null; 9021 final PackageParser.ProviderIntentInfo info = filter; 9022 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9023 return null; 9024 } 9025 final PackageParser.Provider provider = info.provider; 9026 if (mSafeMode && (provider.info.applicationInfo.flags 9027 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9028 return null; 9029 } 9030 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9031 if (ps == null) { 9032 return null; 9033 } 9034 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9035 ps.readUserState(userId), userId); 9036 if (pi == null) { 9037 return null; 9038 } 9039 final ResolveInfo res = new ResolveInfo(); 9040 res.providerInfo = pi; 9041 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9042 res.filter = filter; 9043 } 9044 res.priority = info.getPriority(); 9045 res.preferredOrder = provider.owner.mPreferredOrder; 9046 res.match = match; 9047 res.isDefault = info.hasDefault; 9048 res.labelRes = info.labelRes; 9049 res.nonLocalizedLabel = info.nonLocalizedLabel; 9050 res.icon = info.icon; 9051 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9052 return res; 9053 } 9054 9055 @Override 9056 protected void sortResults(List<ResolveInfo> results) { 9057 Collections.sort(results, mResolvePrioritySorter); 9058 } 9059 9060 @Override 9061 protected void dumpFilter(PrintWriter out, String prefix, 9062 PackageParser.ProviderIntentInfo filter) { 9063 out.print(prefix); 9064 out.print( 9065 Integer.toHexString(System.identityHashCode(filter.provider))); 9066 out.print(' '); 9067 filter.provider.printComponentShortName(out); 9068 out.print(" filter "); 9069 out.println(Integer.toHexString(System.identityHashCode(filter))); 9070 } 9071 9072 @Override 9073 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9074 return filter.provider; 9075 } 9076 9077 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9078 PackageParser.Provider provider = (PackageParser.Provider)label; 9079 out.print(prefix); out.print( 9080 Integer.toHexString(System.identityHashCode(provider))); 9081 out.print(' '); 9082 provider.printComponentShortName(out); 9083 if (count > 1) { 9084 out.print(" ("); out.print(count); out.print(" filters)"); 9085 } 9086 out.println(); 9087 } 9088 9089 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9090 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9091 private int mFlags; 9092 }; 9093 9094 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9095 new Comparator<ResolveInfo>() { 9096 public int compare(ResolveInfo r1, ResolveInfo r2) { 9097 int v1 = r1.priority; 9098 int v2 = r2.priority; 9099 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9100 if (v1 != v2) { 9101 return (v1 > v2) ? -1 : 1; 9102 } 9103 v1 = r1.preferredOrder; 9104 v2 = r2.preferredOrder; 9105 if (v1 != v2) { 9106 return (v1 > v2) ? -1 : 1; 9107 } 9108 if (r1.isDefault != r2.isDefault) { 9109 return r1.isDefault ? -1 : 1; 9110 } 9111 v1 = r1.match; 9112 v2 = r2.match; 9113 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9114 if (v1 != v2) { 9115 return (v1 > v2) ? -1 : 1; 9116 } 9117 if (r1.system != r2.system) { 9118 return r1.system ? -1 : 1; 9119 } 9120 return 0; 9121 } 9122 }; 9123 9124 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9125 new Comparator<ProviderInfo>() { 9126 public int compare(ProviderInfo p1, ProviderInfo p2) { 9127 final int v1 = p1.initOrder; 9128 final int v2 = p2.initOrder; 9129 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9130 } 9131 }; 9132 9133 final void sendPackageBroadcast(final String action, final String pkg, 9134 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9135 final int[] userIds) { 9136 mHandler.post(new Runnable() { 9137 @Override 9138 public void run() { 9139 try { 9140 final IActivityManager am = ActivityManagerNative.getDefault(); 9141 if (am == null) return; 9142 final int[] resolvedUserIds; 9143 if (userIds == null) { 9144 resolvedUserIds = am.getRunningUserIds(); 9145 } else { 9146 resolvedUserIds = userIds; 9147 } 9148 for (int id : resolvedUserIds) { 9149 final Intent intent = new Intent(action, 9150 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9151 if (extras != null) { 9152 intent.putExtras(extras); 9153 } 9154 if (targetPkg != null) { 9155 intent.setPackage(targetPkg); 9156 } 9157 // Modify the UID when posting to other users 9158 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9159 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9160 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9161 intent.putExtra(Intent.EXTRA_UID, uid); 9162 } 9163 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9164 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9165 if (DEBUG_BROADCASTS) { 9166 RuntimeException here = new RuntimeException("here"); 9167 here.fillInStackTrace(); 9168 Slog.d(TAG, "Sending to user " + id + ": " 9169 + intent.toShortString(false, true, false, false) 9170 + " " + intent.getExtras(), here); 9171 } 9172 am.broadcastIntent(null, intent, null, finishedReceiver, 9173 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9174 null, finishedReceiver != null, false, id); 9175 } 9176 } catch (RemoteException ex) { 9177 } 9178 } 9179 }); 9180 } 9181 9182 /** 9183 * Check if the external storage media is available. This is true if there 9184 * is a mounted external storage medium or if the external storage is 9185 * emulated. 9186 */ 9187 private boolean isExternalMediaAvailable() { 9188 return mMediaMounted || Environment.isExternalStorageEmulated(); 9189 } 9190 9191 @Override 9192 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9193 // writer 9194 synchronized (mPackages) { 9195 if (!isExternalMediaAvailable()) { 9196 // If the external storage is no longer mounted at this point, 9197 // the caller may not have been able to delete all of this 9198 // packages files and can not delete any more. Bail. 9199 return null; 9200 } 9201 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9202 if (lastPackage != null) { 9203 pkgs.remove(lastPackage); 9204 } 9205 if (pkgs.size() > 0) { 9206 return pkgs.get(0); 9207 } 9208 } 9209 return null; 9210 } 9211 9212 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9213 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9214 userId, andCode ? 1 : 0, packageName); 9215 if (mSystemReady) { 9216 msg.sendToTarget(); 9217 } else { 9218 if (mPostSystemReadyMessages == null) { 9219 mPostSystemReadyMessages = new ArrayList<>(); 9220 } 9221 mPostSystemReadyMessages.add(msg); 9222 } 9223 } 9224 9225 void startCleaningPackages() { 9226 // reader 9227 synchronized (mPackages) { 9228 if (!isExternalMediaAvailable()) { 9229 return; 9230 } 9231 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9232 return; 9233 } 9234 } 9235 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9236 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9237 IActivityManager am = ActivityManagerNative.getDefault(); 9238 if (am != null) { 9239 try { 9240 am.startService(null, intent, null, mContext.getOpPackageName(), 9241 UserHandle.USER_OWNER); 9242 } catch (RemoteException e) { 9243 } 9244 } 9245 } 9246 9247 @Override 9248 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9249 int installFlags, String installerPackageName, VerificationParams verificationParams, 9250 String packageAbiOverride) { 9251 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9252 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9253 } 9254 9255 @Override 9256 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9257 int installFlags, String installerPackageName, VerificationParams verificationParams, 9258 String packageAbiOverride, int userId) { 9259 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9260 9261 final int callingUid = Binder.getCallingUid(); 9262 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9263 9264 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9265 try { 9266 if (observer != null) { 9267 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9268 } 9269 } catch (RemoteException re) { 9270 } 9271 return; 9272 } 9273 9274 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9275 installFlags |= PackageManager.INSTALL_FROM_ADB; 9276 9277 } else { 9278 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9279 // about installerPackageName. 9280 9281 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9282 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9283 } 9284 9285 UserHandle user; 9286 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9287 user = UserHandle.ALL; 9288 } else { 9289 user = new UserHandle(userId); 9290 } 9291 9292 // Only system components can circumvent runtime permissions when installing. 9293 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9294 && mContext.checkCallingOrSelfPermission(Manifest.permission 9295 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9296 throw new SecurityException("You need the " 9297 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9298 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9299 } 9300 9301 verificationParams.setInstallerUid(callingUid); 9302 9303 final File originFile = new File(originPath); 9304 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9305 9306 final Message msg = mHandler.obtainMessage(INIT_COPY); 9307 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9308 null, verificationParams, user, packageAbiOverride); 9309 mHandler.sendMessage(msg); 9310 } 9311 9312 void installStage(String packageName, File stagedDir, String stagedCid, 9313 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9314 String installerPackageName, int installerUid, UserHandle user) { 9315 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9316 params.referrerUri, installerUid, null); 9317 verifParams.setInstallerUid(installerUid); 9318 9319 final OriginInfo origin; 9320 if (stagedDir != null) { 9321 origin = OriginInfo.fromStagedFile(stagedDir); 9322 } else { 9323 origin = OriginInfo.fromStagedContainer(stagedCid); 9324 } 9325 9326 final Message msg = mHandler.obtainMessage(INIT_COPY); 9327 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9328 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9329 mHandler.sendMessage(msg); 9330 } 9331 9332 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9333 Bundle extras = new Bundle(1); 9334 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9335 9336 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9337 packageName, extras, null, null, new int[] {userId}); 9338 try { 9339 IActivityManager am = ActivityManagerNative.getDefault(); 9340 final boolean isSystem = 9341 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9342 if (isSystem && am.isUserRunning(userId, false)) { 9343 // The just-installed/enabled app is bundled on the system, so presumed 9344 // to be able to run automatically without needing an explicit launch. 9345 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9346 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9347 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9348 .setPackage(packageName); 9349 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9350 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9351 } 9352 } catch (RemoteException e) { 9353 // shouldn't happen 9354 Slog.w(TAG, "Unable to bootstrap installed package", e); 9355 } 9356 } 9357 9358 @Override 9359 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9360 int userId) { 9361 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9362 PackageSetting pkgSetting; 9363 final int uid = Binder.getCallingUid(); 9364 enforceCrossUserPermission(uid, userId, true, true, 9365 "setApplicationHiddenSetting for user " + userId); 9366 9367 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9368 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9369 return false; 9370 } 9371 9372 long callingId = Binder.clearCallingIdentity(); 9373 try { 9374 boolean sendAdded = false; 9375 boolean sendRemoved = false; 9376 // writer 9377 synchronized (mPackages) { 9378 pkgSetting = mSettings.mPackages.get(packageName); 9379 if (pkgSetting == null) { 9380 return false; 9381 } 9382 if (pkgSetting.getHidden(userId) != hidden) { 9383 pkgSetting.setHidden(hidden, userId); 9384 mSettings.writePackageRestrictionsLPr(userId); 9385 if (hidden) { 9386 sendRemoved = true; 9387 } else { 9388 sendAdded = true; 9389 } 9390 } 9391 } 9392 if (sendAdded) { 9393 sendPackageAddedForUser(packageName, pkgSetting, userId); 9394 return true; 9395 } 9396 if (sendRemoved) { 9397 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9398 "hiding pkg"); 9399 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9400 } 9401 } finally { 9402 Binder.restoreCallingIdentity(callingId); 9403 } 9404 return false; 9405 } 9406 9407 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9408 int userId) { 9409 final PackageRemovedInfo info = new PackageRemovedInfo(); 9410 info.removedPackage = packageName; 9411 info.removedUsers = new int[] {userId}; 9412 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9413 info.sendBroadcast(false, false, false); 9414 } 9415 9416 /** 9417 * Returns true if application is not found or there was an error. Otherwise it returns 9418 * the hidden state of the package for the given user. 9419 */ 9420 @Override 9421 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9422 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9423 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9424 false, "getApplicationHidden for user " + userId); 9425 PackageSetting pkgSetting; 9426 long callingId = Binder.clearCallingIdentity(); 9427 try { 9428 // writer 9429 synchronized (mPackages) { 9430 pkgSetting = mSettings.mPackages.get(packageName); 9431 if (pkgSetting == null) { 9432 return true; 9433 } 9434 return pkgSetting.getHidden(userId); 9435 } 9436 } finally { 9437 Binder.restoreCallingIdentity(callingId); 9438 } 9439 } 9440 9441 /** 9442 * @hide 9443 */ 9444 @Override 9445 public int installExistingPackageAsUser(String packageName, int userId) { 9446 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9447 null); 9448 PackageSetting pkgSetting; 9449 final int uid = Binder.getCallingUid(); 9450 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9451 + userId); 9452 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9453 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9454 } 9455 9456 long callingId = Binder.clearCallingIdentity(); 9457 try { 9458 boolean sendAdded = false; 9459 9460 // writer 9461 synchronized (mPackages) { 9462 pkgSetting = mSettings.mPackages.get(packageName); 9463 if (pkgSetting == null) { 9464 return PackageManager.INSTALL_FAILED_INVALID_URI; 9465 } 9466 if (!pkgSetting.getInstalled(userId)) { 9467 pkgSetting.setInstalled(true, userId); 9468 pkgSetting.setHidden(false, userId); 9469 mSettings.writePackageRestrictionsLPr(userId); 9470 sendAdded = true; 9471 } 9472 } 9473 9474 if (sendAdded) { 9475 sendPackageAddedForUser(packageName, pkgSetting, userId); 9476 } 9477 } finally { 9478 Binder.restoreCallingIdentity(callingId); 9479 } 9480 9481 return PackageManager.INSTALL_SUCCEEDED; 9482 } 9483 9484 boolean isUserRestricted(int userId, String restrictionKey) { 9485 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9486 if (restrictions.getBoolean(restrictionKey, false)) { 9487 Log.w(TAG, "User is restricted: " + restrictionKey); 9488 return true; 9489 } 9490 return false; 9491 } 9492 9493 @Override 9494 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9495 mContext.enforceCallingOrSelfPermission( 9496 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9497 "Only package verification agents can verify applications"); 9498 9499 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9500 final PackageVerificationResponse response = new PackageVerificationResponse( 9501 verificationCode, Binder.getCallingUid()); 9502 msg.arg1 = id; 9503 msg.obj = response; 9504 mHandler.sendMessage(msg); 9505 } 9506 9507 @Override 9508 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9509 long millisecondsToDelay) { 9510 mContext.enforceCallingOrSelfPermission( 9511 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9512 "Only package verification agents can extend verification timeouts"); 9513 9514 final PackageVerificationState state = mPendingVerification.get(id); 9515 final PackageVerificationResponse response = new PackageVerificationResponse( 9516 verificationCodeAtTimeout, Binder.getCallingUid()); 9517 9518 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9519 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9520 } 9521 if (millisecondsToDelay < 0) { 9522 millisecondsToDelay = 0; 9523 } 9524 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9525 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9526 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9527 } 9528 9529 if ((state != null) && !state.timeoutExtended()) { 9530 state.extendTimeout(); 9531 9532 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9533 msg.arg1 = id; 9534 msg.obj = response; 9535 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9536 } 9537 } 9538 9539 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9540 int verificationCode, UserHandle user) { 9541 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9542 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9543 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9544 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9545 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9546 9547 mContext.sendBroadcastAsUser(intent, user, 9548 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9549 } 9550 9551 private ComponentName matchComponentForVerifier(String packageName, 9552 List<ResolveInfo> receivers) { 9553 ActivityInfo targetReceiver = null; 9554 9555 final int NR = receivers.size(); 9556 for (int i = 0; i < NR; i++) { 9557 final ResolveInfo info = receivers.get(i); 9558 if (info.activityInfo == null) { 9559 continue; 9560 } 9561 9562 if (packageName.equals(info.activityInfo.packageName)) { 9563 targetReceiver = info.activityInfo; 9564 break; 9565 } 9566 } 9567 9568 if (targetReceiver == null) { 9569 return null; 9570 } 9571 9572 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9573 } 9574 9575 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9576 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9577 if (pkgInfo.verifiers.length == 0) { 9578 return null; 9579 } 9580 9581 final int N = pkgInfo.verifiers.length; 9582 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9583 for (int i = 0; i < N; i++) { 9584 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9585 9586 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9587 receivers); 9588 if (comp == null) { 9589 continue; 9590 } 9591 9592 final int verifierUid = getUidForVerifier(verifierInfo); 9593 if (verifierUid == -1) { 9594 continue; 9595 } 9596 9597 if (DEBUG_VERIFY) { 9598 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9599 + " with the correct signature"); 9600 } 9601 sufficientVerifiers.add(comp); 9602 verificationState.addSufficientVerifier(verifierUid); 9603 } 9604 9605 return sufficientVerifiers; 9606 } 9607 9608 private int getUidForVerifier(VerifierInfo verifierInfo) { 9609 synchronized (mPackages) { 9610 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9611 if (pkg == null) { 9612 return -1; 9613 } else if (pkg.mSignatures.length != 1) { 9614 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9615 + " has more than one signature; ignoring"); 9616 return -1; 9617 } 9618 9619 /* 9620 * If the public key of the package's signature does not match 9621 * our expected public key, then this is a different package and 9622 * we should skip. 9623 */ 9624 9625 final byte[] expectedPublicKey; 9626 try { 9627 final Signature verifierSig = pkg.mSignatures[0]; 9628 final PublicKey publicKey = verifierSig.getPublicKey(); 9629 expectedPublicKey = publicKey.getEncoded(); 9630 } catch (CertificateException e) { 9631 return -1; 9632 } 9633 9634 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9635 9636 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9637 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9638 + " does not have the expected public key; ignoring"); 9639 return -1; 9640 } 9641 9642 return pkg.applicationInfo.uid; 9643 } 9644 } 9645 9646 @Override 9647 public void finishPackageInstall(int token) { 9648 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9649 9650 if (DEBUG_INSTALL) { 9651 Slog.v(TAG, "BM finishing package install for " + token); 9652 } 9653 9654 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9655 mHandler.sendMessage(msg); 9656 } 9657 9658 /** 9659 * Get the verification agent timeout. 9660 * 9661 * @return verification timeout in milliseconds 9662 */ 9663 private long getVerificationTimeout() { 9664 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9665 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9666 DEFAULT_VERIFICATION_TIMEOUT); 9667 } 9668 9669 /** 9670 * Get the default verification agent response code. 9671 * 9672 * @return default verification response code 9673 */ 9674 private int getDefaultVerificationResponse() { 9675 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9676 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9677 DEFAULT_VERIFICATION_RESPONSE); 9678 } 9679 9680 /** 9681 * Check whether or not package verification has been enabled. 9682 * 9683 * @return true if verification should be performed 9684 */ 9685 private boolean isVerificationEnabled(int userId, int installFlags) { 9686 if (!DEFAULT_VERIFY_ENABLE) { 9687 return false; 9688 } 9689 9690 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9691 9692 // Check if installing from ADB 9693 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9694 // Do not run verification in a test harness environment 9695 if (ActivityManager.isRunningInTestHarness()) { 9696 return false; 9697 } 9698 if (ensureVerifyAppsEnabled) { 9699 return true; 9700 } 9701 // Check if the developer does not want package verification for ADB installs 9702 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9703 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9704 return false; 9705 } 9706 } 9707 9708 if (ensureVerifyAppsEnabled) { 9709 return true; 9710 } 9711 9712 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9713 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9714 } 9715 9716 @Override 9717 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9718 throws RemoteException { 9719 mContext.enforceCallingOrSelfPermission( 9720 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9721 "Only intentfilter verification agents can verify applications"); 9722 9723 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9724 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9725 Binder.getCallingUid(), verificationCode, failedDomains); 9726 msg.arg1 = id; 9727 msg.obj = response; 9728 mHandler.sendMessage(msg); 9729 } 9730 9731 @Override 9732 public int getIntentVerificationStatus(String packageName, int userId) { 9733 synchronized (mPackages) { 9734 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9735 } 9736 } 9737 9738 @Override 9739 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9740 mContext.enforceCallingOrSelfPermission( 9741 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9742 9743 boolean result = false; 9744 synchronized (mPackages) { 9745 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9746 } 9747 if (result) { 9748 scheduleWritePackageRestrictionsLocked(userId); 9749 } 9750 return result; 9751 } 9752 9753 @Override 9754 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9755 synchronized (mPackages) { 9756 return mSettings.getIntentFilterVerificationsLPr(packageName); 9757 } 9758 } 9759 9760 @Override 9761 public List<IntentFilter> getAllIntentFilters(String packageName) { 9762 if (TextUtils.isEmpty(packageName)) { 9763 return Collections.<IntentFilter>emptyList(); 9764 } 9765 synchronized (mPackages) { 9766 PackageParser.Package pkg = mPackages.get(packageName); 9767 if (pkg == null || pkg.activities == null) { 9768 return Collections.<IntentFilter>emptyList(); 9769 } 9770 final int count = pkg.activities.size(); 9771 ArrayList<IntentFilter> result = new ArrayList<>(); 9772 for (int n=0; n<count; n++) { 9773 PackageParser.Activity activity = pkg.activities.get(n); 9774 if (activity.intents != null || activity.intents.size() > 0) { 9775 result.addAll(activity.intents); 9776 } 9777 } 9778 return result; 9779 } 9780 } 9781 9782 @Override 9783 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9784 mContext.enforceCallingOrSelfPermission( 9785 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9786 9787 synchronized (mPackages) { 9788 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9789 if (packageName != null) { 9790 result |= updateIntentVerificationStatus(packageName, 9791 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9792 UserHandle.myUserId()); 9793 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9794 packageName, userId); 9795 } 9796 return result; 9797 } 9798 } 9799 9800 @Override 9801 public String getDefaultBrowserPackageName(int userId) { 9802 synchronized (mPackages) { 9803 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9804 } 9805 } 9806 9807 /** 9808 * Get the "allow unknown sources" setting. 9809 * 9810 * @return the current "allow unknown sources" setting 9811 */ 9812 private int getUnknownSourcesSettings() { 9813 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9814 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9815 -1); 9816 } 9817 9818 @Override 9819 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9820 final int uid = Binder.getCallingUid(); 9821 // writer 9822 synchronized (mPackages) { 9823 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9824 if (targetPackageSetting == null) { 9825 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9826 } 9827 9828 PackageSetting installerPackageSetting; 9829 if (installerPackageName != null) { 9830 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9831 if (installerPackageSetting == null) { 9832 throw new IllegalArgumentException("Unknown installer package: " 9833 + installerPackageName); 9834 } 9835 } else { 9836 installerPackageSetting = null; 9837 } 9838 9839 Signature[] callerSignature; 9840 Object obj = mSettings.getUserIdLPr(uid); 9841 if (obj != null) { 9842 if (obj instanceof SharedUserSetting) { 9843 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9844 } else if (obj instanceof PackageSetting) { 9845 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9846 } else { 9847 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9848 } 9849 } else { 9850 throw new SecurityException("Unknown calling uid " + uid); 9851 } 9852 9853 // Verify: can't set installerPackageName to a package that is 9854 // not signed with the same cert as the caller. 9855 if (installerPackageSetting != null) { 9856 if (compareSignatures(callerSignature, 9857 installerPackageSetting.signatures.mSignatures) 9858 != PackageManager.SIGNATURE_MATCH) { 9859 throw new SecurityException( 9860 "Caller does not have same cert as new installer package " 9861 + installerPackageName); 9862 } 9863 } 9864 9865 // Verify: if target already has an installer package, it must 9866 // be signed with the same cert as the caller. 9867 if (targetPackageSetting.installerPackageName != null) { 9868 PackageSetting setting = mSettings.mPackages.get( 9869 targetPackageSetting.installerPackageName); 9870 // If the currently set package isn't valid, then it's always 9871 // okay to change it. 9872 if (setting != null) { 9873 if (compareSignatures(callerSignature, 9874 setting.signatures.mSignatures) 9875 != PackageManager.SIGNATURE_MATCH) { 9876 throw new SecurityException( 9877 "Caller does not have same cert as old installer package " 9878 + targetPackageSetting.installerPackageName); 9879 } 9880 } 9881 } 9882 9883 // Okay! 9884 targetPackageSetting.installerPackageName = installerPackageName; 9885 scheduleWriteSettingsLocked(); 9886 } 9887 } 9888 9889 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9890 // Queue up an async operation since the package installation may take a little while. 9891 mHandler.post(new Runnable() { 9892 public void run() { 9893 mHandler.removeCallbacks(this); 9894 // Result object to be returned 9895 PackageInstalledInfo res = new PackageInstalledInfo(); 9896 res.returnCode = currentStatus; 9897 res.uid = -1; 9898 res.pkg = null; 9899 res.removedInfo = new PackageRemovedInfo(); 9900 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9901 args.doPreInstall(res.returnCode); 9902 synchronized (mInstallLock) { 9903 installPackageLI(args, res); 9904 } 9905 args.doPostInstall(res.returnCode, res.uid); 9906 } 9907 9908 // A restore should be performed at this point if (a) the install 9909 // succeeded, (b) the operation is not an update, and (c) the new 9910 // package has not opted out of backup participation. 9911 final boolean update = res.removedInfo.removedPackage != null; 9912 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9913 boolean doRestore = !update 9914 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9915 9916 // Set up the post-install work request bookkeeping. This will be used 9917 // and cleaned up by the post-install event handling regardless of whether 9918 // there's a restore pass performed. Token values are >= 1. 9919 int token; 9920 if (mNextInstallToken < 0) mNextInstallToken = 1; 9921 token = mNextInstallToken++; 9922 9923 PostInstallData data = new PostInstallData(args, res); 9924 mRunningInstalls.put(token, data); 9925 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9926 9927 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9928 // Pass responsibility to the Backup Manager. It will perform a 9929 // restore if appropriate, then pass responsibility back to the 9930 // Package Manager to run the post-install observer callbacks 9931 // and broadcasts. 9932 IBackupManager bm = IBackupManager.Stub.asInterface( 9933 ServiceManager.getService(Context.BACKUP_SERVICE)); 9934 if (bm != null) { 9935 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9936 + " to BM for possible restore"); 9937 try { 9938 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9939 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9940 } else { 9941 doRestore = false; 9942 } 9943 } catch (RemoteException e) { 9944 // can't happen; the backup manager is local 9945 } catch (Exception e) { 9946 Slog.e(TAG, "Exception trying to enqueue restore", e); 9947 doRestore = false; 9948 } 9949 } else { 9950 Slog.e(TAG, "Backup Manager not found!"); 9951 doRestore = false; 9952 } 9953 } 9954 9955 if (!doRestore) { 9956 // No restore possible, or the Backup Manager was mysteriously not 9957 // available -- just fire the post-install work request directly. 9958 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9959 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9960 mHandler.sendMessage(msg); 9961 } 9962 } 9963 }); 9964 } 9965 9966 private abstract class HandlerParams { 9967 private static final int MAX_RETRIES = 4; 9968 9969 /** 9970 * Number of times startCopy() has been attempted and had a non-fatal 9971 * error. 9972 */ 9973 private int mRetries = 0; 9974 9975 /** User handle for the user requesting the information or installation. */ 9976 private final UserHandle mUser; 9977 9978 HandlerParams(UserHandle user) { 9979 mUser = user; 9980 } 9981 9982 UserHandle getUser() { 9983 return mUser; 9984 } 9985 9986 final boolean startCopy() { 9987 boolean res; 9988 try { 9989 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9990 9991 if (++mRetries > MAX_RETRIES) { 9992 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9993 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9994 handleServiceError(); 9995 return false; 9996 } else { 9997 handleStartCopy(); 9998 res = true; 9999 } 10000 } catch (RemoteException e) { 10001 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10002 mHandler.sendEmptyMessage(MCS_RECONNECT); 10003 res = false; 10004 } 10005 handleReturnCode(); 10006 return res; 10007 } 10008 10009 final void serviceError() { 10010 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10011 handleServiceError(); 10012 handleReturnCode(); 10013 } 10014 10015 abstract void handleStartCopy() throws RemoteException; 10016 abstract void handleServiceError(); 10017 abstract void handleReturnCode(); 10018 } 10019 10020 class MeasureParams extends HandlerParams { 10021 private final PackageStats mStats; 10022 private boolean mSuccess; 10023 10024 private final IPackageStatsObserver mObserver; 10025 10026 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10027 super(new UserHandle(stats.userHandle)); 10028 mObserver = observer; 10029 mStats = stats; 10030 } 10031 10032 @Override 10033 public String toString() { 10034 return "MeasureParams{" 10035 + Integer.toHexString(System.identityHashCode(this)) 10036 + " " + mStats.packageName + "}"; 10037 } 10038 10039 @Override 10040 void handleStartCopy() throws RemoteException { 10041 synchronized (mInstallLock) { 10042 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10043 } 10044 10045 if (mSuccess) { 10046 final boolean mounted; 10047 if (Environment.isExternalStorageEmulated()) { 10048 mounted = true; 10049 } else { 10050 final String status = Environment.getExternalStorageState(); 10051 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10052 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10053 } 10054 10055 if (mounted) { 10056 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10057 10058 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10059 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10060 10061 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10062 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10063 10064 // Always subtract cache size, since it's a subdirectory 10065 mStats.externalDataSize -= mStats.externalCacheSize; 10066 10067 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10068 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10069 10070 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10071 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10072 } 10073 } 10074 } 10075 10076 @Override 10077 void handleReturnCode() { 10078 if (mObserver != null) { 10079 try { 10080 mObserver.onGetStatsCompleted(mStats, mSuccess); 10081 } catch (RemoteException e) { 10082 Slog.i(TAG, "Observer no longer exists."); 10083 } 10084 } 10085 } 10086 10087 @Override 10088 void handleServiceError() { 10089 Slog.e(TAG, "Could not measure application " + mStats.packageName 10090 + " external storage"); 10091 } 10092 } 10093 10094 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10095 throws RemoteException { 10096 long result = 0; 10097 for (File path : paths) { 10098 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10099 } 10100 return result; 10101 } 10102 10103 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10104 for (File path : paths) { 10105 try { 10106 mcs.clearDirectory(path.getAbsolutePath()); 10107 } catch (RemoteException e) { 10108 } 10109 } 10110 } 10111 10112 static class OriginInfo { 10113 /** 10114 * Location where install is coming from, before it has been 10115 * copied/renamed into place. This could be a single monolithic APK 10116 * file, or a cluster directory. This location may be untrusted. 10117 */ 10118 final File file; 10119 final String cid; 10120 10121 /** 10122 * Flag indicating that {@link #file} or {@link #cid} has already been 10123 * staged, meaning downstream users don't need to defensively copy the 10124 * contents. 10125 */ 10126 final boolean staged; 10127 10128 /** 10129 * Flag indicating that {@link #file} or {@link #cid} is an already 10130 * installed app that is being moved. 10131 */ 10132 final boolean existing; 10133 10134 final String resolvedPath; 10135 final File resolvedFile; 10136 10137 static OriginInfo fromNothing() { 10138 return new OriginInfo(null, null, false, false); 10139 } 10140 10141 static OriginInfo fromUntrustedFile(File file) { 10142 return new OriginInfo(file, null, false, false); 10143 } 10144 10145 static OriginInfo fromExistingFile(File file) { 10146 return new OriginInfo(file, null, false, true); 10147 } 10148 10149 static OriginInfo fromStagedFile(File file) { 10150 return new OriginInfo(file, null, true, false); 10151 } 10152 10153 static OriginInfo fromStagedContainer(String cid) { 10154 return new OriginInfo(null, cid, true, false); 10155 } 10156 10157 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10158 this.file = file; 10159 this.cid = cid; 10160 this.staged = staged; 10161 this.existing = existing; 10162 10163 if (cid != null) { 10164 resolvedPath = PackageHelper.getSdDir(cid); 10165 resolvedFile = new File(resolvedPath); 10166 } else if (file != null) { 10167 resolvedPath = file.getAbsolutePath(); 10168 resolvedFile = file; 10169 } else { 10170 resolvedPath = null; 10171 resolvedFile = null; 10172 } 10173 } 10174 } 10175 10176 class MoveInfo { 10177 final int moveId; 10178 final String fromUuid; 10179 final String toUuid; 10180 final String packageName; 10181 final String dataAppName; 10182 final int appId; 10183 final String seinfo; 10184 10185 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10186 String dataAppName, int appId, String seinfo) { 10187 this.moveId = moveId; 10188 this.fromUuid = fromUuid; 10189 this.toUuid = toUuid; 10190 this.packageName = packageName; 10191 this.dataAppName = dataAppName; 10192 this.appId = appId; 10193 this.seinfo = seinfo; 10194 } 10195 } 10196 10197 class InstallParams extends HandlerParams { 10198 final OriginInfo origin; 10199 final MoveInfo move; 10200 final IPackageInstallObserver2 observer; 10201 int installFlags; 10202 final String installerPackageName; 10203 final String volumeUuid; 10204 final VerificationParams verificationParams; 10205 private InstallArgs mArgs; 10206 private int mRet; 10207 final String packageAbiOverride; 10208 10209 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10210 int installFlags, String installerPackageName, String volumeUuid, 10211 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10212 super(user); 10213 this.origin = origin; 10214 this.move = move; 10215 this.observer = observer; 10216 this.installFlags = installFlags; 10217 this.installerPackageName = installerPackageName; 10218 this.volumeUuid = volumeUuid; 10219 this.verificationParams = verificationParams; 10220 this.packageAbiOverride = packageAbiOverride; 10221 } 10222 10223 @Override 10224 public String toString() { 10225 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10226 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10227 } 10228 10229 public ManifestDigest getManifestDigest() { 10230 if (verificationParams == null) { 10231 return null; 10232 } 10233 return verificationParams.getManifestDigest(); 10234 } 10235 10236 private int installLocationPolicy(PackageInfoLite pkgLite) { 10237 String packageName = pkgLite.packageName; 10238 int installLocation = pkgLite.installLocation; 10239 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10240 // reader 10241 synchronized (mPackages) { 10242 PackageParser.Package pkg = mPackages.get(packageName); 10243 if (pkg != null) { 10244 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10245 // Check for downgrading. 10246 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10247 try { 10248 checkDowngrade(pkg, pkgLite); 10249 } catch (PackageManagerException e) { 10250 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10251 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10252 } 10253 } 10254 // Check for updated system application. 10255 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10256 if (onSd) { 10257 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10258 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10259 } 10260 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10261 } else { 10262 if (onSd) { 10263 // Install flag overrides everything. 10264 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10265 } 10266 // If current upgrade specifies particular preference 10267 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10268 // Application explicitly specified internal. 10269 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10270 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10271 // App explictly prefers external. Let policy decide 10272 } else { 10273 // Prefer previous location 10274 if (isExternal(pkg)) { 10275 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10276 } 10277 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10278 } 10279 } 10280 } else { 10281 // Invalid install. Return error code 10282 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10283 } 10284 } 10285 } 10286 // All the special cases have been taken care of. 10287 // Return result based on recommended install location. 10288 if (onSd) { 10289 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10290 } 10291 return pkgLite.recommendedInstallLocation; 10292 } 10293 10294 /* 10295 * Invoke remote method to get package information and install 10296 * location values. Override install location based on default 10297 * policy if needed and then create install arguments based 10298 * on the install location. 10299 */ 10300 public void handleStartCopy() throws RemoteException { 10301 int ret = PackageManager.INSTALL_SUCCEEDED; 10302 10303 // If we're already staged, we've firmly committed to an install location 10304 if (origin.staged) { 10305 if (origin.file != null) { 10306 installFlags |= PackageManager.INSTALL_INTERNAL; 10307 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10308 } else if (origin.cid != null) { 10309 installFlags |= PackageManager.INSTALL_EXTERNAL; 10310 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10311 } else { 10312 throw new IllegalStateException("Invalid stage location"); 10313 } 10314 } 10315 10316 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10317 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10318 10319 PackageInfoLite pkgLite = null; 10320 10321 if (onInt && onSd) { 10322 // Check if both bits are set. 10323 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10324 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10325 } else { 10326 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10327 packageAbiOverride); 10328 10329 /* 10330 * If we have too little free space, try to free cache 10331 * before giving up. 10332 */ 10333 if (!origin.staged && pkgLite.recommendedInstallLocation 10334 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10335 // TODO: focus freeing disk space on the target device 10336 final StorageManager storage = StorageManager.from(mContext); 10337 final long lowThreshold = storage.getStorageLowBytes( 10338 Environment.getDataDirectory()); 10339 10340 final long sizeBytes = mContainerService.calculateInstalledSize( 10341 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10342 10343 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10344 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10345 installFlags, packageAbiOverride); 10346 } 10347 10348 /* 10349 * The cache free must have deleted the file we 10350 * downloaded to install. 10351 * 10352 * TODO: fix the "freeCache" call to not delete 10353 * the file we care about. 10354 */ 10355 if (pkgLite.recommendedInstallLocation 10356 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10357 pkgLite.recommendedInstallLocation 10358 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10359 } 10360 } 10361 } 10362 10363 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10364 int loc = pkgLite.recommendedInstallLocation; 10365 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10366 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10367 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10368 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10369 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10370 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10371 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10372 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10373 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10374 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10375 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10376 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10377 } else { 10378 // Override with defaults if needed. 10379 loc = installLocationPolicy(pkgLite); 10380 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10381 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10382 } else if (!onSd && !onInt) { 10383 // Override install location with flags 10384 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10385 // Set the flag to install on external media. 10386 installFlags |= PackageManager.INSTALL_EXTERNAL; 10387 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10388 } else { 10389 // Make sure the flag for installing on external 10390 // media is unset 10391 installFlags |= PackageManager.INSTALL_INTERNAL; 10392 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10393 } 10394 } 10395 } 10396 } 10397 10398 final InstallArgs args = createInstallArgs(this); 10399 mArgs = args; 10400 10401 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10402 /* 10403 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10404 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10405 */ 10406 int userIdentifier = getUser().getIdentifier(); 10407 if (userIdentifier == UserHandle.USER_ALL 10408 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10409 userIdentifier = UserHandle.USER_OWNER; 10410 } 10411 10412 /* 10413 * Determine if we have any installed package verifiers. If we 10414 * do, then we'll defer to them to verify the packages. 10415 */ 10416 final int requiredUid = mRequiredVerifierPackage == null ? -1 10417 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10418 if (!origin.existing && requiredUid != -1 10419 && isVerificationEnabled(userIdentifier, installFlags)) { 10420 final Intent verification = new Intent( 10421 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10422 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10423 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10424 PACKAGE_MIME_TYPE); 10425 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10426 10427 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10428 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10429 0 /* TODO: Which userId? */); 10430 10431 if (DEBUG_VERIFY) { 10432 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10433 + verification.toString() + " with " + pkgLite.verifiers.length 10434 + " optional verifiers"); 10435 } 10436 10437 final int verificationId = mPendingVerificationToken++; 10438 10439 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10440 10441 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10442 installerPackageName); 10443 10444 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10445 installFlags); 10446 10447 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10448 pkgLite.packageName); 10449 10450 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10451 pkgLite.versionCode); 10452 10453 if (verificationParams != null) { 10454 if (verificationParams.getVerificationURI() != null) { 10455 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10456 verificationParams.getVerificationURI()); 10457 } 10458 if (verificationParams.getOriginatingURI() != null) { 10459 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10460 verificationParams.getOriginatingURI()); 10461 } 10462 if (verificationParams.getReferrer() != null) { 10463 verification.putExtra(Intent.EXTRA_REFERRER, 10464 verificationParams.getReferrer()); 10465 } 10466 if (verificationParams.getOriginatingUid() >= 0) { 10467 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10468 verificationParams.getOriginatingUid()); 10469 } 10470 if (verificationParams.getInstallerUid() >= 0) { 10471 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10472 verificationParams.getInstallerUid()); 10473 } 10474 } 10475 10476 final PackageVerificationState verificationState = new PackageVerificationState( 10477 requiredUid, args); 10478 10479 mPendingVerification.append(verificationId, verificationState); 10480 10481 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10482 receivers, verificationState); 10483 10484 /* 10485 * If any sufficient verifiers were listed in the package 10486 * manifest, attempt to ask them. 10487 */ 10488 if (sufficientVerifiers != null) { 10489 final int N = sufficientVerifiers.size(); 10490 if (N == 0) { 10491 Slog.i(TAG, "Additional verifiers required, but none installed."); 10492 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10493 } else { 10494 for (int i = 0; i < N; i++) { 10495 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10496 10497 final Intent sufficientIntent = new Intent(verification); 10498 sufficientIntent.setComponent(verifierComponent); 10499 10500 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10501 } 10502 } 10503 } 10504 10505 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10506 mRequiredVerifierPackage, receivers); 10507 if (ret == PackageManager.INSTALL_SUCCEEDED 10508 && mRequiredVerifierPackage != null) { 10509 /* 10510 * Send the intent to the required verification agent, 10511 * but only start the verification timeout after the 10512 * target BroadcastReceivers have run. 10513 */ 10514 verification.setComponent(requiredVerifierComponent); 10515 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10516 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10517 new BroadcastReceiver() { 10518 @Override 10519 public void onReceive(Context context, Intent intent) { 10520 final Message msg = mHandler 10521 .obtainMessage(CHECK_PENDING_VERIFICATION); 10522 msg.arg1 = verificationId; 10523 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10524 } 10525 }, null, 0, null, null); 10526 10527 /* 10528 * We don't want the copy to proceed until verification 10529 * succeeds, so null out this field. 10530 */ 10531 mArgs = null; 10532 } 10533 } else { 10534 /* 10535 * No package verification is enabled, so immediately start 10536 * the remote call to initiate copy using temporary file. 10537 */ 10538 ret = args.copyApk(mContainerService, true); 10539 } 10540 } 10541 10542 mRet = ret; 10543 } 10544 10545 @Override 10546 void handleReturnCode() { 10547 // If mArgs is null, then MCS couldn't be reached. When it 10548 // reconnects, it will try again to install. At that point, this 10549 // will succeed. 10550 if (mArgs != null) { 10551 processPendingInstall(mArgs, mRet); 10552 } 10553 } 10554 10555 @Override 10556 void handleServiceError() { 10557 mArgs = createInstallArgs(this); 10558 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10559 } 10560 10561 public boolean isForwardLocked() { 10562 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10563 } 10564 } 10565 10566 /** 10567 * Used during creation of InstallArgs 10568 * 10569 * @param installFlags package installation flags 10570 * @return true if should be installed on external storage 10571 */ 10572 private static boolean installOnExternalAsec(int installFlags) { 10573 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10574 return false; 10575 } 10576 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10577 return true; 10578 } 10579 return false; 10580 } 10581 10582 /** 10583 * Used during creation of InstallArgs 10584 * 10585 * @param installFlags package installation flags 10586 * @return true if should be installed as forward locked 10587 */ 10588 private static boolean installForwardLocked(int installFlags) { 10589 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10590 } 10591 10592 private InstallArgs createInstallArgs(InstallParams params) { 10593 if (params.move != null) { 10594 return new MoveInstallArgs(params); 10595 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10596 return new AsecInstallArgs(params); 10597 } else { 10598 return new FileInstallArgs(params); 10599 } 10600 } 10601 10602 /** 10603 * Create args that describe an existing installed package. Typically used 10604 * when cleaning up old installs, or used as a move source. 10605 */ 10606 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10607 String resourcePath, String[] instructionSets) { 10608 final boolean isInAsec; 10609 if (installOnExternalAsec(installFlags)) { 10610 /* Apps on SD card are always in ASEC containers. */ 10611 isInAsec = true; 10612 } else if (installForwardLocked(installFlags) 10613 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10614 /* 10615 * Forward-locked apps are only in ASEC containers if they're the 10616 * new style 10617 */ 10618 isInAsec = true; 10619 } else { 10620 isInAsec = false; 10621 } 10622 10623 if (isInAsec) { 10624 return new AsecInstallArgs(codePath, instructionSets, 10625 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10626 } else { 10627 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10628 } 10629 } 10630 10631 static abstract class InstallArgs { 10632 /** @see InstallParams#origin */ 10633 final OriginInfo origin; 10634 /** @see InstallParams#move */ 10635 final MoveInfo move; 10636 10637 final IPackageInstallObserver2 observer; 10638 // Always refers to PackageManager flags only 10639 final int installFlags; 10640 final String installerPackageName; 10641 final String volumeUuid; 10642 final ManifestDigest manifestDigest; 10643 final UserHandle user; 10644 final String abiOverride; 10645 10646 // The list of instruction sets supported by this app. This is currently 10647 // only used during the rmdex() phase to clean up resources. We can get rid of this 10648 // if we move dex files under the common app path. 10649 /* nullable */ String[] instructionSets; 10650 10651 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10652 int installFlags, String installerPackageName, String volumeUuid, 10653 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10654 String abiOverride) { 10655 this.origin = origin; 10656 this.move = move; 10657 this.installFlags = installFlags; 10658 this.observer = observer; 10659 this.installerPackageName = installerPackageName; 10660 this.volumeUuid = volumeUuid; 10661 this.manifestDigest = manifestDigest; 10662 this.user = user; 10663 this.instructionSets = instructionSets; 10664 this.abiOverride = abiOverride; 10665 } 10666 10667 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10668 abstract int doPreInstall(int status); 10669 10670 /** 10671 * Rename package into final resting place. All paths on the given 10672 * scanned package should be updated to reflect the rename. 10673 */ 10674 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10675 abstract int doPostInstall(int status, int uid); 10676 10677 /** @see PackageSettingBase#codePathString */ 10678 abstract String getCodePath(); 10679 /** @see PackageSettingBase#resourcePathString */ 10680 abstract String getResourcePath(); 10681 10682 // Need installer lock especially for dex file removal. 10683 abstract void cleanUpResourcesLI(); 10684 abstract boolean doPostDeleteLI(boolean delete); 10685 10686 /** 10687 * Called before the source arguments are copied. This is used mostly 10688 * for MoveParams when it needs to read the source file to put it in the 10689 * destination. 10690 */ 10691 int doPreCopy() { 10692 return PackageManager.INSTALL_SUCCEEDED; 10693 } 10694 10695 /** 10696 * Called after the source arguments are copied. This is used mostly for 10697 * MoveParams when it needs to read the source file to put it in the 10698 * destination. 10699 * 10700 * @return 10701 */ 10702 int doPostCopy(int uid) { 10703 return PackageManager.INSTALL_SUCCEEDED; 10704 } 10705 10706 protected boolean isFwdLocked() { 10707 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10708 } 10709 10710 protected boolean isExternalAsec() { 10711 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10712 } 10713 10714 UserHandle getUser() { 10715 return user; 10716 } 10717 } 10718 10719 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10720 if (!allCodePaths.isEmpty()) { 10721 if (instructionSets == null) { 10722 throw new IllegalStateException("instructionSet == null"); 10723 } 10724 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10725 for (String codePath : allCodePaths) { 10726 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10727 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10728 if (retCode < 0) { 10729 Slog.w(TAG, "Couldn't remove dex file for package: " 10730 + " at location " + codePath + ", retcode=" + retCode); 10731 // we don't consider this to be a failure of the core package deletion 10732 } 10733 } 10734 } 10735 } 10736 } 10737 10738 /** 10739 * Logic to handle installation of non-ASEC applications, including copying 10740 * and renaming logic. 10741 */ 10742 class FileInstallArgs extends InstallArgs { 10743 private File codeFile; 10744 private File resourceFile; 10745 10746 // Example topology: 10747 // /data/app/com.example/base.apk 10748 // /data/app/com.example/split_foo.apk 10749 // /data/app/com.example/lib/arm/libfoo.so 10750 // /data/app/com.example/lib/arm64/libfoo.so 10751 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10752 10753 /** New install */ 10754 FileInstallArgs(InstallParams params) { 10755 super(params.origin, params.move, params.observer, params.installFlags, 10756 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10757 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10758 if (isFwdLocked()) { 10759 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10760 } 10761 } 10762 10763 /** Existing install */ 10764 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10765 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10766 null); 10767 this.codeFile = (codePath != null) ? new File(codePath) : null; 10768 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10769 } 10770 10771 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10772 if (origin.staged) { 10773 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10774 codeFile = origin.file; 10775 resourceFile = origin.file; 10776 return PackageManager.INSTALL_SUCCEEDED; 10777 } 10778 10779 try { 10780 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10781 codeFile = tempDir; 10782 resourceFile = tempDir; 10783 } catch (IOException e) { 10784 Slog.w(TAG, "Failed to create copy file: " + e); 10785 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10786 } 10787 10788 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10789 @Override 10790 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10791 if (!FileUtils.isValidExtFilename(name)) { 10792 throw new IllegalArgumentException("Invalid filename: " + name); 10793 } 10794 try { 10795 final File file = new File(codeFile, name); 10796 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10797 O_RDWR | O_CREAT, 0644); 10798 Os.chmod(file.getAbsolutePath(), 0644); 10799 return new ParcelFileDescriptor(fd); 10800 } catch (ErrnoException e) { 10801 throw new RemoteException("Failed to open: " + e.getMessage()); 10802 } 10803 } 10804 }; 10805 10806 int ret = PackageManager.INSTALL_SUCCEEDED; 10807 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10808 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10809 Slog.e(TAG, "Failed to copy package"); 10810 return ret; 10811 } 10812 10813 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10814 NativeLibraryHelper.Handle handle = null; 10815 try { 10816 handle = NativeLibraryHelper.Handle.create(codeFile); 10817 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10818 abiOverride); 10819 } catch (IOException e) { 10820 Slog.e(TAG, "Copying native libraries failed", e); 10821 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10822 } finally { 10823 IoUtils.closeQuietly(handle); 10824 } 10825 10826 return ret; 10827 } 10828 10829 int doPreInstall(int status) { 10830 if (status != PackageManager.INSTALL_SUCCEEDED) { 10831 cleanUp(); 10832 } 10833 return status; 10834 } 10835 10836 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10837 if (status != PackageManager.INSTALL_SUCCEEDED) { 10838 cleanUp(); 10839 return false; 10840 } 10841 10842 final File targetDir = codeFile.getParentFile(); 10843 final File beforeCodeFile = codeFile; 10844 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10845 10846 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10847 try { 10848 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10849 } catch (ErrnoException e) { 10850 Slog.w(TAG, "Failed to rename", e); 10851 return false; 10852 } 10853 10854 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10855 Slog.w(TAG, "Failed to restorecon"); 10856 return false; 10857 } 10858 10859 // Reflect the rename internally 10860 codeFile = afterCodeFile; 10861 resourceFile = afterCodeFile; 10862 10863 // Reflect the rename in scanned details 10864 pkg.codePath = afterCodeFile.getAbsolutePath(); 10865 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10866 pkg.baseCodePath); 10867 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10868 pkg.splitCodePaths); 10869 10870 // Reflect the rename in app info 10871 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10872 pkg.applicationInfo.setCodePath(pkg.codePath); 10873 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10874 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10875 pkg.applicationInfo.setResourcePath(pkg.codePath); 10876 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10877 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10878 10879 return true; 10880 } 10881 10882 int doPostInstall(int status, int uid) { 10883 if (status != PackageManager.INSTALL_SUCCEEDED) { 10884 cleanUp(); 10885 } 10886 return status; 10887 } 10888 10889 @Override 10890 String getCodePath() { 10891 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10892 } 10893 10894 @Override 10895 String getResourcePath() { 10896 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10897 } 10898 10899 private boolean cleanUp() { 10900 if (codeFile == null || !codeFile.exists()) { 10901 return false; 10902 } 10903 10904 if (codeFile.isDirectory()) { 10905 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10906 } else { 10907 codeFile.delete(); 10908 } 10909 10910 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10911 resourceFile.delete(); 10912 } 10913 10914 return true; 10915 } 10916 10917 void cleanUpResourcesLI() { 10918 // Try enumerating all code paths before deleting 10919 List<String> allCodePaths = Collections.EMPTY_LIST; 10920 if (codeFile != null && codeFile.exists()) { 10921 try { 10922 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10923 allCodePaths = pkg.getAllCodePaths(); 10924 } catch (PackageParserException e) { 10925 // Ignored; we tried our best 10926 } 10927 } 10928 10929 cleanUp(); 10930 removeDexFiles(allCodePaths, instructionSets); 10931 } 10932 10933 boolean doPostDeleteLI(boolean delete) { 10934 // XXX err, shouldn't we respect the delete flag? 10935 cleanUpResourcesLI(); 10936 return true; 10937 } 10938 } 10939 10940 private boolean isAsecExternal(String cid) { 10941 final String asecPath = PackageHelper.getSdFilesystem(cid); 10942 return !asecPath.startsWith(mAsecInternalPath); 10943 } 10944 10945 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10946 PackageManagerException { 10947 if (copyRet < 0) { 10948 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10949 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10950 throw new PackageManagerException(copyRet, message); 10951 } 10952 } 10953 } 10954 10955 /** 10956 * Extract the MountService "container ID" from the full code path of an 10957 * .apk. 10958 */ 10959 static String cidFromCodePath(String fullCodePath) { 10960 int eidx = fullCodePath.lastIndexOf("/"); 10961 String subStr1 = fullCodePath.substring(0, eidx); 10962 int sidx = subStr1.lastIndexOf("/"); 10963 return subStr1.substring(sidx+1, eidx); 10964 } 10965 10966 /** 10967 * Logic to handle installation of ASEC applications, including copying and 10968 * renaming logic. 10969 */ 10970 class AsecInstallArgs extends InstallArgs { 10971 static final String RES_FILE_NAME = "pkg.apk"; 10972 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10973 10974 String cid; 10975 String packagePath; 10976 String resourcePath; 10977 10978 /** New install */ 10979 AsecInstallArgs(InstallParams params) { 10980 super(params.origin, params.move, params.observer, params.installFlags, 10981 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10982 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10983 } 10984 10985 /** Existing install */ 10986 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10987 boolean isExternal, boolean isForwardLocked) { 10988 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10989 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10990 instructionSets, null); 10991 // Hackily pretend we're still looking at a full code path 10992 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10993 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10994 } 10995 10996 // Extract cid from fullCodePath 10997 int eidx = fullCodePath.lastIndexOf("/"); 10998 String subStr1 = fullCodePath.substring(0, eidx); 10999 int sidx = subStr1.lastIndexOf("/"); 11000 cid = subStr1.substring(sidx+1, eidx); 11001 setMountPath(subStr1); 11002 } 11003 11004 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11005 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11006 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11007 instructionSets, null); 11008 this.cid = cid; 11009 setMountPath(PackageHelper.getSdDir(cid)); 11010 } 11011 11012 void createCopyFile() { 11013 cid = mInstallerService.allocateExternalStageCidLegacy(); 11014 } 11015 11016 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11017 if (origin.staged) { 11018 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11019 cid = origin.cid; 11020 setMountPath(PackageHelper.getSdDir(cid)); 11021 return PackageManager.INSTALL_SUCCEEDED; 11022 } 11023 11024 if (temp) { 11025 createCopyFile(); 11026 } else { 11027 /* 11028 * Pre-emptively destroy the container since it's destroyed if 11029 * copying fails due to it existing anyway. 11030 */ 11031 PackageHelper.destroySdDir(cid); 11032 } 11033 11034 final String newMountPath = imcs.copyPackageToContainer( 11035 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11036 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11037 11038 if (newMountPath != null) { 11039 setMountPath(newMountPath); 11040 return PackageManager.INSTALL_SUCCEEDED; 11041 } else { 11042 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11043 } 11044 } 11045 11046 @Override 11047 String getCodePath() { 11048 return packagePath; 11049 } 11050 11051 @Override 11052 String getResourcePath() { 11053 return resourcePath; 11054 } 11055 11056 int doPreInstall(int status) { 11057 if (status != PackageManager.INSTALL_SUCCEEDED) { 11058 // Destroy container 11059 PackageHelper.destroySdDir(cid); 11060 } else { 11061 boolean mounted = PackageHelper.isContainerMounted(cid); 11062 if (!mounted) { 11063 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11064 Process.SYSTEM_UID); 11065 if (newMountPath != null) { 11066 setMountPath(newMountPath); 11067 } else { 11068 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11069 } 11070 } 11071 } 11072 return status; 11073 } 11074 11075 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11076 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11077 String newMountPath = null; 11078 if (PackageHelper.isContainerMounted(cid)) { 11079 // Unmount the container 11080 if (!PackageHelper.unMountSdDir(cid)) { 11081 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11082 return false; 11083 } 11084 } 11085 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11086 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11087 " which might be stale. Will try to clean up."); 11088 // Clean up the stale container and proceed to recreate. 11089 if (!PackageHelper.destroySdDir(newCacheId)) { 11090 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11091 return false; 11092 } 11093 // Successfully cleaned up stale container. Try to rename again. 11094 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11095 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11096 + " inspite of cleaning it up."); 11097 return false; 11098 } 11099 } 11100 if (!PackageHelper.isContainerMounted(newCacheId)) { 11101 Slog.w(TAG, "Mounting container " + newCacheId); 11102 newMountPath = PackageHelper.mountSdDir(newCacheId, 11103 getEncryptKey(), Process.SYSTEM_UID); 11104 } else { 11105 newMountPath = PackageHelper.getSdDir(newCacheId); 11106 } 11107 if (newMountPath == null) { 11108 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11109 return false; 11110 } 11111 Log.i(TAG, "Succesfully renamed " + cid + 11112 " to " + newCacheId + 11113 " at new path: " + newMountPath); 11114 cid = newCacheId; 11115 11116 final File beforeCodeFile = new File(packagePath); 11117 setMountPath(newMountPath); 11118 final File afterCodeFile = new File(packagePath); 11119 11120 // Reflect the rename in scanned details 11121 pkg.codePath = afterCodeFile.getAbsolutePath(); 11122 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11123 pkg.baseCodePath); 11124 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11125 pkg.splitCodePaths); 11126 11127 // Reflect the rename in app info 11128 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11129 pkg.applicationInfo.setCodePath(pkg.codePath); 11130 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11131 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11132 pkg.applicationInfo.setResourcePath(pkg.codePath); 11133 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11134 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11135 11136 return true; 11137 } 11138 11139 private void setMountPath(String mountPath) { 11140 final File mountFile = new File(mountPath); 11141 11142 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11143 if (monolithicFile.exists()) { 11144 packagePath = monolithicFile.getAbsolutePath(); 11145 if (isFwdLocked()) { 11146 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11147 } else { 11148 resourcePath = packagePath; 11149 } 11150 } else { 11151 packagePath = mountFile.getAbsolutePath(); 11152 resourcePath = packagePath; 11153 } 11154 } 11155 11156 int doPostInstall(int status, int uid) { 11157 if (status != PackageManager.INSTALL_SUCCEEDED) { 11158 cleanUp(); 11159 } else { 11160 final int groupOwner; 11161 final String protectedFile; 11162 if (isFwdLocked()) { 11163 groupOwner = UserHandle.getSharedAppGid(uid); 11164 protectedFile = RES_FILE_NAME; 11165 } else { 11166 groupOwner = -1; 11167 protectedFile = null; 11168 } 11169 11170 if (uid < Process.FIRST_APPLICATION_UID 11171 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11172 Slog.e(TAG, "Failed to finalize " + cid); 11173 PackageHelper.destroySdDir(cid); 11174 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11175 } 11176 11177 boolean mounted = PackageHelper.isContainerMounted(cid); 11178 if (!mounted) { 11179 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11180 } 11181 } 11182 return status; 11183 } 11184 11185 private void cleanUp() { 11186 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11187 11188 // Destroy secure container 11189 PackageHelper.destroySdDir(cid); 11190 } 11191 11192 private List<String> getAllCodePaths() { 11193 final File codeFile = new File(getCodePath()); 11194 if (codeFile != null && codeFile.exists()) { 11195 try { 11196 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11197 return pkg.getAllCodePaths(); 11198 } catch (PackageParserException e) { 11199 // Ignored; we tried our best 11200 } 11201 } 11202 return Collections.EMPTY_LIST; 11203 } 11204 11205 void cleanUpResourcesLI() { 11206 // Enumerate all code paths before deleting 11207 cleanUpResourcesLI(getAllCodePaths()); 11208 } 11209 11210 private void cleanUpResourcesLI(List<String> allCodePaths) { 11211 cleanUp(); 11212 removeDexFiles(allCodePaths, instructionSets); 11213 } 11214 11215 String getPackageName() { 11216 return getAsecPackageName(cid); 11217 } 11218 11219 boolean doPostDeleteLI(boolean delete) { 11220 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11221 final List<String> allCodePaths = getAllCodePaths(); 11222 boolean mounted = PackageHelper.isContainerMounted(cid); 11223 if (mounted) { 11224 // Unmount first 11225 if (PackageHelper.unMountSdDir(cid)) { 11226 mounted = false; 11227 } 11228 } 11229 if (!mounted && delete) { 11230 cleanUpResourcesLI(allCodePaths); 11231 } 11232 return !mounted; 11233 } 11234 11235 @Override 11236 int doPreCopy() { 11237 if (isFwdLocked()) { 11238 if (!PackageHelper.fixSdPermissions(cid, 11239 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11240 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11241 } 11242 } 11243 11244 return PackageManager.INSTALL_SUCCEEDED; 11245 } 11246 11247 @Override 11248 int doPostCopy(int uid) { 11249 if (isFwdLocked()) { 11250 if (uid < Process.FIRST_APPLICATION_UID 11251 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11252 RES_FILE_NAME)) { 11253 Slog.e(TAG, "Failed to finalize " + cid); 11254 PackageHelper.destroySdDir(cid); 11255 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11256 } 11257 } 11258 11259 return PackageManager.INSTALL_SUCCEEDED; 11260 } 11261 } 11262 11263 /** 11264 * Logic to handle movement of existing installed applications. 11265 */ 11266 class MoveInstallArgs extends InstallArgs { 11267 private File codeFile; 11268 private File resourceFile; 11269 11270 /** New install */ 11271 MoveInstallArgs(InstallParams params) { 11272 super(params.origin, params.move, params.observer, params.installFlags, 11273 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11274 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11275 } 11276 11277 int copyApk(IMediaContainerService imcs, boolean temp) { 11278 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11279 + move.fromUuid + " to " + move.toUuid); 11280 synchronized (mInstaller) { 11281 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11282 move.dataAppName, move.appId, move.seinfo) != 0) { 11283 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11284 } 11285 } 11286 11287 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11288 resourceFile = codeFile; 11289 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11290 11291 return PackageManager.INSTALL_SUCCEEDED; 11292 } 11293 11294 int doPreInstall(int status) { 11295 if (status != PackageManager.INSTALL_SUCCEEDED) { 11296 cleanUp(); 11297 } 11298 return status; 11299 } 11300 11301 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11302 if (status != PackageManager.INSTALL_SUCCEEDED) { 11303 cleanUp(); 11304 return false; 11305 } 11306 11307 // Reflect the move in app info 11308 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11309 pkg.applicationInfo.setCodePath(pkg.codePath); 11310 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11311 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11312 pkg.applicationInfo.setResourcePath(pkg.codePath); 11313 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11314 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11315 11316 return true; 11317 } 11318 11319 int doPostInstall(int status, int uid) { 11320 if (status != PackageManager.INSTALL_SUCCEEDED) { 11321 cleanUp(); 11322 } 11323 return status; 11324 } 11325 11326 @Override 11327 String getCodePath() { 11328 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11329 } 11330 11331 @Override 11332 String getResourcePath() { 11333 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11334 } 11335 11336 private boolean cleanUp() { 11337 if (codeFile == null || !codeFile.exists()) { 11338 return false; 11339 } 11340 11341 if (codeFile.isDirectory()) { 11342 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11343 } else { 11344 codeFile.delete(); 11345 } 11346 11347 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11348 resourceFile.delete(); 11349 } 11350 11351 return true; 11352 } 11353 11354 void cleanUpResourcesLI() { 11355 cleanUp(); 11356 } 11357 11358 boolean doPostDeleteLI(boolean delete) { 11359 // XXX err, shouldn't we respect the delete flag? 11360 cleanUpResourcesLI(); 11361 return true; 11362 } 11363 } 11364 11365 static String getAsecPackageName(String packageCid) { 11366 int idx = packageCid.lastIndexOf("-"); 11367 if (idx == -1) { 11368 return packageCid; 11369 } 11370 return packageCid.substring(0, idx); 11371 } 11372 11373 // Utility method used to create code paths based on package name and available index. 11374 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11375 String idxStr = ""; 11376 int idx = 1; 11377 // Fall back to default value of idx=1 if prefix is not 11378 // part of oldCodePath 11379 if (oldCodePath != null) { 11380 String subStr = oldCodePath; 11381 // Drop the suffix right away 11382 if (suffix != null && subStr.endsWith(suffix)) { 11383 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11384 } 11385 // If oldCodePath already contains prefix find out the 11386 // ending index to either increment or decrement. 11387 int sidx = subStr.lastIndexOf(prefix); 11388 if (sidx != -1) { 11389 subStr = subStr.substring(sidx + prefix.length()); 11390 if (subStr != null) { 11391 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11392 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11393 } 11394 try { 11395 idx = Integer.parseInt(subStr); 11396 if (idx <= 1) { 11397 idx++; 11398 } else { 11399 idx--; 11400 } 11401 } catch(NumberFormatException e) { 11402 } 11403 } 11404 } 11405 } 11406 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11407 return prefix + idxStr; 11408 } 11409 11410 private File getNextCodePath(File targetDir, String packageName) { 11411 int suffix = 1; 11412 File result; 11413 do { 11414 result = new File(targetDir, packageName + "-" + suffix); 11415 suffix++; 11416 } while (result.exists()); 11417 return result; 11418 } 11419 11420 // Utility method that returns the relative package path with respect 11421 // to the installation directory. Like say for /data/data/com.test-1.apk 11422 // string com.test-1 is returned. 11423 static String deriveCodePathName(String codePath) { 11424 if (codePath == null) { 11425 return null; 11426 } 11427 final File codeFile = new File(codePath); 11428 final String name = codeFile.getName(); 11429 if (codeFile.isDirectory()) { 11430 return name; 11431 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11432 final int lastDot = name.lastIndexOf('.'); 11433 return name.substring(0, lastDot); 11434 } else { 11435 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11436 return null; 11437 } 11438 } 11439 11440 class PackageInstalledInfo { 11441 String name; 11442 int uid; 11443 // The set of users that originally had this package installed. 11444 int[] origUsers; 11445 // The set of users that now have this package installed. 11446 int[] newUsers; 11447 PackageParser.Package pkg; 11448 int returnCode; 11449 String returnMsg; 11450 PackageRemovedInfo removedInfo; 11451 11452 public void setError(int code, String msg) { 11453 returnCode = code; 11454 returnMsg = msg; 11455 Slog.w(TAG, msg); 11456 } 11457 11458 public void setError(String msg, PackageParserException e) { 11459 returnCode = e.error; 11460 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11461 Slog.w(TAG, msg, e); 11462 } 11463 11464 public void setError(String msg, PackageManagerException e) { 11465 returnCode = e.error; 11466 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11467 Slog.w(TAG, msg, e); 11468 } 11469 11470 // In some error cases we want to convey more info back to the observer 11471 String origPackage; 11472 String origPermission; 11473 } 11474 11475 /* 11476 * Install a non-existing package. 11477 */ 11478 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11479 UserHandle user, String installerPackageName, String volumeUuid, 11480 PackageInstalledInfo res) { 11481 // Remember this for later, in case we need to rollback this install 11482 String pkgName = pkg.packageName; 11483 11484 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11485 final boolean dataDirExists = Environment 11486 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11487 synchronized(mPackages) { 11488 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11489 // A package with the same name is already installed, though 11490 // it has been renamed to an older name. The package we 11491 // are trying to install should be installed as an update to 11492 // the existing one, but that has not been requested, so bail. 11493 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11494 + " without first uninstalling package running as " 11495 + mSettings.mRenamedPackages.get(pkgName)); 11496 return; 11497 } 11498 if (mPackages.containsKey(pkgName)) { 11499 // Don't allow installation over an existing package with the same name. 11500 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11501 + " without first uninstalling."); 11502 return; 11503 } 11504 } 11505 11506 try { 11507 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11508 System.currentTimeMillis(), user); 11509 11510 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11511 // delete the partially installed application. the data directory will have to be 11512 // restored if it was already existing 11513 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11514 // remove package from internal structures. Note that we want deletePackageX to 11515 // delete the package data and cache directories that it created in 11516 // scanPackageLocked, unless those directories existed before we even tried to 11517 // install. 11518 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11519 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11520 res.removedInfo, true); 11521 } 11522 11523 } catch (PackageManagerException e) { 11524 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11525 } 11526 } 11527 11528 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11529 // Can't rotate keys during boot or if sharedUser. 11530 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11531 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11532 return false; 11533 } 11534 // app is using upgradeKeySets; make sure all are valid 11535 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11536 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11537 for (int i = 0; i < upgradeKeySets.length; i++) { 11538 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11539 Slog.wtf(TAG, "Package " 11540 + (oldPs.name != null ? oldPs.name : "<null>") 11541 + " contains upgrade-key-set reference to unknown key-set: " 11542 + upgradeKeySets[i] 11543 + " reverting to signatures check."); 11544 return false; 11545 } 11546 } 11547 return true; 11548 } 11549 11550 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11551 // Upgrade keysets are being used. Determine if new package has a superset of the 11552 // required keys. 11553 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11554 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11555 for (int i = 0; i < upgradeKeySets.length; i++) { 11556 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11557 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11558 return true; 11559 } 11560 } 11561 return false; 11562 } 11563 11564 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11565 UserHandle user, String installerPackageName, String volumeUuid, 11566 PackageInstalledInfo res) { 11567 final PackageParser.Package oldPackage; 11568 final String pkgName = pkg.packageName; 11569 final int[] allUsers; 11570 final boolean[] perUserInstalled; 11571 final boolean weFroze; 11572 11573 // First find the old package info and check signatures 11574 synchronized(mPackages) { 11575 oldPackage = mPackages.get(pkgName); 11576 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11577 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11578 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11579 if(!checkUpgradeKeySetLP(ps, pkg)) { 11580 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11581 "New package not signed by keys specified by upgrade-keysets: " 11582 + pkgName); 11583 return; 11584 } 11585 } else { 11586 // default to original signature matching 11587 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11588 != PackageManager.SIGNATURE_MATCH) { 11589 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11590 "New package has a different signature: " + pkgName); 11591 return; 11592 } 11593 } 11594 11595 // In case of rollback, remember per-user/profile install state 11596 allUsers = sUserManager.getUserIds(); 11597 perUserInstalled = new boolean[allUsers.length]; 11598 for (int i = 0; i < allUsers.length; i++) { 11599 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11600 } 11601 11602 // Mark the app as frozen to prevent launching during the upgrade 11603 // process, and then kill all running instances 11604 if (!ps.frozen) { 11605 ps.frozen = true; 11606 weFroze = true; 11607 } else { 11608 weFroze = false; 11609 } 11610 } 11611 11612 // Now that we're guarded by frozen state, kill app during upgrade 11613 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11614 11615 try { 11616 boolean sysPkg = (isSystemApp(oldPackage)); 11617 if (sysPkg) { 11618 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11619 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11620 } else { 11621 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11622 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11623 } 11624 } finally { 11625 // Regardless of success or failure of upgrade steps above, always 11626 // unfreeze the package if we froze it 11627 if (weFroze) { 11628 unfreezePackage(pkgName); 11629 } 11630 } 11631 } 11632 11633 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11634 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11635 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11636 String volumeUuid, PackageInstalledInfo res) { 11637 String pkgName = deletedPackage.packageName; 11638 boolean deletedPkg = true; 11639 boolean updatedSettings = false; 11640 11641 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11642 + deletedPackage); 11643 long origUpdateTime; 11644 if (pkg.mExtras != null) { 11645 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11646 } else { 11647 origUpdateTime = 0; 11648 } 11649 11650 // First delete the existing package while retaining the data directory 11651 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11652 res.removedInfo, true)) { 11653 // If the existing package wasn't successfully deleted 11654 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11655 deletedPkg = false; 11656 } else { 11657 // Successfully deleted the old package; proceed with replace. 11658 11659 // If deleted package lived in a container, give users a chance to 11660 // relinquish resources before killing. 11661 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11662 if (DEBUG_INSTALL) { 11663 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11664 } 11665 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11666 final ArrayList<String> pkgList = new ArrayList<String>(1); 11667 pkgList.add(deletedPackage.applicationInfo.packageName); 11668 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11669 } 11670 11671 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11672 try { 11673 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11674 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11675 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11676 perUserInstalled, res, user); 11677 updatedSettings = true; 11678 } catch (PackageManagerException e) { 11679 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11680 } 11681 } 11682 11683 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11684 // remove package from internal structures. Note that we want deletePackageX to 11685 // delete the package data and cache directories that it created in 11686 // scanPackageLocked, unless those directories existed before we even tried to 11687 // install. 11688 if(updatedSettings) { 11689 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11690 deletePackageLI( 11691 pkgName, null, true, allUsers, perUserInstalled, 11692 PackageManager.DELETE_KEEP_DATA, 11693 res.removedInfo, true); 11694 } 11695 // Since we failed to install the new package we need to restore the old 11696 // package that we deleted. 11697 if (deletedPkg) { 11698 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11699 File restoreFile = new File(deletedPackage.codePath); 11700 // Parse old package 11701 boolean oldExternal = isExternal(deletedPackage); 11702 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11703 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11704 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11705 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11706 try { 11707 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11708 } catch (PackageManagerException e) { 11709 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11710 + e.getMessage()); 11711 return; 11712 } 11713 // Restore of old package succeeded. Update permissions. 11714 // writer 11715 synchronized (mPackages) { 11716 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11717 UPDATE_PERMISSIONS_ALL); 11718 // can downgrade to reader 11719 mSettings.writeLPr(); 11720 } 11721 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11722 } 11723 } 11724 } 11725 11726 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11727 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11728 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11729 String volumeUuid, PackageInstalledInfo res) { 11730 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11731 + ", old=" + deletedPackage); 11732 boolean disabledSystem = false; 11733 boolean updatedSettings = false; 11734 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11735 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11736 != 0) { 11737 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11738 } 11739 String packageName = deletedPackage.packageName; 11740 if (packageName == null) { 11741 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11742 "Attempt to delete null packageName."); 11743 return; 11744 } 11745 PackageParser.Package oldPkg; 11746 PackageSetting oldPkgSetting; 11747 // reader 11748 synchronized (mPackages) { 11749 oldPkg = mPackages.get(packageName); 11750 oldPkgSetting = mSettings.mPackages.get(packageName); 11751 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11752 (oldPkgSetting == null)) { 11753 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11754 "Couldn't find package:" + packageName + " information"); 11755 return; 11756 } 11757 } 11758 11759 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11760 res.removedInfo.removedPackage = packageName; 11761 // Remove existing system package 11762 removePackageLI(oldPkgSetting, true); 11763 // writer 11764 synchronized (mPackages) { 11765 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11766 if (!disabledSystem && deletedPackage != null) { 11767 // We didn't need to disable the .apk as a current system package, 11768 // which means we are replacing another update that is already 11769 // installed. We need to make sure to delete the older one's .apk. 11770 res.removedInfo.args = createInstallArgsForExisting(0, 11771 deletedPackage.applicationInfo.getCodePath(), 11772 deletedPackage.applicationInfo.getResourcePath(), 11773 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11774 } else { 11775 res.removedInfo.args = null; 11776 } 11777 } 11778 11779 // Successfully disabled the old package. Now proceed with re-installation 11780 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11781 11782 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11783 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11784 11785 PackageParser.Package newPackage = null; 11786 try { 11787 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11788 if (newPackage.mExtras != null) { 11789 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11790 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11791 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11792 11793 // is the update attempting to change shared user? that isn't going to work... 11794 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11795 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11796 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11797 + " to " + newPkgSetting.sharedUser); 11798 updatedSettings = true; 11799 } 11800 } 11801 11802 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11803 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11804 perUserInstalled, res, user); 11805 updatedSettings = true; 11806 } 11807 11808 } catch (PackageManagerException e) { 11809 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11810 } 11811 11812 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11813 // Re installation failed. Restore old information 11814 // Remove new pkg information 11815 if (newPackage != null) { 11816 removeInstalledPackageLI(newPackage, true); 11817 } 11818 // Add back the old system package 11819 try { 11820 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11821 } catch (PackageManagerException e) { 11822 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11823 } 11824 // Restore the old system information in Settings 11825 synchronized (mPackages) { 11826 if (disabledSystem) { 11827 mSettings.enableSystemPackageLPw(packageName); 11828 } 11829 if (updatedSettings) { 11830 mSettings.setInstallerPackageName(packageName, 11831 oldPkgSetting.installerPackageName); 11832 } 11833 mSettings.writeLPr(); 11834 } 11835 } 11836 } 11837 11838 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11839 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11840 UserHandle user) { 11841 String pkgName = newPackage.packageName; 11842 synchronized (mPackages) { 11843 //write settings. the installStatus will be incomplete at this stage. 11844 //note that the new package setting would have already been 11845 //added to mPackages. It hasn't been persisted yet. 11846 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11847 mSettings.writeLPr(); 11848 } 11849 11850 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11851 11852 synchronized (mPackages) { 11853 updatePermissionsLPw(newPackage.packageName, newPackage, 11854 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11855 ? UPDATE_PERMISSIONS_ALL : 0)); 11856 // For system-bundled packages, we assume that installing an upgraded version 11857 // of the package implies that the user actually wants to run that new code, 11858 // so we enable the package. 11859 PackageSetting ps = mSettings.mPackages.get(pkgName); 11860 if (ps != null) { 11861 if (isSystemApp(newPackage)) { 11862 // NB: implicit assumption that system package upgrades apply to all users 11863 if (DEBUG_INSTALL) { 11864 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11865 } 11866 if (res.origUsers != null) { 11867 for (int userHandle : res.origUsers) { 11868 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11869 userHandle, installerPackageName); 11870 } 11871 } 11872 // Also convey the prior install/uninstall state 11873 if (allUsers != null && perUserInstalled != null) { 11874 for (int i = 0; i < allUsers.length; i++) { 11875 if (DEBUG_INSTALL) { 11876 Slog.d(TAG, " user " + allUsers[i] 11877 + " => " + perUserInstalled[i]); 11878 } 11879 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11880 } 11881 // these install state changes will be persisted in the 11882 // upcoming call to mSettings.writeLPr(). 11883 } 11884 } 11885 // It's implied that when a user requests installation, they want the app to be 11886 // installed and enabled. 11887 int userId = user.getIdentifier(); 11888 if (userId != UserHandle.USER_ALL) { 11889 ps.setInstalled(true, userId); 11890 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11891 } 11892 } 11893 res.name = pkgName; 11894 res.uid = newPackage.applicationInfo.uid; 11895 res.pkg = newPackage; 11896 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11897 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11898 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11899 //to update install status 11900 mSettings.writeLPr(); 11901 } 11902 } 11903 11904 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11905 final int installFlags = args.installFlags; 11906 final String installerPackageName = args.installerPackageName; 11907 final String volumeUuid = args.volumeUuid; 11908 final File tmpPackageFile = new File(args.getCodePath()); 11909 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11910 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11911 || (args.volumeUuid != null)); 11912 boolean replace = false; 11913 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11914 if (args.move != null) { 11915 // moving a complete application; perfom an initial scan on the new install location 11916 scanFlags |= SCAN_INITIAL; 11917 } 11918 // Result object to be returned 11919 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11920 11921 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11922 // Retrieve PackageSettings and parse package 11923 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11924 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11925 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11926 PackageParser pp = new PackageParser(); 11927 pp.setSeparateProcesses(mSeparateProcesses); 11928 pp.setDisplayMetrics(mMetrics); 11929 11930 final PackageParser.Package pkg; 11931 try { 11932 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11933 } catch (PackageParserException e) { 11934 res.setError("Failed parse during installPackageLI", e); 11935 return; 11936 } 11937 11938 // Mark that we have an install time CPU ABI override. 11939 pkg.cpuAbiOverride = args.abiOverride; 11940 11941 String pkgName = res.name = pkg.packageName; 11942 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11943 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11944 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11945 return; 11946 } 11947 } 11948 11949 try { 11950 pp.collectCertificates(pkg, parseFlags); 11951 pp.collectManifestDigest(pkg); 11952 } catch (PackageParserException e) { 11953 res.setError("Failed collect during installPackageLI", e); 11954 return; 11955 } 11956 11957 /* If the installer passed in a manifest digest, compare it now. */ 11958 if (args.manifestDigest != null) { 11959 if (DEBUG_INSTALL) { 11960 final String parsedManifest = pkg.manifestDigest == null ? "null" 11961 : pkg.manifestDigest.toString(); 11962 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11963 + parsedManifest); 11964 } 11965 11966 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11967 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11968 return; 11969 } 11970 } else if (DEBUG_INSTALL) { 11971 final String parsedManifest = pkg.manifestDigest == null 11972 ? "null" : pkg.manifestDigest.toString(); 11973 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11974 } 11975 11976 // Get rid of all references to package scan path via parser. 11977 pp = null; 11978 String oldCodePath = null; 11979 boolean systemApp = false; 11980 synchronized (mPackages) { 11981 // Check if installing already existing package 11982 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11983 String oldName = mSettings.mRenamedPackages.get(pkgName); 11984 if (pkg.mOriginalPackages != null 11985 && pkg.mOriginalPackages.contains(oldName) 11986 && mPackages.containsKey(oldName)) { 11987 // This package is derived from an original package, 11988 // and this device has been updating from that original 11989 // name. We must continue using the original name, so 11990 // rename the new package here. 11991 pkg.setPackageName(oldName); 11992 pkgName = pkg.packageName; 11993 replace = true; 11994 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11995 + oldName + " pkgName=" + pkgName); 11996 } else if (mPackages.containsKey(pkgName)) { 11997 // This package, under its official name, already exists 11998 // on the device; we should replace it. 11999 replace = true; 12000 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12001 } 12002 12003 // Prevent apps opting out from runtime permissions 12004 if (replace) { 12005 PackageParser.Package oldPackage = mPackages.get(pkgName); 12006 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12007 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12008 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12009 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12010 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12011 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12012 + " doesn't support runtime permissions but the old" 12013 + " target SDK " + oldTargetSdk + " does."); 12014 return; 12015 } 12016 } 12017 } 12018 12019 PackageSetting ps = mSettings.mPackages.get(pkgName); 12020 if (ps != null) { 12021 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12022 12023 // Quick sanity check that we're signed correctly if updating; 12024 // we'll check this again later when scanning, but we want to 12025 // bail early here before tripping over redefined permissions. 12026 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12027 if (!checkUpgradeKeySetLP(ps, pkg)) { 12028 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12029 + pkg.packageName + " upgrade keys do not match the " 12030 + "previously installed version"); 12031 return; 12032 } 12033 } else { 12034 try { 12035 verifySignaturesLP(ps, pkg); 12036 } catch (PackageManagerException e) { 12037 res.setError(e.error, e.getMessage()); 12038 return; 12039 } 12040 } 12041 12042 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12043 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12044 systemApp = (ps.pkg.applicationInfo.flags & 12045 ApplicationInfo.FLAG_SYSTEM) != 0; 12046 } 12047 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12048 } 12049 12050 // Check whether the newly-scanned package wants to define an already-defined perm 12051 int N = pkg.permissions.size(); 12052 for (int i = N-1; i >= 0; i--) { 12053 PackageParser.Permission perm = pkg.permissions.get(i); 12054 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12055 if (bp != null) { 12056 // If the defining package is signed with our cert, it's okay. This 12057 // also includes the "updating the same package" case, of course. 12058 // "updating same package" could also involve key-rotation. 12059 final boolean sigsOk; 12060 if (bp.sourcePackage.equals(pkg.packageName) 12061 && (bp.packageSetting instanceof PackageSetting) 12062 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12063 scanFlags))) { 12064 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12065 } else { 12066 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12067 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12068 } 12069 if (!sigsOk) { 12070 // If the owning package is the system itself, we log but allow 12071 // install to proceed; we fail the install on all other permission 12072 // redefinitions. 12073 if (!bp.sourcePackage.equals("android")) { 12074 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12075 + pkg.packageName + " attempting to redeclare permission " 12076 + perm.info.name + " already owned by " + bp.sourcePackage); 12077 res.origPermission = perm.info.name; 12078 res.origPackage = bp.sourcePackage; 12079 return; 12080 } else { 12081 Slog.w(TAG, "Package " + pkg.packageName 12082 + " attempting to redeclare system permission " 12083 + perm.info.name + "; ignoring new declaration"); 12084 pkg.permissions.remove(i); 12085 } 12086 } 12087 } 12088 } 12089 12090 } 12091 12092 if (systemApp && onExternal) { 12093 // Disable updates to system apps on sdcard 12094 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12095 "Cannot install updates to system apps on sdcard"); 12096 return; 12097 } 12098 12099 if (args.move != null) { 12100 // We did an in-place move, so dex is ready to roll 12101 scanFlags |= SCAN_NO_DEX; 12102 scanFlags |= SCAN_MOVE; 12103 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12104 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12105 scanFlags |= SCAN_NO_DEX; 12106 12107 try { 12108 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12109 true /* extract libs */); 12110 } catch (PackageManagerException pme) { 12111 Slog.e(TAG, "Error deriving application ABI", pme); 12112 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12113 return; 12114 } 12115 12116 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12117 int result = mPackageDexOptimizer 12118 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12119 false /* defer */, false /* inclDependencies */); 12120 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12121 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12122 return; 12123 } 12124 } 12125 12126 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12127 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12128 return; 12129 } 12130 12131 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12132 12133 if (replace) { 12134 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12135 installerPackageName, volumeUuid, res); 12136 } else { 12137 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12138 args.user, installerPackageName, volumeUuid, res); 12139 } 12140 synchronized (mPackages) { 12141 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12142 if (ps != null) { 12143 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12144 } 12145 } 12146 } 12147 12148 private void startIntentFilterVerifications(int userId, boolean replacing, 12149 PackageParser.Package pkg) { 12150 if (mIntentFilterVerifierComponent == null) { 12151 Slog.w(TAG, "No IntentFilter verification will not be done as " 12152 + "there is no IntentFilterVerifier available!"); 12153 return; 12154 } 12155 12156 final int verifierUid = getPackageUid( 12157 mIntentFilterVerifierComponent.getPackageName(), 12158 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12159 12160 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12161 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12162 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12163 mHandler.sendMessage(msg); 12164 } 12165 12166 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12167 PackageParser.Package pkg) { 12168 int size = pkg.activities.size(); 12169 if (size == 0) { 12170 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12171 "No activity, so no need to verify any IntentFilter!"); 12172 return; 12173 } 12174 12175 final boolean hasDomainURLs = hasDomainURLs(pkg); 12176 if (!hasDomainURLs) { 12177 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12178 "No domain URLs, so no need to verify any IntentFilter!"); 12179 return; 12180 } 12181 12182 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12183 + " if any IntentFilter from the " + size 12184 + " Activities needs verification ..."); 12185 12186 int count = 0; 12187 final String packageName = pkg.packageName; 12188 12189 synchronized (mPackages) { 12190 // If this is a new install and we see that we've already run verification for this 12191 // package, we have nothing to do: it means the state was restored from backup. 12192 if (!replacing) { 12193 IntentFilterVerificationInfo ivi = 12194 mSettings.getIntentFilterVerificationLPr(packageName); 12195 if (ivi != null) { 12196 if (DEBUG_DOMAIN_VERIFICATION) { 12197 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12198 + ivi.getStatusString()); 12199 } 12200 return; 12201 } 12202 } 12203 12204 // If any filters need to be verified, then all need to be. 12205 boolean needToVerify = false; 12206 for (PackageParser.Activity a : pkg.activities) { 12207 for (ActivityIntentInfo filter : a.intents) { 12208 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12209 if (DEBUG_DOMAIN_VERIFICATION) { 12210 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12211 } 12212 needToVerify = true; 12213 break; 12214 } 12215 } 12216 } 12217 12218 if (needToVerify) { 12219 final int verificationId = mIntentFilterVerificationToken++; 12220 for (PackageParser.Activity a : pkg.activities) { 12221 for (ActivityIntentInfo filter : a.intents) { 12222 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12223 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12224 "Verification needed for IntentFilter:" + filter.toString()); 12225 mIntentFilterVerifier.addOneIntentFilterVerification( 12226 verifierUid, userId, verificationId, filter, packageName); 12227 count++; 12228 } 12229 } 12230 } 12231 } 12232 } 12233 12234 if (count > 0) { 12235 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12236 + " IntentFilter verification" + (count > 1 ? "s" : "") 12237 + " for userId:" + userId); 12238 mIntentFilterVerifier.startVerifications(userId); 12239 } else { 12240 if (DEBUG_DOMAIN_VERIFICATION) { 12241 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12242 } 12243 } 12244 } 12245 12246 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12247 final ComponentName cn = filter.activity.getComponentName(); 12248 final String packageName = cn.getPackageName(); 12249 12250 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12251 packageName); 12252 if (ivi == null) { 12253 return true; 12254 } 12255 int status = ivi.getStatus(); 12256 switch (status) { 12257 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12258 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12259 return true; 12260 12261 default: 12262 // Nothing to do 12263 return false; 12264 } 12265 } 12266 12267 private static boolean isMultiArch(PackageSetting ps) { 12268 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12269 } 12270 12271 private static boolean isMultiArch(ApplicationInfo info) { 12272 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12273 } 12274 12275 private static boolean isExternal(PackageParser.Package pkg) { 12276 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12277 } 12278 12279 private static boolean isExternal(PackageSetting ps) { 12280 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12281 } 12282 12283 private static boolean isExternal(ApplicationInfo info) { 12284 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12285 } 12286 12287 private static boolean isSystemApp(PackageParser.Package pkg) { 12288 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12289 } 12290 12291 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12292 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12293 } 12294 12295 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12296 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12297 } 12298 12299 private static boolean isSystemApp(PackageSetting ps) { 12300 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12301 } 12302 12303 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12304 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12305 } 12306 12307 private int packageFlagsToInstallFlags(PackageSetting ps) { 12308 int installFlags = 0; 12309 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12310 // This existing package was an external ASEC install when we have 12311 // the external flag without a UUID 12312 installFlags |= PackageManager.INSTALL_EXTERNAL; 12313 } 12314 if (ps.isForwardLocked()) { 12315 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12316 } 12317 return installFlags; 12318 } 12319 12320 private void deleteTempPackageFiles() { 12321 final FilenameFilter filter = new FilenameFilter() { 12322 public boolean accept(File dir, String name) { 12323 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12324 } 12325 }; 12326 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12327 file.delete(); 12328 } 12329 } 12330 12331 @Override 12332 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12333 int flags) { 12334 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12335 flags); 12336 } 12337 12338 @Override 12339 public void deletePackage(final String packageName, 12340 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12341 mContext.enforceCallingOrSelfPermission( 12342 android.Manifest.permission.DELETE_PACKAGES, null); 12343 Preconditions.checkNotNull(packageName); 12344 Preconditions.checkNotNull(observer); 12345 final int uid = Binder.getCallingUid(); 12346 if (UserHandle.getUserId(uid) != userId) { 12347 mContext.enforceCallingPermission( 12348 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12349 "deletePackage for user " + userId); 12350 } 12351 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12352 try { 12353 observer.onPackageDeleted(packageName, 12354 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12355 } catch (RemoteException re) { 12356 } 12357 return; 12358 } 12359 12360 boolean uninstallBlocked = false; 12361 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12362 int[] users = sUserManager.getUserIds(); 12363 for (int i = 0; i < users.length; ++i) { 12364 if (getBlockUninstallForUser(packageName, users[i])) { 12365 uninstallBlocked = true; 12366 break; 12367 } 12368 } 12369 } else { 12370 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12371 } 12372 if (uninstallBlocked) { 12373 try { 12374 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12375 null); 12376 } catch (RemoteException re) { 12377 } 12378 return; 12379 } 12380 12381 if (DEBUG_REMOVE) { 12382 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12383 } 12384 // Queue up an async operation since the package deletion may take a little while. 12385 mHandler.post(new Runnable() { 12386 public void run() { 12387 mHandler.removeCallbacks(this); 12388 final int returnCode = deletePackageX(packageName, userId, flags); 12389 if (observer != null) { 12390 try { 12391 observer.onPackageDeleted(packageName, returnCode, null); 12392 } catch (RemoteException e) { 12393 Log.i(TAG, "Observer no longer exists."); 12394 } //end catch 12395 } //end if 12396 } //end run 12397 }); 12398 } 12399 12400 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12401 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12402 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12403 try { 12404 if (dpm != null) { 12405 if (dpm.isDeviceOwner(packageName)) { 12406 return true; 12407 } 12408 int[] users; 12409 if (userId == UserHandle.USER_ALL) { 12410 users = sUserManager.getUserIds(); 12411 } else { 12412 users = new int[]{userId}; 12413 } 12414 for (int i = 0; i < users.length; ++i) { 12415 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12416 return true; 12417 } 12418 } 12419 } 12420 } catch (RemoteException e) { 12421 } 12422 return false; 12423 } 12424 12425 /** 12426 * This method is an internal method that could be get invoked either 12427 * to delete an installed package or to clean up a failed installation. 12428 * After deleting an installed package, a broadcast is sent to notify any 12429 * listeners that the package has been installed. For cleaning up a failed 12430 * installation, the broadcast is not necessary since the package's 12431 * installation wouldn't have sent the initial broadcast either 12432 * The key steps in deleting a package are 12433 * deleting the package information in internal structures like mPackages, 12434 * deleting the packages base directories through installd 12435 * updating mSettings to reflect current status 12436 * persisting settings for later use 12437 * sending a broadcast if necessary 12438 */ 12439 private int deletePackageX(String packageName, int userId, int flags) { 12440 final PackageRemovedInfo info = new PackageRemovedInfo(); 12441 final boolean res; 12442 12443 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12444 ? UserHandle.ALL : new UserHandle(userId); 12445 12446 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12447 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12448 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12449 } 12450 12451 boolean removedForAllUsers = false; 12452 boolean systemUpdate = false; 12453 12454 // for the uninstall-updates case and restricted profiles, remember the per- 12455 // userhandle installed state 12456 int[] allUsers; 12457 boolean[] perUserInstalled; 12458 synchronized (mPackages) { 12459 PackageSetting ps = mSettings.mPackages.get(packageName); 12460 allUsers = sUserManager.getUserIds(); 12461 perUserInstalled = new boolean[allUsers.length]; 12462 for (int i = 0; i < allUsers.length; i++) { 12463 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12464 } 12465 } 12466 12467 synchronized (mInstallLock) { 12468 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12469 res = deletePackageLI(packageName, removeForUser, 12470 true, allUsers, perUserInstalled, 12471 flags | REMOVE_CHATTY, info, true); 12472 systemUpdate = info.isRemovedPackageSystemUpdate; 12473 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12474 removedForAllUsers = true; 12475 } 12476 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12477 + " removedForAllUsers=" + removedForAllUsers); 12478 } 12479 12480 if (res) { 12481 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12482 12483 // If the removed package was a system update, the old system package 12484 // was re-enabled; we need to broadcast this information 12485 if (systemUpdate) { 12486 Bundle extras = new Bundle(1); 12487 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12488 ? info.removedAppId : info.uid); 12489 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12490 12491 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12492 extras, null, null, null); 12493 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12494 extras, null, null, null); 12495 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12496 null, packageName, null, null); 12497 } 12498 } 12499 // Force a gc here. 12500 Runtime.getRuntime().gc(); 12501 // Delete the resources here after sending the broadcast to let 12502 // other processes clean up before deleting resources. 12503 if (info.args != null) { 12504 synchronized (mInstallLock) { 12505 info.args.doPostDeleteLI(true); 12506 } 12507 } 12508 12509 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12510 } 12511 12512 class PackageRemovedInfo { 12513 String removedPackage; 12514 int uid = -1; 12515 int removedAppId = -1; 12516 int[] removedUsers = null; 12517 boolean isRemovedPackageSystemUpdate = false; 12518 // Clean up resources deleted packages. 12519 InstallArgs args = null; 12520 12521 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12522 Bundle extras = new Bundle(1); 12523 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12524 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12525 if (replacing) { 12526 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12527 } 12528 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12529 if (removedPackage != null) { 12530 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12531 extras, null, null, removedUsers); 12532 if (fullRemove && !replacing) { 12533 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12534 extras, null, null, removedUsers); 12535 } 12536 } 12537 if (removedAppId >= 0) { 12538 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12539 removedUsers); 12540 } 12541 } 12542 } 12543 12544 /* 12545 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12546 * flag is not set, the data directory is removed as well. 12547 * make sure this flag is set for partially installed apps. If not its meaningless to 12548 * delete a partially installed application. 12549 */ 12550 private void removePackageDataLI(PackageSetting ps, 12551 int[] allUserHandles, boolean[] perUserInstalled, 12552 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12553 String packageName = ps.name; 12554 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12555 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12556 // Retrieve object to delete permissions for shared user later on 12557 final PackageSetting deletedPs; 12558 // reader 12559 synchronized (mPackages) { 12560 deletedPs = mSettings.mPackages.get(packageName); 12561 if (outInfo != null) { 12562 outInfo.removedPackage = packageName; 12563 outInfo.removedUsers = deletedPs != null 12564 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12565 : null; 12566 } 12567 } 12568 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12569 removeDataDirsLI(ps.volumeUuid, packageName); 12570 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12571 } 12572 // writer 12573 synchronized (mPackages) { 12574 if (deletedPs != null) { 12575 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12576 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12577 clearDefaultBrowserIfNeeded(packageName); 12578 if (outInfo != null) { 12579 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12580 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12581 } 12582 updatePermissionsLPw(deletedPs.name, null, 0); 12583 if (deletedPs.sharedUser != null) { 12584 // Remove permissions associated with package. Since runtime 12585 // permissions are per user we have to kill the removed package 12586 // or packages running under the shared user of the removed 12587 // package if revoking the permissions requested only by the removed 12588 // package is successful and this causes a change in gids. 12589 for (int userId : UserManagerService.getInstance().getUserIds()) { 12590 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12591 userId); 12592 if (userIdToKill == UserHandle.USER_ALL 12593 || userIdToKill >= UserHandle.USER_OWNER) { 12594 // If gids changed for this user, kill all affected packages. 12595 mHandler.post(new Runnable() { 12596 @Override 12597 public void run() { 12598 // This has to happen with no lock held. 12599 killSettingPackagesForUser(deletedPs, userIdToKill, 12600 KILL_APP_REASON_GIDS_CHANGED); 12601 } 12602 }); 12603 break; 12604 } 12605 } 12606 } 12607 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12608 } 12609 // make sure to preserve per-user disabled state if this removal was just 12610 // a downgrade of a system app to the factory package 12611 if (allUserHandles != null && perUserInstalled != null) { 12612 if (DEBUG_REMOVE) { 12613 Slog.d(TAG, "Propagating install state across downgrade"); 12614 } 12615 for (int i = 0; i < allUserHandles.length; i++) { 12616 if (DEBUG_REMOVE) { 12617 Slog.d(TAG, " user " + allUserHandles[i] 12618 + " => " + perUserInstalled[i]); 12619 } 12620 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12621 } 12622 } 12623 } 12624 // can downgrade to reader 12625 if (writeSettings) { 12626 // Save settings now 12627 mSettings.writeLPr(); 12628 } 12629 } 12630 if (outInfo != null) { 12631 // A user ID was deleted here. Go through all users and remove it 12632 // from KeyStore. 12633 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12634 } 12635 } 12636 12637 static boolean locationIsPrivileged(File path) { 12638 try { 12639 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12640 .getCanonicalPath(); 12641 return path.getCanonicalPath().startsWith(privilegedAppDir); 12642 } catch (IOException e) { 12643 Slog.e(TAG, "Unable to access code path " + path); 12644 } 12645 return false; 12646 } 12647 12648 /* 12649 * Tries to delete system package. 12650 */ 12651 private boolean deleteSystemPackageLI(PackageSetting newPs, 12652 int[] allUserHandles, boolean[] perUserInstalled, 12653 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12654 final boolean applyUserRestrictions 12655 = (allUserHandles != null) && (perUserInstalled != null); 12656 PackageSetting disabledPs = null; 12657 // Confirm if the system package has been updated 12658 // An updated system app can be deleted. This will also have to restore 12659 // the system pkg from system partition 12660 // reader 12661 synchronized (mPackages) { 12662 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12663 } 12664 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12665 + " disabledPs=" + disabledPs); 12666 if (disabledPs == null) { 12667 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12668 return false; 12669 } else if (DEBUG_REMOVE) { 12670 Slog.d(TAG, "Deleting system pkg from data partition"); 12671 } 12672 if (DEBUG_REMOVE) { 12673 if (applyUserRestrictions) { 12674 Slog.d(TAG, "Remembering install states:"); 12675 for (int i = 0; i < allUserHandles.length; i++) { 12676 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12677 } 12678 } 12679 } 12680 // Delete the updated package 12681 outInfo.isRemovedPackageSystemUpdate = true; 12682 if (disabledPs.versionCode < newPs.versionCode) { 12683 // Delete data for downgrades 12684 flags &= ~PackageManager.DELETE_KEEP_DATA; 12685 } else { 12686 // Preserve data by setting flag 12687 flags |= PackageManager.DELETE_KEEP_DATA; 12688 } 12689 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12690 allUserHandles, perUserInstalled, outInfo, writeSettings); 12691 if (!ret) { 12692 return false; 12693 } 12694 // writer 12695 synchronized (mPackages) { 12696 // Reinstate the old system package 12697 mSettings.enableSystemPackageLPw(newPs.name); 12698 // Remove any native libraries from the upgraded package. 12699 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12700 } 12701 // Install the system package 12702 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12703 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12704 if (locationIsPrivileged(disabledPs.codePath)) { 12705 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12706 } 12707 12708 final PackageParser.Package newPkg; 12709 try { 12710 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12711 } catch (PackageManagerException e) { 12712 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12713 return false; 12714 } 12715 12716 // writer 12717 synchronized (mPackages) { 12718 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12719 updatePermissionsLPw(newPkg.packageName, newPkg, 12720 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12721 if (applyUserRestrictions) { 12722 if (DEBUG_REMOVE) { 12723 Slog.d(TAG, "Propagating install state across reinstall"); 12724 } 12725 for (int i = 0; i < allUserHandles.length; i++) { 12726 if (DEBUG_REMOVE) { 12727 Slog.d(TAG, " user " + allUserHandles[i] 12728 + " => " + perUserInstalled[i]); 12729 } 12730 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12731 } 12732 // Regardless of writeSettings we need to ensure that this restriction 12733 // state propagation is persisted 12734 mSettings.writeAllUsersPackageRestrictionsLPr(); 12735 } 12736 // can downgrade to reader here 12737 if (writeSettings) { 12738 mSettings.writeLPr(); 12739 } 12740 } 12741 return true; 12742 } 12743 12744 private boolean deleteInstalledPackageLI(PackageSetting ps, 12745 boolean deleteCodeAndResources, int flags, 12746 int[] allUserHandles, boolean[] perUserInstalled, 12747 PackageRemovedInfo outInfo, boolean writeSettings) { 12748 if (outInfo != null) { 12749 outInfo.uid = ps.appId; 12750 } 12751 12752 // Delete package data from internal structures and also remove data if flag is set 12753 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12754 12755 // Delete application code and resources 12756 if (deleteCodeAndResources && (outInfo != null)) { 12757 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12758 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12759 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12760 } 12761 return true; 12762 } 12763 12764 @Override 12765 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12766 int userId) { 12767 mContext.enforceCallingOrSelfPermission( 12768 android.Manifest.permission.DELETE_PACKAGES, null); 12769 synchronized (mPackages) { 12770 PackageSetting ps = mSettings.mPackages.get(packageName); 12771 if (ps == null) { 12772 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12773 return false; 12774 } 12775 if (!ps.getInstalled(userId)) { 12776 // Can't block uninstall for an app that is not installed or enabled. 12777 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12778 return false; 12779 } 12780 ps.setBlockUninstall(blockUninstall, userId); 12781 mSettings.writePackageRestrictionsLPr(userId); 12782 } 12783 return true; 12784 } 12785 12786 @Override 12787 public boolean getBlockUninstallForUser(String packageName, int userId) { 12788 synchronized (mPackages) { 12789 PackageSetting ps = mSettings.mPackages.get(packageName); 12790 if (ps == null) { 12791 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12792 return false; 12793 } 12794 return ps.getBlockUninstall(userId); 12795 } 12796 } 12797 12798 /* 12799 * This method handles package deletion in general 12800 */ 12801 private boolean deletePackageLI(String packageName, UserHandle user, 12802 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12803 int flags, PackageRemovedInfo outInfo, 12804 boolean writeSettings) { 12805 if (packageName == null) { 12806 Slog.w(TAG, "Attempt to delete null packageName."); 12807 return false; 12808 } 12809 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12810 PackageSetting ps; 12811 boolean dataOnly = false; 12812 int removeUser = -1; 12813 int appId = -1; 12814 synchronized (mPackages) { 12815 ps = mSettings.mPackages.get(packageName); 12816 if (ps == null) { 12817 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12818 return false; 12819 } 12820 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12821 && user.getIdentifier() != UserHandle.USER_ALL) { 12822 // The caller is asking that the package only be deleted for a single 12823 // user. To do this, we just mark its uninstalled state and delete 12824 // its data. If this is a system app, we only allow this to happen if 12825 // they have set the special DELETE_SYSTEM_APP which requests different 12826 // semantics than normal for uninstalling system apps. 12827 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12828 ps.setUserState(user.getIdentifier(), 12829 COMPONENT_ENABLED_STATE_DEFAULT, 12830 false, //installed 12831 true, //stopped 12832 true, //notLaunched 12833 false, //hidden 12834 null, null, null, 12835 false, // blockUninstall 12836 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12837 if (!isSystemApp(ps)) { 12838 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12839 // Other user still have this package installed, so all 12840 // we need to do is clear this user's data and save that 12841 // it is uninstalled. 12842 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12843 removeUser = user.getIdentifier(); 12844 appId = ps.appId; 12845 scheduleWritePackageRestrictionsLocked(removeUser); 12846 } else { 12847 // We need to set it back to 'installed' so the uninstall 12848 // broadcasts will be sent correctly. 12849 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12850 ps.setInstalled(true, user.getIdentifier()); 12851 } 12852 } else { 12853 // This is a system app, so we assume that the 12854 // other users still have this package installed, so all 12855 // we need to do is clear this user's data and save that 12856 // it is uninstalled. 12857 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12858 removeUser = user.getIdentifier(); 12859 appId = ps.appId; 12860 scheduleWritePackageRestrictionsLocked(removeUser); 12861 } 12862 } 12863 } 12864 12865 if (removeUser >= 0) { 12866 // From above, we determined that we are deleting this only 12867 // for a single user. Continue the work here. 12868 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12869 if (outInfo != null) { 12870 outInfo.removedPackage = packageName; 12871 outInfo.removedAppId = appId; 12872 outInfo.removedUsers = new int[] {removeUser}; 12873 } 12874 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12875 removeKeystoreDataIfNeeded(removeUser, appId); 12876 schedulePackageCleaning(packageName, removeUser, false); 12877 synchronized (mPackages) { 12878 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12879 scheduleWritePackageRestrictionsLocked(removeUser); 12880 } 12881 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12882 removeUser); 12883 } 12884 return true; 12885 } 12886 12887 if (dataOnly) { 12888 // Delete application data first 12889 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12890 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12891 return true; 12892 } 12893 12894 boolean ret = false; 12895 if (isSystemApp(ps)) { 12896 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12897 // When an updated system application is deleted we delete the existing resources as well and 12898 // fall back to existing code in system partition 12899 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12900 flags, outInfo, writeSettings); 12901 } else { 12902 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12903 // Kill application pre-emptively especially for apps on sd. 12904 killApplication(packageName, ps.appId, "uninstall pkg"); 12905 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12906 allUserHandles, perUserInstalled, 12907 outInfo, writeSettings); 12908 } 12909 12910 return ret; 12911 } 12912 12913 private final class ClearStorageConnection implements ServiceConnection { 12914 IMediaContainerService mContainerService; 12915 12916 @Override 12917 public void onServiceConnected(ComponentName name, IBinder service) { 12918 synchronized (this) { 12919 mContainerService = IMediaContainerService.Stub.asInterface(service); 12920 notifyAll(); 12921 } 12922 } 12923 12924 @Override 12925 public void onServiceDisconnected(ComponentName name) { 12926 } 12927 } 12928 12929 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12930 final boolean mounted; 12931 if (Environment.isExternalStorageEmulated()) { 12932 mounted = true; 12933 } else { 12934 final String status = Environment.getExternalStorageState(); 12935 12936 mounted = status.equals(Environment.MEDIA_MOUNTED) 12937 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12938 } 12939 12940 if (!mounted) { 12941 return; 12942 } 12943 12944 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12945 int[] users; 12946 if (userId == UserHandle.USER_ALL) { 12947 users = sUserManager.getUserIds(); 12948 } else { 12949 users = new int[] { userId }; 12950 } 12951 final ClearStorageConnection conn = new ClearStorageConnection(); 12952 if (mContext.bindServiceAsUser( 12953 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12954 try { 12955 for (int curUser : users) { 12956 long timeout = SystemClock.uptimeMillis() + 5000; 12957 synchronized (conn) { 12958 long now = SystemClock.uptimeMillis(); 12959 while (conn.mContainerService == null && now < timeout) { 12960 try { 12961 conn.wait(timeout - now); 12962 } catch (InterruptedException e) { 12963 } 12964 } 12965 } 12966 if (conn.mContainerService == null) { 12967 return; 12968 } 12969 12970 final UserEnvironment userEnv = new UserEnvironment(curUser); 12971 clearDirectory(conn.mContainerService, 12972 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12973 if (allData) { 12974 clearDirectory(conn.mContainerService, 12975 userEnv.buildExternalStorageAppDataDirs(packageName)); 12976 clearDirectory(conn.mContainerService, 12977 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12978 } 12979 } 12980 } finally { 12981 mContext.unbindService(conn); 12982 } 12983 } 12984 } 12985 12986 @Override 12987 public void clearApplicationUserData(final String packageName, 12988 final IPackageDataObserver observer, final int userId) { 12989 mContext.enforceCallingOrSelfPermission( 12990 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12991 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12992 // Queue up an async operation since the package deletion may take a little while. 12993 mHandler.post(new Runnable() { 12994 public void run() { 12995 mHandler.removeCallbacks(this); 12996 final boolean succeeded; 12997 synchronized (mInstallLock) { 12998 succeeded = clearApplicationUserDataLI(packageName, userId); 12999 } 13000 clearExternalStorageDataSync(packageName, userId, true); 13001 if (succeeded) { 13002 // invoke DeviceStorageMonitor's update method to clear any notifications 13003 DeviceStorageMonitorInternal 13004 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13005 if (dsm != null) { 13006 dsm.checkMemory(); 13007 } 13008 } 13009 if(observer != null) { 13010 try { 13011 observer.onRemoveCompleted(packageName, succeeded); 13012 } catch (RemoteException e) { 13013 Log.i(TAG, "Observer no longer exists."); 13014 } 13015 } //end if observer 13016 } //end run 13017 }); 13018 } 13019 13020 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13021 if (packageName == null) { 13022 Slog.w(TAG, "Attempt to delete null packageName."); 13023 return false; 13024 } 13025 13026 // Try finding details about the requested package 13027 PackageParser.Package pkg; 13028 synchronized (mPackages) { 13029 pkg = mPackages.get(packageName); 13030 if (pkg == null) { 13031 final PackageSetting ps = mSettings.mPackages.get(packageName); 13032 if (ps != null) { 13033 pkg = ps.pkg; 13034 } 13035 } 13036 13037 if (pkg == null) { 13038 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13039 return false; 13040 } 13041 13042 PackageSetting ps = (PackageSetting) pkg.mExtras; 13043 PermissionsState permissionsState = ps.getPermissionsState(); 13044 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 13045 } 13046 13047 // Always delete data directories for package, even if we found no other 13048 // record of app. This helps users recover from UID mismatches without 13049 // resorting to a full data wipe. 13050 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13051 if (retCode < 0) { 13052 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13053 return false; 13054 } 13055 13056 final int appId = pkg.applicationInfo.uid; 13057 removeKeystoreDataIfNeeded(userId, appId); 13058 13059 // Create a native library symlink only if we have native libraries 13060 // and if the native libraries are 32 bit libraries. We do not provide 13061 // this symlink for 64 bit libraries. 13062 if (pkg.applicationInfo.primaryCpuAbi != null && 13063 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13064 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13065 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13066 nativeLibPath, userId) < 0) { 13067 Slog.w(TAG, "Failed linking native library dir"); 13068 return false; 13069 } 13070 } 13071 13072 return true; 13073 } 13074 13075 13076 /** 13077 * Revokes granted runtime permissions and clears resettable flags 13078 * which are flags that can be set by a user interaction. 13079 * 13080 * @param permissionsState The permission state to reset. 13081 * @param userId The device user for which to do a reset. 13082 */ 13083 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 13084 PermissionsState permissionsState, int userId) { 13085 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13086 | PackageManager.FLAG_PERMISSION_USER_FIXED 13087 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13088 13089 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13090 } 13091 13092 /** 13093 * Revokes granted runtime permissions and clears all flags. 13094 * 13095 * @param permissionsState The permission state to reset. 13096 * @param userId The device user for which to do a reset. 13097 */ 13098 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13099 PermissionsState permissionsState, int userId) { 13100 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13101 PackageManager.MASK_PERMISSION_FLAGS); 13102 } 13103 13104 /** 13105 * Revokes granted runtime permissions and clears certain flags. 13106 * 13107 * @param permissionsState The permission state to reset. 13108 * @param userId The device user for which to do a reset. 13109 * @param flags The flags that is going to be reset. 13110 */ 13111 private void revokeRuntimePermissionsAndClearFlagsLocked( 13112 PermissionsState permissionsState, final int userId, int flags) { 13113 boolean needsWrite = false; 13114 13115 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13116 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13117 if (bp != null) { 13118 permissionsState.revokeRuntimePermission(bp, userId); 13119 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13120 needsWrite = true; 13121 } 13122 } 13123 13124 // Ensure default permissions are never cleared. 13125 mHandler.post(new Runnable() { 13126 @Override 13127 public void run() { 13128 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13129 } 13130 }); 13131 13132 if (needsWrite) { 13133 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13134 } 13135 } 13136 13137 /** 13138 * Remove entries from the keystore daemon. Will only remove it if the 13139 * {@code appId} is valid. 13140 */ 13141 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13142 if (appId < 0) { 13143 return; 13144 } 13145 13146 final KeyStore keyStore = KeyStore.getInstance(); 13147 if (keyStore != null) { 13148 if (userId == UserHandle.USER_ALL) { 13149 for (final int individual : sUserManager.getUserIds()) { 13150 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13151 } 13152 } else { 13153 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13154 } 13155 } else { 13156 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13157 } 13158 } 13159 13160 @Override 13161 public void deleteApplicationCacheFiles(final String packageName, 13162 final IPackageDataObserver observer) { 13163 mContext.enforceCallingOrSelfPermission( 13164 android.Manifest.permission.DELETE_CACHE_FILES, null); 13165 // Queue up an async operation since the package deletion may take a little while. 13166 final int userId = UserHandle.getCallingUserId(); 13167 mHandler.post(new Runnable() { 13168 public void run() { 13169 mHandler.removeCallbacks(this); 13170 final boolean succeded; 13171 synchronized (mInstallLock) { 13172 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13173 } 13174 clearExternalStorageDataSync(packageName, userId, false); 13175 if (observer != null) { 13176 try { 13177 observer.onRemoveCompleted(packageName, succeded); 13178 } catch (RemoteException e) { 13179 Log.i(TAG, "Observer no longer exists."); 13180 } 13181 } //end if observer 13182 } //end run 13183 }); 13184 } 13185 13186 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13187 if (packageName == null) { 13188 Slog.w(TAG, "Attempt to delete null packageName."); 13189 return false; 13190 } 13191 PackageParser.Package p; 13192 synchronized (mPackages) { 13193 p = mPackages.get(packageName); 13194 } 13195 if (p == null) { 13196 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13197 return false; 13198 } 13199 final ApplicationInfo applicationInfo = p.applicationInfo; 13200 if (applicationInfo == null) { 13201 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13202 return false; 13203 } 13204 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13205 if (retCode < 0) { 13206 Slog.w(TAG, "Couldn't remove cache files for package: " 13207 + packageName + " u" + userId); 13208 return false; 13209 } 13210 return true; 13211 } 13212 13213 @Override 13214 public void getPackageSizeInfo(final String packageName, int userHandle, 13215 final IPackageStatsObserver observer) { 13216 mContext.enforceCallingOrSelfPermission( 13217 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13218 if (packageName == null) { 13219 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13220 } 13221 13222 PackageStats stats = new PackageStats(packageName, userHandle); 13223 13224 /* 13225 * Queue up an async operation since the package measurement may take a 13226 * little while. 13227 */ 13228 Message msg = mHandler.obtainMessage(INIT_COPY); 13229 msg.obj = new MeasureParams(stats, observer); 13230 mHandler.sendMessage(msg); 13231 } 13232 13233 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13234 PackageStats pStats) { 13235 if (packageName == null) { 13236 Slog.w(TAG, "Attempt to get size of null packageName."); 13237 return false; 13238 } 13239 PackageParser.Package p; 13240 boolean dataOnly = false; 13241 String libDirRoot = null; 13242 String asecPath = null; 13243 PackageSetting ps = null; 13244 synchronized (mPackages) { 13245 p = mPackages.get(packageName); 13246 ps = mSettings.mPackages.get(packageName); 13247 if(p == null) { 13248 dataOnly = true; 13249 if((ps == null) || (ps.pkg == null)) { 13250 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13251 return false; 13252 } 13253 p = ps.pkg; 13254 } 13255 if (ps != null) { 13256 libDirRoot = ps.legacyNativeLibraryPathString; 13257 } 13258 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13259 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13260 if (secureContainerId != null) { 13261 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13262 } 13263 } 13264 } 13265 String publicSrcDir = null; 13266 if(!dataOnly) { 13267 final ApplicationInfo applicationInfo = p.applicationInfo; 13268 if (applicationInfo == null) { 13269 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13270 return false; 13271 } 13272 if (p.isForwardLocked()) { 13273 publicSrcDir = applicationInfo.getBaseResourcePath(); 13274 } 13275 } 13276 // TODO: extend to measure size of split APKs 13277 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13278 // not just the first level. 13279 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13280 // just the primary. 13281 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13282 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13283 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13284 if (res < 0) { 13285 return false; 13286 } 13287 13288 // Fix-up for forward-locked applications in ASEC containers. 13289 if (!isExternal(p)) { 13290 pStats.codeSize += pStats.externalCodeSize; 13291 pStats.externalCodeSize = 0L; 13292 } 13293 13294 return true; 13295 } 13296 13297 13298 @Override 13299 public void addPackageToPreferred(String packageName) { 13300 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13301 } 13302 13303 @Override 13304 public void removePackageFromPreferred(String packageName) { 13305 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13306 } 13307 13308 @Override 13309 public List<PackageInfo> getPreferredPackages(int flags) { 13310 return new ArrayList<PackageInfo>(); 13311 } 13312 13313 private int getUidTargetSdkVersionLockedLPr(int uid) { 13314 Object obj = mSettings.getUserIdLPr(uid); 13315 if (obj instanceof SharedUserSetting) { 13316 final SharedUserSetting sus = (SharedUserSetting) obj; 13317 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13318 final Iterator<PackageSetting> it = sus.packages.iterator(); 13319 while (it.hasNext()) { 13320 final PackageSetting ps = it.next(); 13321 if (ps.pkg != null) { 13322 int v = ps.pkg.applicationInfo.targetSdkVersion; 13323 if (v < vers) vers = v; 13324 } 13325 } 13326 return vers; 13327 } else if (obj instanceof PackageSetting) { 13328 final PackageSetting ps = (PackageSetting) obj; 13329 if (ps.pkg != null) { 13330 return ps.pkg.applicationInfo.targetSdkVersion; 13331 } 13332 } 13333 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13334 } 13335 13336 @Override 13337 public void addPreferredActivity(IntentFilter filter, int match, 13338 ComponentName[] set, ComponentName activity, int userId) { 13339 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13340 "Adding preferred"); 13341 } 13342 13343 private void addPreferredActivityInternal(IntentFilter filter, int match, 13344 ComponentName[] set, ComponentName activity, boolean always, int userId, 13345 String opname) { 13346 // writer 13347 int callingUid = Binder.getCallingUid(); 13348 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13349 if (filter.countActions() == 0) { 13350 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13351 return; 13352 } 13353 synchronized (mPackages) { 13354 if (mContext.checkCallingOrSelfPermission( 13355 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13356 != PackageManager.PERMISSION_GRANTED) { 13357 if (getUidTargetSdkVersionLockedLPr(callingUid) 13358 < Build.VERSION_CODES.FROYO) { 13359 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13360 + callingUid); 13361 return; 13362 } 13363 mContext.enforceCallingOrSelfPermission( 13364 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13365 } 13366 13367 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13368 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13369 + userId + ":"); 13370 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13371 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13372 scheduleWritePackageRestrictionsLocked(userId); 13373 } 13374 } 13375 13376 @Override 13377 public void replacePreferredActivity(IntentFilter filter, int match, 13378 ComponentName[] set, ComponentName activity, int userId) { 13379 if (filter.countActions() != 1) { 13380 throw new IllegalArgumentException( 13381 "replacePreferredActivity expects filter to have only 1 action."); 13382 } 13383 if (filter.countDataAuthorities() != 0 13384 || filter.countDataPaths() != 0 13385 || filter.countDataSchemes() > 1 13386 || filter.countDataTypes() != 0) { 13387 throw new IllegalArgumentException( 13388 "replacePreferredActivity expects filter to have no data authorities, " + 13389 "paths, or types; and at most one scheme."); 13390 } 13391 13392 final int callingUid = Binder.getCallingUid(); 13393 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13394 synchronized (mPackages) { 13395 if (mContext.checkCallingOrSelfPermission( 13396 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13397 != PackageManager.PERMISSION_GRANTED) { 13398 if (getUidTargetSdkVersionLockedLPr(callingUid) 13399 < Build.VERSION_CODES.FROYO) { 13400 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13401 + Binder.getCallingUid()); 13402 return; 13403 } 13404 mContext.enforceCallingOrSelfPermission( 13405 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13406 } 13407 13408 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13409 if (pir != null) { 13410 // Get all of the existing entries that exactly match this filter. 13411 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13412 if (existing != null && existing.size() == 1) { 13413 PreferredActivity cur = existing.get(0); 13414 if (DEBUG_PREFERRED) { 13415 Slog.i(TAG, "Checking replace of preferred:"); 13416 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13417 if (!cur.mPref.mAlways) { 13418 Slog.i(TAG, " -- CUR; not mAlways!"); 13419 } else { 13420 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13421 Slog.i(TAG, " -- CUR: mSet=" 13422 + Arrays.toString(cur.mPref.mSetComponents)); 13423 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13424 Slog.i(TAG, " -- NEW: mMatch=" 13425 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13426 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13427 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13428 } 13429 } 13430 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13431 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13432 && cur.mPref.sameSet(set)) { 13433 // Setting the preferred activity to what it happens to be already 13434 if (DEBUG_PREFERRED) { 13435 Slog.i(TAG, "Replacing with same preferred activity " 13436 + cur.mPref.mShortComponent + " for user " 13437 + userId + ":"); 13438 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13439 } 13440 return; 13441 } 13442 } 13443 13444 if (existing != null) { 13445 if (DEBUG_PREFERRED) { 13446 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13447 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13448 } 13449 for (int i = 0; i < existing.size(); i++) { 13450 PreferredActivity pa = existing.get(i); 13451 if (DEBUG_PREFERRED) { 13452 Slog.i(TAG, "Removing existing preferred activity " 13453 + pa.mPref.mComponent + ":"); 13454 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13455 } 13456 pir.removeFilter(pa); 13457 } 13458 } 13459 } 13460 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13461 "Replacing preferred"); 13462 } 13463 } 13464 13465 @Override 13466 public void clearPackagePreferredActivities(String packageName) { 13467 final int uid = Binder.getCallingUid(); 13468 // writer 13469 synchronized (mPackages) { 13470 PackageParser.Package pkg = mPackages.get(packageName); 13471 if (pkg == null || pkg.applicationInfo.uid != uid) { 13472 if (mContext.checkCallingOrSelfPermission( 13473 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13474 != PackageManager.PERMISSION_GRANTED) { 13475 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13476 < Build.VERSION_CODES.FROYO) { 13477 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13478 + Binder.getCallingUid()); 13479 return; 13480 } 13481 mContext.enforceCallingOrSelfPermission( 13482 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13483 } 13484 } 13485 13486 int user = UserHandle.getCallingUserId(); 13487 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13488 scheduleWritePackageRestrictionsLocked(user); 13489 } 13490 } 13491 } 13492 13493 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13494 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13495 ArrayList<PreferredActivity> removed = null; 13496 boolean changed = false; 13497 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13498 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13499 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13500 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13501 continue; 13502 } 13503 Iterator<PreferredActivity> it = pir.filterIterator(); 13504 while (it.hasNext()) { 13505 PreferredActivity pa = it.next(); 13506 // Mark entry for removal only if it matches the package name 13507 // and the entry is of type "always". 13508 if (packageName == null || 13509 (pa.mPref.mComponent.getPackageName().equals(packageName) 13510 && pa.mPref.mAlways)) { 13511 if (removed == null) { 13512 removed = new ArrayList<PreferredActivity>(); 13513 } 13514 removed.add(pa); 13515 } 13516 } 13517 if (removed != null) { 13518 for (int j=0; j<removed.size(); j++) { 13519 PreferredActivity pa = removed.get(j); 13520 pir.removeFilter(pa); 13521 } 13522 changed = true; 13523 } 13524 } 13525 return changed; 13526 } 13527 13528 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13529 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13530 if (userId == UserHandle.USER_ALL) { 13531 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13532 sUserManager.getUserIds())) { 13533 for (int oneUserId : sUserManager.getUserIds()) { 13534 scheduleWritePackageRestrictionsLocked(oneUserId); 13535 } 13536 } 13537 } else { 13538 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13539 scheduleWritePackageRestrictionsLocked(userId); 13540 } 13541 } 13542 } 13543 13544 13545 void clearDefaultBrowserIfNeeded(String packageName) { 13546 for (int oneUserId : sUserManager.getUserIds()) { 13547 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13548 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13549 if (packageName.equals(defaultBrowserPackageName)) { 13550 setDefaultBrowserPackageName(null, oneUserId); 13551 } 13552 } 13553 } 13554 13555 @Override 13556 public void resetPreferredActivities(int userId) { 13557 mContext.enforceCallingOrSelfPermission( 13558 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13559 // writer 13560 synchronized (mPackages) { 13561 clearPackagePreferredActivitiesLPw(null, userId); 13562 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13563 applyFactoryDefaultBrowserLPw(userId); 13564 13565 scheduleWritePackageRestrictionsLocked(userId); 13566 } 13567 } 13568 13569 @Override 13570 public int getPreferredActivities(List<IntentFilter> outFilters, 13571 List<ComponentName> outActivities, String packageName) { 13572 13573 int num = 0; 13574 final int userId = UserHandle.getCallingUserId(); 13575 // reader 13576 synchronized (mPackages) { 13577 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13578 if (pir != null) { 13579 final Iterator<PreferredActivity> it = pir.filterIterator(); 13580 while (it.hasNext()) { 13581 final PreferredActivity pa = it.next(); 13582 if (packageName == null 13583 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13584 && pa.mPref.mAlways)) { 13585 if (outFilters != null) { 13586 outFilters.add(new IntentFilter(pa)); 13587 } 13588 if (outActivities != null) { 13589 outActivities.add(pa.mPref.mComponent); 13590 } 13591 } 13592 } 13593 } 13594 } 13595 13596 return num; 13597 } 13598 13599 @Override 13600 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13601 int userId) { 13602 int callingUid = Binder.getCallingUid(); 13603 if (callingUid != Process.SYSTEM_UID) { 13604 throw new SecurityException( 13605 "addPersistentPreferredActivity can only be run by the system"); 13606 } 13607 if (filter.countActions() == 0) { 13608 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13609 return; 13610 } 13611 synchronized (mPackages) { 13612 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13613 " :"); 13614 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13615 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13616 new PersistentPreferredActivity(filter, activity)); 13617 scheduleWritePackageRestrictionsLocked(userId); 13618 } 13619 } 13620 13621 @Override 13622 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13623 int callingUid = Binder.getCallingUid(); 13624 if (callingUid != Process.SYSTEM_UID) { 13625 throw new SecurityException( 13626 "clearPackagePersistentPreferredActivities can only be run by the system"); 13627 } 13628 ArrayList<PersistentPreferredActivity> removed = null; 13629 boolean changed = false; 13630 synchronized (mPackages) { 13631 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13632 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13633 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13634 .valueAt(i); 13635 if (userId != thisUserId) { 13636 continue; 13637 } 13638 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13639 while (it.hasNext()) { 13640 PersistentPreferredActivity ppa = it.next(); 13641 // Mark entry for removal only if it matches the package name. 13642 if (ppa.mComponent.getPackageName().equals(packageName)) { 13643 if (removed == null) { 13644 removed = new ArrayList<PersistentPreferredActivity>(); 13645 } 13646 removed.add(ppa); 13647 } 13648 } 13649 if (removed != null) { 13650 for (int j=0; j<removed.size(); j++) { 13651 PersistentPreferredActivity ppa = removed.get(j); 13652 ppir.removeFilter(ppa); 13653 } 13654 changed = true; 13655 } 13656 } 13657 13658 if (changed) { 13659 scheduleWritePackageRestrictionsLocked(userId); 13660 } 13661 } 13662 } 13663 13664 /** 13665 * Common machinery for picking apart a restored XML blob and passing 13666 * it to a caller-supplied functor to be applied to the running system. 13667 */ 13668 private void restoreFromXml(XmlPullParser parser, int userId, 13669 String expectedStartTag, BlobXmlRestorer functor) 13670 throws IOException, XmlPullParserException { 13671 int type; 13672 while ((type = parser.next()) != XmlPullParser.START_TAG 13673 && type != XmlPullParser.END_DOCUMENT) { 13674 } 13675 if (type != XmlPullParser.START_TAG) { 13676 // oops didn't find a start tag?! 13677 if (DEBUG_BACKUP) { 13678 Slog.e(TAG, "Didn't find start tag during restore"); 13679 } 13680 return; 13681 } 13682 13683 // this is supposed to be TAG_PREFERRED_BACKUP 13684 if (!expectedStartTag.equals(parser.getName())) { 13685 if (DEBUG_BACKUP) { 13686 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13687 } 13688 return; 13689 } 13690 13691 // skip interfering stuff, then we're aligned with the backing implementation 13692 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13693 functor.apply(parser, userId); 13694 } 13695 13696 private interface BlobXmlRestorer { 13697 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13698 } 13699 13700 /** 13701 * Non-Binder method, support for the backup/restore mechanism: write the 13702 * full set of preferred activities in its canonical XML format. Returns the 13703 * XML output as a byte array, or null if there is none. 13704 */ 13705 @Override 13706 public byte[] getPreferredActivityBackup(int userId) { 13707 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13708 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13709 } 13710 13711 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13712 try { 13713 final XmlSerializer serializer = new FastXmlSerializer(); 13714 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13715 serializer.startDocument(null, true); 13716 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13717 13718 synchronized (mPackages) { 13719 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13720 } 13721 13722 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13723 serializer.endDocument(); 13724 serializer.flush(); 13725 } catch (Exception e) { 13726 if (DEBUG_BACKUP) { 13727 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13728 } 13729 return null; 13730 } 13731 13732 return dataStream.toByteArray(); 13733 } 13734 13735 @Override 13736 public void restorePreferredActivities(byte[] backup, int userId) { 13737 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13738 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13739 } 13740 13741 try { 13742 final XmlPullParser parser = Xml.newPullParser(); 13743 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13744 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13745 new BlobXmlRestorer() { 13746 @Override 13747 public void apply(XmlPullParser parser, int userId) 13748 throws XmlPullParserException, IOException { 13749 synchronized (mPackages) { 13750 mSettings.readPreferredActivitiesLPw(parser, userId); 13751 } 13752 } 13753 } ); 13754 } catch (Exception e) { 13755 if (DEBUG_BACKUP) { 13756 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13757 } 13758 } 13759 } 13760 13761 /** 13762 * Non-Binder method, support for the backup/restore mechanism: write the 13763 * default browser (etc) settings in its canonical XML format. Returns the default 13764 * browser XML representation as a byte array, or null if there is none. 13765 */ 13766 @Override 13767 public byte[] getDefaultAppsBackup(int userId) { 13768 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13769 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13770 } 13771 13772 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13773 try { 13774 final XmlSerializer serializer = new FastXmlSerializer(); 13775 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13776 serializer.startDocument(null, true); 13777 serializer.startTag(null, TAG_DEFAULT_APPS); 13778 13779 synchronized (mPackages) { 13780 mSettings.writeDefaultAppsLPr(serializer, userId); 13781 } 13782 13783 serializer.endTag(null, TAG_DEFAULT_APPS); 13784 serializer.endDocument(); 13785 serializer.flush(); 13786 } catch (Exception e) { 13787 if (DEBUG_BACKUP) { 13788 Slog.e(TAG, "Unable to write default apps for backup", e); 13789 } 13790 return null; 13791 } 13792 13793 return dataStream.toByteArray(); 13794 } 13795 13796 @Override 13797 public void restoreDefaultApps(byte[] backup, int userId) { 13798 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13799 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13800 } 13801 13802 try { 13803 final XmlPullParser parser = Xml.newPullParser(); 13804 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13805 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13806 new BlobXmlRestorer() { 13807 @Override 13808 public void apply(XmlPullParser parser, int userId) 13809 throws XmlPullParserException, IOException { 13810 synchronized (mPackages) { 13811 mSettings.readDefaultAppsLPw(parser, userId); 13812 } 13813 } 13814 } ); 13815 } catch (Exception e) { 13816 if (DEBUG_BACKUP) { 13817 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13818 } 13819 } 13820 } 13821 13822 @Override 13823 public byte[] getIntentFilterVerificationBackup(int userId) { 13824 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13825 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13826 } 13827 13828 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13829 try { 13830 final XmlSerializer serializer = new FastXmlSerializer(); 13831 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13832 serializer.startDocument(null, true); 13833 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13834 13835 synchronized (mPackages) { 13836 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13837 } 13838 13839 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13840 serializer.endDocument(); 13841 serializer.flush(); 13842 } catch (Exception e) { 13843 if (DEBUG_BACKUP) { 13844 Slog.e(TAG, "Unable to write default apps for backup", e); 13845 } 13846 return null; 13847 } 13848 13849 return dataStream.toByteArray(); 13850 } 13851 13852 @Override 13853 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13854 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13855 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13856 } 13857 13858 try { 13859 final XmlPullParser parser = Xml.newPullParser(); 13860 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13861 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13862 new BlobXmlRestorer() { 13863 @Override 13864 public void apply(XmlPullParser parser, int userId) 13865 throws XmlPullParserException, IOException { 13866 synchronized (mPackages) { 13867 mSettings.readAllDomainVerificationsLPr(parser, userId); 13868 mSettings.writeLPr(); 13869 } 13870 } 13871 } ); 13872 } catch (Exception e) { 13873 if (DEBUG_BACKUP) { 13874 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13875 } 13876 } 13877 } 13878 13879 @Override 13880 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13881 int sourceUserId, int targetUserId, int flags) { 13882 mContext.enforceCallingOrSelfPermission( 13883 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13884 int callingUid = Binder.getCallingUid(); 13885 enforceOwnerRights(ownerPackage, callingUid); 13886 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13887 if (intentFilter.countActions() == 0) { 13888 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13889 return; 13890 } 13891 synchronized (mPackages) { 13892 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13893 ownerPackage, targetUserId, flags); 13894 CrossProfileIntentResolver resolver = 13895 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13896 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13897 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13898 if (existing != null) { 13899 int size = existing.size(); 13900 for (int i = 0; i < size; i++) { 13901 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13902 return; 13903 } 13904 } 13905 } 13906 resolver.addFilter(newFilter); 13907 scheduleWritePackageRestrictionsLocked(sourceUserId); 13908 } 13909 } 13910 13911 @Override 13912 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13913 mContext.enforceCallingOrSelfPermission( 13914 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13915 int callingUid = Binder.getCallingUid(); 13916 enforceOwnerRights(ownerPackage, callingUid); 13917 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13918 synchronized (mPackages) { 13919 CrossProfileIntentResolver resolver = 13920 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13921 ArraySet<CrossProfileIntentFilter> set = 13922 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13923 for (CrossProfileIntentFilter filter : set) { 13924 if (filter.getOwnerPackage().equals(ownerPackage)) { 13925 resolver.removeFilter(filter); 13926 } 13927 } 13928 scheduleWritePackageRestrictionsLocked(sourceUserId); 13929 } 13930 } 13931 13932 // Enforcing that callingUid is owning pkg on userId 13933 private void enforceOwnerRights(String pkg, int callingUid) { 13934 // The system owns everything. 13935 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13936 return; 13937 } 13938 int callingUserId = UserHandle.getUserId(callingUid); 13939 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13940 if (pi == null) { 13941 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13942 + callingUserId); 13943 } 13944 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13945 throw new SecurityException("Calling uid " + callingUid 13946 + " does not own package " + pkg); 13947 } 13948 } 13949 13950 @Override 13951 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13952 Intent intent = new Intent(Intent.ACTION_MAIN); 13953 intent.addCategory(Intent.CATEGORY_HOME); 13954 13955 final int callingUserId = UserHandle.getCallingUserId(); 13956 List<ResolveInfo> list = queryIntentActivities(intent, null, 13957 PackageManager.GET_META_DATA, callingUserId); 13958 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13959 true, false, false, callingUserId); 13960 13961 allHomeCandidates.clear(); 13962 if (list != null) { 13963 for (ResolveInfo ri : list) { 13964 allHomeCandidates.add(ri); 13965 } 13966 } 13967 return (preferred == null || preferred.activityInfo == null) 13968 ? null 13969 : new ComponentName(preferred.activityInfo.packageName, 13970 preferred.activityInfo.name); 13971 } 13972 13973 @Override 13974 public void setApplicationEnabledSetting(String appPackageName, 13975 int newState, int flags, int userId, String callingPackage) { 13976 if (!sUserManager.exists(userId)) return; 13977 if (callingPackage == null) { 13978 callingPackage = Integer.toString(Binder.getCallingUid()); 13979 } 13980 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13981 } 13982 13983 @Override 13984 public void setComponentEnabledSetting(ComponentName componentName, 13985 int newState, int flags, int userId) { 13986 if (!sUserManager.exists(userId)) return; 13987 setEnabledSetting(componentName.getPackageName(), 13988 componentName.getClassName(), newState, flags, userId, null); 13989 } 13990 13991 private void setEnabledSetting(final String packageName, String className, int newState, 13992 final int flags, int userId, String callingPackage) { 13993 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13994 || newState == COMPONENT_ENABLED_STATE_ENABLED 13995 || newState == COMPONENT_ENABLED_STATE_DISABLED 13996 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13997 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13998 throw new IllegalArgumentException("Invalid new component state: " 13999 + newState); 14000 } 14001 PackageSetting pkgSetting; 14002 final int uid = Binder.getCallingUid(); 14003 final int permission = mContext.checkCallingOrSelfPermission( 14004 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14005 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14006 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14007 boolean sendNow = false; 14008 boolean isApp = (className == null); 14009 String componentName = isApp ? packageName : className; 14010 int packageUid = -1; 14011 ArrayList<String> components; 14012 14013 // writer 14014 synchronized (mPackages) { 14015 pkgSetting = mSettings.mPackages.get(packageName); 14016 if (pkgSetting == null) { 14017 if (className == null) { 14018 throw new IllegalArgumentException( 14019 "Unknown package: " + packageName); 14020 } 14021 throw new IllegalArgumentException( 14022 "Unknown component: " + packageName 14023 + "/" + className); 14024 } 14025 // Allow root and verify that userId is not being specified by a different user 14026 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14027 throw new SecurityException( 14028 "Permission Denial: attempt to change component state from pid=" 14029 + Binder.getCallingPid() 14030 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14031 } 14032 if (className == null) { 14033 // We're dealing with an application/package level state change 14034 if (pkgSetting.getEnabled(userId) == newState) { 14035 // Nothing to do 14036 return; 14037 } 14038 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14039 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14040 // Don't care about who enables an app. 14041 callingPackage = null; 14042 } 14043 pkgSetting.setEnabled(newState, userId, callingPackage); 14044 // pkgSetting.pkg.mSetEnabled = newState; 14045 } else { 14046 // We're dealing with a component level state change 14047 // First, verify that this is a valid class name. 14048 PackageParser.Package pkg = pkgSetting.pkg; 14049 if (pkg == null || !pkg.hasComponentClassName(className)) { 14050 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14051 throw new IllegalArgumentException("Component class " + className 14052 + " does not exist in " + packageName); 14053 } else { 14054 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14055 + className + " does not exist in " + packageName); 14056 } 14057 } 14058 switch (newState) { 14059 case COMPONENT_ENABLED_STATE_ENABLED: 14060 if (!pkgSetting.enableComponentLPw(className, userId)) { 14061 return; 14062 } 14063 break; 14064 case COMPONENT_ENABLED_STATE_DISABLED: 14065 if (!pkgSetting.disableComponentLPw(className, userId)) { 14066 return; 14067 } 14068 break; 14069 case COMPONENT_ENABLED_STATE_DEFAULT: 14070 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14071 return; 14072 } 14073 break; 14074 default: 14075 Slog.e(TAG, "Invalid new component state: " + newState); 14076 return; 14077 } 14078 } 14079 scheduleWritePackageRestrictionsLocked(userId); 14080 components = mPendingBroadcasts.get(userId, packageName); 14081 final boolean newPackage = components == null; 14082 if (newPackage) { 14083 components = new ArrayList<String>(); 14084 } 14085 if (!components.contains(componentName)) { 14086 components.add(componentName); 14087 } 14088 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14089 sendNow = true; 14090 // Purge entry from pending broadcast list if another one exists already 14091 // since we are sending one right away. 14092 mPendingBroadcasts.remove(userId, packageName); 14093 } else { 14094 if (newPackage) { 14095 mPendingBroadcasts.put(userId, packageName, components); 14096 } 14097 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14098 // Schedule a message 14099 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14100 } 14101 } 14102 } 14103 14104 long callingId = Binder.clearCallingIdentity(); 14105 try { 14106 if (sendNow) { 14107 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14108 sendPackageChangedBroadcast(packageName, 14109 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14110 } 14111 } finally { 14112 Binder.restoreCallingIdentity(callingId); 14113 } 14114 } 14115 14116 private void sendPackageChangedBroadcast(String packageName, 14117 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14118 if (DEBUG_INSTALL) 14119 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14120 + componentNames); 14121 Bundle extras = new Bundle(4); 14122 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14123 String nameList[] = new String[componentNames.size()]; 14124 componentNames.toArray(nameList); 14125 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14126 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14127 extras.putInt(Intent.EXTRA_UID, packageUid); 14128 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14129 new int[] {UserHandle.getUserId(packageUid)}); 14130 } 14131 14132 @Override 14133 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14134 if (!sUserManager.exists(userId)) return; 14135 final int uid = Binder.getCallingUid(); 14136 final int permission = mContext.checkCallingOrSelfPermission( 14137 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14138 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14139 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14140 // writer 14141 synchronized (mPackages) { 14142 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14143 allowedByPermission, uid, userId)) { 14144 scheduleWritePackageRestrictionsLocked(userId); 14145 } 14146 } 14147 } 14148 14149 @Override 14150 public String getInstallerPackageName(String packageName) { 14151 // reader 14152 synchronized (mPackages) { 14153 return mSettings.getInstallerPackageNameLPr(packageName); 14154 } 14155 } 14156 14157 @Override 14158 public int getApplicationEnabledSetting(String packageName, int userId) { 14159 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14160 int uid = Binder.getCallingUid(); 14161 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14162 // reader 14163 synchronized (mPackages) { 14164 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14165 } 14166 } 14167 14168 @Override 14169 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14170 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14171 int uid = Binder.getCallingUid(); 14172 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14173 // reader 14174 synchronized (mPackages) { 14175 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14176 } 14177 } 14178 14179 @Override 14180 public void enterSafeMode() { 14181 enforceSystemOrRoot("Only the system can request entering safe mode"); 14182 14183 if (!mSystemReady) { 14184 mSafeMode = true; 14185 } 14186 } 14187 14188 @Override 14189 public void systemReady() { 14190 mSystemReady = true; 14191 14192 // Read the compatibilty setting when the system is ready. 14193 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14194 mContext.getContentResolver(), 14195 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14196 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14197 if (DEBUG_SETTINGS) { 14198 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14199 } 14200 14201 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14202 14203 synchronized (mPackages) { 14204 // Verify that all of the preferred activity components actually 14205 // exist. It is possible for applications to be updated and at 14206 // that point remove a previously declared activity component that 14207 // had been set as a preferred activity. We try to clean this up 14208 // the next time we encounter that preferred activity, but it is 14209 // possible for the user flow to never be able to return to that 14210 // situation so here we do a sanity check to make sure we haven't 14211 // left any junk around. 14212 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14213 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14214 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14215 removed.clear(); 14216 for (PreferredActivity pa : pir.filterSet()) { 14217 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14218 removed.add(pa); 14219 } 14220 } 14221 if (removed.size() > 0) { 14222 for (int r=0; r<removed.size(); r++) { 14223 PreferredActivity pa = removed.get(r); 14224 Slog.w(TAG, "Removing dangling preferred activity: " 14225 + pa.mPref.mComponent); 14226 pir.removeFilter(pa); 14227 } 14228 mSettings.writePackageRestrictionsLPr( 14229 mSettings.mPreferredActivities.keyAt(i)); 14230 } 14231 } 14232 14233 for (int userId : UserManagerService.getInstance().getUserIds()) { 14234 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14235 grantPermissionsUserIds = ArrayUtils.appendInt( 14236 grantPermissionsUserIds, userId); 14237 } 14238 } 14239 } 14240 sUserManager.systemReady(); 14241 14242 // If we upgraded grant all default permissions before kicking off. 14243 for (int userId : grantPermissionsUserIds) { 14244 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14245 } 14246 14247 // Kick off any messages waiting for system ready 14248 if (mPostSystemReadyMessages != null) { 14249 for (Message msg : mPostSystemReadyMessages) { 14250 msg.sendToTarget(); 14251 } 14252 mPostSystemReadyMessages = null; 14253 } 14254 14255 // Watch for external volumes that come and go over time 14256 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14257 storage.registerListener(mStorageListener); 14258 14259 mInstallerService.systemReady(); 14260 mPackageDexOptimizer.systemReady(); 14261 } 14262 14263 @Override 14264 public boolean isSafeMode() { 14265 return mSafeMode; 14266 } 14267 14268 @Override 14269 public boolean hasSystemUidErrors() { 14270 return mHasSystemUidErrors; 14271 } 14272 14273 static String arrayToString(int[] array) { 14274 StringBuffer buf = new StringBuffer(128); 14275 buf.append('['); 14276 if (array != null) { 14277 for (int i=0; i<array.length; i++) { 14278 if (i > 0) buf.append(", "); 14279 buf.append(array[i]); 14280 } 14281 } 14282 buf.append(']'); 14283 return buf.toString(); 14284 } 14285 14286 static class DumpState { 14287 public static final int DUMP_LIBS = 1 << 0; 14288 public static final int DUMP_FEATURES = 1 << 1; 14289 public static final int DUMP_RESOLVERS = 1 << 2; 14290 public static final int DUMP_PERMISSIONS = 1 << 3; 14291 public static final int DUMP_PACKAGES = 1 << 4; 14292 public static final int DUMP_SHARED_USERS = 1 << 5; 14293 public static final int DUMP_MESSAGES = 1 << 6; 14294 public static final int DUMP_PROVIDERS = 1 << 7; 14295 public static final int DUMP_VERIFIERS = 1 << 8; 14296 public static final int DUMP_PREFERRED = 1 << 9; 14297 public static final int DUMP_PREFERRED_XML = 1 << 10; 14298 public static final int DUMP_KEYSETS = 1 << 11; 14299 public static final int DUMP_VERSION = 1 << 12; 14300 public static final int DUMP_INSTALLS = 1 << 13; 14301 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14302 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14303 14304 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14305 14306 private int mTypes; 14307 14308 private int mOptions; 14309 14310 private boolean mTitlePrinted; 14311 14312 private SharedUserSetting mSharedUser; 14313 14314 public boolean isDumping(int type) { 14315 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14316 return true; 14317 } 14318 14319 return (mTypes & type) != 0; 14320 } 14321 14322 public void setDump(int type) { 14323 mTypes |= type; 14324 } 14325 14326 public boolean isOptionEnabled(int option) { 14327 return (mOptions & option) != 0; 14328 } 14329 14330 public void setOptionEnabled(int option) { 14331 mOptions |= option; 14332 } 14333 14334 public boolean onTitlePrinted() { 14335 final boolean printed = mTitlePrinted; 14336 mTitlePrinted = true; 14337 return printed; 14338 } 14339 14340 public boolean getTitlePrinted() { 14341 return mTitlePrinted; 14342 } 14343 14344 public void setTitlePrinted(boolean enabled) { 14345 mTitlePrinted = enabled; 14346 } 14347 14348 public SharedUserSetting getSharedUser() { 14349 return mSharedUser; 14350 } 14351 14352 public void setSharedUser(SharedUserSetting user) { 14353 mSharedUser = user; 14354 } 14355 } 14356 14357 @Override 14358 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14359 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14360 != PackageManager.PERMISSION_GRANTED) { 14361 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14362 + Binder.getCallingPid() 14363 + ", uid=" + Binder.getCallingUid() 14364 + " without permission " 14365 + android.Manifest.permission.DUMP); 14366 return; 14367 } 14368 14369 DumpState dumpState = new DumpState(); 14370 boolean fullPreferred = false; 14371 boolean checkin = false; 14372 14373 String packageName = null; 14374 ArraySet<String> permissionNames = null; 14375 14376 int opti = 0; 14377 while (opti < args.length) { 14378 String opt = args[opti]; 14379 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14380 break; 14381 } 14382 opti++; 14383 14384 if ("-a".equals(opt)) { 14385 // Right now we only know how to print all. 14386 } else if ("-h".equals(opt)) { 14387 pw.println("Package manager dump options:"); 14388 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14389 pw.println(" --checkin: dump for a checkin"); 14390 pw.println(" -f: print details of intent filters"); 14391 pw.println(" -h: print this help"); 14392 pw.println(" cmd may be one of:"); 14393 pw.println(" l[ibraries]: list known shared libraries"); 14394 pw.println(" f[ibraries]: list device features"); 14395 pw.println(" k[eysets]: print known keysets"); 14396 pw.println(" r[esolvers]: dump intent resolvers"); 14397 pw.println(" perm[issions]: dump permissions"); 14398 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14399 pw.println(" pref[erred]: print preferred package settings"); 14400 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14401 pw.println(" prov[iders]: dump content providers"); 14402 pw.println(" p[ackages]: dump installed packages"); 14403 pw.println(" s[hared-users]: dump shared user IDs"); 14404 pw.println(" m[essages]: print collected runtime messages"); 14405 pw.println(" v[erifiers]: print package verifier info"); 14406 pw.println(" version: print database version info"); 14407 pw.println(" write: write current settings now"); 14408 pw.println(" <package.name>: info about given package"); 14409 pw.println(" installs: details about install sessions"); 14410 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14411 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14412 return; 14413 } else if ("--checkin".equals(opt)) { 14414 checkin = true; 14415 } else if ("-f".equals(opt)) { 14416 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14417 } else { 14418 pw.println("Unknown argument: " + opt + "; use -h for help"); 14419 } 14420 } 14421 14422 // Is the caller requesting to dump a particular piece of data? 14423 if (opti < args.length) { 14424 String cmd = args[opti]; 14425 opti++; 14426 // Is this a package name? 14427 if ("android".equals(cmd) || cmd.contains(".")) { 14428 packageName = cmd; 14429 // When dumping a single package, we always dump all of its 14430 // filter information since the amount of data will be reasonable. 14431 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14432 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14433 dumpState.setDump(DumpState.DUMP_LIBS); 14434 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14435 dumpState.setDump(DumpState.DUMP_FEATURES); 14436 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14437 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14438 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14439 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14440 } else if ("permission".equals(cmd)) { 14441 if (opti >= args.length) { 14442 pw.println("Error: permission requires permission name"); 14443 return; 14444 } 14445 permissionNames = new ArraySet<>(); 14446 while (opti < args.length) { 14447 permissionNames.add(args[opti]); 14448 opti++; 14449 } 14450 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14451 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14452 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14453 dumpState.setDump(DumpState.DUMP_PREFERRED); 14454 } else if ("preferred-xml".equals(cmd)) { 14455 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14456 if (opti < args.length && "--full".equals(args[opti])) { 14457 fullPreferred = true; 14458 opti++; 14459 } 14460 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14461 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14462 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14463 dumpState.setDump(DumpState.DUMP_PACKAGES); 14464 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14465 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14466 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14467 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14468 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14469 dumpState.setDump(DumpState.DUMP_MESSAGES); 14470 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14471 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14472 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14473 || "intent-filter-verifiers".equals(cmd)) { 14474 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14475 } else if ("version".equals(cmd)) { 14476 dumpState.setDump(DumpState.DUMP_VERSION); 14477 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14478 dumpState.setDump(DumpState.DUMP_KEYSETS); 14479 } else if ("installs".equals(cmd)) { 14480 dumpState.setDump(DumpState.DUMP_INSTALLS); 14481 } else if ("write".equals(cmd)) { 14482 synchronized (mPackages) { 14483 mSettings.writeLPr(); 14484 pw.println("Settings written."); 14485 return; 14486 } 14487 } 14488 } 14489 14490 if (checkin) { 14491 pw.println("vers,1"); 14492 } 14493 14494 // reader 14495 synchronized (mPackages) { 14496 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14497 if (!checkin) { 14498 if (dumpState.onTitlePrinted()) 14499 pw.println(); 14500 pw.println("Database versions:"); 14501 pw.print(" SDK Version:"); 14502 pw.print(" internal="); 14503 pw.print(mSettings.mInternalSdkPlatform); 14504 pw.print(" external="); 14505 pw.println(mSettings.mExternalSdkPlatform); 14506 pw.print(" DB Version:"); 14507 pw.print(" internal="); 14508 pw.print(mSettings.mInternalDatabaseVersion); 14509 pw.print(" external="); 14510 pw.println(mSettings.mExternalDatabaseVersion); 14511 } 14512 } 14513 14514 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14515 if (!checkin) { 14516 if (dumpState.onTitlePrinted()) 14517 pw.println(); 14518 pw.println("Verifiers:"); 14519 pw.print(" Required: "); 14520 pw.print(mRequiredVerifierPackage); 14521 pw.print(" (uid="); 14522 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14523 pw.println(")"); 14524 } else if (mRequiredVerifierPackage != null) { 14525 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14526 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14527 } 14528 } 14529 14530 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14531 packageName == null) { 14532 if (mIntentFilterVerifierComponent != null) { 14533 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14534 if (!checkin) { 14535 if (dumpState.onTitlePrinted()) 14536 pw.println(); 14537 pw.println("Intent Filter Verifier:"); 14538 pw.print(" Using: "); 14539 pw.print(verifierPackageName); 14540 pw.print(" (uid="); 14541 pw.print(getPackageUid(verifierPackageName, 0)); 14542 pw.println(")"); 14543 } else if (verifierPackageName != null) { 14544 pw.print("ifv,"); pw.print(verifierPackageName); 14545 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14546 } 14547 } else { 14548 pw.println(); 14549 pw.println("No Intent Filter Verifier available!"); 14550 } 14551 } 14552 14553 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14554 boolean printedHeader = false; 14555 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14556 while (it.hasNext()) { 14557 String name = it.next(); 14558 SharedLibraryEntry ent = mSharedLibraries.get(name); 14559 if (!checkin) { 14560 if (!printedHeader) { 14561 if (dumpState.onTitlePrinted()) 14562 pw.println(); 14563 pw.println("Libraries:"); 14564 printedHeader = true; 14565 } 14566 pw.print(" "); 14567 } else { 14568 pw.print("lib,"); 14569 } 14570 pw.print(name); 14571 if (!checkin) { 14572 pw.print(" -> "); 14573 } 14574 if (ent.path != null) { 14575 if (!checkin) { 14576 pw.print("(jar) "); 14577 pw.print(ent.path); 14578 } else { 14579 pw.print(",jar,"); 14580 pw.print(ent.path); 14581 } 14582 } else { 14583 if (!checkin) { 14584 pw.print("(apk) "); 14585 pw.print(ent.apk); 14586 } else { 14587 pw.print(",apk,"); 14588 pw.print(ent.apk); 14589 } 14590 } 14591 pw.println(); 14592 } 14593 } 14594 14595 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14596 if (dumpState.onTitlePrinted()) 14597 pw.println(); 14598 if (!checkin) { 14599 pw.println("Features:"); 14600 } 14601 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14602 while (it.hasNext()) { 14603 String name = it.next(); 14604 if (!checkin) { 14605 pw.print(" "); 14606 } else { 14607 pw.print("feat,"); 14608 } 14609 pw.println(name); 14610 } 14611 } 14612 14613 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14614 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14615 : "Activity Resolver Table:", " ", packageName, 14616 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14617 dumpState.setTitlePrinted(true); 14618 } 14619 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14620 : "Receiver Resolver Table:", " ", packageName, 14621 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14622 dumpState.setTitlePrinted(true); 14623 } 14624 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14625 : "Service Resolver Table:", " ", packageName, 14626 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14627 dumpState.setTitlePrinted(true); 14628 } 14629 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14630 : "Provider Resolver Table:", " ", packageName, 14631 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14632 dumpState.setTitlePrinted(true); 14633 } 14634 } 14635 14636 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14637 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14638 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14639 int user = mSettings.mPreferredActivities.keyAt(i); 14640 if (pir.dump(pw, 14641 dumpState.getTitlePrinted() 14642 ? "\nPreferred Activities User " + user + ":" 14643 : "Preferred Activities User " + user + ":", " ", 14644 packageName, true, false)) { 14645 dumpState.setTitlePrinted(true); 14646 } 14647 } 14648 } 14649 14650 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14651 pw.flush(); 14652 FileOutputStream fout = new FileOutputStream(fd); 14653 BufferedOutputStream str = new BufferedOutputStream(fout); 14654 XmlSerializer serializer = new FastXmlSerializer(); 14655 try { 14656 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14657 serializer.startDocument(null, true); 14658 serializer.setFeature( 14659 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14660 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14661 serializer.endDocument(); 14662 serializer.flush(); 14663 } catch (IllegalArgumentException e) { 14664 pw.println("Failed writing: " + e); 14665 } catch (IllegalStateException e) { 14666 pw.println("Failed writing: " + e); 14667 } catch (IOException e) { 14668 pw.println("Failed writing: " + e); 14669 } 14670 } 14671 14672 if (!checkin 14673 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14674 && packageName == null) { 14675 pw.println(); 14676 int count = mSettings.mPackages.size(); 14677 if (count == 0) { 14678 pw.println("No domain preferred apps!"); 14679 pw.println(); 14680 } else { 14681 final String prefix = " "; 14682 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14683 if (allPackageSettings.size() == 0) { 14684 pw.println("No domain preferred apps!"); 14685 pw.println(); 14686 } else { 14687 pw.println("Domain preferred apps status:"); 14688 pw.println(); 14689 count = 0; 14690 for (PackageSetting ps : allPackageSettings) { 14691 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14692 if (ivi == null || ivi.getPackageName() == null) continue; 14693 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14694 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14695 pw.println(prefix + "Status: " + ivi.getStatusString()); 14696 pw.println(); 14697 count++; 14698 } 14699 if (count == 0) { 14700 pw.println(prefix + "No domain preferred app status!"); 14701 pw.println(); 14702 } 14703 for (int userId : sUserManager.getUserIds()) { 14704 pw.println("Domain preferred apps for User " + userId + ":"); 14705 pw.println(); 14706 count = 0; 14707 for (PackageSetting ps : allPackageSettings) { 14708 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14709 if (ivi == null || ivi.getPackageName() == null) { 14710 continue; 14711 } 14712 final int status = ps.getDomainVerificationStatusForUser(userId); 14713 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14714 continue; 14715 } 14716 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14717 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14718 String statusStr = IntentFilterVerificationInfo. 14719 getStatusStringFromValue(status); 14720 pw.println(prefix + "Status: " + statusStr); 14721 pw.println(); 14722 count++; 14723 } 14724 if (count == 0) { 14725 pw.println(prefix + "No domain preferred apps!"); 14726 pw.println(); 14727 } 14728 } 14729 } 14730 } 14731 } 14732 14733 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14734 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14735 if (packageName == null && permissionNames == null) { 14736 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14737 if (iperm == 0) { 14738 if (dumpState.onTitlePrinted()) 14739 pw.println(); 14740 pw.println("AppOp Permissions:"); 14741 } 14742 pw.print(" AppOp Permission "); 14743 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14744 pw.println(":"); 14745 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14746 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14747 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14748 } 14749 } 14750 } 14751 } 14752 14753 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14754 boolean printedSomething = false; 14755 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14756 if (packageName != null && !packageName.equals(p.info.packageName)) { 14757 continue; 14758 } 14759 if (!printedSomething) { 14760 if (dumpState.onTitlePrinted()) 14761 pw.println(); 14762 pw.println("Registered ContentProviders:"); 14763 printedSomething = true; 14764 } 14765 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14766 pw.print(" "); pw.println(p.toString()); 14767 } 14768 printedSomething = false; 14769 for (Map.Entry<String, PackageParser.Provider> entry : 14770 mProvidersByAuthority.entrySet()) { 14771 PackageParser.Provider p = entry.getValue(); 14772 if (packageName != null && !packageName.equals(p.info.packageName)) { 14773 continue; 14774 } 14775 if (!printedSomething) { 14776 if (dumpState.onTitlePrinted()) 14777 pw.println(); 14778 pw.println("ContentProvider Authorities:"); 14779 printedSomething = true; 14780 } 14781 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14782 pw.print(" "); pw.println(p.toString()); 14783 if (p.info != null && p.info.applicationInfo != null) { 14784 final String appInfo = p.info.applicationInfo.toString(); 14785 pw.print(" applicationInfo="); pw.println(appInfo); 14786 } 14787 } 14788 } 14789 14790 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14791 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14792 } 14793 14794 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14795 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14796 } 14797 14798 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14799 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14800 } 14801 14802 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14803 // XXX should handle packageName != null by dumping only install data that 14804 // the given package is involved with. 14805 if (dumpState.onTitlePrinted()) pw.println(); 14806 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14807 } 14808 14809 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14810 if (dumpState.onTitlePrinted()) pw.println(); 14811 mSettings.dumpReadMessagesLPr(pw, dumpState); 14812 14813 pw.println(); 14814 pw.println("Package warning messages:"); 14815 BufferedReader in = null; 14816 String line = null; 14817 try { 14818 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14819 while ((line = in.readLine()) != null) { 14820 if (line.contains("ignored: updated version")) continue; 14821 pw.println(line); 14822 } 14823 } catch (IOException ignored) { 14824 } finally { 14825 IoUtils.closeQuietly(in); 14826 } 14827 } 14828 14829 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14830 BufferedReader in = null; 14831 String line = null; 14832 try { 14833 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14834 while ((line = in.readLine()) != null) { 14835 if (line.contains("ignored: updated version")) continue; 14836 pw.print("msg,"); 14837 pw.println(line); 14838 } 14839 } catch (IOException ignored) { 14840 } finally { 14841 IoUtils.closeQuietly(in); 14842 } 14843 } 14844 } 14845 } 14846 14847 // ------- apps on sdcard specific code ------- 14848 static final boolean DEBUG_SD_INSTALL = false; 14849 14850 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14851 14852 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14853 14854 private boolean mMediaMounted = false; 14855 14856 static String getEncryptKey() { 14857 try { 14858 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14859 SD_ENCRYPTION_KEYSTORE_NAME); 14860 if (sdEncKey == null) { 14861 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14862 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14863 if (sdEncKey == null) { 14864 Slog.e(TAG, "Failed to create encryption keys"); 14865 return null; 14866 } 14867 } 14868 return sdEncKey; 14869 } catch (NoSuchAlgorithmException nsae) { 14870 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14871 return null; 14872 } catch (IOException ioe) { 14873 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14874 return null; 14875 } 14876 } 14877 14878 /* 14879 * Update media status on PackageManager. 14880 */ 14881 @Override 14882 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14883 int callingUid = Binder.getCallingUid(); 14884 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14885 throw new SecurityException("Media status can only be updated by the system"); 14886 } 14887 // reader; this apparently protects mMediaMounted, but should probably 14888 // be a different lock in that case. 14889 synchronized (mPackages) { 14890 Log.i(TAG, "Updating external media status from " 14891 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14892 + (mediaStatus ? "mounted" : "unmounted")); 14893 if (DEBUG_SD_INSTALL) 14894 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14895 + ", mMediaMounted=" + mMediaMounted); 14896 if (mediaStatus == mMediaMounted) { 14897 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14898 : 0, -1); 14899 mHandler.sendMessage(msg); 14900 return; 14901 } 14902 mMediaMounted = mediaStatus; 14903 } 14904 // Queue up an async operation since the package installation may take a 14905 // little while. 14906 mHandler.post(new Runnable() { 14907 public void run() { 14908 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14909 } 14910 }); 14911 } 14912 14913 /** 14914 * Called by MountService when the initial ASECs to scan are available. 14915 * Should block until all the ASEC containers are finished being scanned. 14916 */ 14917 public void scanAvailableAsecs() { 14918 updateExternalMediaStatusInner(true, false, false); 14919 if (mShouldRestoreconData) { 14920 SELinuxMMAC.setRestoreconDone(); 14921 mShouldRestoreconData = false; 14922 } 14923 } 14924 14925 /* 14926 * Collect information of applications on external media, map them against 14927 * existing containers and update information based on current mount status. 14928 * Please note that we always have to report status if reportStatus has been 14929 * set to true especially when unloading packages. 14930 */ 14931 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14932 boolean externalStorage) { 14933 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14934 int[] uidArr = EmptyArray.INT; 14935 14936 final String[] list = PackageHelper.getSecureContainerList(); 14937 if (ArrayUtils.isEmpty(list)) { 14938 Log.i(TAG, "No secure containers found"); 14939 } else { 14940 // Process list of secure containers and categorize them 14941 // as active or stale based on their package internal state. 14942 14943 // reader 14944 synchronized (mPackages) { 14945 for (String cid : list) { 14946 // Leave stages untouched for now; installer service owns them 14947 if (PackageInstallerService.isStageName(cid)) continue; 14948 14949 if (DEBUG_SD_INSTALL) 14950 Log.i(TAG, "Processing container " + cid); 14951 String pkgName = getAsecPackageName(cid); 14952 if (pkgName == null) { 14953 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14954 continue; 14955 } 14956 if (DEBUG_SD_INSTALL) 14957 Log.i(TAG, "Looking for pkg : " + pkgName); 14958 14959 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14960 if (ps == null) { 14961 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14962 continue; 14963 } 14964 14965 /* 14966 * Skip packages that are not external if we're unmounting 14967 * external storage. 14968 */ 14969 if (externalStorage && !isMounted && !isExternal(ps)) { 14970 continue; 14971 } 14972 14973 final AsecInstallArgs args = new AsecInstallArgs(cid, 14974 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14975 // The package status is changed only if the code path 14976 // matches between settings and the container id. 14977 if (ps.codePathString != null 14978 && ps.codePathString.startsWith(args.getCodePath())) { 14979 if (DEBUG_SD_INSTALL) { 14980 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14981 + " at code path: " + ps.codePathString); 14982 } 14983 14984 // We do have a valid package installed on sdcard 14985 processCids.put(args, ps.codePathString); 14986 final int uid = ps.appId; 14987 if (uid != -1) { 14988 uidArr = ArrayUtils.appendInt(uidArr, uid); 14989 } 14990 } else { 14991 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14992 + ps.codePathString); 14993 } 14994 } 14995 } 14996 14997 Arrays.sort(uidArr); 14998 } 14999 15000 // Process packages with valid entries. 15001 if (isMounted) { 15002 if (DEBUG_SD_INSTALL) 15003 Log.i(TAG, "Loading packages"); 15004 loadMediaPackages(processCids, uidArr); 15005 startCleaningPackages(); 15006 mInstallerService.onSecureContainersAvailable(); 15007 } else { 15008 if (DEBUG_SD_INSTALL) 15009 Log.i(TAG, "Unloading packages"); 15010 unloadMediaPackages(processCids, uidArr, reportStatus); 15011 } 15012 } 15013 15014 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15015 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15016 final int size = infos.size(); 15017 final String[] packageNames = new String[size]; 15018 final int[] packageUids = new int[size]; 15019 for (int i = 0; i < size; i++) { 15020 final ApplicationInfo info = infos.get(i); 15021 packageNames[i] = info.packageName; 15022 packageUids[i] = info.uid; 15023 } 15024 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15025 finishedReceiver); 15026 } 15027 15028 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15029 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15030 sendResourcesChangedBroadcast(mediaStatus, replacing, 15031 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15032 } 15033 15034 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15035 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15036 int size = pkgList.length; 15037 if (size > 0) { 15038 // Send broadcasts here 15039 Bundle extras = new Bundle(); 15040 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15041 if (uidArr != null) { 15042 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15043 } 15044 if (replacing) { 15045 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15046 } 15047 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15048 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15049 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15050 } 15051 } 15052 15053 /* 15054 * Look at potentially valid container ids from processCids If package 15055 * information doesn't match the one on record or package scanning fails, 15056 * the cid is added to list of removeCids. We currently don't delete stale 15057 * containers. 15058 */ 15059 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15060 ArrayList<String> pkgList = new ArrayList<String>(); 15061 Set<AsecInstallArgs> keys = processCids.keySet(); 15062 15063 for (AsecInstallArgs args : keys) { 15064 String codePath = processCids.get(args); 15065 if (DEBUG_SD_INSTALL) 15066 Log.i(TAG, "Loading container : " + args.cid); 15067 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15068 try { 15069 // Make sure there are no container errors first. 15070 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15071 Slog.e(TAG, "Failed to mount cid : " + args.cid 15072 + " when installing from sdcard"); 15073 continue; 15074 } 15075 // Check code path here. 15076 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15077 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15078 + " does not match one in settings " + codePath); 15079 continue; 15080 } 15081 // Parse package 15082 int parseFlags = mDefParseFlags; 15083 if (args.isExternalAsec()) { 15084 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15085 } 15086 if (args.isFwdLocked()) { 15087 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15088 } 15089 15090 synchronized (mInstallLock) { 15091 PackageParser.Package pkg = null; 15092 try { 15093 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15094 } catch (PackageManagerException e) { 15095 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15096 } 15097 // Scan the package 15098 if (pkg != null) { 15099 /* 15100 * TODO why is the lock being held? doPostInstall is 15101 * called in other places without the lock. This needs 15102 * to be straightened out. 15103 */ 15104 // writer 15105 synchronized (mPackages) { 15106 retCode = PackageManager.INSTALL_SUCCEEDED; 15107 pkgList.add(pkg.packageName); 15108 // Post process args 15109 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15110 pkg.applicationInfo.uid); 15111 } 15112 } else { 15113 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15114 } 15115 } 15116 15117 } finally { 15118 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15119 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15120 } 15121 } 15122 } 15123 // writer 15124 synchronized (mPackages) { 15125 // If the platform SDK has changed since the last time we booted, 15126 // we need to re-grant app permission to catch any new ones that 15127 // appear. This is really a hack, and means that apps can in some 15128 // cases get permissions that the user didn't initially explicitly 15129 // allow... it would be nice to have some better way to handle 15130 // this situation. 15131 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15132 if (regrantPermissions) 15133 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15134 + mSdkVersion + "; regranting permissions for external storage"); 15135 mSettings.mExternalSdkPlatform = mSdkVersion; 15136 15137 // Make sure group IDs have been assigned, and any permission 15138 // changes in other apps are accounted for 15139 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15140 | (regrantPermissions 15141 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15142 : 0)); 15143 15144 mSettings.updateExternalDatabaseVersion(); 15145 15146 // can downgrade to reader 15147 // Persist settings 15148 mSettings.writeLPr(); 15149 } 15150 // Send a broadcast to let everyone know we are done processing 15151 if (pkgList.size() > 0) { 15152 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15153 } 15154 } 15155 15156 /* 15157 * Utility method to unload a list of specified containers 15158 */ 15159 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15160 // Just unmount all valid containers. 15161 for (AsecInstallArgs arg : cidArgs) { 15162 synchronized (mInstallLock) { 15163 arg.doPostDeleteLI(false); 15164 } 15165 } 15166 } 15167 15168 /* 15169 * Unload packages mounted on external media. This involves deleting package 15170 * data from internal structures, sending broadcasts about diabled packages, 15171 * gc'ing to free up references, unmounting all secure containers 15172 * corresponding to packages on external media, and posting a 15173 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15174 * that we always have to post this message if status has been requested no 15175 * matter what. 15176 */ 15177 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15178 final boolean reportStatus) { 15179 if (DEBUG_SD_INSTALL) 15180 Log.i(TAG, "unloading media packages"); 15181 ArrayList<String> pkgList = new ArrayList<String>(); 15182 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15183 final Set<AsecInstallArgs> keys = processCids.keySet(); 15184 for (AsecInstallArgs args : keys) { 15185 String pkgName = args.getPackageName(); 15186 if (DEBUG_SD_INSTALL) 15187 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15188 // Delete package internally 15189 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15190 synchronized (mInstallLock) { 15191 boolean res = deletePackageLI(pkgName, null, false, null, null, 15192 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15193 if (res) { 15194 pkgList.add(pkgName); 15195 } else { 15196 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15197 failedList.add(args); 15198 } 15199 } 15200 } 15201 15202 // reader 15203 synchronized (mPackages) { 15204 // We didn't update the settings after removing each package; 15205 // write them now for all packages. 15206 mSettings.writeLPr(); 15207 } 15208 15209 // We have to absolutely send UPDATED_MEDIA_STATUS only 15210 // after confirming that all the receivers processed the ordered 15211 // broadcast when packages get disabled, force a gc to clean things up. 15212 // and unload all the containers. 15213 if (pkgList.size() > 0) { 15214 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15215 new IIntentReceiver.Stub() { 15216 public void performReceive(Intent intent, int resultCode, String data, 15217 Bundle extras, boolean ordered, boolean sticky, 15218 int sendingUser) throws RemoteException { 15219 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15220 reportStatus ? 1 : 0, 1, keys); 15221 mHandler.sendMessage(msg); 15222 } 15223 }); 15224 } else { 15225 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15226 keys); 15227 mHandler.sendMessage(msg); 15228 } 15229 } 15230 15231 private void loadPrivatePackages(VolumeInfo vol) { 15232 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15233 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15234 synchronized (mInstallLock) { 15235 synchronized (mPackages) { 15236 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15237 for (PackageSetting ps : packages) { 15238 final PackageParser.Package pkg; 15239 try { 15240 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15241 loaded.add(pkg.applicationInfo); 15242 } catch (PackageManagerException e) { 15243 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15244 } 15245 } 15246 15247 // TODO: regrant any permissions that changed based since original install 15248 15249 mSettings.writeLPr(); 15250 } 15251 } 15252 15253 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15254 sendResourcesChangedBroadcast(true, false, loaded, null); 15255 } 15256 15257 private void unloadPrivatePackages(VolumeInfo vol) { 15258 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15259 synchronized (mInstallLock) { 15260 synchronized (mPackages) { 15261 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15262 for (PackageSetting ps : packages) { 15263 if (ps.pkg == null) continue; 15264 15265 final ApplicationInfo info = ps.pkg.applicationInfo; 15266 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15267 if (deletePackageLI(ps.name, null, false, null, null, 15268 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15269 unloaded.add(info); 15270 } else { 15271 Slog.w(TAG, "Failed to unload " + ps.codePath); 15272 } 15273 } 15274 15275 mSettings.writeLPr(); 15276 } 15277 } 15278 15279 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15280 sendResourcesChangedBroadcast(false, false, unloaded, null); 15281 } 15282 15283 /** 15284 * Examine all users present on given mounted volume, and destroy data 15285 * belonging to users that are no longer valid, or whose user ID has been 15286 * recycled. 15287 */ 15288 private void reconcileUsers(String volumeUuid) { 15289 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15290 if (ArrayUtils.isEmpty(files)) { 15291 Slog.d(TAG, "No users found on " + volumeUuid); 15292 return; 15293 } 15294 15295 for (File file : files) { 15296 if (!file.isDirectory()) continue; 15297 15298 final int userId; 15299 final UserInfo info; 15300 try { 15301 userId = Integer.parseInt(file.getName()); 15302 info = sUserManager.getUserInfo(userId); 15303 } catch (NumberFormatException e) { 15304 Slog.w(TAG, "Invalid user directory " + file); 15305 continue; 15306 } 15307 15308 boolean destroyUser = false; 15309 if (info == null) { 15310 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15311 + " because no matching user was found"); 15312 destroyUser = true; 15313 } else { 15314 try { 15315 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15316 } catch (IOException e) { 15317 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15318 + " because we failed to enforce serial number: " + e); 15319 destroyUser = true; 15320 } 15321 } 15322 15323 if (destroyUser) { 15324 synchronized (mInstallLock) { 15325 mInstaller.removeUserDataDirs(volumeUuid, userId); 15326 } 15327 } 15328 } 15329 15330 final UserManager um = mContext.getSystemService(UserManager.class); 15331 for (UserInfo user : um.getUsers()) { 15332 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15333 if (userDir.exists()) continue; 15334 15335 try { 15336 UserManagerService.prepareUserDirectory(userDir); 15337 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15338 } catch (IOException e) { 15339 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15340 } 15341 } 15342 } 15343 15344 /** 15345 * Examine all apps present on given mounted volume, and destroy apps that 15346 * aren't expected, either due to uninstallation or reinstallation on 15347 * another volume. 15348 */ 15349 private void reconcileApps(String volumeUuid) { 15350 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15351 if (ArrayUtils.isEmpty(files)) { 15352 Slog.d(TAG, "No apps found on " + volumeUuid); 15353 return; 15354 } 15355 15356 for (File file : files) { 15357 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15358 && !PackageInstallerService.isStageName(file.getName()); 15359 if (!isPackage) { 15360 // Ignore entries which are not packages 15361 continue; 15362 } 15363 15364 boolean destroyApp = false; 15365 String packageName = null; 15366 try { 15367 final PackageLite pkg = PackageParser.parsePackageLite(file, 15368 PackageParser.PARSE_MUST_BE_APK); 15369 packageName = pkg.packageName; 15370 15371 synchronized (mPackages) { 15372 final PackageSetting ps = mSettings.mPackages.get(packageName); 15373 if (ps == null) { 15374 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15375 + volumeUuid + " because we found no install record"); 15376 destroyApp = true; 15377 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15378 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15379 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15380 destroyApp = true; 15381 } 15382 } 15383 15384 } catch (PackageParserException e) { 15385 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15386 destroyApp = true; 15387 } 15388 15389 if (destroyApp) { 15390 synchronized (mInstallLock) { 15391 if (packageName != null) { 15392 removeDataDirsLI(volumeUuid, packageName); 15393 } 15394 if (file.isDirectory()) { 15395 mInstaller.rmPackageDir(file.getAbsolutePath()); 15396 } else { 15397 file.delete(); 15398 } 15399 } 15400 } 15401 } 15402 } 15403 15404 private void unfreezePackage(String packageName) { 15405 synchronized (mPackages) { 15406 final PackageSetting ps = mSettings.mPackages.get(packageName); 15407 if (ps != null) { 15408 ps.frozen = false; 15409 } 15410 } 15411 } 15412 15413 @Override 15414 public int movePackage(final String packageName, final String volumeUuid) { 15415 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15416 15417 final int moveId = mNextMoveId.getAndIncrement(); 15418 try { 15419 movePackageInternal(packageName, volumeUuid, moveId); 15420 } catch (PackageManagerException e) { 15421 Slog.w(TAG, "Failed to move " + packageName, e); 15422 mMoveCallbacks.notifyStatusChanged(moveId, 15423 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15424 } 15425 return moveId; 15426 } 15427 15428 private void movePackageInternal(final String packageName, final String volumeUuid, 15429 final int moveId) throws PackageManagerException { 15430 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15431 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15432 final PackageManager pm = mContext.getPackageManager(); 15433 15434 final boolean currentAsec; 15435 final String currentVolumeUuid; 15436 final File codeFile; 15437 final String installerPackageName; 15438 final String packageAbiOverride; 15439 final int appId; 15440 final String seinfo; 15441 final String label; 15442 15443 // reader 15444 synchronized (mPackages) { 15445 final PackageParser.Package pkg = mPackages.get(packageName); 15446 final PackageSetting ps = mSettings.mPackages.get(packageName); 15447 if (pkg == null || ps == null) { 15448 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15449 } 15450 15451 if (pkg.applicationInfo.isSystemApp()) { 15452 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15453 "Cannot move system application"); 15454 } 15455 15456 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15457 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15458 "Package already moved to " + volumeUuid); 15459 } 15460 15461 final File probe = new File(pkg.codePath); 15462 final File probeOat = new File(probe, "oat"); 15463 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15464 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15465 "Move only supported for modern cluster style installs"); 15466 } 15467 15468 if (ps.frozen) { 15469 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15470 "Failed to move already frozen package"); 15471 } 15472 ps.frozen = true; 15473 15474 currentAsec = pkg.applicationInfo.isForwardLocked() 15475 || pkg.applicationInfo.isExternalAsec(); 15476 currentVolumeUuid = ps.volumeUuid; 15477 codeFile = new File(pkg.codePath); 15478 installerPackageName = ps.installerPackageName; 15479 packageAbiOverride = ps.cpuAbiOverrideString; 15480 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15481 seinfo = pkg.applicationInfo.seinfo; 15482 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15483 } 15484 15485 // Now that we're guarded by frozen state, kill app during move 15486 killApplication(packageName, appId, "move pkg"); 15487 15488 final Bundle extras = new Bundle(); 15489 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15490 extras.putString(Intent.EXTRA_TITLE, label); 15491 mMoveCallbacks.notifyCreated(moveId, extras); 15492 15493 int installFlags; 15494 final boolean moveCompleteApp; 15495 final File measurePath; 15496 15497 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15498 installFlags = INSTALL_INTERNAL; 15499 moveCompleteApp = !currentAsec; 15500 measurePath = Environment.getDataAppDirectory(volumeUuid); 15501 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15502 installFlags = INSTALL_EXTERNAL; 15503 moveCompleteApp = false; 15504 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15505 } else { 15506 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15507 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15508 || !volume.isMountedWritable()) { 15509 unfreezePackage(packageName); 15510 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15511 "Move location not mounted private volume"); 15512 } 15513 15514 Preconditions.checkState(!currentAsec); 15515 15516 installFlags = INSTALL_INTERNAL; 15517 moveCompleteApp = true; 15518 measurePath = Environment.getDataAppDirectory(volumeUuid); 15519 } 15520 15521 final PackageStats stats = new PackageStats(null, -1); 15522 synchronized (mInstaller) { 15523 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15524 unfreezePackage(packageName); 15525 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15526 "Failed to measure package size"); 15527 } 15528 } 15529 15530 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15531 + stats.dataSize); 15532 15533 final long startFreeBytes = measurePath.getFreeSpace(); 15534 final long sizeBytes; 15535 if (moveCompleteApp) { 15536 sizeBytes = stats.codeSize + stats.dataSize; 15537 } else { 15538 sizeBytes = stats.codeSize; 15539 } 15540 15541 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15542 unfreezePackage(packageName); 15543 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15544 "Not enough free space to move"); 15545 } 15546 15547 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15548 15549 final CountDownLatch installedLatch = new CountDownLatch(1); 15550 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15551 @Override 15552 public void onUserActionRequired(Intent intent) throws RemoteException { 15553 throw new IllegalStateException(); 15554 } 15555 15556 @Override 15557 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15558 Bundle extras) throws RemoteException { 15559 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15560 + PackageManager.installStatusToString(returnCode, msg)); 15561 15562 installedLatch.countDown(); 15563 15564 // Regardless of success or failure of the move operation, 15565 // always unfreeze the package 15566 unfreezePackage(packageName); 15567 15568 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15569 switch (status) { 15570 case PackageInstaller.STATUS_SUCCESS: 15571 mMoveCallbacks.notifyStatusChanged(moveId, 15572 PackageManager.MOVE_SUCCEEDED); 15573 break; 15574 case PackageInstaller.STATUS_FAILURE_STORAGE: 15575 mMoveCallbacks.notifyStatusChanged(moveId, 15576 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15577 break; 15578 default: 15579 mMoveCallbacks.notifyStatusChanged(moveId, 15580 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15581 break; 15582 } 15583 } 15584 }; 15585 15586 final MoveInfo move; 15587 if (moveCompleteApp) { 15588 // Kick off a thread to report progress estimates 15589 new Thread() { 15590 @Override 15591 public void run() { 15592 while (true) { 15593 try { 15594 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15595 break; 15596 } 15597 } catch (InterruptedException ignored) { 15598 } 15599 15600 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15601 final int progress = 10 + (int) MathUtils.constrain( 15602 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15603 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15604 } 15605 } 15606 }.start(); 15607 15608 final String dataAppName = codeFile.getName(); 15609 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15610 dataAppName, appId, seinfo); 15611 } else { 15612 move = null; 15613 } 15614 15615 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15616 15617 final Message msg = mHandler.obtainMessage(INIT_COPY); 15618 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15619 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15620 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15621 mHandler.sendMessage(msg); 15622 } 15623 15624 @Override 15625 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15626 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15627 15628 final int realMoveId = mNextMoveId.getAndIncrement(); 15629 final Bundle extras = new Bundle(); 15630 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15631 mMoveCallbacks.notifyCreated(realMoveId, extras); 15632 15633 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15634 @Override 15635 public void onCreated(int moveId, Bundle extras) { 15636 // Ignored 15637 } 15638 15639 @Override 15640 public void onStatusChanged(int moveId, int status, long estMillis) { 15641 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15642 } 15643 }; 15644 15645 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15646 storage.setPrimaryStorageUuid(volumeUuid, callback); 15647 return realMoveId; 15648 } 15649 15650 @Override 15651 public int getMoveStatus(int moveId) { 15652 mContext.enforceCallingOrSelfPermission( 15653 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15654 return mMoveCallbacks.mLastStatus.get(moveId); 15655 } 15656 15657 @Override 15658 public void registerMoveCallback(IPackageMoveObserver callback) { 15659 mContext.enforceCallingOrSelfPermission( 15660 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15661 mMoveCallbacks.register(callback); 15662 } 15663 15664 @Override 15665 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15666 mContext.enforceCallingOrSelfPermission( 15667 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15668 mMoveCallbacks.unregister(callback); 15669 } 15670 15671 @Override 15672 public boolean setInstallLocation(int loc) { 15673 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15674 null); 15675 if (getInstallLocation() == loc) { 15676 return true; 15677 } 15678 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15679 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15680 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15681 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15682 return true; 15683 } 15684 return false; 15685 } 15686 15687 @Override 15688 public int getInstallLocation() { 15689 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15690 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15691 PackageHelper.APP_INSTALL_AUTO); 15692 } 15693 15694 /** Called by UserManagerService */ 15695 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15696 mDirtyUsers.remove(userHandle); 15697 mSettings.removeUserLPw(userHandle); 15698 mPendingBroadcasts.remove(userHandle); 15699 if (mInstaller != null) { 15700 // Technically, we shouldn't be doing this with the package lock 15701 // held. However, this is very rare, and there is already so much 15702 // other disk I/O going on, that we'll let it slide for now. 15703 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15704 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15705 final String volumeUuid = vol.getFsUuid(); 15706 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15707 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15708 } 15709 } 15710 mUserNeedsBadging.delete(userHandle); 15711 removeUnusedPackagesLILPw(userManager, userHandle); 15712 } 15713 15714 /** 15715 * We're removing userHandle and would like to remove any downloaded packages 15716 * that are no longer in use by any other user. 15717 * @param userHandle the user being removed 15718 */ 15719 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15720 final boolean DEBUG_CLEAN_APKS = false; 15721 int [] users = userManager.getUserIdsLPr(); 15722 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15723 while (psit.hasNext()) { 15724 PackageSetting ps = psit.next(); 15725 if (ps.pkg == null) { 15726 continue; 15727 } 15728 final String packageName = ps.pkg.packageName; 15729 // Skip over if system app 15730 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15731 continue; 15732 } 15733 if (DEBUG_CLEAN_APKS) { 15734 Slog.i(TAG, "Checking package " + packageName); 15735 } 15736 boolean keep = false; 15737 for (int i = 0; i < users.length; i++) { 15738 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15739 keep = true; 15740 if (DEBUG_CLEAN_APKS) { 15741 Slog.i(TAG, " Keeping package " + packageName + " for user " 15742 + users[i]); 15743 } 15744 break; 15745 } 15746 } 15747 if (!keep) { 15748 if (DEBUG_CLEAN_APKS) { 15749 Slog.i(TAG, " Removing package " + packageName); 15750 } 15751 mHandler.post(new Runnable() { 15752 public void run() { 15753 deletePackageX(packageName, userHandle, 0); 15754 } //end run 15755 }); 15756 } 15757 } 15758 } 15759 15760 /** Called by UserManagerService */ 15761 void createNewUserLILPw(int userHandle) { 15762 if (mInstaller != null) { 15763 mInstaller.createUserConfig(userHandle); 15764 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15765 applyFactoryDefaultBrowserLPw(userHandle); 15766 } 15767 } 15768 15769 void newUserCreatedLILPw(final int userHandle) { 15770 // We cannot grant the default permissions with a lock held as 15771 // we query providers from other components for default handlers 15772 // such as enabled IMEs, etc. 15773 mHandler.post(new Runnable() { 15774 @Override 15775 public void run() { 15776 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15777 } 15778 }); 15779 } 15780 15781 @Override 15782 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15783 mContext.enforceCallingOrSelfPermission( 15784 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15785 "Only package verification agents can read the verifier device identity"); 15786 15787 synchronized (mPackages) { 15788 return mSettings.getVerifierDeviceIdentityLPw(); 15789 } 15790 } 15791 15792 @Override 15793 public void setPermissionEnforced(String permission, boolean enforced) { 15794 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15795 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15796 synchronized (mPackages) { 15797 if (mSettings.mReadExternalStorageEnforced == null 15798 || mSettings.mReadExternalStorageEnforced != enforced) { 15799 mSettings.mReadExternalStorageEnforced = enforced; 15800 mSettings.writeLPr(); 15801 } 15802 } 15803 // kill any non-foreground processes so we restart them and 15804 // grant/revoke the GID. 15805 final IActivityManager am = ActivityManagerNative.getDefault(); 15806 if (am != null) { 15807 final long token = Binder.clearCallingIdentity(); 15808 try { 15809 am.killProcessesBelowForeground("setPermissionEnforcement"); 15810 } catch (RemoteException e) { 15811 } finally { 15812 Binder.restoreCallingIdentity(token); 15813 } 15814 } 15815 } else { 15816 throw new IllegalArgumentException("No selective enforcement for " + permission); 15817 } 15818 } 15819 15820 @Override 15821 @Deprecated 15822 public boolean isPermissionEnforced(String permission) { 15823 return true; 15824 } 15825 15826 @Override 15827 public boolean isStorageLow() { 15828 final long token = Binder.clearCallingIdentity(); 15829 try { 15830 final DeviceStorageMonitorInternal 15831 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15832 if (dsm != null) { 15833 return dsm.isMemoryLow(); 15834 } else { 15835 return false; 15836 } 15837 } finally { 15838 Binder.restoreCallingIdentity(token); 15839 } 15840 } 15841 15842 @Override 15843 public IPackageInstaller getPackageInstaller() { 15844 return mInstallerService; 15845 } 15846 15847 private boolean userNeedsBadging(int userId) { 15848 int index = mUserNeedsBadging.indexOfKey(userId); 15849 if (index < 0) { 15850 final UserInfo userInfo; 15851 final long token = Binder.clearCallingIdentity(); 15852 try { 15853 userInfo = sUserManager.getUserInfo(userId); 15854 } finally { 15855 Binder.restoreCallingIdentity(token); 15856 } 15857 final boolean b; 15858 if (userInfo != null && userInfo.isManagedProfile()) { 15859 b = true; 15860 } else { 15861 b = false; 15862 } 15863 mUserNeedsBadging.put(userId, b); 15864 return b; 15865 } 15866 return mUserNeedsBadging.valueAt(index); 15867 } 15868 15869 @Override 15870 public KeySet getKeySetByAlias(String packageName, String alias) { 15871 if (packageName == null || alias == null) { 15872 return null; 15873 } 15874 synchronized(mPackages) { 15875 final PackageParser.Package pkg = mPackages.get(packageName); 15876 if (pkg == null) { 15877 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15878 throw new IllegalArgumentException("Unknown package: " + packageName); 15879 } 15880 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15881 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15882 } 15883 } 15884 15885 @Override 15886 public KeySet getSigningKeySet(String packageName) { 15887 if (packageName == null) { 15888 return null; 15889 } 15890 synchronized(mPackages) { 15891 final PackageParser.Package pkg = mPackages.get(packageName); 15892 if (pkg == null) { 15893 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15894 throw new IllegalArgumentException("Unknown package: " + packageName); 15895 } 15896 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15897 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15898 throw new SecurityException("May not access signing KeySet of other apps."); 15899 } 15900 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15901 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15902 } 15903 } 15904 15905 @Override 15906 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15907 if (packageName == null || ks == null) { 15908 return false; 15909 } 15910 synchronized(mPackages) { 15911 final PackageParser.Package pkg = mPackages.get(packageName); 15912 if (pkg == null) { 15913 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15914 throw new IllegalArgumentException("Unknown package: " + packageName); 15915 } 15916 IBinder ksh = ks.getToken(); 15917 if (ksh instanceof KeySetHandle) { 15918 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15919 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15920 } 15921 return false; 15922 } 15923 } 15924 15925 @Override 15926 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15927 if (packageName == null || ks == null) { 15928 return false; 15929 } 15930 synchronized(mPackages) { 15931 final PackageParser.Package pkg = mPackages.get(packageName); 15932 if (pkg == null) { 15933 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15934 throw new IllegalArgumentException("Unknown package: " + packageName); 15935 } 15936 IBinder ksh = ks.getToken(); 15937 if (ksh instanceof KeySetHandle) { 15938 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15939 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15940 } 15941 return false; 15942 } 15943 } 15944 15945 public void getUsageStatsIfNoPackageUsageInfo() { 15946 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15947 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15948 if (usm == null) { 15949 throw new IllegalStateException("UsageStatsManager must be initialized"); 15950 } 15951 long now = System.currentTimeMillis(); 15952 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15953 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15954 String packageName = entry.getKey(); 15955 PackageParser.Package pkg = mPackages.get(packageName); 15956 if (pkg == null) { 15957 continue; 15958 } 15959 UsageStats usage = entry.getValue(); 15960 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15961 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15962 } 15963 } 15964 } 15965 15966 /** 15967 * Check and throw if the given before/after packages would be considered a 15968 * downgrade. 15969 */ 15970 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15971 throws PackageManagerException { 15972 if (after.versionCode < before.mVersionCode) { 15973 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15974 "Update version code " + after.versionCode + " is older than current " 15975 + before.mVersionCode); 15976 } else if (after.versionCode == before.mVersionCode) { 15977 if (after.baseRevisionCode < before.baseRevisionCode) { 15978 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15979 "Update base revision code " + after.baseRevisionCode 15980 + " is older than current " + before.baseRevisionCode); 15981 } 15982 15983 if (!ArrayUtils.isEmpty(after.splitNames)) { 15984 for (int i = 0; i < after.splitNames.length; i++) { 15985 final String splitName = after.splitNames[i]; 15986 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15987 if (j != -1) { 15988 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15989 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15990 "Update split " + splitName + " revision code " 15991 + after.splitRevisionCodes[i] + " is older than current " 15992 + before.splitRevisionCodes[j]); 15993 } 15994 } 15995 } 15996 } 15997 } 15998 } 15999 16000 private static class MoveCallbacks extends Handler { 16001 private static final int MSG_CREATED = 1; 16002 private static final int MSG_STATUS_CHANGED = 2; 16003 16004 private final RemoteCallbackList<IPackageMoveObserver> 16005 mCallbacks = new RemoteCallbackList<>(); 16006 16007 private final SparseIntArray mLastStatus = new SparseIntArray(); 16008 16009 public MoveCallbacks(Looper looper) { 16010 super(looper); 16011 } 16012 16013 public void register(IPackageMoveObserver callback) { 16014 mCallbacks.register(callback); 16015 } 16016 16017 public void unregister(IPackageMoveObserver callback) { 16018 mCallbacks.unregister(callback); 16019 } 16020 16021 @Override 16022 public void handleMessage(Message msg) { 16023 final SomeArgs args = (SomeArgs) msg.obj; 16024 final int n = mCallbacks.beginBroadcast(); 16025 for (int i = 0; i < n; i++) { 16026 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16027 try { 16028 invokeCallback(callback, msg.what, args); 16029 } catch (RemoteException ignored) { 16030 } 16031 } 16032 mCallbacks.finishBroadcast(); 16033 args.recycle(); 16034 } 16035 16036 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16037 throws RemoteException { 16038 switch (what) { 16039 case MSG_CREATED: { 16040 callback.onCreated(args.argi1, (Bundle) args.arg2); 16041 break; 16042 } 16043 case MSG_STATUS_CHANGED: { 16044 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16045 break; 16046 } 16047 } 16048 } 16049 16050 private void notifyCreated(int moveId, Bundle extras) { 16051 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16052 16053 final SomeArgs args = SomeArgs.obtain(); 16054 args.argi1 = moveId; 16055 args.arg2 = extras; 16056 obtainMessage(MSG_CREATED, args).sendToTarget(); 16057 } 16058 16059 private void notifyStatusChanged(int moveId, int status) { 16060 notifyStatusChanged(moveId, status, -1); 16061 } 16062 16063 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16064 Slog.v(TAG, "Move " + moveId + " status " + status); 16065 16066 final SomeArgs args = SomeArgs.obtain(); 16067 args.argi1 = moveId; 16068 args.argi2 = status; 16069 args.arg3 = estMillis; 16070 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16071 16072 synchronized (mLastStatus) { 16073 mLastStatus.put(moveId, status); 16074 } 16075 } 16076 } 16077 16078 private final class OnPermissionChangeListeners extends Handler { 16079 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16080 16081 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16082 new RemoteCallbackList<>(); 16083 16084 public OnPermissionChangeListeners(Looper looper) { 16085 super(looper); 16086 } 16087 16088 @Override 16089 public void handleMessage(Message msg) { 16090 switch (msg.what) { 16091 case MSG_ON_PERMISSIONS_CHANGED: { 16092 final int uid = msg.arg1; 16093 handleOnPermissionsChanged(uid); 16094 } break; 16095 } 16096 } 16097 16098 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16099 mPermissionListeners.register(listener); 16100 16101 } 16102 16103 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16104 mPermissionListeners.unregister(listener); 16105 } 16106 16107 public void onPermissionsChanged(int uid) { 16108 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16109 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16110 } 16111 } 16112 16113 private void handleOnPermissionsChanged(int uid) { 16114 final int count = mPermissionListeners.beginBroadcast(); 16115 try { 16116 for (int i = 0; i < count; i++) { 16117 IOnPermissionsChangeListener callback = mPermissionListeners 16118 .getBroadcastItem(i); 16119 try { 16120 callback.onPermissionsChanged(uid); 16121 } catch (RemoteException e) { 16122 Log.e(TAG, "Permission listener is dead", e); 16123 } 16124 } 16125 } finally { 16126 mPermissionListeners.finishBroadcast(); 16127 } 16128 } 16129 } 16130 16131 private class PackageManagerInternalImpl extends PackageManagerInternal { 16132 @Override 16133 public void setLocationPackagesProvider(PackagesProvider provider) { 16134 synchronized (mPackages) { 16135 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16136 } 16137 } 16138 16139 @Override 16140 public void setImePackagesProvider(PackagesProvider provider) { 16141 synchronized (mPackages) { 16142 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16143 } 16144 } 16145 16146 @Override 16147 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16148 synchronized (mPackages) { 16149 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16150 } 16151 } 16152 16153 @Override 16154 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16155 synchronized (mPackages) { 16156 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16157 } 16158 } 16159 16160 @Override 16161 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16162 synchronized (mPackages) { 16163 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16164 } 16165 } 16166 16167 @Override 16168 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16169 synchronized (mPackages) { 16170 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16171 } 16172 } 16173 16174 @Override 16175 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16176 synchronized (mPackages) { 16177 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16178 packageName, userId); 16179 } 16180 } 16181 16182 @Override 16183 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16184 synchronized (mPackages) { 16185 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16186 packageName, userId); 16187 } 16188 } 16189 } 16190 16191 @Override 16192 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16193 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16194 synchronized (mPackages) { 16195 final long identity = Binder.clearCallingIdentity(); 16196 try { 16197 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16198 packageNames, userId); 16199 } finally { 16200 Binder.restoreCallingIdentity(identity); 16201 } 16202 } 16203 } 16204 16205 private static void enforceSystemOrPhoneCaller(String tag) { 16206 int callingUid = Binder.getCallingUid(); 16207 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16208 throw new SecurityException( 16209 "Cannot call " + tag + " from UID " + callingUid); 16210 } 16211 } 16212} 16213