PackageManagerService.java revision 6b7bb60457501ff4110933c3e9b66446eb4f7b19
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 1317 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1318 final String packageName = res.pkg.applicationInfo.packageName; 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.copyCompleteApp(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(move.toUuid); 11297 } 11298 return status; 11299 } 11300 11301 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11302 if (status != PackageManager.INSTALL_SUCCEEDED) { 11303 cleanUp(move.toUuid); 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(move.fromUuid); 11322 } else { 11323 cleanUp(move.toUuid); 11324 } 11325 return status; 11326 } 11327 11328 @Override 11329 String getCodePath() { 11330 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11331 } 11332 11333 @Override 11334 String getResourcePath() { 11335 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11336 } 11337 11338 private boolean cleanUp(String volumeUuid) { 11339 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11340 move.dataAppName); 11341 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11342 synchronized (mInstallLock) { 11343 // Clean up both app data and code 11344 removeDataDirsLI(volumeUuid, move.packageName); 11345 if (codeFile.isDirectory()) { 11346 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11347 } else { 11348 codeFile.delete(); 11349 } 11350 } 11351 return true; 11352 } 11353 11354 void cleanUpResourcesLI() { 11355 throw new UnsupportedOperationException(); 11356 } 11357 11358 boolean doPostDeleteLI(boolean delete) { 11359 throw new UnsupportedOperationException(); 11360 } 11361 } 11362 11363 static String getAsecPackageName(String packageCid) { 11364 int idx = packageCid.lastIndexOf("-"); 11365 if (idx == -1) { 11366 return packageCid; 11367 } 11368 return packageCid.substring(0, idx); 11369 } 11370 11371 // Utility method used to create code paths based on package name and available index. 11372 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11373 String idxStr = ""; 11374 int idx = 1; 11375 // Fall back to default value of idx=1 if prefix is not 11376 // part of oldCodePath 11377 if (oldCodePath != null) { 11378 String subStr = oldCodePath; 11379 // Drop the suffix right away 11380 if (suffix != null && subStr.endsWith(suffix)) { 11381 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11382 } 11383 // If oldCodePath already contains prefix find out the 11384 // ending index to either increment or decrement. 11385 int sidx = subStr.lastIndexOf(prefix); 11386 if (sidx != -1) { 11387 subStr = subStr.substring(sidx + prefix.length()); 11388 if (subStr != null) { 11389 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11390 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11391 } 11392 try { 11393 idx = Integer.parseInt(subStr); 11394 if (idx <= 1) { 11395 idx++; 11396 } else { 11397 idx--; 11398 } 11399 } catch(NumberFormatException e) { 11400 } 11401 } 11402 } 11403 } 11404 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11405 return prefix + idxStr; 11406 } 11407 11408 private File getNextCodePath(File targetDir, String packageName) { 11409 int suffix = 1; 11410 File result; 11411 do { 11412 result = new File(targetDir, packageName + "-" + suffix); 11413 suffix++; 11414 } while (result.exists()); 11415 return result; 11416 } 11417 11418 // Utility method that returns the relative package path with respect 11419 // to the installation directory. Like say for /data/data/com.test-1.apk 11420 // string com.test-1 is returned. 11421 static String deriveCodePathName(String codePath) { 11422 if (codePath == null) { 11423 return null; 11424 } 11425 final File codeFile = new File(codePath); 11426 final String name = codeFile.getName(); 11427 if (codeFile.isDirectory()) { 11428 return name; 11429 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11430 final int lastDot = name.lastIndexOf('.'); 11431 return name.substring(0, lastDot); 11432 } else { 11433 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11434 return null; 11435 } 11436 } 11437 11438 class PackageInstalledInfo { 11439 String name; 11440 int uid; 11441 // The set of users that originally had this package installed. 11442 int[] origUsers; 11443 // The set of users that now have this package installed. 11444 int[] newUsers; 11445 PackageParser.Package pkg; 11446 int returnCode; 11447 String returnMsg; 11448 PackageRemovedInfo removedInfo; 11449 11450 public void setError(int code, String msg) { 11451 returnCode = code; 11452 returnMsg = msg; 11453 Slog.w(TAG, msg); 11454 } 11455 11456 public void setError(String msg, PackageParserException e) { 11457 returnCode = e.error; 11458 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11459 Slog.w(TAG, msg, e); 11460 } 11461 11462 public void setError(String msg, PackageManagerException e) { 11463 returnCode = e.error; 11464 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11465 Slog.w(TAG, msg, e); 11466 } 11467 11468 // In some error cases we want to convey more info back to the observer 11469 String origPackage; 11470 String origPermission; 11471 } 11472 11473 /* 11474 * Install a non-existing package. 11475 */ 11476 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11477 UserHandle user, String installerPackageName, String volumeUuid, 11478 PackageInstalledInfo res) { 11479 // Remember this for later, in case we need to rollback this install 11480 String pkgName = pkg.packageName; 11481 11482 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11483 final boolean dataDirExists = Environment 11484 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11485 synchronized(mPackages) { 11486 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11487 // A package with the same name is already installed, though 11488 // it has been renamed to an older name. The package we 11489 // are trying to install should be installed as an update to 11490 // the existing one, but that has not been requested, so bail. 11491 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11492 + " without first uninstalling package running as " 11493 + mSettings.mRenamedPackages.get(pkgName)); 11494 return; 11495 } 11496 if (mPackages.containsKey(pkgName)) { 11497 // Don't allow installation over an existing package with the same name. 11498 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11499 + " without first uninstalling."); 11500 return; 11501 } 11502 } 11503 11504 try { 11505 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11506 System.currentTimeMillis(), user); 11507 11508 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11509 // delete the partially installed application. the data directory will have to be 11510 // restored if it was already existing 11511 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11512 // remove package from internal structures. Note that we want deletePackageX to 11513 // delete the package data and cache directories that it created in 11514 // scanPackageLocked, unless those directories existed before we even tried to 11515 // install. 11516 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11517 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11518 res.removedInfo, true); 11519 } 11520 11521 } catch (PackageManagerException e) { 11522 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11523 } 11524 } 11525 11526 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11527 // Can't rotate keys during boot or if sharedUser. 11528 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11529 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11530 return false; 11531 } 11532 // app is using upgradeKeySets; make sure all are valid 11533 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11534 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11535 for (int i = 0; i < upgradeKeySets.length; i++) { 11536 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11537 Slog.wtf(TAG, "Package " 11538 + (oldPs.name != null ? oldPs.name : "<null>") 11539 + " contains upgrade-key-set reference to unknown key-set: " 11540 + upgradeKeySets[i] 11541 + " reverting to signatures check."); 11542 return false; 11543 } 11544 } 11545 return true; 11546 } 11547 11548 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11549 // Upgrade keysets are being used. Determine if new package has a superset of the 11550 // required keys. 11551 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11552 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11553 for (int i = 0; i < upgradeKeySets.length; i++) { 11554 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11555 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11556 return true; 11557 } 11558 } 11559 return false; 11560 } 11561 11562 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11563 UserHandle user, String installerPackageName, String volumeUuid, 11564 PackageInstalledInfo res) { 11565 final PackageParser.Package oldPackage; 11566 final String pkgName = pkg.packageName; 11567 final int[] allUsers; 11568 final boolean[] perUserInstalled; 11569 final boolean weFroze; 11570 11571 // First find the old package info and check signatures 11572 synchronized(mPackages) { 11573 oldPackage = mPackages.get(pkgName); 11574 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11575 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11576 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11577 if(!checkUpgradeKeySetLP(ps, pkg)) { 11578 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11579 "New package not signed by keys specified by upgrade-keysets: " 11580 + pkgName); 11581 return; 11582 } 11583 } else { 11584 // default to original signature matching 11585 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11586 != PackageManager.SIGNATURE_MATCH) { 11587 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11588 "New package has a different signature: " + pkgName); 11589 return; 11590 } 11591 } 11592 11593 // In case of rollback, remember per-user/profile install state 11594 allUsers = sUserManager.getUserIds(); 11595 perUserInstalled = new boolean[allUsers.length]; 11596 for (int i = 0; i < allUsers.length; i++) { 11597 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11598 } 11599 11600 // Mark the app as frozen to prevent launching during the upgrade 11601 // process, and then kill all running instances 11602 if (!ps.frozen) { 11603 ps.frozen = true; 11604 weFroze = true; 11605 } else { 11606 weFroze = false; 11607 } 11608 } 11609 11610 // Now that we're guarded by frozen state, kill app during upgrade 11611 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11612 11613 try { 11614 boolean sysPkg = (isSystemApp(oldPackage)); 11615 if (sysPkg) { 11616 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11617 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11618 } else { 11619 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11620 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11621 } 11622 } finally { 11623 // Regardless of success or failure of upgrade steps above, always 11624 // unfreeze the package if we froze it 11625 if (weFroze) { 11626 unfreezePackage(pkgName); 11627 } 11628 } 11629 } 11630 11631 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11632 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11633 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11634 String volumeUuid, PackageInstalledInfo res) { 11635 String pkgName = deletedPackage.packageName; 11636 boolean deletedPkg = true; 11637 boolean updatedSettings = false; 11638 11639 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11640 + deletedPackage); 11641 long origUpdateTime; 11642 if (pkg.mExtras != null) { 11643 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11644 } else { 11645 origUpdateTime = 0; 11646 } 11647 11648 // First delete the existing package while retaining the data directory 11649 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11650 res.removedInfo, true)) { 11651 // If the existing package wasn't successfully deleted 11652 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11653 deletedPkg = false; 11654 } else { 11655 // Successfully deleted the old package; proceed with replace. 11656 11657 // If deleted package lived in a container, give users a chance to 11658 // relinquish resources before killing. 11659 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11660 if (DEBUG_INSTALL) { 11661 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11662 } 11663 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11664 final ArrayList<String> pkgList = new ArrayList<String>(1); 11665 pkgList.add(deletedPackage.applicationInfo.packageName); 11666 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11667 } 11668 11669 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11670 try { 11671 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11672 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11673 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11674 perUserInstalled, res, user); 11675 updatedSettings = true; 11676 } catch (PackageManagerException e) { 11677 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11678 } 11679 } 11680 11681 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11682 // remove package from internal structures. Note that we want deletePackageX to 11683 // delete the package data and cache directories that it created in 11684 // scanPackageLocked, unless those directories existed before we even tried to 11685 // install. 11686 if(updatedSettings) { 11687 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11688 deletePackageLI( 11689 pkgName, null, true, allUsers, perUserInstalled, 11690 PackageManager.DELETE_KEEP_DATA, 11691 res.removedInfo, true); 11692 } 11693 // Since we failed to install the new package we need to restore the old 11694 // package that we deleted. 11695 if (deletedPkg) { 11696 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11697 File restoreFile = new File(deletedPackage.codePath); 11698 // Parse old package 11699 boolean oldExternal = isExternal(deletedPackage); 11700 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11701 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11702 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11703 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11704 try { 11705 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11706 } catch (PackageManagerException e) { 11707 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11708 + e.getMessage()); 11709 return; 11710 } 11711 // Restore of old package succeeded. Update permissions. 11712 // writer 11713 synchronized (mPackages) { 11714 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11715 UPDATE_PERMISSIONS_ALL); 11716 // can downgrade to reader 11717 mSettings.writeLPr(); 11718 } 11719 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11720 } 11721 } 11722 } 11723 11724 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11725 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11726 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11727 String volumeUuid, PackageInstalledInfo res) { 11728 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11729 + ", old=" + deletedPackage); 11730 boolean disabledSystem = false; 11731 boolean updatedSettings = false; 11732 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11733 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11734 != 0) { 11735 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11736 } 11737 String packageName = deletedPackage.packageName; 11738 if (packageName == null) { 11739 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11740 "Attempt to delete null packageName."); 11741 return; 11742 } 11743 PackageParser.Package oldPkg; 11744 PackageSetting oldPkgSetting; 11745 // reader 11746 synchronized (mPackages) { 11747 oldPkg = mPackages.get(packageName); 11748 oldPkgSetting = mSettings.mPackages.get(packageName); 11749 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11750 (oldPkgSetting == null)) { 11751 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11752 "Couldn't find package:" + packageName + " information"); 11753 return; 11754 } 11755 } 11756 11757 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11758 res.removedInfo.removedPackage = packageName; 11759 // Remove existing system package 11760 removePackageLI(oldPkgSetting, true); 11761 // writer 11762 synchronized (mPackages) { 11763 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11764 if (!disabledSystem && deletedPackage != null) { 11765 // We didn't need to disable the .apk as a current system package, 11766 // which means we are replacing another update that is already 11767 // installed. We need to make sure to delete the older one's .apk. 11768 res.removedInfo.args = createInstallArgsForExisting(0, 11769 deletedPackage.applicationInfo.getCodePath(), 11770 deletedPackage.applicationInfo.getResourcePath(), 11771 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11772 } else { 11773 res.removedInfo.args = null; 11774 } 11775 } 11776 11777 // Successfully disabled the old package. Now proceed with re-installation 11778 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11779 11780 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11781 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11782 11783 PackageParser.Package newPackage = null; 11784 try { 11785 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11786 if (newPackage.mExtras != null) { 11787 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11788 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11789 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11790 11791 // is the update attempting to change shared user? that isn't going to work... 11792 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11793 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11794 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11795 + " to " + newPkgSetting.sharedUser); 11796 updatedSettings = true; 11797 } 11798 } 11799 11800 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11801 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11802 perUserInstalled, res, user); 11803 updatedSettings = true; 11804 } 11805 11806 } catch (PackageManagerException e) { 11807 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11808 } 11809 11810 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11811 // Re installation failed. Restore old information 11812 // Remove new pkg information 11813 if (newPackage != null) { 11814 removeInstalledPackageLI(newPackage, true); 11815 } 11816 // Add back the old system package 11817 try { 11818 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11819 } catch (PackageManagerException e) { 11820 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11821 } 11822 // Restore the old system information in Settings 11823 synchronized (mPackages) { 11824 if (disabledSystem) { 11825 mSettings.enableSystemPackageLPw(packageName); 11826 } 11827 if (updatedSettings) { 11828 mSettings.setInstallerPackageName(packageName, 11829 oldPkgSetting.installerPackageName); 11830 } 11831 mSettings.writeLPr(); 11832 } 11833 } 11834 } 11835 11836 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11837 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11838 UserHandle user) { 11839 String pkgName = newPackage.packageName; 11840 synchronized (mPackages) { 11841 //write settings. the installStatus will be incomplete at this stage. 11842 //note that the new package setting would have already been 11843 //added to mPackages. It hasn't been persisted yet. 11844 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11845 mSettings.writeLPr(); 11846 } 11847 11848 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11849 11850 synchronized (mPackages) { 11851 updatePermissionsLPw(newPackage.packageName, newPackage, 11852 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11853 ? UPDATE_PERMISSIONS_ALL : 0)); 11854 // For system-bundled packages, we assume that installing an upgraded version 11855 // of the package implies that the user actually wants to run that new code, 11856 // so we enable the package. 11857 PackageSetting ps = mSettings.mPackages.get(pkgName); 11858 if (ps != null) { 11859 if (isSystemApp(newPackage)) { 11860 // NB: implicit assumption that system package upgrades apply to all users 11861 if (DEBUG_INSTALL) { 11862 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11863 } 11864 if (res.origUsers != null) { 11865 for (int userHandle : res.origUsers) { 11866 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11867 userHandle, installerPackageName); 11868 } 11869 } 11870 // Also convey the prior install/uninstall state 11871 if (allUsers != null && perUserInstalled != null) { 11872 for (int i = 0; i < allUsers.length; i++) { 11873 if (DEBUG_INSTALL) { 11874 Slog.d(TAG, " user " + allUsers[i] 11875 + " => " + perUserInstalled[i]); 11876 } 11877 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11878 } 11879 // these install state changes will be persisted in the 11880 // upcoming call to mSettings.writeLPr(). 11881 } 11882 } 11883 // It's implied that when a user requests installation, they want the app to be 11884 // installed and enabled. 11885 int userId = user.getIdentifier(); 11886 if (userId != UserHandle.USER_ALL) { 11887 ps.setInstalled(true, userId); 11888 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11889 } 11890 } 11891 res.name = pkgName; 11892 res.uid = newPackage.applicationInfo.uid; 11893 res.pkg = newPackage; 11894 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11895 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11896 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11897 //to update install status 11898 mSettings.writeLPr(); 11899 } 11900 } 11901 11902 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11903 final int installFlags = args.installFlags; 11904 final String installerPackageName = args.installerPackageName; 11905 final String volumeUuid = args.volumeUuid; 11906 final File tmpPackageFile = new File(args.getCodePath()); 11907 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11908 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11909 || (args.volumeUuid != null)); 11910 boolean replace = false; 11911 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11912 if (args.move != null) { 11913 // moving a complete application; perfom an initial scan on the new install location 11914 scanFlags |= SCAN_INITIAL; 11915 } 11916 // Result object to be returned 11917 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11918 11919 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11920 // Retrieve PackageSettings and parse package 11921 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11922 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11923 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11924 PackageParser pp = new PackageParser(); 11925 pp.setSeparateProcesses(mSeparateProcesses); 11926 pp.setDisplayMetrics(mMetrics); 11927 11928 final PackageParser.Package pkg; 11929 try { 11930 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11931 } catch (PackageParserException e) { 11932 res.setError("Failed parse during installPackageLI", e); 11933 return; 11934 } 11935 11936 // Mark that we have an install time CPU ABI override. 11937 pkg.cpuAbiOverride = args.abiOverride; 11938 11939 String pkgName = res.name = pkg.packageName; 11940 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11941 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11942 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11943 return; 11944 } 11945 } 11946 11947 try { 11948 pp.collectCertificates(pkg, parseFlags); 11949 pp.collectManifestDigest(pkg); 11950 } catch (PackageParserException e) { 11951 res.setError("Failed collect during installPackageLI", e); 11952 return; 11953 } 11954 11955 /* If the installer passed in a manifest digest, compare it now. */ 11956 if (args.manifestDigest != null) { 11957 if (DEBUG_INSTALL) { 11958 final String parsedManifest = pkg.manifestDigest == null ? "null" 11959 : pkg.manifestDigest.toString(); 11960 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11961 + parsedManifest); 11962 } 11963 11964 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11965 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11966 return; 11967 } 11968 } else if (DEBUG_INSTALL) { 11969 final String parsedManifest = pkg.manifestDigest == null 11970 ? "null" : pkg.manifestDigest.toString(); 11971 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11972 } 11973 11974 // Get rid of all references to package scan path via parser. 11975 pp = null; 11976 String oldCodePath = null; 11977 boolean systemApp = false; 11978 synchronized (mPackages) { 11979 // Check if installing already existing package 11980 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11981 String oldName = mSettings.mRenamedPackages.get(pkgName); 11982 if (pkg.mOriginalPackages != null 11983 && pkg.mOriginalPackages.contains(oldName) 11984 && mPackages.containsKey(oldName)) { 11985 // This package is derived from an original package, 11986 // and this device has been updating from that original 11987 // name. We must continue using the original name, so 11988 // rename the new package here. 11989 pkg.setPackageName(oldName); 11990 pkgName = pkg.packageName; 11991 replace = true; 11992 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11993 + oldName + " pkgName=" + pkgName); 11994 } else if (mPackages.containsKey(pkgName)) { 11995 // This package, under its official name, already exists 11996 // on the device; we should replace it. 11997 replace = true; 11998 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11999 } 12000 12001 // Prevent apps opting out from runtime permissions 12002 if (replace) { 12003 PackageParser.Package oldPackage = mPackages.get(pkgName); 12004 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12005 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12006 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12007 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12008 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12009 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12010 + " doesn't support runtime permissions but the old" 12011 + " target SDK " + oldTargetSdk + " does."); 12012 return; 12013 } 12014 } 12015 } 12016 12017 PackageSetting ps = mSettings.mPackages.get(pkgName); 12018 if (ps != null) { 12019 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12020 12021 // Quick sanity check that we're signed correctly if updating; 12022 // we'll check this again later when scanning, but we want to 12023 // bail early here before tripping over redefined permissions. 12024 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12025 if (!checkUpgradeKeySetLP(ps, pkg)) { 12026 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12027 + pkg.packageName + " upgrade keys do not match the " 12028 + "previously installed version"); 12029 return; 12030 } 12031 } else { 12032 try { 12033 verifySignaturesLP(ps, pkg); 12034 } catch (PackageManagerException e) { 12035 res.setError(e.error, e.getMessage()); 12036 return; 12037 } 12038 } 12039 12040 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12041 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12042 systemApp = (ps.pkg.applicationInfo.flags & 12043 ApplicationInfo.FLAG_SYSTEM) != 0; 12044 } 12045 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12046 } 12047 12048 // Check whether the newly-scanned package wants to define an already-defined perm 12049 int N = pkg.permissions.size(); 12050 for (int i = N-1; i >= 0; i--) { 12051 PackageParser.Permission perm = pkg.permissions.get(i); 12052 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12053 if (bp != null) { 12054 // If the defining package is signed with our cert, it's okay. This 12055 // also includes the "updating the same package" case, of course. 12056 // "updating same package" could also involve key-rotation. 12057 final boolean sigsOk; 12058 if (bp.sourcePackage.equals(pkg.packageName) 12059 && (bp.packageSetting instanceof PackageSetting) 12060 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12061 scanFlags))) { 12062 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12063 } else { 12064 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12065 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12066 } 12067 if (!sigsOk) { 12068 // If the owning package is the system itself, we log but allow 12069 // install to proceed; we fail the install on all other permission 12070 // redefinitions. 12071 if (!bp.sourcePackage.equals("android")) { 12072 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12073 + pkg.packageName + " attempting to redeclare permission " 12074 + perm.info.name + " already owned by " + bp.sourcePackage); 12075 res.origPermission = perm.info.name; 12076 res.origPackage = bp.sourcePackage; 12077 return; 12078 } else { 12079 Slog.w(TAG, "Package " + pkg.packageName 12080 + " attempting to redeclare system permission " 12081 + perm.info.name + "; ignoring new declaration"); 12082 pkg.permissions.remove(i); 12083 } 12084 } 12085 } 12086 } 12087 12088 } 12089 12090 if (systemApp && onExternal) { 12091 // Disable updates to system apps on sdcard 12092 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12093 "Cannot install updates to system apps on sdcard"); 12094 return; 12095 } 12096 12097 if (args.move != null) { 12098 // We did an in-place move, so dex is ready to roll 12099 scanFlags |= SCAN_NO_DEX; 12100 scanFlags |= SCAN_MOVE; 12101 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12102 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12103 scanFlags |= SCAN_NO_DEX; 12104 12105 try { 12106 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12107 true /* extract libs */); 12108 } catch (PackageManagerException pme) { 12109 Slog.e(TAG, "Error deriving application ABI", pme); 12110 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12111 return; 12112 } 12113 12114 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12115 int result = mPackageDexOptimizer 12116 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12117 false /* defer */, false /* inclDependencies */); 12118 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12119 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12120 return; 12121 } 12122 } 12123 12124 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12125 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12126 return; 12127 } 12128 12129 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12130 12131 if (replace) { 12132 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12133 installerPackageName, volumeUuid, res); 12134 } else { 12135 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12136 args.user, installerPackageName, volumeUuid, res); 12137 } 12138 synchronized (mPackages) { 12139 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12140 if (ps != null) { 12141 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12142 } 12143 } 12144 } 12145 12146 private void startIntentFilterVerifications(int userId, boolean replacing, 12147 PackageParser.Package pkg) { 12148 if (mIntentFilterVerifierComponent == null) { 12149 Slog.w(TAG, "No IntentFilter verification will not be done as " 12150 + "there is no IntentFilterVerifier available!"); 12151 return; 12152 } 12153 12154 final int verifierUid = getPackageUid( 12155 mIntentFilterVerifierComponent.getPackageName(), 12156 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12157 12158 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12159 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12160 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12161 mHandler.sendMessage(msg); 12162 } 12163 12164 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12165 PackageParser.Package pkg) { 12166 int size = pkg.activities.size(); 12167 if (size == 0) { 12168 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12169 "No activity, so no need to verify any IntentFilter!"); 12170 return; 12171 } 12172 12173 final boolean hasDomainURLs = hasDomainURLs(pkg); 12174 if (!hasDomainURLs) { 12175 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12176 "No domain URLs, so no need to verify any IntentFilter!"); 12177 return; 12178 } 12179 12180 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12181 + " if any IntentFilter from the " + size 12182 + " Activities needs verification ..."); 12183 12184 int count = 0; 12185 final String packageName = pkg.packageName; 12186 12187 synchronized (mPackages) { 12188 // If this is a new install and we see that we've already run verification for this 12189 // package, we have nothing to do: it means the state was restored from backup. 12190 if (!replacing) { 12191 IntentFilterVerificationInfo ivi = 12192 mSettings.getIntentFilterVerificationLPr(packageName); 12193 if (ivi != null) { 12194 if (DEBUG_DOMAIN_VERIFICATION) { 12195 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12196 + ivi.getStatusString()); 12197 } 12198 return; 12199 } 12200 } 12201 12202 // If any filters need to be verified, then all need to be. 12203 boolean needToVerify = false; 12204 for (PackageParser.Activity a : pkg.activities) { 12205 for (ActivityIntentInfo filter : a.intents) { 12206 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12207 if (DEBUG_DOMAIN_VERIFICATION) { 12208 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12209 } 12210 needToVerify = true; 12211 break; 12212 } 12213 } 12214 } 12215 12216 if (needToVerify) { 12217 final int verificationId = mIntentFilterVerificationToken++; 12218 for (PackageParser.Activity a : pkg.activities) { 12219 for (ActivityIntentInfo filter : a.intents) { 12220 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12221 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12222 "Verification needed for IntentFilter:" + filter.toString()); 12223 mIntentFilterVerifier.addOneIntentFilterVerification( 12224 verifierUid, userId, verificationId, filter, packageName); 12225 count++; 12226 } 12227 } 12228 } 12229 } 12230 } 12231 12232 if (count > 0) { 12233 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12234 + " IntentFilter verification" + (count > 1 ? "s" : "") 12235 + " for userId:" + userId); 12236 mIntentFilterVerifier.startVerifications(userId); 12237 } else { 12238 if (DEBUG_DOMAIN_VERIFICATION) { 12239 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12240 } 12241 } 12242 } 12243 12244 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12245 final ComponentName cn = filter.activity.getComponentName(); 12246 final String packageName = cn.getPackageName(); 12247 12248 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12249 packageName); 12250 if (ivi == null) { 12251 return true; 12252 } 12253 int status = ivi.getStatus(); 12254 switch (status) { 12255 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12256 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12257 return true; 12258 12259 default: 12260 // Nothing to do 12261 return false; 12262 } 12263 } 12264 12265 private static boolean isMultiArch(PackageSetting ps) { 12266 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12267 } 12268 12269 private static boolean isMultiArch(ApplicationInfo info) { 12270 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12271 } 12272 12273 private static boolean isExternal(PackageParser.Package pkg) { 12274 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12275 } 12276 12277 private static boolean isExternal(PackageSetting ps) { 12278 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12279 } 12280 12281 private static boolean isExternal(ApplicationInfo info) { 12282 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12283 } 12284 12285 private static boolean isSystemApp(PackageParser.Package pkg) { 12286 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12287 } 12288 12289 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12290 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12291 } 12292 12293 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12294 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12295 } 12296 12297 private static boolean isSystemApp(PackageSetting ps) { 12298 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12299 } 12300 12301 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12302 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12303 } 12304 12305 private int packageFlagsToInstallFlags(PackageSetting ps) { 12306 int installFlags = 0; 12307 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12308 // This existing package was an external ASEC install when we have 12309 // the external flag without a UUID 12310 installFlags |= PackageManager.INSTALL_EXTERNAL; 12311 } 12312 if (ps.isForwardLocked()) { 12313 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12314 } 12315 return installFlags; 12316 } 12317 12318 private void deleteTempPackageFiles() { 12319 final FilenameFilter filter = new FilenameFilter() { 12320 public boolean accept(File dir, String name) { 12321 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12322 } 12323 }; 12324 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12325 file.delete(); 12326 } 12327 } 12328 12329 @Override 12330 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12331 int flags) { 12332 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12333 flags); 12334 } 12335 12336 @Override 12337 public void deletePackage(final String packageName, 12338 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12339 mContext.enforceCallingOrSelfPermission( 12340 android.Manifest.permission.DELETE_PACKAGES, null); 12341 Preconditions.checkNotNull(packageName); 12342 Preconditions.checkNotNull(observer); 12343 final int uid = Binder.getCallingUid(); 12344 if (UserHandle.getUserId(uid) != userId) { 12345 mContext.enforceCallingPermission( 12346 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12347 "deletePackage for user " + userId); 12348 } 12349 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12350 try { 12351 observer.onPackageDeleted(packageName, 12352 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12353 } catch (RemoteException re) { 12354 } 12355 return; 12356 } 12357 12358 boolean uninstallBlocked = false; 12359 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12360 int[] users = sUserManager.getUserIds(); 12361 for (int i = 0; i < users.length; ++i) { 12362 if (getBlockUninstallForUser(packageName, users[i])) { 12363 uninstallBlocked = true; 12364 break; 12365 } 12366 } 12367 } else { 12368 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12369 } 12370 if (uninstallBlocked) { 12371 try { 12372 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12373 null); 12374 } catch (RemoteException re) { 12375 } 12376 return; 12377 } 12378 12379 if (DEBUG_REMOVE) { 12380 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12381 } 12382 // Queue up an async operation since the package deletion may take a little while. 12383 mHandler.post(new Runnable() { 12384 public void run() { 12385 mHandler.removeCallbacks(this); 12386 final int returnCode = deletePackageX(packageName, userId, flags); 12387 if (observer != null) { 12388 try { 12389 observer.onPackageDeleted(packageName, returnCode, null); 12390 } catch (RemoteException e) { 12391 Log.i(TAG, "Observer no longer exists."); 12392 } //end catch 12393 } //end if 12394 } //end run 12395 }); 12396 } 12397 12398 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12399 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12400 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12401 try { 12402 if (dpm != null) { 12403 if (dpm.isDeviceOwner(packageName)) { 12404 return true; 12405 } 12406 int[] users; 12407 if (userId == UserHandle.USER_ALL) { 12408 users = sUserManager.getUserIds(); 12409 } else { 12410 users = new int[]{userId}; 12411 } 12412 for (int i = 0; i < users.length; ++i) { 12413 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12414 return true; 12415 } 12416 } 12417 } 12418 } catch (RemoteException e) { 12419 } 12420 return false; 12421 } 12422 12423 /** 12424 * This method is an internal method that could be get invoked either 12425 * to delete an installed package or to clean up a failed installation. 12426 * After deleting an installed package, a broadcast is sent to notify any 12427 * listeners that the package has been installed. For cleaning up a failed 12428 * installation, the broadcast is not necessary since the package's 12429 * installation wouldn't have sent the initial broadcast either 12430 * The key steps in deleting a package are 12431 * deleting the package information in internal structures like mPackages, 12432 * deleting the packages base directories through installd 12433 * updating mSettings to reflect current status 12434 * persisting settings for later use 12435 * sending a broadcast if necessary 12436 */ 12437 private int deletePackageX(String packageName, int userId, int flags) { 12438 final PackageRemovedInfo info = new PackageRemovedInfo(); 12439 final boolean res; 12440 12441 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12442 ? UserHandle.ALL : new UserHandle(userId); 12443 12444 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12445 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12446 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12447 } 12448 12449 boolean removedForAllUsers = false; 12450 boolean systemUpdate = false; 12451 12452 // for the uninstall-updates case and restricted profiles, remember the per- 12453 // userhandle installed state 12454 int[] allUsers; 12455 boolean[] perUserInstalled; 12456 synchronized (mPackages) { 12457 PackageSetting ps = mSettings.mPackages.get(packageName); 12458 allUsers = sUserManager.getUserIds(); 12459 perUserInstalled = new boolean[allUsers.length]; 12460 for (int i = 0; i < allUsers.length; i++) { 12461 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12462 } 12463 } 12464 12465 synchronized (mInstallLock) { 12466 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12467 res = deletePackageLI(packageName, removeForUser, 12468 true, allUsers, perUserInstalled, 12469 flags | REMOVE_CHATTY, info, true); 12470 systemUpdate = info.isRemovedPackageSystemUpdate; 12471 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12472 removedForAllUsers = true; 12473 } 12474 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12475 + " removedForAllUsers=" + removedForAllUsers); 12476 } 12477 12478 if (res) { 12479 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12480 12481 // If the removed package was a system update, the old system package 12482 // was re-enabled; we need to broadcast this information 12483 if (systemUpdate) { 12484 Bundle extras = new Bundle(1); 12485 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12486 ? info.removedAppId : info.uid); 12487 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12488 12489 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12490 extras, null, null, null); 12491 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12492 extras, null, null, null); 12493 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12494 null, packageName, null, null); 12495 } 12496 } 12497 // Force a gc here. 12498 Runtime.getRuntime().gc(); 12499 // Delete the resources here after sending the broadcast to let 12500 // other processes clean up before deleting resources. 12501 if (info.args != null) { 12502 synchronized (mInstallLock) { 12503 info.args.doPostDeleteLI(true); 12504 } 12505 } 12506 12507 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12508 } 12509 12510 class PackageRemovedInfo { 12511 String removedPackage; 12512 int uid = -1; 12513 int removedAppId = -1; 12514 int[] removedUsers = null; 12515 boolean isRemovedPackageSystemUpdate = false; 12516 // Clean up resources deleted packages. 12517 InstallArgs args = null; 12518 12519 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12520 Bundle extras = new Bundle(1); 12521 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12522 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12523 if (replacing) { 12524 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12525 } 12526 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12527 if (removedPackage != null) { 12528 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12529 extras, null, null, removedUsers); 12530 if (fullRemove && !replacing) { 12531 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12532 extras, null, null, removedUsers); 12533 } 12534 } 12535 if (removedAppId >= 0) { 12536 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12537 removedUsers); 12538 } 12539 } 12540 } 12541 12542 /* 12543 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12544 * flag is not set, the data directory is removed as well. 12545 * make sure this flag is set for partially installed apps. If not its meaningless to 12546 * delete a partially installed application. 12547 */ 12548 private void removePackageDataLI(PackageSetting ps, 12549 int[] allUserHandles, boolean[] perUserInstalled, 12550 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12551 String packageName = ps.name; 12552 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12553 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12554 // Retrieve object to delete permissions for shared user later on 12555 final PackageSetting deletedPs; 12556 // reader 12557 synchronized (mPackages) { 12558 deletedPs = mSettings.mPackages.get(packageName); 12559 if (outInfo != null) { 12560 outInfo.removedPackage = packageName; 12561 outInfo.removedUsers = deletedPs != null 12562 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12563 : null; 12564 } 12565 } 12566 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12567 removeDataDirsLI(ps.volumeUuid, packageName); 12568 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12569 } 12570 // writer 12571 synchronized (mPackages) { 12572 if (deletedPs != null) { 12573 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12574 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12575 clearDefaultBrowserIfNeeded(packageName); 12576 if (outInfo != null) { 12577 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12578 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12579 } 12580 updatePermissionsLPw(deletedPs.name, null, 0); 12581 if (deletedPs.sharedUser != null) { 12582 // Remove permissions associated with package. Since runtime 12583 // permissions are per user we have to kill the removed package 12584 // or packages running under the shared user of the removed 12585 // package if revoking the permissions requested only by the removed 12586 // package is successful and this causes a change in gids. 12587 for (int userId : UserManagerService.getInstance().getUserIds()) { 12588 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12589 userId); 12590 if (userIdToKill == UserHandle.USER_ALL 12591 || userIdToKill >= UserHandle.USER_OWNER) { 12592 // If gids changed for this user, kill all affected packages. 12593 mHandler.post(new Runnable() { 12594 @Override 12595 public void run() { 12596 // This has to happen with no lock held. 12597 killSettingPackagesForUser(deletedPs, userIdToKill, 12598 KILL_APP_REASON_GIDS_CHANGED); 12599 } 12600 }); 12601 break; 12602 } 12603 } 12604 } 12605 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12606 } 12607 // make sure to preserve per-user disabled state if this removal was just 12608 // a downgrade of a system app to the factory package 12609 if (allUserHandles != null && perUserInstalled != null) { 12610 if (DEBUG_REMOVE) { 12611 Slog.d(TAG, "Propagating install state across downgrade"); 12612 } 12613 for (int i = 0; i < allUserHandles.length; i++) { 12614 if (DEBUG_REMOVE) { 12615 Slog.d(TAG, " user " + allUserHandles[i] 12616 + " => " + perUserInstalled[i]); 12617 } 12618 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12619 } 12620 } 12621 } 12622 // can downgrade to reader 12623 if (writeSettings) { 12624 // Save settings now 12625 mSettings.writeLPr(); 12626 } 12627 } 12628 if (outInfo != null) { 12629 // A user ID was deleted here. Go through all users and remove it 12630 // from KeyStore. 12631 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12632 } 12633 } 12634 12635 static boolean locationIsPrivileged(File path) { 12636 try { 12637 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12638 .getCanonicalPath(); 12639 return path.getCanonicalPath().startsWith(privilegedAppDir); 12640 } catch (IOException e) { 12641 Slog.e(TAG, "Unable to access code path " + path); 12642 } 12643 return false; 12644 } 12645 12646 /* 12647 * Tries to delete system package. 12648 */ 12649 private boolean deleteSystemPackageLI(PackageSetting newPs, 12650 int[] allUserHandles, boolean[] perUserInstalled, 12651 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12652 final boolean applyUserRestrictions 12653 = (allUserHandles != null) && (perUserInstalled != null); 12654 PackageSetting disabledPs = null; 12655 // Confirm if the system package has been updated 12656 // An updated system app can be deleted. This will also have to restore 12657 // the system pkg from system partition 12658 // reader 12659 synchronized (mPackages) { 12660 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12661 } 12662 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12663 + " disabledPs=" + disabledPs); 12664 if (disabledPs == null) { 12665 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12666 return false; 12667 } else if (DEBUG_REMOVE) { 12668 Slog.d(TAG, "Deleting system pkg from data partition"); 12669 } 12670 if (DEBUG_REMOVE) { 12671 if (applyUserRestrictions) { 12672 Slog.d(TAG, "Remembering install states:"); 12673 for (int i = 0; i < allUserHandles.length; i++) { 12674 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12675 } 12676 } 12677 } 12678 // Delete the updated package 12679 outInfo.isRemovedPackageSystemUpdate = true; 12680 if (disabledPs.versionCode < newPs.versionCode) { 12681 // Delete data for downgrades 12682 flags &= ~PackageManager.DELETE_KEEP_DATA; 12683 } else { 12684 // Preserve data by setting flag 12685 flags |= PackageManager.DELETE_KEEP_DATA; 12686 } 12687 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12688 allUserHandles, perUserInstalled, outInfo, writeSettings); 12689 if (!ret) { 12690 return false; 12691 } 12692 // writer 12693 synchronized (mPackages) { 12694 // Reinstate the old system package 12695 mSettings.enableSystemPackageLPw(newPs.name); 12696 // Remove any native libraries from the upgraded package. 12697 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12698 } 12699 // Install the system package 12700 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12701 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12702 if (locationIsPrivileged(disabledPs.codePath)) { 12703 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12704 } 12705 12706 final PackageParser.Package newPkg; 12707 try { 12708 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12709 } catch (PackageManagerException e) { 12710 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12711 return false; 12712 } 12713 12714 // writer 12715 synchronized (mPackages) { 12716 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12717 updatePermissionsLPw(newPkg.packageName, newPkg, 12718 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12719 if (applyUserRestrictions) { 12720 if (DEBUG_REMOVE) { 12721 Slog.d(TAG, "Propagating install state across reinstall"); 12722 } 12723 for (int i = 0; i < allUserHandles.length; i++) { 12724 if (DEBUG_REMOVE) { 12725 Slog.d(TAG, " user " + allUserHandles[i] 12726 + " => " + perUserInstalled[i]); 12727 } 12728 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12729 } 12730 // Regardless of writeSettings we need to ensure that this restriction 12731 // state propagation is persisted 12732 mSettings.writeAllUsersPackageRestrictionsLPr(); 12733 } 12734 // can downgrade to reader here 12735 if (writeSettings) { 12736 mSettings.writeLPr(); 12737 } 12738 } 12739 return true; 12740 } 12741 12742 private boolean deleteInstalledPackageLI(PackageSetting ps, 12743 boolean deleteCodeAndResources, int flags, 12744 int[] allUserHandles, boolean[] perUserInstalled, 12745 PackageRemovedInfo outInfo, boolean writeSettings) { 12746 if (outInfo != null) { 12747 outInfo.uid = ps.appId; 12748 } 12749 12750 // Delete package data from internal structures and also remove data if flag is set 12751 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12752 12753 // Delete application code and resources 12754 if (deleteCodeAndResources && (outInfo != null)) { 12755 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12756 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12757 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12758 } 12759 return true; 12760 } 12761 12762 @Override 12763 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12764 int userId) { 12765 mContext.enforceCallingOrSelfPermission( 12766 android.Manifest.permission.DELETE_PACKAGES, null); 12767 synchronized (mPackages) { 12768 PackageSetting ps = mSettings.mPackages.get(packageName); 12769 if (ps == null) { 12770 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12771 return false; 12772 } 12773 if (!ps.getInstalled(userId)) { 12774 // Can't block uninstall for an app that is not installed or enabled. 12775 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12776 return false; 12777 } 12778 ps.setBlockUninstall(blockUninstall, userId); 12779 mSettings.writePackageRestrictionsLPr(userId); 12780 } 12781 return true; 12782 } 12783 12784 @Override 12785 public boolean getBlockUninstallForUser(String packageName, int userId) { 12786 synchronized (mPackages) { 12787 PackageSetting ps = mSettings.mPackages.get(packageName); 12788 if (ps == null) { 12789 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12790 return false; 12791 } 12792 return ps.getBlockUninstall(userId); 12793 } 12794 } 12795 12796 /* 12797 * This method handles package deletion in general 12798 */ 12799 private boolean deletePackageLI(String packageName, UserHandle user, 12800 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12801 int flags, PackageRemovedInfo outInfo, 12802 boolean writeSettings) { 12803 if (packageName == null) { 12804 Slog.w(TAG, "Attempt to delete null packageName."); 12805 return false; 12806 } 12807 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12808 PackageSetting ps; 12809 boolean dataOnly = false; 12810 int removeUser = -1; 12811 int appId = -1; 12812 synchronized (mPackages) { 12813 ps = mSettings.mPackages.get(packageName); 12814 if (ps == null) { 12815 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12816 return false; 12817 } 12818 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12819 && user.getIdentifier() != UserHandle.USER_ALL) { 12820 // The caller is asking that the package only be deleted for a single 12821 // user. To do this, we just mark its uninstalled state and delete 12822 // its data. If this is a system app, we only allow this to happen if 12823 // they have set the special DELETE_SYSTEM_APP which requests different 12824 // semantics than normal for uninstalling system apps. 12825 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12826 ps.setUserState(user.getIdentifier(), 12827 COMPONENT_ENABLED_STATE_DEFAULT, 12828 false, //installed 12829 true, //stopped 12830 true, //notLaunched 12831 false, //hidden 12832 null, null, null, 12833 false, // blockUninstall 12834 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12835 if (!isSystemApp(ps)) { 12836 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12837 // Other user still have this package installed, so all 12838 // we need to do is clear this user's data and save that 12839 // it is uninstalled. 12840 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12841 removeUser = user.getIdentifier(); 12842 appId = ps.appId; 12843 scheduleWritePackageRestrictionsLocked(removeUser); 12844 } else { 12845 // We need to set it back to 'installed' so the uninstall 12846 // broadcasts will be sent correctly. 12847 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12848 ps.setInstalled(true, user.getIdentifier()); 12849 } 12850 } else { 12851 // This is a system app, so we assume that the 12852 // other users still have this package installed, so all 12853 // we need to do is clear this user's data and save that 12854 // it is uninstalled. 12855 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12856 removeUser = user.getIdentifier(); 12857 appId = ps.appId; 12858 scheduleWritePackageRestrictionsLocked(removeUser); 12859 } 12860 } 12861 } 12862 12863 if (removeUser >= 0) { 12864 // From above, we determined that we are deleting this only 12865 // for a single user. Continue the work here. 12866 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12867 if (outInfo != null) { 12868 outInfo.removedPackage = packageName; 12869 outInfo.removedAppId = appId; 12870 outInfo.removedUsers = new int[] {removeUser}; 12871 } 12872 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12873 removeKeystoreDataIfNeeded(removeUser, appId); 12874 schedulePackageCleaning(packageName, removeUser, false); 12875 synchronized (mPackages) { 12876 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12877 scheduleWritePackageRestrictionsLocked(removeUser); 12878 } 12879 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12880 removeUser); 12881 } 12882 return true; 12883 } 12884 12885 if (dataOnly) { 12886 // Delete application data first 12887 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12888 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12889 return true; 12890 } 12891 12892 boolean ret = false; 12893 if (isSystemApp(ps)) { 12894 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12895 // When an updated system application is deleted we delete the existing resources as well and 12896 // fall back to existing code in system partition 12897 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12898 flags, outInfo, writeSettings); 12899 } else { 12900 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12901 // Kill application pre-emptively especially for apps on sd. 12902 killApplication(packageName, ps.appId, "uninstall pkg"); 12903 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12904 allUserHandles, perUserInstalled, 12905 outInfo, writeSettings); 12906 } 12907 12908 return ret; 12909 } 12910 12911 private final class ClearStorageConnection implements ServiceConnection { 12912 IMediaContainerService mContainerService; 12913 12914 @Override 12915 public void onServiceConnected(ComponentName name, IBinder service) { 12916 synchronized (this) { 12917 mContainerService = IMediaContainerService.Stub.asInterface(service); 12918 notifyAll(); 12919 } 12920 } 12921 12922 @Override 12923 public void onServiceDisconnected(ComponentName name) { 12924 } 12925 } 12926 12927 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12928 final boolean mounted; 12929 if (Environment.isExternalStorageEmulated()) { 12930 mounted = true; 12931 } else { 12932 final String status = Environment.getExternalStorageState(); 12933 12934 mounted = status.equals(Environment.MEDIA_MOUNTED) 12935 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12936 } 12937 12938 if (!mounted) { 12939 return; 12940 } 12941 12942 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12943 int[] users; 12944 if (userId == UserHandle.USER_ALL) { 12945 users = sUserManager.getUserIds(); 12946 } else { 12947 users = new int[] { userId }; 12948 } 12949 final ClearStorageConnection conn = new ClearStorageConnection(); 12950 if (mContext.bindServiceAsUser( 12951 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12952 try { 12953 for (int curUser : users) { 12954 long timeout = SystemClock.uptimeMillis() + 5000; 12955 synchronized (conn) { 12956 long now = SystemClock.uptimeMillis(); 12957 while (conn.mContainerService == null && now < timeout) { 12958 try { 12959 conn.wait(timeout - now); 12960 } catch (InterruptedException e) { 12961 } 12962 } 12963 } 12964 if (conn.mContainerService == null) { 12965 return; 12966 } 12967 12968 final UserEnvironment userEnv = new UserEnvironment(curUser); 12969 clearDirectory(conn.mContainerService, 12970 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12971 if (allData) { 12972 clearDirectory(conn.mContainerService, 12973 userEnv.buildExternalStorageAppDataDirs(packageName)); 12974 clearDirectory(conn.mContainerService, 12975 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12976 } 12977 } 12978 } finally { 12979 mContext.unbindService(conn); 12980 } 12981 } 12982 } 12983 12984 @Override 12985 public void clearApplicationUserData(final String packageName, 12986 final IPackageDataObserver observer, final int userId) { 12987 mContext.enforceCallingOrSelfPermission( 12988 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12989 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12990 // Queue up an async operation since the package deletion may take a little while. 12991 mHandler.post(new Runnable() { 12992 public void run() { 12993 mHandler.removeCallbacks(this); 12994 final boolean succeeded; 12995 synchronized (mInstallLock) { 12996 succeeded = clearApplicationUserDataLI(packageName, userId); 12997 } 12998 clearExternalStorageDataSync(packageName, userId, true); 12999 if (succeeded) { 13000 // invoke DeviceStorageMonitor's update method to clear any notifications 13001 DeviceStorageMonitorInternal 13002 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13003 if (dsm != null) { 13004 dsm.checkMemory(); 13005 } 13006 } 13007 if(observer != null) { 13008 try { 13009 observer.onRemoveCompleted(packageName, succeeded); 13010 } catch (RemoteException e) { 13011 Log.i(TAG, "Observer no longer exists."); 13012 } 13013 } //end if observer 13014 } //end run 13015 }); 13016 } 13017 13018 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13019 if (packageName == null) { 13020 Slog.w(TAG, "Attempt to delete null packageName."); 13021 return false; 13022 } 13023 13024 // Try finding details about the requested package 13025 PackageParser.Package pkg; 13026 synchronized (mPackages) { 13027 pkg = mPackages.get(packageName); 13028 if (pkg == null) { 13029 final PackageSetting ps = mSettings.mPackages.get(packageName); 13030 if (ps != null) { 13031 pkg = ps.pkg; 13032 } 13033 } 13034 13035 if (pkg == null) { 13036 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13037 return false; 13038 } 13039 13040 PackageSetting ps = (PackageSetting) pkg.mExtras; 13041 PermissionsState permissionsState = ps.getPermissionsState(); 13042 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 13043 } 13044 13045 // Always delete data directories for package, even if we found no other 13046 // record of app. This helps users recover from UID mismatches without 13047 // resorting to a full data wipe. 13048 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13049 if (retCode < 0) { 13050 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13051 return false; 13052 } 13053 13054 final int appId = pkg.applicationInfo.uid; 13055 removeKeystoreDataIfNeeded(userId, appId); 13056 13057 // Create a native library symlink only if we have native libraries 13058 // and if the native libraries are 32 bit libraries. We do not provide 13059 // this symlink for 64 bit libraries. 13060 if (pkg.applicationInfo.primaryCpuAbi != null && 13061 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13062 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13063 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13064 nativeLibPath, userId) < 0) { 13065 Slog.w(TAG, "Failed linking native library dir"); 13066 return false; 13067 } 13068 } 13069 13070 return true; 13071 } 13072 13073 13074 /** 13075 * Revokes granted runtime permissions and clears resettable flags 13076 * which are flags that can be set by a user interaction. 13077 * 13078 * @param permissionsState The permission state to reset. 13079 * @param userId The device user for which to do a reset. 13080 */ 13081 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 13082 PermissionsState permissionsState, int userId) { 13083 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13084 | PackageManager.FLAG_PERMISSION_USER_FIXED 13085 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13086 13087 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13088 } 13089 13090 /** 13091 * Revokes granted runtime permissions and clears all flags. 13092 * 13093 * @param permissionsState The permission state to reset. 13094 * @param userId The device user for which to do a reset. 13095 */ 13096 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13097 PermissionsState permissionsState, int userId) { 13098 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13099 PackageManager.MASK_PERMISSION_FLAGS); 13100 } 13101 13102 /** 13103 * Revokes granted runtime permissions and clears certain flags. 13104 * 13105 * @param permissionsState The permission state to reset. 13106 * @param userId The device user for which to do a reset. 13107 * @param flags The flags that is going to be reset. 13108 */ 13109 private void revokeRuntimePermissionsAndClearFlagsLocked( 13110 PermissionsState permissionsState, final int userId, int flags) { 13111 boolean needsWrite = false; 13112 13113 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13114 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13115 if (bp != null) { 13116 permissionsState.revokeRuntimePermission(bp, userId); 13117 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13118 needsWrite = true; 13119 } 13120 } 13121 13122 // Ensure default permissions are never cleared. 13123 mHandler.post(new Runnable() { 13124 @Override 13125 public void run() { 13126 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13127 } 13128 }); 13129 13130 if (needsWrite) { 13131 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13132 } 13133 } 13134 13135 /** 13136 * Remove entries from the keystore daemon. Will only remove it if the 13137 * {@code appId} is valid. 13138 */ 13139 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13140 if (appId < 0) { 13141 return; 13142 } 13143 13144 final KeyStore keyStore = KeyStore.getInstance(); 13145 if (keyStore != null) { 13146 if (userId == UserHandle.USER_ALL) { 13147 for (final int individual : sUserManager.getUserIds()) { 13148 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13149 } 13150 } else { 13151 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13152 } 13153 } else { 13154 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13155 } 13156 } 13157 13158 @Override 13159 public void deleteApplicationCacheFiles(final String packageName, 13160 final IPackageDataObserver observer) { 13161 mContext.enforceCallingOrSelfPermission( 13162 android.Manifest.permission.DELETE_CACHE_FILES, null); 13163 // Queue up an async operation since the package deletion may take a little while. 13164 final int userId = UserHandle.getCallingUserId(); 13165 mHandler.post(new Runnable() { 13166 public void run() { 13167 mHandler.removeCallbacks(this); 13168 final boolean succeded; 13169 synchronized (mInstallLock) { 13170 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13171 } 13172 clearExternalStorageDataSync(packageName, userId, false); 13173 if (observer != null) { 13174 try { 13175 observer.onRemoveCompleted(packageName, succeded); 13176 } catch (RemoteException e) { 13177 Log.i(TAG, "Observer no longer exists."); 13178 } 13179 } //end if observer 13180 } //end run 13181 }); 13182 } 13183 13184 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13185 if (packageName == null) { 13186 Slog.w(TAG, "Attempt to delete null packageName."); 13187 return false; 13188 } 13189 PackageParser.Package p; 13190 synchronized (mPackages) { 13191 p = mPackages.get(packageName); 13192 } 13193 if (p == null) { 13194 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13195 return false; 13196 } 13197 final ApplicationInfo applicationInfo = p.applicationInfo; 13198 if (applicationInfo == null) { 13199 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13200 return false; 13201 } 13202 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13203 if (retCode < 0) { 13204 Slog.w(TAG, "Couldn't remove cache files for package: " 13205 + packageName + " u" + userId); 13206 return false; 13207 } 13208 return true; 13209 } 13210 13211 @Override 13212 public void getPackageSizeInfo(final String packageName, int userHandle, 13213 final IPackageStatsObserver observer) { 13214 mContext.enforceCallingOrSelfPermission( 13215 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13216 if (packageName == null) { 13217 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13218 } 13219 13220 PackageStats stats = new PackageStats(packageName, userHandle); 13221 13222 /* 13223 * Queue up an async operation since the package measurement may take a 13224 * little while. 13225 */ 13226 Message msg = mHandler.obtainMessage(INIT_COPY); 13227 msg.obj = new MeasureParams(stats, observer); 13228 mHandler.sendMessage(msg); 13229 } 13230 13231 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13232 PackageStats pStats) { 13233 if (packageName == null) { 13234 Slog.w(TAG, "Attempt to get size of null packageName."); 13235 return false; 13236 } 13237 PackageParser.Package p; 13238 boolean dataOnly = false; 13239 String libDirRoot = null; 13240 String asecPath = null; 13241 PackageSetting ps = null; 13242 synchronized (mPackages) { 13243 p = mPackages.get(packageName); 13244 ps = mSettings.mPackages.get(packageName); 13245 if(p == null) { 13246 dataOnly = true; 13247 if((ps == null) || (ps.pkg == null)) { 13248 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13249 return false; 13250 } 13251 p = ps.pkg; 13252 } 13253 if (ps != null) { 13254 libDirRoot = ps.legacyNativeLibraryPathString; 13255 } 13256 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13257 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13258 if (secureContainerId != null) { 13259 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13260 } 13261 } 13262 } 13263 String publicSrcDir = null; 13264 if(!dataOnly) { 13265 final ApplicationInfo applicationInfo = p.applicationInfo; 13266 if (applicationInfo == null) { 13267 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13268 return false; 13269 } 13270 if (p.isForwardLocked()) { 13271 publicSrcDir = applicationInfo.getBaseResourcePath(); 13272 } 13273 } 13274 // TODO: extend to measure size of split APKs 13275 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13276 // not just the first level. 13277 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13278 // just the primary. 13279 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13280 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13281 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13282 if (res < 0) { 13283 return false; 13284 } 13285 13286 // Fix-up for forward-locked applications in ASEC containers. 13287 if (!isExternal(p)) { 13288 pStats.codeSize += pStats.externalCodeSize; 13289 pStats.externalCodeSize = 0L; 13290 } 13291 13292 return true; 13293 } 13294 13295 13296 @Override 13297 public void addPackageToPreferred(String packageName) { 13298 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13299 } 13300 13301 @Override 13302 public void removePackageFromPreferred(String packageName) { 13303 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13304 } 13305 13306 @Override 13307 public List<PackageInfo> getPreferredPackages(int flags) { 13308 return new ArrayList<PackageInfo>(); 13309 } 13310 13311 private int getUidTargetSdkVersionLockedLPr(int uid) { 13312 Object obj = mSettings.getUserIdLPr(uid); 13313 if (obj instanceof SharedUserSetting) { 13314 final SharedUserSetting sus = (SharedUserSetting) obj; 13315 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13316 final Iterator<PackageSetting> it = sus.packages.iterator(); 13317 while (it.hasNext()) { 13318 final PackageSetting ps = it.next(); 13319 if (ps.pkg != null) { 13320 int v = ps.pkg.applicationInfo.targetSdkVersion; 13321 if (v < vers) vers = v; 13322 } 13323 } 13324 return vers; 13325 } else if (obj instanceof PackageSetting) { 13326 final PackageSetting ps = (PackageSetting) obj; 13327 if (ps.pkg != null) { 13328 return ps.pkg.applicationInfo.targetSdkVersion; 13329 } 13330 } 13331 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13332 } 13333 13334 @Override 13335 public void addPreferredActivity(IntentFilter filter, int match, 13336 ComponentName[] set, ComponentName activity, int userId) { 13337 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13338 "Adding preferred"); 13339 } 13340 13341 private void addPreferredActivityInternal(IntentFilter filter, int match, 13342 ComponentName[] set, ComponentName activity, boolean always, int userId, 13343 String opname) { 13344 // writer 13345 int callingUid = Binder.getCallingUid(); 13346 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13347 if (filter.countActions() == 0) { 13348 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13349 return; 13350 } 13351 synchronized (mPackages) { 13352 if (mContext.checkCallingOrSelfPermission( 13353 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13354 != PackageManager.PERMISSION_GRANTED) { 13355 if (getUidTargetSdkVersionLockedLPr(callingUid) 13356 < Build.VERSION_CODES.FROYO) { 13357 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13358 + callingUid); 13359 return; 13360 } 13361 mContext.enforceCallingOrSelfPermission( 13362 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13363 } 13364 13365 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13366 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13367 + userId + ":"); 13368 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13369 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13370 scheduleWritePackageRestrictionsLocked(userId); 13371 } 13372 } 13373 13374 @Override 13375 public void replacePreferredActivity(IntentFilter filter, int match, 13376 ComponentName[] set, ComponentName activity, int userId) { 13377 if (filter.countActions() != 1) { 13378 throw new IllegalArgumentException( 13379 "replacePreferredActivity expects filter to have only 1 action."); 13380 } 13381 if (filter.countDataAuthorities() != 0 13382 || filter.countDataPaths() != 0 13383 || filter.countDataSchemes() > 1 13384 || filter.countDataTypes() != 0) { 13385 throw new IllegalArgumentException( 13386 "replacePreferredActivity expects filter to have no data authorities, " + 13387 "paths, or types; and at most one scheme."); 13388 } 13389 13390 final int callingUid = Binder.getCallingUid(); 13391 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13392 synchronized (mPackages) { 13393 if (mContext.checkCallingOrSelfPermission( 13394 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13395 != PackageManager.PERMISSION_GRANTED) { 13396 if (getUidTargetSdkVersionLockedLPr(callingUid) 13397 < Build.VERSION_CODES.FROYO) { 13398 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13399 + Binder.getCallingUid()); 13400 return; 13401 } 13402 mContext.enforceCallingOrSelfPermission( 13403 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13404 } 13405 13406 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13407 if (pir != null) { 13408 // Get all of the existing entries that exactly match this filter. 13409 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13410 if (existing != null && existing.size() == 1) { 13411 PreferredActivity cur = existing.get(0); 13412 if (DEBUG_PREFERRED) { 13413 Slog.i(TAG, "Checking replace of preferred:"); 13414 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13415 if (!cur.mPref.mAlways) { 13416 Slog.i(TAG, " -- CUR; not mAlways!"); 13417 } else { 13418 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13419 Slog.i(TAG, " -- CUR: mSet=" 13420 + Arrays.toString(cur.mPref.mSetComponents)); 13421 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13422 Slog.i(TAG, " -- NEW: mMatch=" 13423 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13424 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13425 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13426 } 13427 } 13428 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13429 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13430 && cur.mPref.sameSet(set)) { 13431 // Setting the preferred activity to what it happens to be already 13432 if (DEBUG_PREFERRED) { 13433 Slog.i(TAG, "Replacing with same preferred activity " 13434 + cur.mPref.mShortComponent + " for user " 13435 + userId + ":"); 13436 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13437 } 13438 return; 13439 } 13440 } 13441 13442 if (existing != null) { 13443 if (DEBUG_PREFERRED) { 13444 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13445 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13446 } 13447 for (int i = 0; i < existing.size(); i++) { 13448 PreferredActivity pa = existing.get(i); 13449 if (DEBUG_PREFERRED) { 13450 Slog.i(TAG, "Removing existing preferred activity " 13451 + pa.mPref.mComponent + ":"); 13452 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13453 } 13454 pir.removeFilter(pa); 13455 } 13456 } 13457 } 13458 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13459 "Replacing preferred"); 13460 } 13461 } 13462 13463 @Override 13464 public void clearPackagePreferredActivities(String packageName) { 13465 final int uid = Binder.getCallingUid(); 13466 // writer 13467 synchronized (mPackages) { 13468 PackageParser.Package pkg = mPackages.get(packageName); 13469 if (pkg == null || pkg.applicationInfo.uid != uid) { 13470 if (mContext.checkCallingOrSelfPermission( 13471 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13472 != PackageManager.PERMISSION_GRANTED) { 13473 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13474 < Build.VERSION_CODES.FROYO) { 13475 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13476 + Binder.getCallingUid()); 13477 return; 13478 } 13479 mContext.enforceCallingOrSelfPermission( 13480 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13481 } 13482 } 13483 13484 int user = UserHandle.getCallingUserId(); 13485 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13486 scheduleWritePackageRestrictionsLocked(user); 13487 } 13488 } 13489 } 13490 13491 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13492 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13493 ArrayList<PreferredActivity> removed = null; 13494 boolean changed = false; 13495 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13496 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13497 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13498 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13499 continue; 13500 } 13501 Iterator<PreferredActivity> it = pir.filterIterator(); 13502 while (it.hasNext()) { 13503 PreferredActivity pa = it.next(); 13504 // Mark entry for removal only if it matches the package name 13505 // and the entry is of type "always". 13506 if (packageName == null || 13507 (pa.mPref.mComponent.getPackageName().equals(packageName) 13508 && pa.mPref.mAlways)) { 13509 if (removed == null) { 13510 removed = new ArrayList<PreferredActivity>(); 13511 } 13512 removed.add(pa); 13513 } 13514 } 13515 if (removed != null) { 13516 for (int j=0; j<removed.size(); j++) { 13517 PreferredActivity pa = removed.get(j); 13518 pir.removeFilter(pa); 13519 } 13520 changed = true; 13521 } 13522 } 13523 return changed; 13524 } 13525 13526 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13527 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13528 if (userId == UserHandle.USER_ALL) { 13529 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13530 sUserManager.getUserIds())) { 13531 for (int oneUserId : sUserManager.getUserIds()) { 13532 scheduleWritePackageRestrictionsLocked(oneUserId); 13533 } 13534 } 13535 } else { 13536 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13537 scheduleWritePackageRestrictionsLocked(userId); 13538 } 13539 } 13540 } 13541 13542 13543 void clearDefaultBrowserIfNeeded(String packageName) { 13544 for (int oneUserId : sUserManager.getUserIds()) { 13545 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13546 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13547 if (packageName.equals(defaultBrowserPackageName)) { 13548 setDefaultBrowserPackageName(null, oneUserId); 13549 } 13550 } 13551 } 13552 13553 @Override 13554 public void resetPreferredActivities(int userId) { 13555 mContext.enforceCallingOrSelfPermission( 13556 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13557 // writer 13558 synchronized (mPackages) { 13559 clearPackagePreferredActivitiesLPw(null, userId); 13560 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13561 applyFactoryDefaultBrowserLPw(userId); 13562 13563 scheduleWritePackageRestrictionsLocked(userId); 13564 } 13565 } 13566 13567 @Override 13568 public int getPreferredActivities(List<IntentFilter> outFilters, 13569 List<ComponentName> outActivities, String packageName) { 13570 13571 int num = 0; 13572 final int userId = UserHandle.getCallingUserId(); 13573 // reader 13574 synchronized (mPackages) { 13575 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13576 if (pir != null) { 13577 final Iterator<PreferredActivity> it = pir.filterIterator(); 13578 while (it.hasNext()) { 13579 final PreferredActivity pa = it.next(); 13580 if (packageName == null 13581 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13582 && pa.mPref.mAlways)) { 13583 if (outFilters != null) { 13584 outFilters.add(new IntentFilter(pa)); 13585 } 13586 if (outActivities != null) { 13587 outActivities.add(pa.mPref.mComponent); 13588 } 13589 } 13590 } 13591 } 13592 } 13593 13594 return num; 13595 } 13596 13597 @Override 13598 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13599 int userId) { 13600 int callingUid = Binder.getCallingUid(); 13601 if (callingUid != Process.SYSTEM_UID) { 13602 throw new SecurityException( 13603 "addPersistentPreferredActivity can only be run by the system"); 13604 } 13605 if (filter.countActions() == 0) { 13606 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13607 return; 13608 } 13609 synchronized (mPackages) { 13610 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13611 " :"); 13612 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13613 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13614 new PersistentPreferredActivity(filter, activity)); 13615 scheduleWritePackageRestrictionsLocked(userId); 13616 } 13617 } 13618 13619 @Override 13620 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13621 int callingUid = Binder.getCallingUid(); 13622 if (callingUid != Process.SYSTEM_UID) { 13623 throw new SecurityException( 13624 "clearPackagePersistentPreferredActivities can only be run by the system"); 13625 } 13626 ArrayList<PersistentPreferredActivity> removed = null; 13627 boolean changed = false; 13628 synchronized (mPackages) { 13629 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13630 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13631 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13632 .valueAt(i); 13633 if (userId != thisUserId) { 13634 continue; 13635 } 13636 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13637 while (it.hasNext()) { 13638 PersistentPreferredActivity ppa = it.next(); 13639 // Mark entry for removal only if it matches the package name. 13640 if (ppa.mComponent.getPackageName().equals(packageName)) { 13641 if (removed == null) { 13642 removed = new ArrayList<PersistentPreferredActivity>(); 13643 } 13644 removed.add(ppa); 13645 } 13646 } 13647 if (removed != null) { 13648 for (int j=0; j<removed.size(); j++) { 13649 PersistentPreferredActivity ppa = removed.get(j); 13650 ppir.removeFilter(ppa); 13651 } 13652 changed = true; 13653 } 13654 } 13655 13656 if (changed) { 13657 scheduleWritePackageRestrictionsLocked(userId); 13658 } 13659 } 13660 } 13661 13662 /** 13663 * Common machinery for picking apart a restored XML blob and passing 13664 * it to a caller-supplied functor to be applied to the running system. 13665 */ 13666 private void restoreFromXml(XmlPullParser parser, int userId, 13667 String expectedStartTag, BlobXmlRestorer functor) 13668 throws IOException, XmlPullParserException { 13669 int type; 13670 while ((type = parser.next()) != XmlPullParser.START_TAG 13671 && type != XmlPullParser.END_DOCUMENT) { 13672 } 13673 if (type != XmlPullParser.START_TAG) { 13674 // oops didn't find a start tag?! 13675 if (DEBUG_BACKUP) { 13676 Slog.e(TAG, "Didn't find start tag during restore"); 13677 } 13678 return; 13679 } 13680 13681 // this is supposed to be TAG_PREFERRED_BACKUP 13682 if (!expectedStartTag.equals(parser.getName())) { 13683 if (DEBUG_BACKUP) { 13684 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13685 } 13686 return; 13687 } 13688 13689 // skip interfering stuff, then we're aligned with the backing implementation 13690 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13691 functor.apply(parser, userId); 13692 } 13693 13694 private interface BlobXmlRestorer { 13695 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13696 } 13697 13698 /** 13699 * Non-Binder method, support for the backup/restore mechanism: write the 13700 * full set of preferred activities in its canonical XML format. Returns the 13701 * XML output as a byte array, or null if there is none. 13702 */ 13703 @Override 13704 public byte[] getPreferredActivityBackup(int userId) { 13705 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13706 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13707 } 13708 13709 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13710 try { 13711 final XmlSerializer serializer = new FastXmlSerializer(); 13712 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13713 serializer.startDocument(null, true); 13714 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13715 13716 synchronized (mPackages) { 13717 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13718 } 13719 13720 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13721 serializer.endDocument(); 13722 serializer.flush(); 13723 } catch (Exception e) { 13724 if (DEBUG_BACKUP) { 13725 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13726 } 13727 return null; 13728 } 13729 13730 return dataStream.toByteArray(); 13731 } 13732 13733 @Override 13734 public void restorePreferredActivities(byte[] backup, int userId) { 13735 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13736 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13737 } 13738 13739 try { 13740 final XmlPullParser parser = Xml.newPullParser(); 13741 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13742 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13743 new BlobXmlRestorer() { 13744 @Override 13745 public void apply(XmlPullParser parser, int userId) 13746 throws XmlPullParserException, IOException { 13747 synchronized (mPackages) { 13748 mSettings.readPreferredActivitiesLPw(parser, userId); 13749 } 13750 } 13751 } ); 13752 } catch (Exception e) { 13753 if (DEBUG_BACKUP) { 13754 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13755 } 13756 } 13757 } 13758 13759 /** 13760 * Non-Binder method, support for the backup/restore mechanism: write the 13761 * default browser (etc) settings in its canonical XML format. Returns the default 13762 * browser XML representation as a byte array, or null if there is none. 13763 */ 13764 @Override 13765 public byte[] getDefaultAppsBackup(int userId) { 13766 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13767 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13768 } 13769 13770 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13771 try { 13772 final XmlSerializer serializer = new FastXmlSerializer(); 13773 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13774 serializer.startDocument(null, true); 13775 serializer.startTag(null, TAG_DEFAULT_APPS); 13776 13777 synchronized (mPackages) { 13778 mSettings.writeDefaultAppsLPr(serializer, userId); 13779 } 13780 13781 serializer.endTag(null, TAG_DEFAULT_APPS); 13782 serializer.endDocument(); 13783 serializer.flush(); 13784 } catch (Exception e) { 13785 if (DEBUG_BACKUP) { 13786 Slog.e(TAG, "Unable to write default apps for backup", e); 13787 } 13788 return null; 13789 } 13790 13791 return dataStream.toByteArray(); 13792 } 13793 13794 @Override 13795 public void restoreDefaultApps(byte[] backup, int userId) { 13796 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13797 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13798 } 13799 13800 try { 13801 final XmlPullParser parser = Xml.newPullParser(); 13802 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13803 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13804 new BlobXmlRestorer() { 13805 @Override 13806 public void apply(XmlPullParser parser, int userId) 13807 throws XmlPullParserException, IOException { 13808 synchronized (mPackages) { 13809 mSettings.readDefaultAppsLPw(parser, userId); 13810 } 13811 } 13812 } ); 13813 } catch (Exception e) { 13814 if (DEBUG_BACKUP) { 13815 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13816 } 13817 } 13818 } 13819 13820 @Override 13821 public byte[] getIntentFilterVerificationBackup(int userId) { 13822 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13823 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13824 } 13825 13826 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13827 try { 13828 final XmlSerializer serializer = new FastXmlSerializer(); 13829 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13830 serializer.startDocument(null, true); 13831 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13832 13833 synchronized (mPackages) { 13834 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13835 } 13836 13837 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13838 serializer.endDocument(); 13839 serializer.flush(); 13840 } catch (Exception e) { 13841 if (DEBUG_BACKUP) { 13842 Slog.e(TAG, "Unable to write default apps for backup", e); 13843 } 13844 return null; 13845 } 13846 13847 return dataStream.toByteArray(); 13848 } 13849 13850 @Override 13851 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13852 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13853 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13854 } 13855 13856 try { 13857 final XmlPullParser parser = Xml.newPullParser(); 13858 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13859 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13860 new BlobXmlRestorer() { 13861 @Override 13862 public void apply(XmlPullParser parser, int userId) 13863 throws XmlPullParserException, IOException { 13864 synchronized (mPackages) { 13865 mSettings.readAllDomainVerificationsLPr(parser, userId); 13866 mSettings.writeLPr(); 13867 } 13868 } 13869 } ); 13870 } catch (Exception e) { 13871 if (DEBUG_BACKUP) { 13872 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13873 } 13874 } 13875 } 13876 13877 @Override 13878 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13879 int sourceUserId, int targetUserId, int flags) { 13880 mContext.enforceCallingOrSelfPermission( 13881 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13882 int callingUid = Binder.getCallingUid(); 13883 enforceOwnerRights(ownerPackage, callingUid); 13884 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13885 if (intentFilter.countActions() == 0) { 13886 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13887 return; 13888 } 13889 synchronized (mPackages) { 13890 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13891 ownerPackage, targetUserId, flags); 13892 CrossProfileIntentResolver resolver = 13893 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13894 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13895 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13896 if (existing != null) { 13897 int size = existing.size(); 13898 for (int i = 0; i < size; i++) { 13899 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13900 return; 13901 } 13902 } 13903 } 13904 resolver.addFilter(newFilter); 13905 scheduleWritePackageRestrictionsLocked(sourceUserId); 13906 } 13907 } 13908 13909 @Override 13910 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13911 mContext.enforceCallingOrSelfPermission( 13912 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13913 int callingUid = Binder.getCallingUid(); 13914 enforceOwnerRights(ownerPackage, callingUid); 13915 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13916 synchronized (mPackages) { 13917 CrossProfileIntentResolver resolver = 13918 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13919 ArraySet<CrossProfileIntentFilter> set = 13920 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13921 for (CrossProfileIntentFilter filter : set) { 13922 if (filter.getOwnerPackage().equals(ownerPackage)) { 13923 resolver.removeFilter(filter); 13924 } 13925 } 13926 scheduleWritePackageRestrictionsLocked(sourceUserId); 13927 } 13928 } 13929 13930 // Enforcing that callingUid is owning pkg on userId 13931 private void enforceOwnerRights(String pkg, int callingUid) { 13932 // The system owns everything. 13933 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13934 return; 13935 } 13936 int callingUserId = UserHandle.getUserId(callingUid); 13937 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13938 if (pi == null) { 13939 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13940 + callingUserId); 13941 } 13942 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13943 throw new SecurityException("Calling uid " + callingUid 13944 + " does not own package " + pkg); 13945 } 13946 } 13947 13948 @Override 13949 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13950 Intent intent = new Intent(Intent.ACTION_MAIN); 13951 intent.addCategory(Intent.CATEGORY_HOME); 13952 13953 final int callingUserId = UserHandle.getCallingUserId(); 13954 List<ResolveInfo> list = queryIntentActivities(intent, null, 13955 PackageManager.GET_META_DATA, callingUserId); 13956 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13957 true, false, false, callingUserId); 13958 13959 allHomeCandidates.clear(); 13960 if (list != null) { 13961 for (ResolveInfo ri : list) { 13962 allHomeCandidates.add(ri); 13963 } 13964 } 13965 return (preferred == null || preferred.activityInfo == null) 13966 ? null 13967 : new ComponentName(preferred.activityInfo.packageName, 13968 preferred.activityInfo.name); 13969 } 13970 13971 @Override 13972 public void setApplicationEnabledSetting(String appPackageName, 13973 int newState, int flags, int userId, String callingPackage) { 13974 if (!sUserManager.exists(userId)) return; 13975 if (callingPackage == null) { 13976 callingPackage = Integer.toString(Binder.getCallingUid()); 13977 } 13978 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13979 } 13980 13981 @Override 13982 public void setComponentEnabledSetting(ComponentName componentName, 13983 int newState, int flags, int userId) { 13984 if (!sUserManager.exists(userId)) return; 13985 setEnabledSetting(componentName.getPackageName(), 13986 componentName.getClassName(), newState, flags, userId, null); 13987 } 13988 13989 private void setEnabledSetting(final String packageName, String className, int newState, 13990 final int flags, int userId, String callingPackage) { 13991 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13992 || newState == COMPONENT_ENABLED_STATE_ENABLED 13993 || newState == COMPONENT_ENABLED_STATE_DISABLED 13994 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13995 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13996 throw new IllegalArgumentException("Invalid new component state: " 13997 + newState); 13998 } 13999 PackageSetting pkgSetting; 14000 final int uid = Binder.getCallingUid(); 14001 final int permission = mContext.checkCallingOrSelfPermission( 14002 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14003 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14004 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14005 boolean sendNow = false; 14006 boolean isApp = (className == null); 14007 String componentName = isApp ? packageName : className; 14008 int packageUid = -1; 14009 ArrayList<String> components; 14010 14011 // writer 14012 synchronized (mPackages) { 14013 pkgSetting = mSettings.mPackages.get(packageName); 14014 if (pkgSetting == null) { 14015 if (className == null) { 14016 throw new IllegalArgumentException( 14017 "Unknown package: " + packageName); 14018 } 14019 throw new IllegalArgumentException( 14020 "Unknown component: " + packageName 14021 + "/" + className); 14022 } 14023 // Allow root and verify that userId is not being specified by a different user 14024 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14025 throw new SecurityException( 14026 "Permission Denial: attempt to change component state from pid=" 14027 + Binder.getCallingPid() 14028 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14029 } 14030 if (className == null) { 14031 // We're dealing with an application/package level state change 14032 if (pkgSetting.getEnabled(userId) == newState) { 14033 // Nothing to do 14034 return; 14035 } 14036 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14037 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14038 // Don't care about who enables an app. 14039 callingPackage = null; 14040 } 14041 pkgSetting.setEnabled(newState, userId, callingPackage); 14042 // pkgSetting.pkg.mSetEnabled = newState; 14043 } else { 14044 // We're dealing with a component level state change 14045 // First, verify that this is a valid class name. 14046 PackageParser.Package pkg = pkgSetting.pkg; 14047 if (pkg == null || !pkg.hasComponentClassName(className)) { 14048 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14049 throw new IllegalArgumentException("Component class " + className 14050 + " does not exist in " + packageName); 14051 } else { 14052 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14053 + className + " does not exist in " + packageName); 14054 } 14055 } 14056 switch (newState) { 14057 case COMPONENT_ENABLED_STATE_ENABLED: 14058 if (!pkgSetting.enableComponentLPw(className, userId)) { 14059 return; 14060 } 14061 break; 14062 case COMPONENT_ENABLED_STATE_DISABLED: 14063 if (!pkgSetting.disableComponentLPw(className, userId)) { 14064 return; 14065 } 14066 break; 14067 case COMPONENT_ENABLED_STATE_DEFAULT: 14068 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14069 return; 14070 } 14071 break; 14072 default: 14073 Slog.e(TAG, "Invalid new component state: " + newState); 14074 return; 14075 } 14076 } 14077 scheduleWritePackageRestrictionsLocked(userId); 14078 components = mPendingBroadcasts.get(userId, packageName); 14079 final boolean newPackage = components == null; 14080 if (newPackage) { 14081 components = new ArrayList<String>(); 14082 } 14083 if (!components.contains(componentName)) { 14084 components.add(componentName); 14085 } 14086 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14087 sendNow = true; 14088 // Purge entry from pending broadcast list if another one exists already 14089 // since we are sending one right away. 14090 mPendingBroadcasts.remove(userId, packageName); 14091 } else { 14092 if (newPackage) { 14093 mPendingBroadcasts.put(userId, packageName, components); 14094 } 14095 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14096 // Schedule a message 14097 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14098 } 14099 } 14100 } 14101 14102 long callingId = Binder.clearCallingIdentity(); 14103 try { 14104 if (sendNow) { 14105 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14106 sendPackageChangedBroadcast(packageName, 14107 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14108 } 14109 } finally { 14110 Binder.restoreCallingIdentity(callingId); 14111 } 14112 } 14113 14114 private void sendPackageChangedBroadcast(String packageName, 14115 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14116 if (DEBUG_INSTALL) 14117 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14118 + componentNames); 14119 Bundle extras = new Bundle(4); 14120 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14121 String nameList[] = new String[componentNames.size()]; 14122 componentNames.toArray(nameList); 14123 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14124 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14125 extras.putInt(Intent.EXTRA_UID, packageUid); 14126 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14127 new int[] {UserHandle.getUserId(packageUid)}); 14128 } 14129 14130 @Override 14131 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14132 if (!sUserManager.exists(userId)) return; 14133 final int uid = Binder.getCallingUid(); 14134 final int permission = mContext.checkCallingOrSelfPermission( 14135 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14136 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14137 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14138 // writer 14139 synchronized (mPackages) { 14140 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14141 allowedByPermission, uid, userId)) { 14142 scheduleWritePackageRestrictionsLocked(userId); 14143 } 14144 } 14145 } 14146 14147 @Override 14148 public String getInstallerPackageName(String packageName) { 14149 // reader 14150 synchronized (mPackages) { 14151 return mSettings.getInstallerPackageNameLPr(packageName); 14152 } 14153 } 14154 14155 @Override 14156 public int getApplicationEnabledSetting(String packageName, int userId) { 14157 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14158 int uid = Binder.getCallingUid(); 14159 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14160 // reader 14161 synchronized (mPackages) { 14162 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14163 } 14164 } 14165 14166 @Override 14167 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14168 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14169 int uid = Binder.getCallingUid(); 14170 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14171 // reader 14172 synchronized (mPackages) { 14173 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14174 } 14175 } 14176 14177 @Override 14178 public void enterSafeMode() { 14179 enforceSystemOrRoot("Only the system can request entering safe mode"); 14180 14181 if (!mSystemReady) { 14182 mSafeMode = true; 14183 } 14184 } 14185 14186 @Override 14187 public void systemReady() { 14188 mSystemReady = true; 14189 14190 // Read the compatibilty setting when the system is ready. 14191 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14192 mContext.getContentResolver(), 14193 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14194 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14195 if (DEBUG_SETTINGS) { 14196 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14197 } 14198 14199 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14200 14201 synchronized (mPackages) { 14202 // Verify that all of the preferred activity components actually 14203 // exist. It is possible for applications to be updated and at 14204 // that point remove a previously declared activity component that 14205 // had been set as a preferred activity. We try to clean this up 14206 // the next time we encounter that preferred activity, but it is 14207 // possible for the user flow to never be able to return to that 14208 // situation so here we do a sanity check to make sure we haven't 14209 // left any junk around. 14210 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14211 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14212 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14213 removed.clear(); 14214 for (PreferredActivity pa : pir.filterSet()) { 14215 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14216 removed.add(pa); 14217 } 14218 } 14219 if (removed.size() > 0) { 14220 for (int r=0; r<removed.size(); r++) { 14221 PreferredActivity pa = removed.get(r); 14222 Slog.w(TAG, "Removing dangling preferred activity: " 14223 + pa.mPref.mComponent); 14224 pir.removeFilter(pa); 14225 } 14226 mSettings.writePackageRestrictionsLPr( 14227 mSettings.mPreferredActivities.keyAt(i)); 14228 } 14229 } 14230 14231 for (int userId : UserManagerService.getInstance().getUserIds()) { 14232 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14233 grantPermissionsUserIds = ArrayUtils.appendInt( 14234 grantPermissionsUserIds, userId); 14235 } 14236 } 14237 } 14238 sUserManager.systemReady(); 14239 14240 // If we upgraded grant all default permissions before kicking off. 14241 for (int userId : grantPermissionsUserIds) { 14242 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14243 } 14244 14245 // Kick off any messages waiting for system ready 14246 if (mPostSystemReadyMessages != null) { 14247 for (Message msg : mPostSystemReadyMessages) { 14248 msg.sendToTarget(); 14249 } 14250 mPostSystemReadyMessages = null; 14251 } 14252 14253 // Watch for external volumes that come and go over time 14254 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14255 storage.registerListener(mStorageListener); 14256 14257 mInstallerService.systemReady(); 14258 mPackageDexOptimizer.systemReady(); 14259 } 14260 14261 @Override 14262 public boolean isSafeMode() { 14263 return mSafeMode; 14264 } 14265 14266 @Override 14267 public boolean hasSystemUidErrors() { 14268 return mHasSystemUidErrors; 14269 } 14270 14271 static String arrayToString(int[] array) { 14272 StringBuffer buf = new StringBuffer(128); 14273 buf.append('['); 14274 if (array != null) { 14275 for (int i=0; i<array.length; i++) { 14276 if (i > 0) buf.append(", "); 14277 buf.append(array[i]); 14278 } 14279 } 14280 buf.append(']'); 14281 return buf.toString(); 14282 } 14283 14284 static class DumpState { 14285 public static final int DUMP_LIBS = 1 << 0; 14286 public static final int DUMP_FEATURES = 1 << 1; 14287 public static final int DUMP_RESOLVERS = 1 << 2; 14288 public static final int DUMP_PERMISSIONS = 1 << 3; 14289 public static final int DUMP_PACKAGES = 1 << 4; 14290 public static final int DUMP_SHARED_USERS = 1 << 5; 14291 public static final int DUMP_MESSAGES = 1 << 6; 14292 public static final int DUMP_PROVIDERS = 1 << 7; 14293 public static final int DUMP_VERIFIERS = 1 << 8; 14294 public static final int DUMP_PREFERRED = 1 << 9; 14295 public static final int DUMP_PREFERRED_XML = 1 << 10; 14296 public static final int DUMP_KEYSETS = 1 << 11; 14297 public static final int DUMP_VERSION = 1 << 12; 14298 public static final int DUMP_INSTALLS = 1 << 13; 14299 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14300 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14301 14302 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14303 14304 private int mTypes; 14305 14306 private int mOptions; 14307 14308 private boolean mTitlePrinted; 14309 14310 private SharedUserSetting mSharedUser; 14311 14312 public boolean isDumping(int type) { 14313 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14314 return true; 14315 } 14316 14317 return (mTypes & type) != 0; 14318 } 14319 14320 public void setDump(int type) { 14321 mTypes |= type; 14322 } 14323 14324 public boolean isOptionEnabled(int option) { 14325 return (mOptions & option) != 0; 14326 } 14327 14328 public void setOptionEnabled(int option) { 14329 mOptions |= option; 14330 } 14331 14332 public boolean onTitlePrinted() { 14333 final boolean printed = mTitlePrinted; 14334 mTitlePrinted = true; 14335 return printed; 14336 } 14337 14338 public boolean getTitlePrinted() { 14339 return mTitlePrinted; 14340 } 14341 14342 public void setTitlePrinted(boolean enabled) { 14343 mTitlePrinted = enabled; 14344 } 14345 14346 public SharedUserSetting getSharedUser() { 14347 return mSharedUser; 14348 } 14349 14350 public void setSharedUser(SharedUserSetting user) { 14351 mSharedUser = user; 14352 } 14353 } 14354 14355 @Override 14356 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14357 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14358 != PackageManager.PERMISSION_GRANTED) { 14359 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14360 + Binder.getCallingPid() 14361 + ", uid=" + Binder.getCallingUid() 14362 + " without permission " 14363 + android.Manifest.permission.DUMP); 14364 return; 14365 } 14366 14367 DumpState dumpState = new DumpState(); 14368 boolean fullPreferred = false; 14369 boolean checkin = false; 14370 14371 String packageName = null; 14372 ArraySet<String> permissionNames = null; 14373 14374 int opti = 0; 14375 while (opti < args.length) { 14376 String opt = args[opti]; 14377 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14378 break; 14379 } 14380 opti++; 14381 14382 if ("-a".equals(opt)) { 14383 // Right now we only know how to print all. 14384 } else if ("-h".equals(opt)) { 14385 pw.println("Package manager dump options:"); 14386 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14387 pw.println(" --checkin: dump for a checkin"); 14388 pw.println(" -f: print details of intent filters"); 14389 pw.println(" -h: print this help"); 14390 pw.println(" cmd may be one of:"); 14391 pw.println(" l[ibraries]: list known shared libraries"); 14392 pw.println(" f[ibraries]: list device features"); 14393 pw.println(" k[eysets]: print known keysets"); 14394 pw.println(" r[esolvers]: dump intent resolvers"); 14395 pw.println(" perm[issions]: dump permissions"); 14396 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14397 pw.println(" pref[erred]: print preferred package settings"); 14398 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14399 pw.println(" prov[iders]: dump content providers"); 14400 pw.println(" p[ackages]: dump installed packages"); 14401 pw.println(" s[hared-users]: dump shared user IDs"); 14402 pw.println(" m[essages]: print collected runtime messages"); 14403 pw.println(" v[erifiers]: print package verifier info"); 14404 pw.println(" version: print database version info"); 14405 pw.println(" write: write current settings now"); 14406 pw.println(" <package.name>: info about given package"); 14407 pw.println(" installs: details about install sessions"); 14408 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14409 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14410 return; 14411 } else if ("--checkin".equals(opt)) { 14412 checkin = true; 14413 } else if ("-f".equals(opt)) { 14414 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14415 } else { 14416 pw.println("Unknown argument: " + opt + "; use -h for help"); 14417 } 14418 } 14419 14420 // Is the caller requesting to dump a particular piece of data? 14421 if (opti < args.length) { 14422 String cmd = args[opti]; 14423 opti++; 14424 // Is this a package name? 14425 if ("android".equals(cmd) || cmd.contains(".")) { 14426 packageName = cmd; 14427 // When dumping a single package, we always dump all of its 14428 // filter information since the amount of data will be reasonable. 14429 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14430 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14431 dumpState.setDump(DumpState.DUMP_LIBS); 14432 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14433 dumpState.setDump(DumpState.DUMP_FEATURES); 14434 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14435 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14436 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14437 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14438 } else if ("permission".equals(cmd)) { 14439 if (opti >= args.length) { 14440 pw.println("Error: permission requires permission name"); 14441 return; 14442 } 14443 permissionNames = new ArraySet<>(); 14444 while (opti < args.length) { 14445 permissionNames.add(args[opti]); 14446 opti++; 14447 } 14448 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14449 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14450 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14451 dumpState.setDump(DumpState.DUMP_PREFERRED); 14452 } else if ("preferred-xml".equals(cmd)) { 14453 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14454 if (opti < args.length && "--full".equals(args[opti])) { 14455 fullPreferred = true; 14456 opti++; 14457 } 14458 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14459 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14460 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14461 dumpState.setDump(DumpState.DUMP_PACKAGES); 14462 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14463 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14464 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14465 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14466 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14467 dumpState.setDump(DumpState.DUMP_MESSAGES); 14468 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14469 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14470 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14471 || "intent-filter-verifiers".equals(cmd)) { 14472 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14473 } else if ("version".equals(cmd)) { 14474 dumpState.setDump(DumpState.DUMP_VERSION); 14475 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14476 dumpState.setDump(DumpState.DUMP_KEYSETS); 14477 } else if ("installs".equals(cmd)) { 14478 dumpState.setDump(DumpState.DUMP_INSTALLS); 14479 } else if ("write".equals(cmd)) { 14480 synchronized (mPackages) { 14481 mSettings.writeLPr(); 14482 pw.println("Settings written."); 14483 return; 14484 } 14485 } 14486 } 14487 14488 if (checkin) { 14489 pw.println("vers,1"); 14490 } 14491 14492 // reader 14493 synchronized (mPackages) { 14494 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14495 if (!checkin) { 14496 if (dumpState.onTitlePrinted()) 14497 pw.println(); 14498 pw.println("Database versions:"); 14499 pw.print(" SDK Version:"); 14500 pw.print(" internal="); 14501 pw.print(mSettings.mInternalSdkPlatform); 14502 pw.print(" external="); 14503 pw.println(mSettings.mExternalSdkPlatform); 14504 pw.print(" DB Version:"); 14505 pw.print(" internal="); 14506 pw.print(mSettings.mInternalDatabaseVersion); 14507 pw.print(" external="); 14508 pw.println(mSettings.mExternalDatabaseVersion); 14509 } 14510 } 14511 14512 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14513 if (!checkin) { 14514 if (dumpState.onTitlePrinted()) 14515 pw.println(); 14516 pw.println("Verifiers:"); 14517 pw.print(" Required: "); 14518 pw.print(mRequiredVerifierPackage); 14519 pw.print(" (uid="); 14520 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14521 pw.println(")"); 14522 } else if (mRequiredVerifierPackage != null) { 14523 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14524 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14525 } 14526 } 14527 14528 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14529 packageName == null) { 14530 if (mIntentFilterVerifierComponent != null) { 14531 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14532 if (!checkin) { 14533 if (dumpState.onTitlePrinted()) 14534 pw.println(); 14535 pw.println("Intent Filter Verifier:"); 14536 pw.print(" Using: "); 14537 pw.print(verifierPackageName); 14538 pw.print(" (uid="); 14539 pw.print(getPackageUid(verifierPackageName, 0)); 14540 pw.println(")"); 14541 } else if (verifierPackageName != null) { 14542 pw.print("ifv,"); pw.print(verifierPackageName); 14543 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14544 } 14545 } else { 14546 pw.println(); 14547 pw.println("No Intent Filter Verifier available!"); 14548 } 14549 } 14550 14551 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14552 boolean printedHeader = false; 14553 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14554 while (it.hasNext()) { 14555 String name = it.next(); 14556 SharedLibraryEntry ent = mSharedLibraries.get(name); 14557 if (!checkin) { 14558 if (!printedHeader) { 14559 if (dumpState.onTitlePrinted()) 14560 pw.println(); 14561 pw.println("Libraries:"); 14562 printedHeader = true; 14563 } 14564 pw.print(" "); 14565 } else { 14566 pw.print("lib,"); 14567 } 14568 pw.print(name); 14569 if (!checkin) { 14570 pw.print(" -> "); 14571 } 14572 if (ent.path != null) { 14573 if (!checkin) { 14574 pw.print("(jar) "); 14575 pw.print(ent.path); 14576 } else { 14577 pw.print(",jar,"); 14578 pw.print(ent.path); 14579 } 14580 } else { 14581 if (!checkin) { 14582 pw.print("(apk) "); 14583 pw.print(ent.apk); 14584 } else { 14585 pw.print(",apk,"); 14586 pw.print(ent.apk); 14587 } 14588 } 14589 pw.println(); 14590 } 14591 } 14592 14593 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14594 if (dumpState.onTitlePrinted()) 14595 pw.println(); 14596 if (!checkin) { 14597 pw.println("Features:"); 14598 } 14599 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14600 while (it.hasNext()) { 14601 String name = it.next(); 14602 if (!checkin) { 14603 pw.print(" "); 14604 } else { 14605 pw.print("feat,"); 14606 } 14607 pw.println(name); 14608 } 14609 } 14610 14611 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14612 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14613 : "Activity Resolver Table:", " ", packageName, 14614 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14615 dumpState.setTitlePrinted(true); 14616 } 14617 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14618 : "Receiver Resolver Table:", " ", packageName, 14619 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14620 dumpState.setTitlePrinted(true); 14621 } 14622 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14623 : "Service Resolver Table:", " ", packageName, 14624 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14625 dumpState.setTitlePrinted(true); 14626 } 14627 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14628 : "Provider Resolver Table:", " ", packageName, 14629 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14630 dumpState.setTitlePrinted(true); 14631 } 14632 } 14633 14634 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14635 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14636 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14637 int user = mSettings.mPreferredActivities.keyAt(i); 14638 if (pir.dump(pw, 14639 dumpState.getTitlePrinted() 14640 ? "\nPreferred Activities User " + user + ":" 14641 : "Preferred Activities User " + user + ":", " ", 14642 packageName, true, false)) { 14643 dumpState.setTitlePrinted(true); 14644 } 14645 } 14646 } 14647 14648 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14649 pw.flush(); 14650 FileOutputStream fout = new FileOutputStream(fd); 14651 BufferedOutputStream str = new BufferedOutputStream(fout); 14652 XmlSerializer serializer = new FastXmlSerializer(); 14653 try { 14654 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14655 serializer.startDocument(null, true); 14656 serializer.setFeature( 14657 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14658 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14659 serializer.endDocument(); 14660 serializer.flush(); 14661 } catch (IllegalArgumentException e) { 14662 pw.println("Failed writing: " + e); 14663 } catch (IllegalStateException e) { 14664 pw.println("Failed writing: " + e); 14665 } catch (IOException e) { 14666 pw.println("Failed writing: " + e); 14667 } 14668 } 14669 14670 if (!checkin 14671 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14672 && packageName == null) { 14673 pw.println(); 14674 int count = mSettings.mPackages.size(); 14675 if (count == 0) { 14676 pw.println("No domain preferred apps!"); 14677 pw.println(); 14678 } else { 14679 final String prefix = " "; 14680 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14681 if (allPackageSettings.size() == 0) { 14682 pw.println("No domain preferred apps!"); 14683 pw.println(); 14684 } else { 14685 pw.println("Domain preferred apps status:"); 14686 pw.println(); 14687 count = 0; 14688 for (PackageSetting ps : allPackageSettings) { 14689 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14690 if (ivi == null || ivi.getPackageName() == null) continue; 14691 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14692 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14693 pw.println(prefix + "Status: " + ivi.getStatusString()); 14694 pw.println(); 14695 count++; 14696 } 14697 if (count == 0) { 14698 pw.println(prefix + "No domain preferred app status!"); 14699 pw.println(); 14700 } 14701 for (int userId : sUserManager.getUserIds()) { 14702 pw.println("Domain preferred apps for User " + userId + ":"); 14703 pw.println(); 14704 count = 0; 14705 for (PackageSetting ps : allPackageSettings) { 14706 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14707 if (ivi == null || ivi.getPackageName() == null) { 14708 continue; 14709 } 14710 final int status = ps.getDomainVerificationStatusForUser(userId); 14711 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14712 continue; 14713 } 14714 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14715 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14716 String statusStr = IntentFilterVerificationInfo. 14717 getStatusStringFromValue(status); 14718 pw.println(prefix + "Status: " + statusStr); 14719 pw.println(); 14720 count++; 14721 } 14722 if (count == 0) { 14723 pw.println(prefix + "No domain preferred apps!"); 14724 pw.println(); 14725 } 14726 } 14727 } 14728 } 14729 } 14730 14731 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14732 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14733 if (packageName == null && permissionNames == null) { 14734 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14735 if (iperm == 0) { 14736 if (dumpState.onTitlePrinted()) 14737 pw.println(); 14738 pw.println("AppOp Permissions:"); 14739 } 14740 pw.print(" AppOp Permission "); 14741 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14742 pw.println(":"); 14743 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14744 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14745 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14746 } 14747 } 14748 } 14749 } 14750 14751 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14752 boolean printedSomething = false; 14753 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14754 if (packageName != null && !packageName.equals(p.info.packageName)) { 14755 continue; 14756 } 14757 if (!printedSomething) { 14758 if (dumpState.onTitlePrinted()) 14759 pw.println(); 14760 pw.println("Registered ContentProviders:"); 14761 printedSomething = true; 14762 } 14763 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14764 pw.print(" "); pw.println(p.toString()); 14765 } 14766 printedSomething = false; 14767 for (Map.Entry<String, PackageParser.Provider> entry : 14768 mProvidersByAuthority.entrySet()) { 14769 PackageParser.Provider p = entry.getValue(); 14770 if (packageName != null && !packageName.equals(p.info.packageName)) { 14771 continue; 14772 } 14773 if (!printedSomething) { 14774 if (dumpState.onTitlePrinted()) 14775 pw.println(); 14776 pw.println("ContentProvider Authorities:"); 14777 printedSomething = true; 14778 } 14779 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14780 pw.print(" "); pw.println(p.toString()); 14781 if (p.info != null && p.info.applicationInfo != null) { 14782 final String appInfo = p.info.applicationInfo.toString(); 14783 pw.print(" applicationInfo="); pw.println(appInfo); 14784 } 14785 } 14786 } 14787 14788 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14789 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14790 } 14791 14792 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14793 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14794 } 14795 14796 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14797 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14798 } 14799 14800 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14801 // XXX should handle packageName != null by dumping only install data that 14802 // the given package is involved with. 14803 if (dumpState.onTitlePrinted()) pw.println(); 14804 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14805 } 14806 14807 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14808 if (dumpState.onTitlePrinted()) pw.println(); 14809 mSettings.dumpReadMessagesLPr(pw, dumpState); 14810 14811 pw.println(); 14812 pw.println("Package warning messages:"); 14813 BufferedReader in = null; 14814 String line = null; 14815 try { 14816 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14817 while ((line = in.readLine()) != null) { 14818 if (line.contains("ignored: updated version")) continue; 14819 pw.println(line); 14820 } 14821 } catch (IOException ignored) { 14822 } finally { 14823 IoUtils.closeQuietly(in); 14824 } 14825 } 14826 14827 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14828 BufferedReader in = null; 14829 String line = null; 14830 try { 14831 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14832 while ((line = in.readLine()) != null) { 14833 if (line.contains("ignored: updated version")) continue; 14834 pw.print("msg,"); 14835 pw.println(line); 14836 } 14837 } catch (IOException ignored) { 14838 } finally { 14839 IoUtils.closeQuietly(in); 14840 } 14841 } 14842 } 14843 } 14844 14845 // ------- apps on sdcard specific code ------- 14846 static final boolean DEBUG_SD_INSTALL = false; 14847 14848 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14849 14850 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14851 14852 private boolean mMediaMounted = false; 14853 14854 static String getEncryptKey() { 14855 try { 14856 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14857 SD_ENCRYPTION_KEYSTORE_NAME); 14858 if (sdEncKey == null) { 14859 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14860 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14861 if (sdEncKey == null) { 14862 Slog.e(TAG, "Failed to create encryption keys"); 14863 return null; 14864 } 14865 } 14866 return sdEncKey; 14867 } catch (NoSuchAlgorithmException nsae) { 14868 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14869 return null; 14870 } catch (IOException ioe) { 14871 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14872 return null; 14873 } 14874 } 14875 14876 /* 14877 * Update media status on PackageManager. 14878 */ 14879 @Override 14880 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14881 int callingUid = Binder.getCallingUid(); 14882 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14883 throw new SecurityException("Media status can only be updated by the system"); 14884 } 14885 // reader; this apparently protects mMediaMounted, but should probably 14886 // be a different lock in that case. 14887 synchronized (mPackages) { 14888 Log.i(TAG, "Updating external media status from " 14889 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14890 + (mediaStatus ? "mounted" : "unmounted")); 14891 if (DEBUG_SD_INSTALL) 14892 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14893 + ", mMediaMounted=" + mMediaMounted); 14894 if (mediaStatus == mMediaMounted) { 14895 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14896 : 0, -1); 14897 mHandler.sendMessage(msg); 14898 return; 14899 } 14900 mMediaMounted = mediaStatus; 14901 } 14902 // Queue up an async operation since the package installation may take a 14903 // little while. 14904 mHandler.post(new Runnable() { 14905 public void run() { 14906 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14907 } 14908 }); 14909 } 14910 14911 /** 14912 * Called by MountService when the initial ASECs to scan are available. 14913 * Should block until all the ASEC containers are finished being scanned. 14914 */ 14915 public void scanAvailableAsecs() { 14916 updateExternalMediaStatusInner(true, false, false); 14917 if (mShouldRestoreconData) { 14918 SELinuxMMAC.setRestoreconDone(); 14919 mShouldRestoreconData = false; 14920 } 14921 } 14922 14923 /* 14924 * Collect information of applications on external media, map them against 14925 * existing containers and update information based on current mount status. 14926 * Please note that we always have to report status if reportStatus has been 14927 * set to true especially when unloading packages. 14928 */ 14929 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14930 boolean externalStorage) { 14931 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14932 int[] uidArr = EmptyArray.INT; 14933 14934 final String[] list = PackageHelper.getSecureContainerList(); 14935 if (ArrayUtils.isEmpty(list)) { 14936 Log.i(TAG, "No secure containers found"); 14937 } else { 14938 // Process list of secure containers and categorize them 14939 // as active or stale based on their package internal state. 14940 14941 // reader 14942 synchronized (mPackages) { 14943 for (String cid : list) { 14944 // Leave stages untouched for now; installer service owns them 14945 if (PackageInstallerService.isStageName(cid)) continue; 14946 14947 if (DEBUG_SD_INSTALL) 14948 Log.i(TAG, "Processing container " + cid); 14949 String pkgName = getAsecPackageName(cid); 14950 if (pkgName == null) { 14951 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14952 continue; 14953 } 14954 if (DEBUG_SD_INSTALL) 14955 Log.i(TAG, "Looking for pkg : " + pkgName); 14956 14957 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14958 if (ps == null) { 14959 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14960 continue; 14961 } 14962 14963 /* 14964 * Skip packages that are not external if we're unmounting 14965 * external storage. 14966 */ 14967 if (externalStorage && !isMounted && !isExternal(ps)) { 14968 continue; 14969 } 14970 14971 final AsecInstallArgs args = new AsecInstallArgs(cid, 14972 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14973 // The package status is changed only if the code path 14974 // matches between settings and the container id. 14975 if (ps.codePathString != null 14976 && ps.codePathString.startsWith(args.getCodePath())) { 14977 if (DEBUG_SD_INSTALL) { 14978 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14979 + " at code path: " + ps.codePathString); 14980 } 14981 14982 // We do have a valid package installed on sdcard 14983 processCids.put(args, ps.codePathString); 14984 final int uid = ps.appId; 14985 if (uid != -1) { 14986 uidArr = ArrayUtils.appendInt(uidArr, uid); 14987 } 14988 } else { 14989 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14990 + ps.codePathString); 14991 } 14992 } 14993 } 14994 14995 Arrays.sort(uidArr); 14996 } 14997 14998 // Process packages with valid entries. 14999 if (isMounted) { 15000 if (DEBUG_SD_INSTALL) 15001 Log.i(TAG, "Loading packages"); 15002 loadMediaPackages(processCids, uidArr); 15003 startCleaningPackages(); 15004 mInstallerService.onSecureContainersAvailable(); 15005 } else { 15006 if (DEBUG_SD_INSTALL) 15007 Log.i(TAG, "Unloading packages"); 15008 unloadMediaPackages(processCids, uidArr, reportStatus); 15009 } 15010 } 15011 15012 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15013 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15014 final int size = infos.size(); 15015 final String[] packageNames = new String[size]; 15016 final int[] packageUids = new int[size]; 15017 for (int i = 0; i < size; i++) { 15018 final ApplicationInfo info = infos.get(i); 15019 packageNames[i] = info.packageName; 15020 packageUids[i] = info.uid; 15021 } 15022 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15023 finishedReceiver); 15024 } 15025 15026 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15027 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15028 sendResourcesChangedBroadcast(mediaStatus, replacing, 15029 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15030 } 15031 15032 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15033 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15034 int size = pkgList.length; 15035 if (size > 0) { 15036 // Send broadcasts here 15037 Bundle extras = new Bundle(); 15038 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15039 if (uidArr != null) { 15040 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15041 } 15042 if (replacing) { 15043 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15044 } 15045 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15046 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15047 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15048 } 15049 } 15050 15051 /* 15052 * Look at potentially valid container ids from processCids If package 15053 * information doesn't match the one on record or package scanning fails, 15054 * the cid is added to list of removeCids. We currently don't delete stale 15055 * containers. 15056 */ 15057 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15058 ArrayList<String> pkgList = new ArrayList<String>(); 15059 Set<AsecInstallArgs> keys = processCids.keySet(); 15060 15061 for (AsecInstallArgs args : keys) { 15062 String codePath = processCids.get(args); 15063 if (DEBUG_SD_INSTALL) 15064 Log.i(TAG, "Loading container : " + args.cid); 15065 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15066 try { 15067 // Make sure there are no container errors first. 15068 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15069 Slog.e(TAG, "Failed to mount cid : " + args.cid 15070 + " when installing from sdcard"); 15071 continue; 15072 } 15073 // Check code path here. 15074 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15075 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15076 + " does not match one in settings " + codePath); 15077 continue; 15078 } 15079 // Parse package 15080 int parseFlags = mDefParseFlags; 15081 if (args.isExternalAsec()) { 15082 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15083 } 15084 if (args.isFwdLocked()) { 15085 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15086 } 15087 15088 synchronized (mInstallLock) { 15089 PackageParser.Package pkg = null; 15090 try { 15091 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15092 } catch (PackageManagerException e) { 15093 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15094 } 15095 // Scan the package 15096 if (pkg != null) { 15097 /* 15098 * TODO why is the lock being held? doPostInstall is 15099 * called in other places without the lock. This needs 15100 * to be straightened out. 15101 */ 15102 // writer 15103 synchronized (mPackages) { 15104 retCode = PackageManager.INSTALL_SUCCEEDED; 15105 pkgList.add(pkg.packageName); 15106 // Post process args 15107 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15108 pkg.applicationInfo.uid); 15109 } 15110 } else { 15111 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15112 } 15113 } 15114 15115 } finally { 15116 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15117 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15118 } 15119 } 15120 } 15121 // writer 15122 synchronized (mPackages) { 15123 // If the platform SDK has changed since the last time we booted, 15124 // we need to re-grant app permission to catch any new ones that 15125 // appear. This is really a hack, and means that apps can in some 15126 // cases get permissions that the user didn't initially explicitly 15127 // allow... it would be nice to have some better way to handle 15128 // this situation. 15129 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15130 if (regrantPermissions) 15131 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15132 + mSdkVersion + "; regranting permissions for external storage"); 15133 mSettings.mExternalSdkPlatform = mSdkVersion; 15134 15135 // Make sure group IDs have been assigned, and any permission 15136 // changes in other apps are accounted for 15137 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15138 | (regrantPermissions 15139 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15140 : 0)); 15141 15142 mSettings.updateExternalDatabaseVersion(); 15143 15144 // can downgrade to reader 15145 // Persist settings 15146 mSettings.writeLPr(); 15147 } 15148 // Send a broadcast to let everyone know we are done processing 15149 if (pkgList.size() > 0) { 15150 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15151 } 15152 } 15153 15154 /* 15155 * Utility method to unload a list of specified containers 15156 */ 15157 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15158 // Just unmount all valid containers. 15159 for (AsecInstallArgs arg : cidArgs) { 15160 synchronized (mInstallLock) { 15161 arg.doPostDeleteLI(false); 15162 } 15163 } 15164 } 15165 15166 /* 15167 * Unload packages mounted on external media. This involves deleting package 15168 * data from internal structures, sending broadcasts about diabled packages, 15169 * gc'ing to free up references, unmounting all secure containers 15170 * corresponding to packages on external media, and posting a 15171 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15172 * that we always have to post this message if status has been requested no 15173 * matter what. 15174 */ 15175 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15176 final boolean reportStatus) { 15177 if (DEBUG_SD_INSTALL) 15178 Log.i(TAG, "unloading media packages"); 15179 ArrayList<String> pkgList = new ArrayList<String>(); 15180 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15181 final Set<AsecInstallArgs> keys = processCids.keySet(); 15182 for (AsecInstallArgs args : keys) { 15183 String pkgName = args.getPackageName(); 15184 if (DEBUG_SD_INSTALL) 15185 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15186 // Delete package internally 15187 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15188 synchronized (mInstallLock) { 15189 boolean res = deletePackageLI(pkgName, null, false, null, null, 15190 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15191 if (res) { 15192 pkgList.add(pkgName); 15193 } else { 15194 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15195 failedList.add(args); 15196 } 15197 } 15198 } 15199 15200 // reader 15201 synchronized (mPackages) { 15202 // We didn't update the settings after removing each package; 15203 // write them now for all packages. 15204 mSettings.writeLPr(); 15205 } 15206 15207 // We have to absolutely send UPDATED_MEDIA_STATUS only 15208 // after confirming that all the receivers processed the ordered 15209 // broadcast when packages get disabled, force a gc to clean things up. 15210 // and unload all the containers. 15211 if (pkgList.size() > 0) { 15212 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15213 new IIntentReceiver.Stub() { 15214 public void performReceive(Intent intent, int resultCode, String data, 15215 Bundle extras, boolean ordered, boolean sticky, 15216 int sendingUser) throws RemoteException { 15217 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15218 reportStatus ? 1 : 0, 1, keys); 15219 mHandler.sendMessage(msg); 15220 } 15221 }); 15222 } else { 15223 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15224 keys); 15225 mHandler.sendMessage(msg); 15226 } 15227 } 15228 15229 private void loadPrivatePackages(VolumeInfo vol) { 15230 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15231 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15232 synchronized (mInstallLock) { 15233 synchronized (mPackages) { 15234 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15235 for (PackageSetting ps : packages) { 15236 final PackageParser.Package pkg; 15237 try { 15238 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15239 loaded.add(pkg.applicationInfo); 15240 } catch (PackageManagerException e) { 15241 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15242 } 15243 } 15244 15245 // TODO: regrant any permissions that changed based since original install 15246 15247 mSettings.writeLPr(); 15248 } 15249 } 15250 15251 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15252 sendResourcesChangedBroadcast(true, false, loaded, null); 15253 } 15254 15255 private void unloadPrivatePackages(VolumeInfo vol) { 15256 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15257 synchronized (mInstallLock) { 15258 synchronized (mPackages) { 15259 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15260 for (PackageSetting ps : packages) { 15261 if (ps.pkg == null) continue; 15262 15263 final ApplicationInfo info = ps.pkg.applicationInfo; 15264 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15265 if (deletePackageLI(ps.name, null, false, null, null, 15266 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15267 unloaded.add(info); 15268 } else { 15269 Slog.w(TAG, "Failed to unload " + ps.codePath); 15270 } 15271 } 15272 15273 mSettings.writeLPr(); 15274 } 15275 } 15276 15277 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15278 sendResourcesChangedBroadcast(false, false, unloaded, null); 15279 } 15280 15281 /** 15282 * Examine all users present on given mounted volume, and destroy data 15283 * belonging to users that are no longer valid, or whose user ID has been 15284 * recycled. 15285 */ 15286 private void reconcileUsers(String volumeUuid) { 15287 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15288 if (ArrayUtils.isEmpty(files)) { 15289 Slog.d(TAG, "No users found on " + volumeUuid); 15290 return; 15291 } 15292 15293 for (File file : files) { 15294 if (!file.isDirectory()) continue; 15295 15296 final int userId; 15297 final UserInfo info; 15298 try { 15299 userId = Integer.parseInt(file.getName()); 15300 info = sUserManager.getUserInfo(userId); 15301 } catch (NumberFormatException e) { 15302 Slog.w(TAG, "Invalid user directory " + file); 15303 continue; 15304 } 15305 15306 boolean destroyUser = false; 15307 if (info == null) { 15308 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15309 + " because no matching user was found"); 15310 destroyUser = true; 15311 } else { 15312 try { 15313 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15314 } catch (IOException e) { 15315 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15316 + " because we failed to enforce serial number: " + e); 15317 destroyUser = true; 15318 } 15319 } 15320 15321 if (destroyUser) { 15322 synchronized (mInstallLock) { 15323 mInstaller.removeUserDataDirs(volumeUuid, userId); 15324 } 15325 } 15326 } 15327 15328 final UserManager um = mContext.getSystemService(UserManager.class); 15329 for (UserInfo user : um.getUsers()) { 15330 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15331 if (userDir.exists()) continue; 15332 15333 try { 15334 UserManagerService.prepareUserDirectory(userDir); 15335 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15336 } catch (IOException e) { 15337 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15338 } 15339 } 15340 } 15341 15342 /** 15343 * Examine all apps present on given mounted volume, and destroy apps that 15344 * aren't expected, either due to uninstallation or reinstallation on 15345 * another volume. 15346 */ 15347 private void reconcileApps(String volumeUuid) { 15348 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15349 if (ArrayUtils.isEmpty(files)) { 15350 Slog.d(TAG, "No apps found on " + volumeUuid); 15351 return; 15352 } 15353 15354 for (File file : files) { 15355 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15356 && !PackageInstallerService.isStageName(file.getName()); 15357 if (!isPackage) { 15358 // Ignore entries which are not packages 15359 continue; 15360 } 15361 15362 boolean destroyApp = false; 15363 String packageName = null; 15364 try { 15365 final PackageLite pkg = PackageParser.parsePackageLite(file, 15366 PackageParser.PARSE_MUST_BE_APK); 15367 packageName = pkg.packageName; 15368 15369 synchronized (mPackages) { 15370 final PackageSetting ps = mSettings.mPackages.get(packageName); 15371 if (ps == null) { 15372 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15373 + volumeUuid + " because we found no install record"); 15374 destroyApp = true; 15375 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15376 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15377 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15378 destroyApp = true; 15379 } 15380 } 15381 15382 } catch (PackageParserException e) { 15383 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15384 destroyApp = true; 15385 } 15386 15387 if (destroyApp) { 15388 synchronized (mInstallLock) { 15389 if (packageName != null) { 15390 removeDataDirsLI(volumeUuid, packageName); 15391 } 15392 if (file.isDirectory()) { 15393 mInstaller.rmPackageDir(file.getAbsolutePath()); 15394 } else { 15395 file.delete(); 15396 } 15397 } 15398 } 15399 } 15400 } 15401 15402 private void unfreezePackage(String packageName) { 15403 synchronized (mPackages) { 15404 final PackageSetting ps = mSettings.mPackages.get(packageName); 15405 if (ps != null) { 15406 ps.frozen = false; 15407 } 15408 } 15409 } 15410 15411 @Override 15412 public int movePackage(final String packageName, final String volumeUuid) { 15413 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15414 15415 final int moveId = mNextMoveId.getAndIncrement(); 15416 try { 15417 movePackageInternal(packageName, volumeUuid, moveId); 15418 } catch (PackageManagerException e) { 15419 Slog.w(TAG, "Failed to move " + packageName, e); 15420 mMoveCallbacks.notifyStatusChanged(moveId, 15421 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15422 } 15423 return moveId; 15424 } 15425 15426 private void movePackageInternal(final String packageName, final String volumeUuid, 15427 final int moveId) throws PackageManagerException { 15428 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15429 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15430 final PackageManager pm = mContext.getPackageManager(); 15431 15432 final boolean currentAsec; 15433 final String currentVolumeUuid; 15434 final File codeFile; 15435 final String installerPackageName; 15436 final String packageAbiOverride; 15437 final int appId; 15438 final String seinfo; 15439 final String label; 15440 15441 // reader 15442 synchronized (mPackages) { 15443 final PackageParser.Package pkg = mPackages.get(packageName); 15444 final PackageSetting ps = mSettings.mPackages.get(packageName); 15445 if (pkg == null || ps == null) { 15446 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15447 } 15448 15449 if (pkg.applicationInfo.isSystemApp()) { 15450 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15451 "Cannot move system application"); 15452 } 15453 15454 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15455 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15456 "Package already moved to " + volumeUuid); 15457 } 15458 15459 final File probe = new File(pkg.codePath); 15460 final File probeOat = new File(probe, "oat"); 15461 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15462 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15463 "Move only supported for modern cluster style installs"); 15464 } 15465 15466 if (ps.frozen) { 15467 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15468 "Failed to move already frozen package"); 15469 } 15470 ps.frozen = true; 15471 15472 currentAsec = pkg.applicationInfo.isForwardLocked() 15473 || pkg.applicationInfo.isExternalAsec(); 15474 currentVolumeUuid = ps.volumeUuid; 15475 codeFile = new File(pkg.codePath); 15476 installerPackageName = ps.installerPackageName; 15477 packageAbiOverride = ps.cpuAbiOverrideString; 15478 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15479 seinfo = pkg.applicationInfo.seinfo; 15480 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15481 } 15482 15483 // Now that we're guarded by frozen state, kill app during move 15484 killApplication(packageName, appId, "move pkg"); 15485 15486 final Bundle extras = new Bundle(); 15487 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15488 extras.putString(Intent.EXTRA_TITLE, label); 15489 mMoveCallbacks.notifyCreated(moveId, extras); 15490 15491 int installFlags; 15492 final boolean moveCompleteApp; 15493 final File measurePath; 15494 15495 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15496 installFlags = INSTALL_INTERNAL; 15497 moveCompleteApp = !currentAsec; 15498 measurePath = Environment.getDataAppDirectory(volumeUuid); 15499 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15500 installFlags = INSTALL_EXTERNAL; 15501 moveCompleteApp = false; 15502 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15503 } else { 15504 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15505 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15506 || !volume.isMountedWritable()) { 15507 unfreezePackage(packageName); 15508 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15509 "Move location not mounted private volume"); 15510 } 15511 15512 Preconditions.checkState(!currentAsec); 15513 15514 installFlags = INSTALL_INTERNAL; 15515 moveCompleteApp = true; 15516 measurePath = Environment.getDataAppDirectory(volumeUuid); 15517 } 15518 15519 final PackageStats stats = new PackageStats(null, -1); 15520 synchronized (mInstaller) { 15521 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15522 unfreezePackage(packageName); 15523 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15524 "Failed to measure package size"); 15525 } 15526 } 15527 15528 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15529 + stats.dataSize); 15530 15531 final long startFreeBytes = measurePath.getFreeSpace(); 15532 final long sizeBytes; 15533 if (moveCompleteApp) { 15534 sizeBytes = stats.codeSize + stats.dataSize; 15535 } else { 15536 sizeBytes = stats.codeSize; 15537 } 15538 15539 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15540 unfreezePackage(packageName); 15541 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15542 "Not enough free space to move"); 15543 } 15544 15545 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15546 15547 final CountDownLatch installedLatch = new CountDownLatch(1); 15548 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15549 @Override 15550 public void onUserActionRequired(Intent intent) throws RemoteException { 15551 throw new IllegalStateException(); 15552 } 15553 15554 @Override 15555 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15556 Bundle extras) throws RemoteException { 15557 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15558 + PackageManager.installStatusToString(returnCode, msg)); 15559 15560 installedLatch.countDown(); 15561 15562 // Regardless of success or failure of the move operation, 15563 // always unfreeze the package 15564 unfreezePackage(packageName); 15565 15566 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15567 switch (status) { 15568 case PackageInstaller.STATUS_SUCCESS: 15569 mMoveCallbacks.notifyStatusChanged(moveId, 15570 PackageManager.MOVE_SUCCEEDED); 15571 break; 15572 case PackageInstaller.STATUS_FAILURE_STORAGE: 15573 mMoveCallbacks.notifyStatusChanged(moveId, 15574 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15575 break; 15576 default: 15577 mMoveCallbacks.notifyStatusChanged(moveId, 15578 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15579 break; 15580 } 15581 } 15582 }; 15583 15584 final MoveInfo move; 15585 if (moveCompleteApp) { 15586 // Kick off a thread to report progress estimates 15587 new Thread() { 15588 @Override 15589 public void run() { 15590 while (true) { 15591 try { 15592 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15593 break; 15594 } 15595 } catch (InterruptedException ignored) { 15596 } 15597 15598 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15599 final int progress = 10 + (int) MathUtils.constrain( 15600 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15601 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15602 } 15603 } 15604 }.start(); 15605 15606 final String dataAppName = codeFile.getName(); 15607 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15608 dataAppName, appId, seinfo); 15609 } else { 15610 move = null; 15611 } 15612 15613 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15614 15615 final Message msg = mHandler.obtainMessage(INIT_COPY); 15616 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15617 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15618 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15619 mHandler.sendMessage(msg); 15620 } 15621 15622 @Override 15623 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15624 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15625 15626 final int realMoveId = mNextMoveId.getAndIncrement(); 15627 final Bundle extras = new Bundle(); 15628 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15629 mMoveCallbacks.notifyCreated(realMoveId, extras); 15630 15631 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15632 @Override 15633 public void onCreated(int moveId, Bundle extras) { 15634 // Ignored 15635 } 15636 15637 @Override 15638 public void onStatusChanged(int moveId, int status, long estMillis) { 15639 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15640 } 15641 }; 15642 15643 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15644 storage.setPrimaryStorageUuid(volumeUuid, callback); 15645 return realMoveId; 15646 } 15647 15648 @Override 15649 public int getMoveStatus(int moveId) { 15650 mContext.enforceCallingOrSelfPermission( 15651 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15652 return mMoveCallbacks.mLastStatus.get(moveId); 15653 } 15654 15655 @Override 15656 public void registerMoveCallback(IPackageMoveObserver callback) { 15657 mContext.enforceCallingOrSelfPermission( 15658 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15659 mMoveCallbacks.register(callback); 15660 } 15661 15662 @Override 15663 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15664 mContext.enforceCallingOrSelfPermission( 15665 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15666 mMoveCallbacks.unregister(callback); 15667 } 15668 15669 @Override 15670 public boolean setInstallLocation(int loc) { 15671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15672 null); 15673 if (getInstallLocation() == loc) { 15674 return true; 15675 } 15676 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15677 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15678 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15679 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15680 return true; 15681 } 15682 return false; 15683 } 15684 15685 @Override 15686 public int getInstallLocation() { 15687 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15688 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15689 PackageHelper.APP_INSTALL_AUTO); 15690 } 15691 15692 /** Called by UserManagerService */ 15693 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15694 mDirtyUsers.remove(userHandle); 15695 mSettings.removeUserLPw(userHandle); 15696 mPendingBroadcasts.remove(userHandle); 15697 if (mInstaller != null) { 15698 // Technically, we shouldn't be doing this with the package lock 15699 // held. However, this is very rare, and there is already so much 15700 // other disk I/O going on, that we'll let it slide for now. 15701 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15702 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15703 final String volumeUuid = vol.getFsUuid(); 15704 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15705 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15706 } 15707 } 15708 mUserNeedsBadging.delete(userHandle); 15709 removeUnusedPackagesLILPw(userManager, userHandle); 15710 } 15711 15712 /** 15713 * We're removing userHandle and would like to remove any downloaded packages 15714 * that are no longer in use by any other user. 15715 * @param userHandle the user being removed 15716 */ 15717 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15718 final boolean DEBUG_CLEAN_APKS = false; 15719 int [] users = userManager.getUserIdsLPr(); 15720 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15721 while (psit.hasNext()) { 15722 PackageSetting ps = psit.next(); 15723 if (ps.pkg == null) { 15724 continue; 15725 } 15726 final String packageName = ps.pkg.packageName; 15727 // Skip over if system app 15728 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15729 continue; 15730 } 15731 if (DEBUG_CLEAN_APKS) { 15732 Slog.i(TAG, "Checking package " + packageName); 15733 } 15734 boolean keep = false; 15735 for (int i = 0; i < users.length; i++) { 15736 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15737 keep = true; 15738 if (DEBUG_CLEAN_APKS) { 15739 Slog.i(TAG, " Keeping package " + packageName + " for user " 15740 + users[i]); 15741 } 15742 break; 15743 } 15744 } 15745 if (!keep) { 15746 if (DEBUG_CLEAN_APKS) { 15747 Slog.i(TAG, " Removing package " + packageName); 15748 } 15749 mHandler.post(new Runnable() { 15750 public void run() { 15751 deletePackageX(packageName, userHandle, 0); 15752 } //end run 15753 }); 15754 } 15755 } 15756 } 15757 15758 /** Called by UserManagerService */ 15759 void createNewUserLILPw(int userHandle) { 15760 if (mInstaller != null) { 15761 mInstaller.createUserConfig(userHandle); 15762 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15763 applyFactoryDefaultBrowserLPw(userHandle); 15764 } 15765 } 15766 15767 void newUserCreatedLILPw(final int userHandle) { 15768 // We cannot grant the default permissions with a lock held as 15769 // we query providers from other components for default handlers 15770 // such as enabled IMEs, etc. 15771 mHandler.post(new Runnable() { 15772 @Override 15773 public void run() { 15774 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15775 } 15776 }); 15777 } 15778 15779 @Override 15780 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15781 mContext.enforceCallingOrSelfPermission( 15782 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15783 "Only package verification agents can read the verifier device identity"); 15784 15785 synchronized (mPackages) { 15786 return mSettings.getVerifierDeviceIdentityLPw(); 15787 } 15788 } 15789 15790 @Override 15791 public void setPermissionEnforced(String permission, boolean enforced) { 15792 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15793 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15794 synchronized (mPackages) { 15795 if (mSettings.mReadExternalStorageEnforced == null 15796 || mSettings.mReadExternalStorageEnforced != enforced) { 15797 mSettings.mReadExternalStorageEnforced = enforced; 15798 mSettings.writeLPr(); 15799 } 15800 } 15801 // kill any non-foreground processes so we restart them and 15802 // grant/revoke the GID. 15803 final IActivityManager am = ActivityManagerNative.getDefault(); 15804 if (am != null) { 15805 final long token = Binder.clearCallingIdentity(); 15806 try { 15807 am.killProcessesBelowForeground("setPermissionEnforcement"); 15808 } catch (RemoteException e) { 15809 } finally { 15810 Binder.restoreCallingIdentity(token); 15811 } 15812 } 15813 } else { 15814 throw new IllegalArgumentException("No selective enforcement for " + permission); 15815 } 15816 } 15817 15818 @Override 15819 @Deprecated 15820 public boolean isPermissionEnforced(String permission) { 15821 return true; 15822 } 15823 15824 @Override 15825 public boolean isStorageLow() { 15826 final long token = Binder.clearCallingIdentity(); 15827 try { 15828 final DeviceStorageMonitorInternal 15829 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15830 if (dsm != null) { 15831 return dsm.isMemoryLow(); 15832 } else { 15833 return false; 15834 } 15835 } finally { 15836 Binder.restoreCallingIdentity(token); 15837 } 15838 } 15839 15840 @Override 15841 public IPackageInstaller getPackageInstaller() { 15842 return mInstallerService; 15843 } 15844 15845 private boolean userNeedsBadging(int userId) { 15846 int index = mUserNeedsBadging.indexOfKey(userId); 15847 if (index < 0) { 15848 final UserInfo userInfo; 15849 final long token = Binder.clearCallingIdentity(); 15850 try { 15851 userInfo = sUserManager.getUserInfo(userId); 15852 } finally { 15853 Binder.restoreCallingIdentity(token); 15854 } 15855 final boolean b; 15856 if (userInfo != null && userInfo.isManagedProfile()) { 15857 b = true; 15858 } else { 15859 b = false; 15860 } 15861 mUserNeedsBadging.put(userId, b); 15862 return b; 15863 } 15864 return mUserNeedsBadging.valueAt(index); 15865 } 15866 15867 @Override 15868 public KeySet getKeySetByAlias(String packageName, String alias) { 15869 if (packageName == null || alias == null) { 15870 return null; 15871 } 15872 synchronized(mPackages) { 15873 final PackageParser.Package pkg = mPackages.get(packageName); 15874 if (pkg == null) { 15875 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15876 throw new IllegalArgumentException("Unknown package: " + packageName); 15877 } 15878 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15879 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15880 } 15881 } 15882 15883 @Override 15884 public KeySet getSigningKeySet(String packageName) { 15885 if (packageName == null) { 15886 return null; 15887 } 15888 synchronized(mPackages) { 15889 final PackageParser.Package pkg = mPackages.get(packageName); 15890 if (pkg == null) { 15891 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15892 throw new IllegalArgumentException("Unknown package: " + packageName); 15893 } 15894 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15895 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15896 throw new SecurityException("May not access signing KeySet of other apps."); 15897 } 15898 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15899 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15900 } 15901 } 15902 15903 @Override 15904 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15905 if (packageName == null || ks == null) { 15906 return false; 15907 } 15908 synchronized(mPackages) { 15909 final PackageParser.Package pkg = mPackages.get(packageName); 15910 if (pkg == null) { 15911 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15912 throw new IllegalArgumentException("Unknown package: " + packageName); 15913 } 15914 IBinder ksh = ks.getToken(); 15915 if (ksh instanceof KeySetHandle) { 15916 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15917 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15918 } 15919 return false; 15920 } 15921 } 15922 15923 @Override 15924 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15925 if (packageName == null || ks == null) { 15926 return false; 15927 } 15928 synchronized(mPackages) { 15929 final PackageParser.Package pkg = mPackages.get(packageName); 15930 if (pkg == null) { 15931 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15932 throw new IllegalArgumentException("Unknown package: " + packageName); 15933 } 15934 IBinder ksh = ks.getToken(); 15935 if (ksh instanceof KeySetHandle) { 15936 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15937 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15938 } 15939 return false; 15940 } 15941 } 15942 15943 public void getUsageStatsIfNoPackageUsageInfo() { 15944 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15945 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15946 if (usm == null) { 15947 throw new IllegalStateException("UsageStatsManager must be initialized"); 15948 } 15949 long now = System.currentTimeMillis(); 15950 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15951 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15952 String packageName = entry.getKey(); 15953 PackageParser.Package pkg = mPackages.get(packageName); 15954 if (pkg == null) { 15955 continue; 15956 } 15957 UsageStats usage = entry.getValue(); 15958 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15959 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15960 } 15961 } 15962 } 15963 15964 /** 15965 * Check and throw if the given before/after packages would be considered a 15966 * downgrade. 15967 */ 15968 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15969 throws PackageManagerException { 15970 if (after.versionCode < before.mVersionCode) { 15971 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15972 "Update version code " + after.versionCode + " is older than current " 15973 + before.mVersionCode); 15974 } else if (after.versionCode == before.mVersionCode) { 15975 if (after.baseRevisionCode < before.baseRevisionCode) { 15976 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15977 "Update base revision code " + after.baseRevisionCode 15978 + " is older than current " + before.baseRevisionCode); 15979 } 15980 15981 if (!ArrayUtils.isEmpty(after.splitNames)) { 15982 for (int i = 0; i < after.splitNames.length; i++) { 15983 final String splitName = after.splitNames[i]; 15984 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15985 if (j != -1) { 15986 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15987 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15988 "Update split " + splitName + " revision code " 15989 + after.splitRevisionCodes[i] + " is older than current " 15990 + before.splitRevisionCodes[j]); 15991 } 15992 } 15993 } 15994 } 15995 } 15996 } 15997 15998 private static class MoveCallbacks extends Handler { 15999 private static final int MSG_CREATED = 1; 16000 private static final int MSG_STATUS_CHANGED = 2; 16001 16002 private final RemoteCallbackList<IPackageMoveObserver> 16003 mCallbacks = new RemoteCallbackList<>(); 16004 16005 private final SparseIntArray mLastStatus = new SparseIntArray(); 16006 16007 public MoveCallbacks(Looper looper) { 16008 super(looper); 16009 } 16010 16011 public void register(IPackageMoveObserver callback) { 16012 mCallbacks.register(callback); 16013 } 16014 16015 public void unregister(IPackageMoveObserver callback) { 16016 mCallbacks.unregister(callback); 16017 } 16018 16019 @Override 16020 public void handleMessage(Message msg) { 16021 final SomeArgs args = (SomeArgs) msg.obj; 16022 final int n = mCallbacks.beginBroadcast(); 16023 for (int i = 0; i < n; i++) { 16024 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16025 try { 16026 invokeCallback(callback, msg.what, args); 16027 } catch (RemoteException ignored) { 16028 } 16029 } 16030 mCallbacks.finishBroadcast(); 16031 args.recycle(); 16032 } 16033 16034 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16035 throws RemoteException { 16036 switch (what) { 16037 case MSG_CREATED: { 16038 callback.onCreated(args.argi1, (Bundle) args.arg2); 16039 break; 16040 } 16041 case MSG_STATUS_CHANGED: { 16042 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16043 break; 16044 } 16045 } 16046 } 16047 16048 private void notifyCreated(int moveId, Bundle extras) { 16049 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16050 16051 final SomeArgs args = SomeArgs.obtain(); 16052 args.argi1 = moveId; 16053 args.arg2 = extras; 16054 obtainMessage(MSG_CREATED, args).sendToTarget(); 16055 } 16056 16057 private void notifyStatusChanged(int moveId, int status) { 16058 notifyStatusChanged(moveId, status, -1); 16059 } 16060 16061 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16062 Slog.v(TAG, "Move " + moveId + " status " + status); 16063 16064 final SomeArgs args = SomeArgs.obtain(); 16065 args.argi1 = moveId; 16066 args.argi2 = status; 16067 args.arg3 = estMillis; 16068 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16069 16070 synchronized (mLastStatus) { 16071 mLastStatus.put(moveId, status); 16072 } 16073 } 16074 } 16075 16076 private final class OnPermissionChangeListeners extends Handler { 16077 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16078 16079 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16080 new RemoteCallbackList<>(); 16081 16082 public OnPermissionChangeListeners(Looper looper) { 16083 super(looper); 16084 } 16085 16086 @Override 16087 public void handleMessage(Message msg) { 16088 switch (msg.what) { 16089 case MSG_ON_PERMISSIONS_CHANGED: { 16090 final int uid = msg.arg1; 16091 handleOnPermissionsChanged(uid); 16092 } break; 16093 } 16094 } 16095 16096 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16097 mPermissionListeners.register(listener); 16098 16099 } 16100 16101 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16102 mPermissionListeners.unregister(listener); 16103 } 16104 16105 public void onPermissionsChanged(int uid) { 16106 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16107 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16108 } 16109 } 16110 16111 private void handleOnPermissionsChanged(int uid) { 16112 final int count = mPermissionListeners.beginBroadcast(); 16113 try { 16114 for (int i = 0; i < count; i++) { 16115 IOnPermissionsChangeListener callback = mPermissionListeners 16116 .getBroadcastItem(i); 16117 try { 16118 callback.onPermissionsChanged(uid); 16119 } catch (RemoteException e) { 16120 Log.e(TAG, "Permission listener is dead", e); 16121 } 16122 } 16123 } finally { 16124 mPermissionListeners.finishBroadcast(); 16125 } 16126 } 16127 } 16128 16129 private class PackageManagerInternalImpl extends PackageManagerInternal { 16130 @Override 16131 public void setLocationPackagesProvider(PackagesProvider provider) { 16132 synchronized (mPackages) { 16133 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16134 } 16135 } 16136 16137 @Override 16138 public void setImePackagesProvider(PackagesProvider provider) { 16139 synchronized (mPackages) { 16140 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16141 } 16142 } 16143 16144 @Override 16145 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16146 synchronized (mPackages) { 16147 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16148 } 16149 } 16150 16151 @Override 16152 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16153 synchronized (mPackages) { 16154 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16155 } 16156 } 16157 16158 @Override 16159 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16160 synchronized (mPackages) { 16161 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16162 } 16163 } 16164 16165 @Override 16166 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16167 synchronized (mPackages) { 16168 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16169 } 16170 } 16171 16172 @Override 16173 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16174 synchronized (mPackages) { 16175 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16176 packageName, userId); 16177 } 16178 } 16179 16180 @Override 16181 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16182 synchronized (mPackages) { 16183 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16184 packageName, userId); 16185 } 16186 } 16187 } 16188 16189 @Override 16190 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16191 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16192 synchronized (mPackages) { 16193 final long identity = Binder.clearCallingIdentity(); 16194 try { 16195 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16196 packageNames, userId); 16197 } finally { 16198 Binder.restoreCallingIdentity(identity); 16199 } 16200 } 16201 } 16202 16203 private static void enforceSystemOrPhoneCaller(String tag) { 16204 int callingUid = Binder.getCallingUid(); 16205 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16206 throw new SecurityException( 16207 "Cannot call " + tag + " from UID " + callingUid); 16208 } 16209 } 16210} 16211