PackageManagerService.java revision 38cae6c8bcb86236b21d69f852473351c0c1d82a
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 28import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 29import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 37import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 38import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 39import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 43import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 45import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 46import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 47import static android.content.pm.PackageManager.INSTALL_INTERNAL; 48import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 53import static android.content.pm.PackageManager.MATCH_ALL; 54import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 55import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 56import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 57import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 58import static android.content.pm.PackageManager.PERMISSION_GRANTED; 59import static android.content.pm.PackageParser.isApkFile; 60import static android.os.Process.PACKAGE_INFO_GID; 61import static android.os.Process.SYSTEM_UID; 62import static android.system.OsConstants.O_CREAT; 63import static android.system.OsConstants.O_RDWR; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 66import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 67import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 68import static com.android.internal.util.ArrayUtils.appendInt; 69import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 72import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 73import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 74 75import android.Manifest; 76import android.app.ActivityManager; 77import android.app.ActivityManagerNative; 78import android.app.AppGlobals; 79import android.app.IActivityManager; 80import android.app.admin.IDevicePolicyManager; 81import android.app.backup.IBackupManager; 82import android.app.usage.UsageStats; 83import android.app.usage.UsageStatsManager; 84import android.content.BroadcastReceiver; 85import android.content.ComponentName; 86import android.content.Context; 87import android.content.IIntentReceiver; 88import android.content.Intent; 89import android.content.IntentFilter; 90import android.content.IntentSender; 91import android.content.IntentSender.SendIntentException; 92import android.content.ServiceConnection; 93import android.content.pm.ActivityInfo; 94import android.content.pm.ApplicationInfo; 95import android.content.pm.FeatureInfo; 96import android.content.pm.IOnPermissionsChangeListener; 97import android.content.pm.IPackageDataObserver; 98import android.content.pm.IPackageDeleteObserver; 99import android.content.pm.IPackageDeleteObserver2; 100import android.content.pm.IPackageInstallObserver2; 101import android.content.pm.IPackageInstaller; 102import android.content.pm.IPackageManager; 103import android.content.pm.IPackageMoveObserver; 104import android.content.pm.IPackageStatsObserver; 105import android.content.pm.InstrumentationInfo; 106import android.content.pm.IntentFilterVerificationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageManagerInternal; 116import android.content.pm.PackageParser; 117import android.content.pm.PackageParser.ActivityIntentInfo; 118import android.content.pm.PackageParser.PackageLite; 119import android.content.pm.PackageParser.PackageParserException; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Debug; 140import android.os.Environment; 141import android.os.Environment.UserEnvironment; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteCallbackList; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.os.storage.IMountService; 159import android.os.storage.StorageEventListener; 160import android.os.storage.StorageManager; 161import android.os.storage.VolumeInfo; 162import android.os.storage.VolumeRecord; 163import android.security.KeyStore; 164import android.security.SystemKeyStore; 165import android.system.ErrnoException; 166import android.system.Os; 167import android.system.StructStat; 168import android.text.TextUtils; 169import android.text.format.DateUtils; 170import android.util.ArrayMap; 171import android.util.ArraySet; 172import android.util.AtomicFile; 173import android.util.DisplayMetrics; 174import android.util.EventLog; 175import android.util.ExceptionUtils; 176import android.util.Log; 177import android.util.LogPrinter; 178import android.util.MathUtils; 179import android.util.PrintStreamPrinter; 180import android.util.Slog; 181import android.util.SparseArray; 182import android.util.SparseBooleanArray; 183import android.util.SparseIntArray; 184import android.util.Xml; 185import android.view.Display; 186 187import dalvik.system.DexFile; 188import dalvik.system.VMRuntime; 189 190import libcore.io.IoUtils; 191import libcore.util.EmptyArray; 192 193import com.android.internal.R; 194import com.android.internal.annotations.GuardedBy; 195import com.android.internal.app.IMediaContainerService; 196import com.android.internal.app.ResolverActivity; 197import com.android.internal.content.NativeLibraryHelper; 198import com.android.internal.content.PackageHelper; 199import com.android.internal.os.IParcelFileDescriptorFactory; 200import com.android.internal.os.SomeArgs; 201import com.android.internal.os.Zygote; 202import com.android.internal.util.ArrayUtils; 203import com.android.internal.util.FastPrintWriter; 204import com.android.internal.util.FastXmlSerializer; 205import com.android.internal.util.IndentingPrintWriter; 206import com.android.internal.util.Preconditions; 207import com.android.server.EventLogTags; 208import com.android.server.FgThread; 209import com.android.server.IntentResolver; 210import com.android.server.LocalServices; 211import com.android.server.ServiceThread; 212import com.android.server.SystemConfig; 213import com.android.server.Watchdog; 214import com.android.server.pm.PermissionsState.PermissionState; 215import com.android.server.pm.Settings.DatabaseVersion; 216import com.android.server.storage.DeviceStorageMonitorInternal; 217 218import org.xmlpull.v1.XmlPullParser; 219import org.xmlpull.v1.XmlPullParserException; 220import org.xmlpull.v1.XmlSerializer; 221 222import java.io.BufferedInputStream; 223import java.io.BufferedOutputStream; 224import java.io.BufferedReader; 225import java.io.ByteArrayInputStream; 226import java.io.ByteArrayOutputStream; 227import java.io.File; 228import java.io.FileDescriptor; 229import java.io.FileNotFoundException; 230import java.io.FileOutputStream; 231import java.io.FileReader; 232import java.io.FilenameFilter; 233import java.io.IOException; 234import java.io.InputStream; 235import java.io.PrintWriter; 236import java.nio.charset.StandardCharsets; 237import java.security.NoSuchAlgorithmException; 238import java.security.PublicKey; 239import java.security.cert.CertificateEncodingException; 240import java.security.cert.CertificateException; 241import java.text.SimpleDateFormat; 242import java.util.ArrayList; 243import java.util.Arrays; 244import java.util.Collection; 245import java.util.Collections; 246import java.util.Comparator; 247import java.util.Date; 248import java.util.Iterator; 249import java.util.List; 250import java.util.Map; 251import java.util.Objects; 252import java.util.Set; 253import java.util.concurrent.CountDownLatch; 254import java.util.concurrent.TimeUnit; 255import java.util.concurrent.atomic.AtomicBoolean; 256import java.util.concurrent.atomic.AtomicInteger; 257import java.util.concurrent.atomic.AtomicLong; 258 259/** 260 * Keep track of all those .apks everywhere. 261 * 262 * This is very central to the platform's security; please run the unit 263 * tests whenever making modifications here: 264 * 265mmm frameworks/base/tests/AndroidTests 266adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 267adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 268 * 269 * {@hide} 270 */ 271public class PackageManagerService extends IPackageManager.Stub { 272 static final String TAG = "PackageManager"; 273 static final boolean DEBUG_SETTINGS = false; 274 static final boolean DEBUG_PREFERRED = false; 275 static final boolean DEBUG_UPGRADE = false; 276 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 277 private static final boolean DEBUG_BACKUP = true; 278 private static final boolean DEBUG_INSTALL = false; 279 private static final boolean DEBUG_REMOVE = false; 280 private static final boolean DEBUG_BROADCASTS = false; 281 private static final boolean DEBUG_SHOW_INFO = false; 282 private static final boolean DEBUG_PACKAGE_INFO = false; 283 private static final boolean DEBUG_INTENT_MATCHING = false; 284 private static final boolean DEBUG_PACKAGE_SCANNING = false; 285 private static final boolean DEBUG_VERIFY = false; 286 private static final boolean DEBUG_DEXOPT = false; 287 private static final boolean DEBUG_ABI_SELECTION = false; 288 289 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 290 291 private static final int RADIO_UID = Process.PHONE_UID; 292 private static final int LOG_UID = Process.LOG_UID; 293 private static final int NFC_UID = Process.NFC_UID; 294 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 295 private static final int SHELL_UID = Process.SHELL_UID; 296 297 // Cap the size of permission trees that 3rd party apps can define 298 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 299 300 // Suffix used during package installation when copying/moving 301 // package apks to install directory. 302 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 303 304 static final int SCAN_NO_DEX = 1<<1; 305 static final int SCAN_FORCE_DEX = 1<<2; 306 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 307 static final int SCAN_NEW_INSTALL = 1<<4; 308 static final int SCAN_NO_PATHS = 1<<5; 309 static final int SCAN_UPDATE_TIME = 1<<6; 310 static final int SCAN_DEFER_DEX = 1<<7; 311 static final int SCAN_BOOTING = 1<<8; 312 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 313 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 314 static final int SCAN_REQUIRE_KNOWN = 1<<12; 315 static final int SCAN_MOVE = 1<<13; 316 static final int SCAN_INITIAL = 1<<14; 317 318 static final int REMOVE_CHATTY = 1<<16; 319 320 private static final int[] EMPTY_INT_ARRAY = new int[0]; 321 322 /** 323 * Timeout (in milliseconds) after which the watchdog should declare that 324 * our handler thread is wedged. The usual default for such things is one 325 * minute but we sometimes do very lengthy I/O operations on this thread, 326 * such as installing multi-gigabyte applications, so ours needs to be longer. 327 */ 328 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 329 330 /** 331 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 332 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 333 * settings entry if available, otherwise we use the hardcoded default. If it's been 334 * more than this long since the last fstrim, we force one during the boot sequence. 335 * 336 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 337 * one gets run at the next available charging+idle time. This final mandatory 338 * no-fstrim check kicks in only of the other scheduling criteria is never met. 339 */ 340 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 341 342 /** 343 * Whether verification is enabled by default. 344 */ 345 private static final boolean DEFAULT_VERIFY_ENABLE = true; 346 347 /** 348 * The default maximum time to wait for the verification agent to return in 349 * milliseconds. 350 */ 351 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 352 353 /** 354 * The default response for package verification timeout. 355 * 356 * This can be either PackageManager.VERIFICATION_ALLOW or 357 * PackageManager.VERIFICATION_REJECT. 358 */ 359 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 360 361 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 362 363 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 364 DEFAULT_CONTAINER_PACKAGE, 365 "com.android.defcontainer.DefaultContainerService"); 366 367 private static final String KILL_APP_REASON_GIDS_CHANGED = 368 "permission grant or revoke changed gids"; 369 370 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 371 "permissions revoked"; 372 373 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 374 375 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 376 377 /** Permission grant: not grant the permission. */ 378 private static final int GRANT_DENIED = 1; 379 380 /** Permission grant: grant the permission as an install permission. */ 381 private static final int GRANT_INSTALL = 2; 382 383 /** Permission grant: grant the permission as an install permission for a legacy app. */ 384 private static final int GRANT_INSTALL_LEGACY = 3; 385 386 /** Permission grant: grant the permission as a runtime one. */ 387 private static final int GRANT_RUNTIME = 4; 388 389 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 390 private static final int GRANT_UPGRADE = 5; 391 392 /** Canonical intent used to identify what counts as a "web browser" app */ 393 private static final Intent sBrowserIntent; 394 static { 395 sBrowserIntent = new Intent(); 396 sBrowserIntent.setAction(Intent.ACTION_VIEW); 397 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 398 sBrowserIntent.setData(Uri.parse("http:")); 399 } 400 401 final ServiceThread mHandlerThread; 402 403 final PackageHandler mHandler; 404 405 /** 406 * Messages for {@link #mHandler} that need to wait for system ready before 407 * being dispatched. 408 */ 409 private ArrayList<Message> mPostSystemReadyMessages; 410 411 final int mSdkVersion = Build.VERSION.SDK_INT; 412 413 final Context mContext; 414 final boolean mFactoryTest; 415 final boolean mOnlyCore; 416 final boolean mLazyDexOpt; 417 final long mDexOptLRUThresholdInMills; 418 final DisplayMetrics mMetrics; 419 final int mDefParseFlags; 420 final String[] mSeparateProcesses; 421 final boolean mIsUpgrade; 422 423 // This is where all application persistent data goes. 424 final File mAppDataDir; 425 426 // This is where all application persistent data goes for secondary users. 427 final File mUserAppDataDir; 428 429 /** The location for ASEC container files on internal storage. */ 430 final String mAsecInternalPath; 431 432 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 433 // LOCK HELD. Can be called with mInstallLock held. 434 @GuardedBy("mInstallLock") 435 final Installer mInstaller; 436 437 /** Directory where installed third-party apps stored */ 438 final File mAppInstallDir; 439 440 /** 441 * Directory to which applications installed internally have their 442 * 32 bit native libraries copied. 443 */ 444 private File mAppLib32InstallDir; 445 446 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 447 // apps. 448 final File mDrmAppPrivateInstallDir; 449 450 // ---------------------------------------------------------------- 451 452 // Lock for state used when installing and doing other long running 453 // operations. Methods that must be called with this lock held have 454 // the suffix "LI". 455 final Object mInstallLock = new Object(); 456 457 // ---------------------------------------------------------------- 458 459 // Keys are String (package name), values are Package. This also serves 460 // as the lock for the global state. Methods that must be called with 461 // this lock held have the prefix "LP". 462 @GuardedBy("mPackages") 463 final ArrayMap<String, PackageParser.Package> mPackages = 464 new ArrayMap<String, PackageParser.Package>(); 465 466 // Tracks available target package names -> overlay package paths. 467 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 468 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 469 470 final Settings mSettings; 471 boolean mRestoredSettings; 472 473 // System configuration read by SystemConfig. 474 final int[] mGlobalGids; 475 final SparseArray<ArraySet<String>> mSystemPermissions; 476 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 477 478 // If mac_permissions.xml was found for seinfo labeling. 479 boolean mFoundPolicyFile; 480 481 // If a recursive restorecon of /data/data/<pkg> is needed. 482 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 483 484 public static final class SharedLibraryEntry { 485 public final String path; 486 public final String apk; 487 488 SharedLibraryEntry(String _path, String _apk) { 489 path = _path; 490 apk = _apk; 491 } 492 } 493 494 // Currently known shared libraries. 495 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 496 new ArrayMap<String, SharedLibraryEntry>(); 497 498 // All available activities, for your resolving pleasure. 499 final ActivityIntentResolver mActivities = 500 new ActivityIntentResolver(); 501 502 // All available receivers, for your resolving pleasure. 503 final ActivityIntentResolver mReceivers = 504 new ActivityIntentResolver(); 505 506 // All available services, for your resolving pleasure. 507 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 508 509 // All available providers, for your resolving pleasure. 510 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 511 512 // Mapping from provider base names (first directory in content URI codePath) 513 // to the provider information. 514 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 515 new ArrayMap<String, PackageParser.Provider>(); 516 517 // Mapping from instrumentation class names to info about them. 518 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 519 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 520 521 // Mapping from permission names to info about them. 522 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 523 new ArrayMap<String, PackageParser.PermissionGroup>(); 524 525 // Packages whose data we have transfered into another package, thus 526 // should no longer exist. 527 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 528 529 // Broadcast actions that are only available to the system. 530 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 531 532 /** List of packages waiting for verification. */ 533 final SparseArray<PackageVerificationState> mPendingVerification 534 = new SparseArray<PackageVerificationState>(); 535 536 /** Set of packages associated with each app op permission. */ 537 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 538 539 final PackageInstallerService mInstallerService; 540 541 private final PackageDexOptimizer mPackageDexOptimizer; 542 543 private AtomicInteger mNextMoveId = new AtomicInteger(); 544 private final MoveCallbacks mMoveCallbacks; 545 546 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 547 548 // Cache of users who need badging. 549 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 550 551 /** Token for keys in mPendingVerification. */ 552 private int mPendingVerificationToken = 0; 553 554 volatile boolean mSystemReady; 555 volatile boolean mSafeMode; 556 volatile boolean mHasSystemUidErrors; 557 558 ApplicationInfo mAndroidApplication; 559 final ActivityInfo mResolveActivity = new ActivityInfo(); 560 final ResolveInfo mResolveInfo = new ResolveInfo(); 561 ComponentName mResolveComponentName; 562 PackageParser.Package mPlatformPackage; 563 ComponentName mCustomResolverComponentName; 564 565 boolean mResolverReplaced = false; 566 567 private final ComponentName mIntentFilterVerifierComponent; 568 private int mIntentFilterVerificationToken = 0; 569 570 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 571 = new SparseArray<IntentFilterVerificationState>(); 572 573 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 574 new DefaultPermissionGrantPolicy(this); 575 576 private static class IFVerificationParams { 577 PackageParser.Package pkg; 578 boolean replacing; 579 int userId; 580 int verifierUid; 581 582 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 583 int _userId, int _verifierUid) { 584 pkg = _pkg; 585 replacing = _replacing; 586 userId = _userId; 587 replacing = _replacing; 588 verifierUid = _verifierUid; 589 } 590 } 591 592 private interface IntentFilterVerifier<T extends IntentFilter> { 593 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 594 T filter, String packageName); 595 void startVerifications(int userId); 596 void receiveVerificationResponse(int verificationId); 597 } 598 599 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 600 private Context mContext; 601 private ComponentName mIntentFilterVerifierComponent; 602 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 603 604 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 605 mContext = context; 606 mIntentFilterVerifierComponent = verifierComponent; 607 } 608 609 private String getDefaultScheme() { 610 return IntentFilter.SCHEME_HTTPS; 611 } 612 613 @Override 614 public void startVerifications(int userId) { 615 // Launch verifications requests 616 int count = mCurrentIntentFilterVerifications.size(); 617 for (int n=0; n<count; n++) { 618 int verificationId = mCurrentIntentFilterVerifications.get(n); 619 final IntentFilterVerificationState ivs = 620 mIntentFilterVerificationStates.get(verificationId); 621 622 String packageName = ivs.getPackageName(); 623 624 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 625 final int filterCount = filters.size(); 626 ArraySet<String> domainsSet = new ArraySet<>(); 627 for (int m=0; m<filterCount; m++) { 628 PackageParser.ActivityIntentInfo filter = filters.get(m); 629 domainsSet.addAll(filter.getHostsList()); 630 } 631 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 632 synchronized (mPackages) { 633 if (mSettings.createIntentFilterVerificationIfNeededLPw( 634 packageName, domainsList) != null) { 635 scheduleWriteSettingsLocked(); 636 } 637 } 638 sendVerificationRequest(userId, verificationId, ivs); 639 } 640 mCurrentIntentFilterVerifications.clear(); 641 } 642 643 private void sendVerificationRequest(int userId, int verificationId, 644 IntentFilterVerificationState ivs) { 645 646 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 647 verificationIntent.putExtra( 648 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 649 verificationId); 650 verificationIntent.putExtra( 651 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 652 getDefaultScheme()); 653 verificationIntent.putExtra( 654 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 655 ivs.getHostsString()); 656 verificationIntent.putExtra( 657 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 658 ivs.getPackageName()); 659 verificationIntent.setComponent(mIntentFilterVerifierComponent); 660 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 661 662 UserHandle user = new UserHandle(userId); 663 mContext.sendBroadcastAsUser(verificationIntent, user); 664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 665 "Sending IntentFilter verification broadcast"); 666 } 667 668 public void receiveVerificationResponse(int verificationId) { 669 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 670 671 final boolean verified = ivs.isVerified(); 672 673 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 674 final int count = filters.size(); 675 if (DEBUG_DOMAIN_VERIFICATION) { 676 Slog.i(TAG, "Received verification response " + verificationId 677 + " for " + count + " filters, verified=" + verified); 678 } 679 for (int n=0; n<count; n++) { 680 PackageParser.ActivityIntentInfo filter = filters.get(n); 681 filter.setVerified(verified); 682 683 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 684 + " verified with result:" + verified + " and hosts:" 685 + ivs.getHostsString()); 686 } 687 688 mIntentFilterVerificationStates.remove(verificationId); 689 690 final String packageName = ivs.getPackageName(); 691 IntentFilterVerificationInfo ivi = null; 692 693 synchronized (mPackages) { 694 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 695 } 696 if (ivi == null) { 697 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 698 + verificationId + " packageName:" + packageName); 699 return; 700 } 701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 702 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 703 704 synchronized (mPackages) { 705 if (verified) { 706 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 707 } else { 708 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 709 } 710 scheduleWriteSettingsLocked(); 711 712 final int userId = ivs.getUserId(); 713 if (userId != UserHandle.USER_ALL) { 714 final int userStatus = 715 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 716 717 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 718 boolean needUpdate = false; 719 720 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 721 // already been set by the User thru the Disambiguation dialog 722 switch (userStatus) { 723 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 724 if (verified) { 725 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 726 } else { 727 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 728 } 729 needUpdate = true; 730 break; 731 732 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 733 if (verified) { 734 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 735 needUpdate = true; 736 } 737 break; 738 739 default: 740 // Nothing to do 741 } 742 743 if (needUpdate) { 744 mSettings.updateIntentFilterVerificationStatusLPw( 745 packageName, updatedStatus, userId); 746 scheduleWritePackageRestrictionsLocked(userId); 747 } 748 } 749 } 750 } 751 752 @Override 753 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 754 ActivityIntentInfo filter, String packageName) { 755 if (!hasValidDomains(filter)) { 756 return false; 757 } 758 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 759 if (ivs == null) { 760 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 761 packageName); 762 } 763 if (DEBUG_DOMAIN_VERIFICATION) { 764 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 765 } 766 ivs.addFilter(filter); 767 return true; 768 } 769 770 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 771 int userId, int verificationId, String packageName) { 772 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 773 verifierUid, userId, packageName); 774 ivs.setPendingState(); 775 synchronized (mPackages) { 776 mIntentFilterVerificationStates.append(verificationId, ivs); 777 mCurrentIntentFilterVerifications.add(verificationId); 778 } 779 return ivs; 780 } 781 } 782 783 private static boolean hasValidDomains(ActivityIntentInfo filter) { 784 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 785 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 786 if (!hasHTTPorHTTPS) { 787 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 788 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 789 return false; 790 } 791 return true; 792 } 793 794 private IntentFilterVerifier mIntentFilterVerifier; 795 796 // Set of pending broadcasts for aggregating enable/disable of components. 797 static class PendingPackageBroadcasts { 798 // for each user id, a map of <package name -> components within that package> 799 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 800 801 public PendingPackageBroadcasts() { 802 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 803 } 804 805 public ArrayList<String> get(int userId, String packageName) { 806 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 807 return packages.get(packageName); 808 } 809 810 public void put(int userId, String packageName, ArrayList<String> components) { 811 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 812 packages.put(packageName, components); 813 } 814 815 public void remove(int userId, String packageName) { 816 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 817 if (packages != null) { 818 packages.remove(packageName); 819 } 820 } 821 822 public void remove(int userId) { 823 mUidMap.remove(userId); 824 } 825 826 public int userIdCount() { 827 return mUidMap.size(); 828 } 829 830 public int userIdAt(int n) { 831 return mUidMap.keyAt(n); 832 } 833 834 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 835 return mUidMap.get(userId); 836 } 837 838 public int size() { 839 // total number of pending broadcast entries across all userIds 840 int num = 0; 841 for (int i = 0; i< mUidMap.size(); i++) { 842 num += mUidMap.valueAt(i).size(); 843 } 844 return num; 845 } 846 847 public void clear() { 848 mUidMap.clear(); 849 } 850 851 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 852 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 853 if (map == null) { 854 map = new ArrayMap<String, ArrayList<String>>(); 855 mUidMap.put(userId, map); 856 } 857 return map; 858 } 859 } 860 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 861 862 // Service Connection to remote media container service to copy 863 // package uri's from external media onto secure containers 864 // or internal storage. 865 private IMediaContainerService mContainerService = null; 866 867 static final int SEND_PENDING_BROADCAST = 1; 868 static final int MCS_BOUND = 3; 869 static final int END_COPY = 4; 870 static final int INIT_COPY = 5; 871 static final int MCS_UNBIND = 6; 872 static final int START_CLEANING_PACKAGE = 7; 873 static final int FIND_INSTALL_LOC = 8; 874 static final int POST_INSTALL = 9; 875 static final int MCS_RECONNECT = 10; 876 static final int MCS_GIVE_UP = 11; 877 static final int UPDATED_MEDIA_STATUS = 12; 878 static final int WRITE_SETTINGS = 13; 879 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 880 static final int PACKAGE_VERIFIED = 15; 881 static final int CHECK_PENDING_VERIFICATION = 16; 882 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 883 static final int INTENT_FILTER_VERIFIED = 18; 884 885 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 886 887 // Delay time in millisecs 888 static final int BROADCAST_DELAY = 10 * 1000; 889 890 static UserManagerService sUserManager; 891 892 // Stores a list of users whose package restrictions file needs to be updated 893 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 894 895 final private DefaultContainerConnection mDefContainerConn = 896 new DefaultContainerConnection(); 897 class DefaultContainerConnection implements ServiceConnection { 898 public void onServiceConnected(ComponentName name, IBinder service) { 899 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 900 IMediaContainerService imcs = 901 IMediaContainerService.Stub.asInterface(service); 902 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 903 } 904 905 public void onServiceDisconnected(ComponentName name) { 906 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 907 } 908 } 909 910 // Recordkeeping of restore-after-install operations that are currently in flight 911 // between the Package Manager and the Backup Manager 912 class PostInstallData { 913 public InstallArgs args; 914 public PackageInstalledInfo res; 915 916 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 917 args = _a; 918 res = _r; 919 } 920 } 921 922 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 923 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 924 925 // XML tags for backup/restore of various bits of state 926 private static final String TAG_PREFERRED_BACKUP = "pa"; 927 private static final String TAG_DEFAULT_APPS = "da"; 928 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 929 930 private final String mRequiredVerifierPackage; 931 932 private final PackageUsage mPackageUsage = new PackageUsage(); 933 934 private class PackageUsage { 935 private static final int WRITE_INTERVAL 936 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 937 938 private final Object mFileLock = new Object(); 939 private final AtomicLong mLastWritten = new AtomicLong(0); 940 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 941 942 private boolean mIsHistoricalPackageUsageAvailable = true; 943 944 boolean isHistoricalPackageUsageAvailable() { 945 return mIsHistoricalPackageUsageAvailable; 946 } 947 948 void write(boolean force) { 949 if (force) { 950 writeInternal(); 951 return; 952 } 953 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 954 && !DEBUG_DEXOPT) { 955 return; 956 } 957 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 958 new Thread("PackageUsage_DiskWriter") { 959 @Override 960 public void run() { 961 try { 962 writeInternal(); 963 } finally { 964 mBackgroundWriteRunning.set(false); 965 } 966 } 967 }.start(); 968 } 969 } 970 971 private void writeInternal() { 972 synchronized (mPackages) { 973 synchronized (mFileLock) { 974 AtomicFile file = getFile(); 975 FileOutputStream f = null; 976 try { 977 f = file.startWrite(); 978 BufferedOutputStream out = new BufferedOutputStream(f); 979 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 980 StringBuilder sb = new StringBuilder(); 981 for (PackageParser.Package pkg : mPackages.values()) { 982 if (pkg.mLastPackageUsageTimeInMills == 0) { 983 continue; 984 } 985 sb.setLength(0); 986 sb.append(pkg.packageName); 987 sb.append(' '); 988 sb.append((long)pkg.mLastPackageUsageTimeInMills); 989 sb.append('\n'); 990 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 991 } 992 out.flush(); 993 file.finishWrite(f); 994 } catch (IOException e) { 995 if (f != null) { 996 file.failWrite(f); 997 } 998 Log.e(TAG, "Failed to write package usage times", e); 999 } 1000 } 1001 } 1002 mLastWritten.set(SystemClock.elapsedRealtime()); 1003 } 1004 1005 void readLP() { 1006 synchronized (mFileLock) { 1007 AtomicFile file = getFile(); 1008 BufferedInputStream in = null; 1009 try { 1010 in = new BufferedInputStream(file.openRead()); 1011 StringBuffer sb = new StringBuffer(); 1012 while (true) { 1013 String packageName = readToken(in, sb, ' '); 1014 if (packageName == null) { 1015 break; 1016 } 1017 String timeInMillisString = readToken(in, sb, '\n'); 1018 if (timeInMillisString == null) { 1019 throw new IOException("Failed to find last usage time for package " 1020 + packageName); 1021 } 1022 PackageParser.Package pkg = mPackages.get(packageName); 1023 if (pkg == null) { 1024 continue; 1025 } 1026 long timeInMillis; 1027 try { 1028 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1029 } catch (NumberFormatException e) { 1030 throw new IOException("Failed to parse " + timeInMillisString 1031 + " as a long.", e); 1032 } 1033 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1034 } 1035 } catch (FileNotFoundException expected) { 1036 mIsHistoricalPackageUsageAvailable = false; 1037 } catch (IOException e) { 1038 Log.w(TAG, "Failed to read package usage times", e); 1039 } finally { 1040 IoUtils.closeQuietly(in); 1041 } 1042 } 1043 mLastWritten.set(SystemClock.elapsedRealtime()); 1044 } 1045 1046 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1047 throws IOException { 1048 sb.setLength(0); 1049 while (true) { 1050 int ch = in.read(); 1051 if (ch == -1) { 1052 if (sb.length() == 0) { 1053 return null; 1054 } 1055 throw new IOException("Unexpected EOF"); 1056 } 1057 if (ch == endOfToken) { 1058 return sb.toString(); 1059 } 1060 sb.append((char)ch); 1061 } 1062 } 1063 1064 private AtomicFile getFile() { 1065 File dataDir = Environment.getDataDirectory(); 1066 File systemDir = new File(dataDir, "system"); 1067 File fname = new File(systemDir, "package-usage.list"); 1068 return new AtomicFile(fname); 1069 } 1070 } 1071 1072 class PackageHandler extends Handler { 1073 private boolean mBound = false; 1074 final ArrayList<HandlerParams> mPendingInstalls = 1075 new ArrayList<HandlerParams>(); 1076 1077 private boolean connectToService() { 1078 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1079 " DefaultContainerService"); 1080 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1081 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1082 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1083 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1084 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1085 mBound = true; 1086 return true; 1087 } 1088 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1089 return false; 1090 } 1091 1092 private void disconnectService() { 1093 mContainerService = null; 1094 mBound = false; 1095 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1096 mContext.unbindService(mDefContainerConn); 1097 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1098 } 1099 1100 PackageHandler(Looper looper) { 1101 super(looper); 1102 } 1103 1104 public void handleMessage(Message msg) { 1105 try { 1106 doHandleMessage(msg); 1107 } finally { 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1109 } 1110 } 1111 1112 void doHandleMessage(Message msg) { 1113 switch (msg.what) { 1114 case INIT_COPY: { 1115 HandlerParams params = (HandlerParams) msg.obj; 1116 int idx = mPendingInstalls.size(); 1117 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1118 // If a bind was already initiated we dont really 1119 // need to do anything. The pending install 1120 // will be processed later on. 1121 if (!mBound) { 1122 // If this is the only one pending we might 1123 // have to bind to the service again. 1124 if (!connectToService()) { 1125 Slog.e(TAG, "Failed to bind to media container service"); 1126 params.serviceError(); 1127 return; 1128 } else { 1129 // Once we bind to the service, the first 1130 // pending request will be processed. 1131 mPendingInstalls.add(idx, params); 1132 } 1133 } else { 1134 mPendingInstalls.add(idx, params); 1135 // Already bound to the service. Just make 1136 // sure we trigger off processing the first request. 1137 if (idx == 0) { 1138 mHandler.sendEmptyMessage(MCS_BOUND); 1139 } 1140 } 1141 break; 1142 } 1143 case MCS_BOUND: { 1144 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1145 if (msg.obj != null) { 1146 mContainerService = (IMediaContainerService) msg.obj; 1147 } 1148 if (mContainerService == null) { 1149 if (!mBound) { 1150 // Something seriously wrong since we are not bound and we are not 1151 // waiting for connection. Bail out. 1152 Slog.e(TAG, "Cannot bind to media container service"); 1153 for (HandlerParams params : mPendingInstalls) { 1154 // Indicate service bind error 1155 params.serviceError(); 1156 } 1157 mPendingInstalls.clear(); 1158 } else { 1159 Slog.w(TAG, "Waiting to connect to media container service"); 1160 } 1161 } else if (mPendingInstalls.size() > 0) { 1162 HandlerParams params = mPendingInstalls.get(0); 1163 if (params != null) { 1164 if (params.startCopy()) { 1165 // We are done... look for more work or to 1166 // go idle. 1167 if (DEBUG_SD_INSTALL) Log.i(TAG, 1168 "Checking for more work or unbind..."); 1169 // Delete pending install 1170 if (mPendingInstalls.size() > 0) { 1171 mPendingInstalls.remove(0); 1172 } 1173 if (mPendingInstalls.size() == 0) { 1174 if (mBound) { 1175 if (DEBUG_SD_INSTALL) Log.i(TAG, 1176 "Posting delayed MCS_UNBIND"); 1177 removeMessages(MCS_UNBIND); 1178 Message ubmsg = obtainMessage(MCS_UNBIND); 1179 // Unbind after a little delay, to avoid 1180 // continual thrashing. 1181 sendMessageDelayed(ubmsg, 10000); 1182 } 1183 } else { 1184 // There are more pending requests in queue. 1185 // Just post MCS_BOUND message to trigger processing 1186 // of next pending install. 1187 if (DEBUG_SD_INSTALL) Log.i(TAG, 1188 "Posting MCS_BOUND for next work"); 1189 mHandler.sendEmptyMessage(MCS_BOUND); 1190 } 1191 } 1192 } 1193 } else { 1194 // Should never happen ideally. 1195 Slog.w(TAG, "Empty queue"); 1196 } 1197 break; 1198 } 1199 case MCS_RECONNECT: { 1200 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1201 if (mPendingInstalls.size() > 0) { 1202 if (mBound) { 1203 disconnectService(); 1204 } 1205 if (!connectToService()) { 1206 Slog.e(TAG, "Failed to bind to media container service"); 1207 for (HandlerParams params : mPendingInstalls) { 1208 // Indicate service bind error 1209 params.serviceError(); 1210 } 1211 mPendingInstalls.clear(); 1212 } 1213 } 1214 break; 1215 } 1216 case MCS_UNBIND: { 1217 // If there is no actual work left, then time to unbind. 1218 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1219 1220 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1221 if (mBound) { 1222 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1223 1224 disconnectService(); 1225 } 1226 } else if (mPendingInstalls.size() > 0) { 1227 // There are more pending requests in queue. 1228 // Just post MCS_BOUND message to trigger processing 1229 // of next pending install. 1230 mHandler.sendEmptyMessage(MCS_BOUND); 1231 } 1232 1233 break; 1234 } 1235 case MCS_GIVE_UP: { 1236 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1237 mPendingInstalls.remove(0); 1238 break; 1239 } 1240 case SEND_PENDING_BROADCAST: { 1241 String packages[]; 1242 ArrayList<String> components[]; 1243 int size = 0; 1244 int uids[]; 1245 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1246 synchronized (mPackages) { 1247 if (mPendingBroadcasts == null) { 1248 return; 1249 } 1250 size = mPendingBroadcasts.size(); 1251 if (size <= 0) { 1252 // Nothing to be done. Just return 1253 return; 1254 } 1255 packages = new String[size]; 1256 components = new ArrayList[size]; 1257 uids = new int[size]; 1258 int i = 0; // filling out the above arrays 1259 1260 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1261 int packageUserId = mPendingBroadcasts.userIdAt(n); 1262 Iterator<Map.Entry<String, ArrayList<String>>> it 1263 = mPendingBroadcasts.packagesForUserId(packageUserId) 1264 .entrySet().iterator(); 1265 while (it.hasNext() && i < size) { 1266 Map.Entry<String, ArrayList<String>> ent = it.next(); 1267 packages[i] = ent.getKey(); 1268 components[i] = ent.getValue(); 1269 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1270 uids[i] = (ps != null) 1271 ? UserHandle.getUid(packageUserId, ps.appId) 1272 : -1; 1273 i++; 1274 } 1275 } 1276 size = i; 1277 mPendingBroadcasts.clear(); 1278 } 1279 // Send broadcasts 1280 for (int i = 0; i < size; i++) { 1281 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1282 } 1283 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1284 break; 1285 } 1286 case START_CLEANING_PACKAGE: { 1287 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1288 final String packageName = (String)msg.obj; 1289 final int userId = msg.arg1; 1290 final boolean andCode = msg.arg2 != 0; 1291 synchronized (mPackages) { 1292 if (userId == UserHandle.USER_ALL) { 1293 int[] users = sUserManager.getUserIds(); 1294 for (int user : users) { 1295 mSettings.addPackageToCleanLPw( 1296 new PackageCleanItem(user, packageName, andCode)); 1297 } 1298 } else { 1299 mSettings.addPackageToCleanLPw( 1300 new PackageCleanItem(userId, packageName, andCode)); 1301 } 1302 } 1303 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1304 startCleaningPackages(); 1305 } break; 1306 case POST_INSTALL: { 1307 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1308 PostInstallData data = mRunningInstalls.get(msg.arg1); 1309 mRunningInstalls.delete(msg.arg1); 1310 boolean deleteOld = false; 1311 1312 if (data != null) { 1313 InstallArgs args = data.args; 1314 PackageInstalledInfo res = data.res; 1315 1316 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1317 final String packageName = res.pkg.applicationInfo.packageName; 1318 res.removedInfo.sendBroadcast(false, true, false); 1319 Bundle extras = new Bundle(1); 1320 extras.putInt(Intent.EXTRA_UID, res.uid); 1321 1322 // Now that we successfully installed the package, grant runtime 1323 // permissions if requested before broadcasting the install. 1324 if ((args.installFlags 1325 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1326 grantRequestedRuntimePermissions(res.pkg, 1327 args.user.getIdentifier()); 1328 } 1329 1330 // Determine the set of users who are adding this 1331 // package for the first time vs. those who are seeing 1332 // an update. 1333 int[] firstUsers; 1334 int[] updateUsers = new int[0]; 1335 if (res.origUsers == null || res.origUsers.length == 0) { 1336 firstUsers = res.newUsers; 1337 } else { 1338 firstUsers = new int[0]; 1339 for (int i=0; i<res.newUsers.length; i++) { 1340 int user = res.newUsers[i]; 1341 boolean isNew = true; 1342 for (int j=0; j<res.origUsers.length; j++) { 1343 if (res.origUsers[j] == user) { 1344 isNew = false; 1345 break; 1346 } 1347 } 1348 if (isNew) { 1349 int[] newFirst = new int[firstUsers.length+1]; 1350 System.arraycopy(firstUsers, 0, newFirst, 0, 1351 firstUsers.length); 1352 newFirst[firstUsers.length] = user; 1353 firstUsers = newFirst; 1354 } else { 1355 int[] newUpdate = new int[updateUsers.length+1]; 1356 System.arraycopy(updateUsers, 0, newUpdate, 0, 1357 updateUsers.length); 1358 newUpdate[updateUsers.length] = user; 1359 updateUsers = newUpdate; 1360 } 1361 } 1362 } 1363 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1364 packageName, extras, null, null, firstUsers); 1365 final boolean update = res.removedInfo.removedPackage != null; 1366 if (update) { 1367 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1368 } 1369 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1370 packageName, extras, null, null, updateUsers); 1371 if (update) { 1372 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1373 packageName, extras, null, null, updateUsers); 1374 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1375 null, null, packageName, null, updateUsers); 1376 1377 // treat asec-hosted packages like removable media on upgrade 1378 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1379 if (DEBUG_INSTALL) { 1380 Slog.i(TAG, "upgrading pkg " + res.pkg 1381 + " is ASEC-hosted -> AVAILABLE"); 1382 } 1383 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1384 ArrayList<String> pkgList = new ArrayList<String>(1); 1385 pkgList.add(packageName); 1386 sendResourcesChangedBroadcast(true, true, 1387 pkgList,uidArray, null); 1388 } 1389 } 1390 if (res.removedInfo.args != null) { 1391 // Remove the replaced package's older resources safely now 1392 deleteOld = true; 1393 } 1394 1395 // If this app is a browser and it's newly-installed for some 1396 // users, clear any default-browser state in those users 1397 if (firstUsers.length > 0) { 1398 // the app's nature doesn't depend on the user, so we can just 1399 // check its browser nature in any user and generalize. 1400 if (packageIsBrowser(packageName, firstUsers[0])) { 1401 synchronized (mPackages) { 1402 for (int userId : firstUsers) { 1403 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1404 } 1405 } 1406 } 1407 } 1408 // Log current value of "unknown sources" setting 1409 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1410 getUnknownSourcesSettings()); 1411 } 1412 // Force a gc to clear up things 1413 Runtime.getRuntime().gc(); 1414 // We delete after a gc for applications on sdcard. 1415 if (deleteOld) { 1416 synchronized (mInstallLock) { 1417 res.removedInfo.args.doPostDeleteLI(true); 1418 } 1419 } 1420 if (args.observer != null) { 1421 try { 1422 Bundle extras = extrasForInstallResult(res); 1423 args.observer.onPackageInstalled(res.name, res.returnCode, 1424 res.returnMsg, extras); 1425 } catch (RemoteException e) { 1426 Slog.i(TAG, "Observer no longer exists."); 1427 } 1428 } 1429 } else { 1430 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1431 } 1432 } break; 1433 case UPDATED_MEDIA_STATUS: { 1434 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1435 boolean reportStatus = msg.arg1 == 1; 1436 boolean doGc = msg.arg2 == 1; 1437 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1438 if (doGc) { 1439 // Force a gc to clear up stale containers. 1440 Runtime.getRuntime().gc(); 1441 } 1442 if (msg.obj != null) { 1443 @SuppressWarnings("unchecked") 1444 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1446 // Unload containers 1447 unloadAllContainers(args); 1448 } 1449 if (reportStatus) { 1450 try { 1451 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1452 PackageHelper.getMountService().finishMediaUpdate(); 1453 } catch (RemoteException e) { 1454 Log.e(TAG, "MountService not running?"); 1455 } 1456 } 1457 } break; 1458 case WRITE_SETTINGS: { 1459 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1460 synchronized (mPackages) { 1461 removeMessages(WRITE_SETTINGS); 1462 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1463 mSettings.writeLPr(); 1464 mDirtyUsers.clear(); 1465 } 1466 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1467 } break; 1468 case WRITE_PACKAGE_RESTRICTIONS: { 1469 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1470 synchronized (mPackages) { 1471 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1472 for (int userId : mDirtyUsers) { 1473 mSettings.writePackageRestrictionsLPr(userId); 1474 } 1475 mDirtyUsers.clear(); 1476 } 1477 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1478 } break; 1479 case CHECK_PENDING_VERIFICATION: { 1480 final int verificationId = msg.arg1; 1481 final PackageVerificationState state = mPendingVerification.get(verificationId); 1482 1483 if ((state != null) && !state.timeoutExtended()) { 1484 final InstallArgs args = state.getInstallArgs(); 1485 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1486 1487 Slog.i(TAG, "Verification timed out for " + originUri); 1488 mPendingVerification.remove(verificationId); 1489 1490 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1491 1492 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1493 Slog.i(TAG, "Continuing with installation of " + originUri); 1494 state.setVerifierResponse(Binder.getCallingUid(), 1495 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1496 broadcastPackageVerified(verificationId, originUri, 1497 PackageManager.VERIFICATION_ALLOW, 1498 state.getInstallArgs().getUser()); 1499 try { 1500 ret = args.copyApk(mContainerService, true); 1501 } catch (RemoteException e) { 1502 Slog.e(TAG, "Could not contact the ContainerService"); 1503 } 1504 } else { 1505 broadcastPackageVerified(verificationId, originUri, 1506 PackageManager.VERIFICATION_REJECT, 1507 state.getInstallArgs().getUser()); 1508 } 1509 1510 processPendingInstall(args, ret); 1511 mHandler.sendEmptyMessage(MCS_UNBIND); 1512 } 1513 break; 1514 } 1515 case PACKAGE_VERIFIED: { 1516 final int verificationId = msg.arg1; 1517 1518 final PackageVerificationState state = mPendingVerification.get(verificationId); 1519 if (state == null) { 1520 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1521 break; 1522 } 1523 1524 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1525 1526 state.setVerifierResponse(response.callerUid, response.code); 1527 1528 if (state.isVerificationComplete()) { 1529 mPendingVerification.remove(verificationId); 1530 1531 final InstallArgs args = state.getInstallArgs(); 1532 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1533 1534 int ret; 1535 if (state.isInstallAllowed()) { 1536 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1537 broadcastPackageVerified(verificationId, originUri, 1538 response.code, state.getInstallArgs().getUser()); 1539 try { 1540 ret = args.copyApk(mContainerService, true); 1541 } catch (RemoteException e) { 1542 Slog.e(TAG, "Could not contact the ContainerService"); 1543 } 1544 } else { 1545 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1546 } 1547 1548 processPendingInstall(args, ret); 1549 1550 mHandler.sendEmptyMessage(MCS_UNBIND); 1551 } 1552 1553 break; 1554 } 1555 case START_INTENT_FILTER_VERIFICATIONS: { 1556 IFVerificationParams params = (IFVerificationParams) msg.obj; 1557 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1558 params.replacing, params.pkg); 1559 break; 1560 } 1561 case INTENT_FILTER_VERIFIED: { 1562 final int verificationId = msg.arg1; 1563 1564 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1565 verificationId); 1566 if (state == null) { 1567 Slog.w(TAG, "Invalid IntentFilter verification token " 1568 + verificationId + " received"); 1569 break; 1570 } 1571 1572 final int userId = state.getUserId(); 1573 1574 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1575 "Processing IntentFilter verification with token:" 1576 + verificationId + " and userId:" + userId); 1577 1578 final IntentFilterVerificationResponse response = 1579 (IntentFilterVerificationResponse) msg.obj; 1580 1581 state.setVerifierResponse(response.callerUid, response.code); 1582 1583 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1584 "IntentFilter verification with token:" + verificationId 1585 + " and userId:" + userId 1586 + " is settings verifier response with response code:" 1587 + response.code); 1588 1589 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1590 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1591 + response.getFailedDomainsString()); 1592 } 1593 1594 if (state.isVerificationComplete()) { 1595 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1596 } else { 1597 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1598 "IntentFilter verification with token:" + verificationId 1599 + " was not said to be complete"); 1600 } 1601 1602 break; 1603 } 1604 } 1605 } 1606 } 1607 1608 private StorageEventListener mStorageListener = new StorageEventListener() { 1609 @Override 1610 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1611 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1612 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1613 final String volumeUuid = vol.getFsUuid(); 1614 1615 // Clean up any users or apps that were removed or recreated 1616 // while this volume was missing 1617 reconcileUsers(volumeUuid); 1618 reconcileApps(volumeUuid); 1619 1620 // Clean up any install sessions that expired or were 1621 // cancelled while this volume was missing 1622 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1623 1624 loadPrivatePackages(vol); 1625 1626 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1627 unloadPrivatePackages(vol); 1628 } 1629 } 1630 1631 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1632 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1633 updateExternalMediaStatus(true, false); 1634 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1635 updateExternalMediaStatus(false, false); 1636 } 1637 } 1638 } 1639 1640 @Override 1641 public void onVolumeForgotten(String fsUuid) { 1642 // Remove any apps installed on the forgotten volume 1643 synchronized (mPackages) { 1644 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1645 for (PackageSetting ps : packages) { 1646 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1647 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1648 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1649 } 1650 1651 mSettings.writeLPr(); 1652 } 1653 } 1654 }; 1655 1656 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1657 if (userId >= UserHandle.USER_OWNER) { 1658 grantRequestedRuntimePermissionsForUser(pkg, userId); 1659 } else if (userId == UserHandle.USER_ALL) { 1660 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1661 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1662 } 1663 } 1664 1665 // We could have touched GID membership, so flush out packages.list 1666 synchronized (mPackages) { 1667 mSettings.writePackageListLPr(); 1668 } 1669 } 1670 1671 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1672 SettingBase sb = (SettingBase) pkg.mExtras; 1673 if (sb == null) { 1674 return; 1675 } 1676 1677 PermissionsState permissionsState = sb.getPermissionsState(); 1678 1679 for (String permission : pkg.requestedPermissions) { 1680 BasePermission bp = mSettings.mPermissions.get(permission); 1681 if (bp != null && bp.isRuntime()) { 1682 permissionsState.grantRuntimePermission(bp, userId); 1683 } 1684 } 1685 } 1686 1687 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1688 Bundle extras = null; 1689 switch (res.returnCode) { 1690 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1691 extras = new Bundle(); 1692 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1693 res.origPermission); 1694 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1695 res.origPackage); 1696 break; 1697 } 1698 case PackageManager.INSTALL_SUCCEEDED: { 1699 extras = new Bundle(); 1700 extras.putBoolean(Intent.EXTRA_REPLACING, 1701 res.removedInfo != null && res.removedInfo.removedPackage != null); 1702 break; 1703 } 1704 } 1705 return extras; 1706 } 1707 1708 void scheduleWriteSettingsLocked() { 1709 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1710 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1711 } 1712 } 1713 1714 void scheduleWritePackageRestrictionsLocked(int userId) { 1715 if (!sUserManager.exists(userId)) return; 1716 mDirtyUsers.add(userId); 1717 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1718 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1719 } 1720 } 1721 1722 public static PackageManagerService main(Context context, Installer installer, 1723 boolean factoryTest, boolean onlyCore) { 1724 PackageManagerService m = new PackageManagerService(context, installer, 1725 factoryTest, onlyCore); 1726 ServiceManager.addService("package", m); 1727 return m; 1728 } 1729 1730 static String[] splitString(String str, char sep) { 1731 int count = 1; 1732 int i = 0; 1733 while ((i=str.indexOf(sep, i)) >= 0) { 1734 count++; 1735 i++; 1736 } 1737 1738 String[] res = new String[count]; 1739 i=0; 1740 count = 0; 1741 int lastI=0; 1742 while ((i=str.indexOf(sep, i)) >= 0) { 1743 res[count] = str.substring(lastI, i); 1744 count++; 1745 i++; 1746 lastI = i; 1747 } 1748 res[count] = str.substring(lastI, str.length()); 1749 return res; 1750 } 1751 1752 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1753 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1754 Context.DISPLAY_SERVICE); 1755 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1756 } 1757 1758 public PackageManagerService(Context context, Installer installer, 1759 boolean factoryTest, boolean onlyCore) { 1760 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1761 SystemClock.uptimeMillis()); 1762 1763 if (mSdkVersion <= 0) { 1764 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1765 } 1766 1767 mContext = context; 1768 mFactoryTest = factoryTest; 1769 mOnlyCore = onlyCore; 1770 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1771 mMetrics = new DisplayMetrics(); 1772 mSettings = new Settings(mPackages); 1773 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1774 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1775 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1776 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1777 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1778 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1779 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1780 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1781 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1782 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1783 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1784 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1785 1786 // TODO: add a property to control this? 1787 long dexOptLRUThresholdInMinutes; 1788 if (mLazyDexOpt) { 1789 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1790 } else { 1791 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1792 } 1793 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1794 1795 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1796 if (separateProcesses != null && separateProcesses.length() > 0) { 1797 if ("*".equals(separateProcesses)) { 1798 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1799 mSeparateProcesses = null; 1800 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1801 } else { 1802 mDefParseFlags = 0; 1803 mSeparateProcesses = separateProcesses.split(","); 1804 Slog.w(TAG, "Running with debug.separate_processes: " 1805 + separateProcesses); 1806 } 1807 } else { 1808 mDefParseFlags = 0; 1809 mSeparateProcesses = null; 1810 } 1811 1812 mInstaller = installer; 1813 mPackageDexOptimizer = new PackageDexOptimizer(this); 1814 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1815 1816 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1817 FgThread.get().getLooper()); 1818 1819 getDefaultDisplayMetrics(context, mMetrics); 1820 1821 SystemConfig systemConfig = SystemConfig.getInstance(); 1822 mGlobalGids = systemConfig.getGlobalGids(); 1823 mSystemPermissions = systemConfig.getSystemPermissions(); 1824 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1825 1826 synchronized (mInstallLock) { 1827 // writer 1828 synchronized (mPackages) { 1829 mHandlerThread = new ServiceThread(TAG, 1830 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1831 mHandlerThread.start(); 1832 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1833 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1834 1835 File dataDir = Environment.getDataDirectory(); 1836 mAppDataDir = new File(dataDir, "data"); 1837 mAppInstallDir = new File(dataDir, "app"); 1838 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1839 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1840 mUserAppDataDir = new File(dataDir, "user"); 1841 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1842 1843 sUserManager = new UserManagerService(context, this, 1844 mInstallLock, mPackages); 1845 1846 // Propagate permission configuration in to package manager. 1847 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1848 = systemConfig.getPermissions(); 1849 for (int i=0; i<permConfig.size(); i++) { 1850 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1851 BasePermission bp = mSettings.mPermissions.get(perm.name); 1852 if (bp == null) { 1853 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1854 mSettings.mPermissions.put(perm.name, bp); 1855 } 1856 if (perm.gids != null) { 1857 bp.setGids(perm.gids, perm.perUser); 1858 } 1859 } 1860 1861 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1862 for (int i=0; i<libConfig.size(); i++) { 1863 mSharedLibraries.put(libConfig.keyAt(i), 1864 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1865 } 1866 1867 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1868 1869 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1870 mSdkVersion, mOnlyCore); 1871 1872 String customResolverActivity = Resources.getSystem().getString( 1873 R.string.config_customResolverActivity); 1874 if (TextUtils.isEmpty(customResolverActivity)) { 1875 customResolverActivity = null; 1876 } else { 1877 mCustomResolverComponentName = ComponentName.unflattenFromString( 1878 customResolverActivity); 1879 } 1880 1881 long startTime = SystemClock.uptimeMillis(); 1882 1883 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1884 startTime); 1885 1886 // Set flag to monitor and not change apk file paths when 1887 // scanning install directories. 1888 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1889 1890 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1891 1892 /** 1893 * Add everything in the in the boot class path to the 1894 * list of process files because dexopt will have been run 1895 * if necessary during zygote startup. 1896 */ 1897 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1898 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1899 1900 if (bootClassPath != null) { 1901 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1902 for (String element : bootClassPathElements) { 1903 alreadyDexOpted.add(element); 1904 } 1905 } else { 1906 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1907 } 1908 1909 if (systemServerClassPath != null) { 1910 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1911 for (String element : systemServerClassPathElements) { 1912 alreadyDexOpted.add(element); 1913 } 1914 } else { 1915 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1916 } 1917 1918 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1919 final String[] dexCodeInstructionSets = 1920 getDexCodeInstructionSets( 1921 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1922 1923 /** 1924 * Ensure all external libraries have had dexopt run on them. 1925 */ 1926 if (mSharedLibraries.size() > 0) { 1927 // NOTE: For now, we're compiling these system "shared libraries" 1928 // (and framework jars) into all available architectures. It's possible 1929 // to compile them only when we come across an app that uses them (there's 1930 // already logic for that in scanPackageLI) but that adds some complexity. 1931 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1932 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1933 final String lib = libEntry.path; 1934 if (lib == null) { 1935 continue; 1936 } 1937 1938 try { 1939 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1940 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1941 alreadyDexOpted.add(lib); 1942 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1943 } 1944 } catch (FileNotFoundException e) { 1945 Slog.w(TAG, "Library not found: " + lib); 1946 } catch (IOException e) { 1947 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1948 + e.getMessage()); 1949 } 1950 } 1951 } 1952 } 1953 1954 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1955 1956 // Gross hack for now: we know this file doesn't contain any 1957 // code, so don't dexopt it to avoid the resulting log spew. 1958 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1959 1960 // Gross hack for now: we know this file is only part of 1961 // the boot class path for art, so don't dexopt it to 1962 // avoid the resulting log spew. 1963 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1964 1965 /** 1966 * There are a number of commands implemented in Java, which 1967 * we currently need to do the dexopt on so that they can be 1968 * run from a non-root shell. 1969 */ 1970 String[] frameworkFiles = frameworkDir.list(); 1971 if (frameworkFiles != null) { 1972 // TODO: We could compile these only for the most preferred ABI. We should 1973 // first double check that the dex files for these commands are not referenced 1974 // by other system apps. 1975 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1976 for (int i=0; i<frameworkFiles.length; i++) { 1977 File libPath = new File(frameworkDir, frameworkFiles[i]); 1978 String path = libPath.getPath(); 1979 // Skip the file if we already did it. 1980 if (alreadyDexOpted.contains(path)) { 1981 continue; 1982 } 1983 // Skip the file if it is not a type we want to dexopt. 1984 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1985 continue; 1986 } 1987 try { 1988 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1989 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1990 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1991 } 1992 } catch (FileNotFoundException e) { 1993 Slog.w(TAG, "Jar not found: " + path); 1994 } catch (IOException e) { 1995 Slog.w(TAG, "Exception reading jar: " + path, e); 1996 } 1997 } 1998 } 1999 } 2000 2001 // Collect vendor overlay packages. 2002 // (Do this before scanning any apps.) 2003 // For security and version matching reason, only consider 2004 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2005 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2006 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2007 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2008 2009 // Find base frameworks (resource packages without code). 2010 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2011 | PackageParser.PARSE_IS_SYSTEM_DIR 2012 | PackageParser.PARSE_IS_PRIVILEGED, 2013 scanFlags | SCAN_NO_DEX, 0); 2014 2015 // Collected privileged system packages. 2016 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2017 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2018 | PackageParser.PARSE_IS_SYSTEM_DIR 2019 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2020 2021 // Collect ordinary system packages. 2022 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2023 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2024 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2025 2026 // Collect all vendor packages. 2027 File vendorAppDir = new File("/vendor/app"); 2028 try { 2029 vendorAppDir = vendorAppDir.getCanonicalFile(); 2030 } catch (IOException e) { 2031 // failed to look up canonical path, continue with original one 2032 } 2033 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2034 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2035 2036 // Collect all OEM packages. 2037 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2038 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2039 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2040 2041 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2042 mInstaller.moveFiles(); 2043 2044 // Prune any system packages that no longer exist. 2045 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2046 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2047 if (!mOnlyCore) { 2048 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2049 while (psit.hasNext()) { 2050 PackageSetting ps = psit.next(); 2051 2052 /* 2053 * If this is not a system app, it can't be a 2054 * disable system app. 2055 */ 2056 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2057 continue; 2058 } 2059 2060 /* 2061 * If the package is scanned, it's not erased. 2062 */ 2063 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2064 if (scannedPkg != null) { 2065 /* 2066 * If the system app is both scanned and in the 2067 * disabled packages list, then it must have been 2068 * added via OTA. Remove it from the currently 2069 * scanned package so the previously user-installed 2070 * application can be scanned. 2071 */ 2072 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2073 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2074 + ps.name + "; removing system app. Last known codePath=" 2075 + ps.codePathString + ", installStatus=" + ps.installStatus 2076 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2077 + scannedPkg.mVersionCode); 2078 removePackageLI(ps, true); 2079 expectingBetter.put(ps.name, ps.codePath); 2080 } 2081 2082 continue; 2083 } 2084 2085 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2086 psit.remove(); 2087 logCriticalInfo(Log.WARN, "System package " + ps.name 2088 + " no longer exists; wiping its data"); 2089 removeDataDirsLI(null, ps.name); 2090 } else { 2091 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2092 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2093 possiblyDeletedUpdatedSystemApps.add(ps.name); 2094 } 2095 } 2096 } 2097 } 2098 2099 //look for any incomplete package installations 2100 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2101 //clean up list 2102 for(int i = 0; i < deletePkgsList.size(); i++) { 2103 //clean up here 2104 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2105 } 2106 //delete tmp files 2107 deleteTempPackageFiles(); 2108 2109 // Remove any shared userIDs that have no associated packages 2110 mSettings.pruneSharedUsersLPw(); 2111 2112 if (!mOnlyCore) { 2113 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2114 SystemClock.uptimeMillis()); 2115 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2116 2117 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2118 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2119 2120 /** 2121 * Remove disable package settings for any updated system 2122 * apps that were removed via an OTA. If they're not a 2123 * previously-updated app, remove them completely. 2124 * Otherwise, just revoke their system-level permissions. 2125 */ 2126 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2127 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2128 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2129 2130 String msg; 2131 if (deletedPkg == null) { 2132 msg = "Updated system package " + deletedAppName 2133 + " no longer exists; wiping its data"; 2134 removeDataDirsLI(null, deletedAppName); 2135 } else { 2136 msg = "Updated system app + " + deletedAppName 2137 + " no longer present; removing system privileges for " 2138 + deletedAppName; 2139 2140 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2141 2142 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2143 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2144 } 2145 logCriticalInfo(Log.WARN, msg); 2146 } 2147 2148 /** 2149 * Make sure all system apps that we expected to appear on 2150 * the userdata partition actually showed up. If they never 2151 * appeared, crawl back and revive the system version. 2152 */ 2153 for (int i = 0; i < expectingBetter.size(); i++) { 2154 final String packageName = expectingBetter.keyAt(i); 2155 if (!mPackages.containsKey(packageName)) { 2156 final File scanFile = expectingBetter.valueAt(i); 2157 2158 logCriticalInfo(Log.WARN, "Expected better " + packageName 2159 + " but never showed up; reverting to system"); 2160 2161 final int reparseFlags; 2162 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2163 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2164 | PackageParser.PARSE_IS_SYSTEM_DIR 2165 | PackageParser.PARSE_IS_PRIVILEGED; 2166 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2167 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2168 | PackageParser.PARSE_IS_SYSTEM_DIR; 2169 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2170 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2171 | PackageParser.PARSE_IS_SYSTEM_DIR; 2172 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2173 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2174 | PackageParser.PARSE_IS_SYSTEM_DIR; 2175 } else { 2176 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2177 continue; 2178 } 2179 2180 mSettings.enableSystemPackageLPw(packageName); 2181 2182 try { 2183 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2184 } catch (PackageManagerException e) { 2185 Slog.e(TAG, "Failed to parse original system package: " 2186 + e.getMessage()); 2187 } 2188 } 2189 } 2190 } 2191 2192 // Now that we know all of the shared libraries, update all clients to have 2193 // the correct library paths. 2194 updateAllSharedLibrariesLPw(); 2195 2196 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2197 // NOTE: We ignore potential failures here during a system scan (like 2198 // the rest of the commands above) because there's precious little we 2199 // can do about it. A settings error is reported, though. 2200 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2201 false /* force dexopt */, false /* defer dexopt */); 2202 } 2203 2204 // Now that we know all the packages we are keeping, 2205 // read and update their last usage times. 2206 mPackageUsage.readLP(); 2207 2208 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2209 SystemClock.uptimeMillis()); 2210 Slog.i(TAG, "Time to scan packages: " 2211 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2212 + " seconds"); 2213 2214 // If the platform SDK has changed since the last time we booted, 2215 // we need to re-grant app permission to catch any new ones that 2216 // appear. This is really a hack, and means that apps can in some 2217 // cases get permissions that the user didn't initially explicitly 2218 // allow... it would be nice to have some better way to handle 2219 // this situation. 2220 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2221 != mSdkVersion; 2222 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2223 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2224 + "; regranting permissions for internal storage"); 2225 mSettings.mInternalSdkPlatform = mSdkVersion; 2226 2227 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2228 | (regrantPermissions 2229 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2230 : 0)); 2231 2232 // If this is the first boot, and it is a normal boot, then 2233 // we need to initialize the default preferred apps. 2234 if (!mRestoredSettings && !onlyCore) { 2235 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2236 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2237 } 2238 2239 // If this is first boot after an OTA, and a normal boot, then 2240 // we need to clear code cache directories. 2241 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2242 if (mIsUpgrade && !onlyCore) { 2243 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2244 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2245 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2246 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2247 } 2248 mSettings.mFingerprint = Build.FINGERPRINT; 2249 } 2250 2251 primeDomainVerificationsLPw(); 2252 checkDefaultBrowser(); 2253 2254 // All the changes are done during package scanning. 2255 mSettings.updateInternalDatabaseVersion(); 2256 2257 // can downgrade to reader 2258 mSettings.writeLPr(); 2259 2260 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2261 SystemClock.uptimeMillis()); 2262 2263 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2264 2265 mInstallerService = new PackageInstallerService(context, this); 2266 2267 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2268 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2269 mIntentFilterVerifierComponent); 2270 2271 } // synchronized (mPackages) 2272 } // synchronized (mInstallLock) 2273 2274 // Now after opening every single application zip, make sure they 2275 // are all flushed. Not really needed, but keeps things nice and 2276 // tidy. 2277 Runtime.getRuntime().gc(); 2278 2279 // Expose private service for system components to use. 2280 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2281 } 2282 2283 @Override 2284 public boolean isFirstBoot() { 2285 return !mRestoredSettings; 2286 } 2287 2288 @Override 2289 public boolean isOnlyCoreApps() { 2290 return mOnlyCore; 2291 } 2292 2293 @Override 2294 public boolean isUpgrade() { 2295 return mIsUpgrade; 2296 } 2297 2298 private String getRequiredVerifierLPr() { 2299 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2300 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2301 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2302 2303 String requiredVerifier = null; 2304 2305 final int N = receivers.size(); 2306 for (int i = 0; i < N; i++) { 2307 final ResolveInfo info = receivers.get(i); 2308 2309 if (info.activityInfo == null) { 2310 continue; 2311 } 2312 2313 final String packageName = info.activityInfo.packageName; 2314 2315 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2316 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2317 continue; 2318 } 2319 2320 if (requiredVerifier != null) { 2321 throw new RuntimeException("There can be only one required verifier"); 2322 } 2323 2324 requiredVerifier = packageName; 2325 } 2326 2327 return requiredVerifier; 2328 } 2329 2330 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2331 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2332 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2333 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2334 2335 ComponentName verifierComponentName = null; 2336 2337 int priority = -1000; 2338 final int N = receivers.size(); 2339 for (int i = 0; i < N; i++) { 2340 final ResolveInfo info = receivers.get(i); 2341 2342 if (info.activityInfo == null) { 2343 continue; 2344 } 2345 2346 final String packageName = info.activityInfo.packageName; 2347 2348 final PackageSetting ps = mSettings.mPackages.get(packageName); 2349 if (ps == null) { 2350 continue; 2351 } 2352 2353 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2354 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2355 continue; 2356 } 2357 2358 // Select the IntentFilterVerifier with the highest priority 2359 if (priority < info.priority) { 2360 priority = info.priority; 2361 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2362 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2363 + verifierComponentName + " with priority: " + info.priority); 2364 } 2365 } 2366 2367 return verifierComponentName; 2368 } 2369 2370 private void primeDomainVerificationsLPw() { 2371 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2372 boolean updated = false; 2373 ArraySet<String> allHostsSet = new ArraySet<>(); 2374 for (PackageParser.Package pkg : mPackages.values()) { 2375 final String packageName = pkg.packageName; 2376 if (!hasDomainURLs(pkg)) { 2377 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2378 "package with no domain URLs: " + packageName); 2379 continue; 2380 } 2381 if (!pkg.isSystemApp()) { 2382 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2383 "No priming domain verifications for a non system package : " + 2384 packageName); 2385 continue; 2386 } 2387 for (PackageParser.Activity a : pkg.activities) { 2388 for (ActivityIntentInfo filter : a.intents) { 2389 if (hasValidDomains(filter)) { 2390 allHostsSet.addAll(filter.getHostsList()); 2391 } 2392 } 2393 } 2394 if (allHostsSet.size() == 0) { 2395 allHostsSet.add("*"); 2396 } 2397 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2398 IntentFilterVerificationInfo ivi = 2399 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2400 if (ivi != null) { 2401 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2402 "Priming domain verifications for package: " + packageName + 2403 " with hosts:" + ivi.getDomainsString()); 2404 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2405 updated = true; 2406 } 2407 else { 2408 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2409 "No priming domain verifications for package: " + packageName); 2410 } 2411 allHostsSet.clear(); 2412 } 2413 if (updated) { 2414 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2415 "Will need to write primed domain verifications"); 2416 } 2417 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2418 } 2419 2420 private void applyFactoryDefaultBrowserLPw(int userId) { 2421 // The default browser app's package name is stored in a string resource, 2422 // with a product-specific overlay used for vendor customization. 2423 String browserPkg = mContext.getResources().getString( 2424 com.android.internal.R.string.default_browser); 2425 if (browserPkg != null) { 2426 // non-empty string => required to be a known package 2427 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2428 if (ps == null) { 2429 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2430 browserPkg = null; 2431 } else { 2432 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2433 } 2434 } 2435 2436 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2437 // default. If there's more than one, just leave everything alone. 2438 if (browserPkg == null) { 2439 calculateDefaultBrowserLPw(userId); 2440 } 2441 } 2442 2443 private void calculateDefaultBrowserLPw(int userId) { 2444 List<String> allBrowsers = resolveAllBrowserApps(userId); 2445 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2446 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2447 } 2448 2449 private List<String> resolveAllBrowserApps(int userId) { 2450 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2451 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2452 PackageManager.MATCH_ALL, userId); 2453 2454 final int count = list.size(); 2455 List<String> result = new ArrayList<String>(count); 2456 for (int i=0; i<count; i++) { 2457 ResolveInfo info = list.get(i); 2458 if (info.activityInfo == null 2459 || !info.handleAllWebDataURI 2460 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2461 || result.contains(info.activityInfo.packageName)) { 2462 continue; 2463 } 2464 result.add(info.activityInfo.packageName); 2465 } 2466 2467 return result; 2468 } 2469 2470 private boolean packageIsBrowser(String packageName, int userId) { 2471 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2472 PackageManager.MATCH_ALL, userId); 2473 final int N = list.size(); 2474 for (int i = 0; i < N; i++) { 2475 ResolveInfo info = list.get(i); 2476 if (packageName.equals(info.activityInfo.packageName)) { 2477 return true; 2478 } 2479 } 2480 return false; 2481 } 2482 2483 private void checkDefaultBrowser() { 2484 final int myUserId = UserHandle.myUserId(); 2485 final String packageName = getDefaultBrowserPackageName(myUserId); 2486 if (packageName != null) { 2487 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2488 if (info == null) { 2489 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2490 synchronized (mPackages) { 2491 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2492 } 2493 } 2494 } 2495 } 2496 2497 @Override 2498 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2499 throws RemoteException { 2500 try { 2501 return super.onTransact(code, data, reply, flags); 2502 } catch (RuntimeException e) { 2503 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2504 Slog.wtf(TAG, "Package Manager Crash", e); 2505 } 2506 throw e; 2507 } 2508 } 2509 2510 void cleanupInstallFailedPackage(PackageSetting ps) { 2511 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2512 2513 removeDataDirsLI(ps.volumeUuid, ps.name); 2514 if (ps.codePath != null) { 2515 if (ps.codePath.isDirectory()) { 2516 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2517 } else { 2518 ps.codePath.delete(); 2519 } 2520 } 2521 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2522 if (ps.resourcePath.isDirectory()) { 2523 FileUtils.deleteContents(ps.resourcePath); 2524 } 2525 ps.resourcePath.delete(); 2526 } 2527 mSettings.removePackageLPw(ps.name); 2528 } 2529 2530 static int[] appendInts(int[] cur, int[] add) { 2531 if (add == null) return cur; 2532 if (cur == null) return add; 2533 final int N = add.length; 2534 for (int i=0; i<N; i++) { 2535 cur = appendInt(cur, add[i]); 2536 } 2537 return cur; 2538 } 2539 2540 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2541 if (!sUserManager.exists(userId)) return null; 2542 final PackageSetting ps = (PackageSetting) p.mExtras; 2543 if (ps == null) { 2544 return null; 2545 } 2546 2547 final PermissionsState permissionsState = ps.getPermissionsState(); 2548 2549 final int[] gids = permissionsState.computeGids(userId); 2550 final Set<String> permissions = permissionsState.getPermissions(userId); 2551 final PackageUserState state = ps.readUserState(userId); 2552 2553 return PackageParser.generatePackageInfo(p, gids, flags, 2554 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2555 } 2556 2557 @Override 2558 public boolean isPackageFrozen(String packageName) { 2559 synchronized (mPackages) { 2560 final PackageSetting ps = mSettings.mPackages.get(packageName); 2561 if (ps != null) { 2562 return ps.frozen; 2563 } 2564 } 2565 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2566 return true; 2567 } 2568 2569 @Override 2570 public boolean isPackageAvailable(String packageName, int userId) { 2571 if (!sUserManager.exists(userId)) return false; 2572 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2573 synchronized (mPackages) { 2574 PackageParser.Package p = mPackages.get(packageName); 2575 if (p != null) { 2576 final PackageSetting ps = (PackageSetting) p.mExtras; 2577 if (ps != null) { 2578 final PackageUserState state = ps.readUserState(userId); 2579 if (state != null) { 2580 return PackageParser.isAvailable(state); 2581 } 2582 } 2583 } 2584 } 2585 return false; 2586 } 2587 2588 @Override 2589 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2590 if (!sUserManager.exists(userId)) return null; 2591 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2592 // reader 2593 synchronized (mPackages) { 2594 PackageParser.Package p = mPackages.get(packageName); 2595 if (DEBUG_PACKAGE_INFO) 2596 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2597 if (p != null) { 2598 return generatePackageInfo(p, flags, userId); 2599 } 2600 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2601 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2602 } 2603 } 2604 return null; 2605 } 2606 2607 @Override 2608 public String[] currentToCanonicalPackageNames(String[] names) { 2609 String[] out = new String[names.length]; 2610 // reader 2611 synchronized (mPackages) { 2612 for (int i=names.length-1; i>=0; i--) { 2613 PackageSetting ps = mSettings.mPackages.get(names[i]); 2614 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2615 } 2616 } 2617 return out; 2618 } 2619 2620 @Override 2621 public String[] canonicalToCurrentPackageNames(String[] names) { 2622 String[] out = new String[names.length]; 2623 // reader 2624 synchronized (mPackages) { 2625 for (int i=names.length-1; i>=0; i--) { 2626 String cur = mSettings.mRenamedPackages.get(names[i]); 2627 out[i] = cur != null ? cur : names[i]; 2628 } 2629 } 2630 return out; 2631 } 2632 2633 @Override 2634 public int getPackageUid(String packageName, int userId) { 2635 if (!sUserManager.exists(userId)) return -1; 2636 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2637 2638 // reader 2639 synchronized (mPackages) { 2640 PackageParser.Package p = mPackages.get(packageName); 2641 if(p != null) { 2642 return UserHandle.getUid(userId, p.applicationInfo.uid); 2643 } 2644 PackageSetting ps = mSettings.mPackages.get(packageName); 2645 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2646 return -1; 2647 } 2648 p = ps.pkg; 2649 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2650 } 2651 } 2652 2653 @Override 2654 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2655 if (!sUserManager.exists(userId)) { 2656 return null; 2657 } 2658 2659 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2660 "getPackageGids"); 2661 2662 // reader 2663 synchronized (mPackages) { 2664 PackageParser.Package p = mPackages.get(packageName); 2665 if (DEBUG_PACKAGE_INFO) { 2666 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2667 } 2668 if (p != null) { 2669 PackageSetting ps = (PackageSetting) p.mExtras; 2670 return ps.getPermissionsState().computeGids(userId); 2671 } 2672 } 2673 2674 return null; 2675 } 2676 2677 @Override 2678 public int getMountExternalMode(int uid) { 2679 if (Process.isIsolated(uid)) { 2680 return Zygote.MOUNT_EXTERNAL_NONE; 2681 } else { 2682 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2683 return Zygote.MOUNT_EXTERNAL_WRITE; 2684 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2685 return Zygote.MOUNT_EXTERNAL_READ; 2686 } else { 2687 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2688 } 2689 } 2690 } 2691 2692 static PermissionInfo generatePermissionInfo( 2693 BasePermission bp, int flags) { 2694 if (bp.perm != null) { 2695 return PackageParser.generatePermissionInfo(bp.perm, flags); 2696 } 2697 PermissionInfo pi = new PermissionInfo(); 2698 pi.name = bp.name; 2699 pi.packageName = bp.sourcePackage; 2700 pi.nonLocalizedLabel = bp.name; 2701 pi.protectionLevel = bp.protectionLevel; 2702 return pi; 2703 } 2704 2705 @Override 2706 public PermissionInfo getPermissionInfo(String name, int flags) { 2707 // reader 2708 synchronized (mPackages) { 2709 final BasePermission p = mSettings.mPermissions.get(name); 2710 if (p != null) { 2711 return generatePermissionInfo(p, flags); 2712 } 2713 return null; 2714 } 2715 } 2716 2717 @Override 2718 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2719 // reader 2720 synchronized (mPackages) { 2721 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2722 for (BasePermission p : mSettings.mPermissions.values()) { 2723 if (group == null) { 2724 if (p.perm == null || p.perm.info.group == null) { 2725 out.add(generatePermissionInfo(p, flags)); 2726 } 2727 } else { 2728 if (p.perm != null && group.equals(p.perm.info.group)) { 2729 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2730 } 2731 } 2732 } 2733 2734 if (out.size() > 0) { 2735 return out; 2736 } 2737 return mPermissionGroups.containsKey(group) ? out : null; 2738 } 2739 } 2740 2741 @Override 2742 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2743 // reader 2744 synchronized (mPackages) { 2745 return PackageParser.generatePermissionGroupInfo( 2746 mPermissionGroups.get(name), flags); 2747 } 2748 } 2749 2750 @Override 2751 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2752 // reader 2753 synchronized (mPackages) { 2754 final int N = mPermissionGroups.size(); 2755 ArrayList<PermissionGroupInfo> out 2756 = new ArrayList<PermissionGroupInfo>(N); 2757 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2758 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2759 } 2760 return out; 2761 } 2762 } 2763 2764 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2765 int userId) { 2766 if (!sUserManager.exists(userId)) return null; 2767 PackageSetting ps = mSettings.mPackages.get(packageName); 2768 if (ps != null) { 2769 if (ps.pkg == null) { 2770 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2771 flags, userId); 2772 if (pInfo != null) { 2773 return pInfo.applicationInfo; 2774 } 2775 return null; 2776 } 2777 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2778 ps.readUserState(userId), userId); 2779 } 2780 return null; 2781 } 2782 2783 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2784 int userId) { 2785 if (!sUserManager.exists(userId)) return null; 2786 PackageSetting ps = mSettings.mPackages.get(packageName); 2787 if (ps != null) { 2788 PackageParser.Package pkg = ps.pkg; 2789 if (pkg == null) { 2790 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2791 return null; 2792 } 2793 // Only data remains, so we aren't worried about code paths 2794 pkg = new PackageParser.Package(packageName); 2795 pkg.applicationInfo.packageName = packageName; 2796 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2797 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2798 pkg.applicationInfo.dataDir = Environment 2799 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2800 .getAbsolutePath(); 2801 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2802 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2803 } 2804 return generatePackageInfo(pkg, flags, userId); 2805 } 2806 return null; 2807 } 2808 2809 @Override 2810 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2811 if (!sUserManager.exists(userId)) return null; 2812 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2813 // writer 2814 synchronized (mPackages) { 2815 PackageParser.Package p = mPackages.get(packageName); 2816 if (DEBUG_PACKAGE_INFO) Log.v( 2817 TAG, "getApplicationInfo " + packageName 2818 + ": " + p); 2819 if (p != null) { 2820 PackageSetting ps = mSettings.mPackages.get(packageName); 2821 if (ps == null) return null; 2822 // Note: isEnabledLP() does not apply here - always return info 2823 return PackageParser.generateApplicationInfo( 2824 p, flags, ps.readUserState(userId), userId); 2825 } 2826 if ("android".equals(packageName)||"system".equals(packageName)) { 2827 return mAndroidApplication; 2828 } 2829 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2830 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2831 } 2832 } 2833 return null; 2834 } 2835 2836 @Override 2837 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2838 final IPackageDataObserver observer) { 2839 mContext.enforceCallingOrSelfPermission( 2840 android.Manifest.permission.CLEAR_APP_CACHE, null); 2841 // Queue up an async operation since clearing cache may take a little while. 2842 mHandler.post(new Runnable() { 2843 public void run() { 2844 mHandler.removeCallbacks(this); 2845 int retCode = -1; 2846 synchronized (mInstallLock) { 2847 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2848 if (retCode < 0) { 2849 Slog.w(TAG, "Couldn't clear application caches"); 2850 } 2851 } 2852 if (observer != null) { 2853 try { 2854 observer.onRemoveCompleted(null, (retCode >= 0)); 2855 } catch (RemoteException e) { 2856 Slog.w(TAG, "RemoveException when invoking call back"); 2857 } 2858 } 2859 } 2860 }); 2861 } 2862 2863 @Override 2864 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2865 final IntentSender pi) { 2866 mContext.enforceCallingOrSelfPermission( 2867 android.Manifest.permission.CLEAR_APP_CACHE, null); 2868 // Queue up an async operation since clearing cache may take a little while. 2869 mHandler.post(new Runnable() { 2870 public void run() { 2871 mHandler.removeCallbacks(this); 2872 int retCode = -1; 2873 synchronized (mInstallLock) { 2874 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2875 if (retCode < 0) { 2876 Slog.w(TAG, "Couldn't clear application caches"); 2877 } 2878 } 2879 if(pi != null) { 2880 try { 2881 // Callback via pending intent 2882 int code = (retCode >= 0) ? 1 : 0; 2883 pi.sendIntent(null, code, null, 2884 null, null); 2885 } catch (SendIntentException e1) { 2886 Slog.i(TAG, "Failed to send pending intent"); 2887 } 2888 } 2889 } 2890 }); 2891 } 2892 2893 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2894 synchronized (mInstallLock) { 2895 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2896 throw new IOException("Failed to free enough space"); 2897 } 2898 } 2899 } 2900 2901 @Override 2902 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2903 if (!sUserManager.exists(userId)) return null; 2904 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2905 synchronized (mPackages) { 2906 PackageParser.Activity a = mActivities.mActivities.get(component); 2907 2908 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2909 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2910 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2911 if (ps == null) return null; 2912 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2913 userId); 2914 } 2915 if (mResolveComponentName.equals(component)) { 2916 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2917 new PackageUserState(), userId); 2918 } 2919 } 2920 return null; 2921 } 2922 2923 @Override 2924 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2925 String resolvedType) { 2926 synchronized (mPackages) { 2927 PackageParser.Activity a = mActivities.mActivities.get(component); 2928 if (a == null) { 2929 return false; 2930 } 2931 for (int i=0; i<a.intents.size(); i++) { 2932 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2933 intent.getData(), intent.getCategories(), TAG) >= 0) { 2934 return true; 2935 } 2936 } 2937 return false; 2938 } 2939 } 2940 2941 @Override 2942 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2943 if (!sUserManager.exists(userId)) return null; 2944 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2945 synchronized (mPackages) { 2946 PackageParser.Activity a = mReceivers.mActivities.get(component); 2947 if (DEBUG_PACKAGE_INFO) Log.v( 2948 TAG, "getReceiverInfo " + component + ": " + a); 2949 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2950 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2951 if (ps == null) return null; 2952 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2953 userId); 2954 } 2955 } 2956 return null; 2957 } 2958 2959 @Override 2960 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2961 if (!sUserManager.exists(userId)) return null; 2962 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2963 synchronized (mPackages) { 2964 PackageParser.Service s = mServices.mServices.get(component); 2965 if (DEBUG_PACKAGE_INFO) Log.v( 2966 TAG, "getServiceInfo " + component + ": " + s); 2967 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2968 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2969 if (ps == null) return null; 2970 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2971 userId); 2972 } 2973 } 2974 return null; 2975 } 2976 2977 @Override 2978 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2979 if (!sUserManager.exists(userId)) return null; 2980 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2981 synchronized (mPackages) { 2982 PackageParser.Provider p = mProviders.mProviders.get(component); 2983 if (DEBUG_PACKAGE_INFO) Log.v( 2984 TAG, "getProviderInfo " + component + ": " + p); 2985 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2986 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2987 if (ps == null) return null; 2988 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2989 userId); 2990 } 2991 } 2992 return null; 2993 } 2994 2995 @Override 2996 public String[] getSystemSharedLibraryNames() { 2997 Set<String> libSet; 2998 synchronized (mPackages) { 2999 libSet = mSharedLibraries.keySet(); 3000 int size = libSet.size(); 3001 if (size > 0) { 3002 String[] libs = new String[size]; 3003 libSet.toArray(libs); 3004 return libs; 3005 } 3006 } 3007 return null; 3008 } 3009 3010 /** 3011 * @hide 3012 */ 3013 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3014 synchronized (mPackages) { 3015 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3016 if (lib != null && lib.apk != null) { 3017 return mPackages.get(lib.apk); 3018 } 3019 } 3020 return null; 3021 } 3022 3023 @Override 3024 public FeatureInfo[] getSystemAvailableFeatures() { 3025 Collection<FeatureInfo> featSet; 3026 synchronized (mPackages) { 3027 featSet = mAvailableFeatures.values(); 3028 int size = featSet.size(); 3029 if (size > 0) { 3030 FeatureInfo[] features = new FeatureInfo[size+1]; 3031 featSet.toArray(features); 3032 FeatureInfo fi = new FeatureInfo(); 3033 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3034 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3035 features[size] = fi; 3036 return features; 3037 } 3038 } 3039 return null; 3040 } 3041 3042 @Override 3043 public boolean hasSystemFeature(String name) { 3044 synchronized (mPackages) { 3045 return mAvailableFeatures.containsKey(name); 3046 } 3047 } 3048 3049 private void checkValidCaller(int uid, int userId) { 3050 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3051 return; 3052 3053 throw new SecurityException("Caller uid=" + uid 3054 + " is not privileged to communicate with user=" + userId); 3055 } 3056 3057 @Override 3058 public int checkPermission(String permName, String pkgName, int userId) { 3059 if (!sUserManager.exists(userId)) { 3060 return PackageManager.PERMISSION_DENIED; 3061 } 3062 3063 synchronized (mPackages) { 3064 final PackageParser.Package p = mPackages.get(pkgName); 3065 if (p != null && p.mExtras != null) { 3066 final PackageSetting ps = (PackageSetting) p.mExtras; 3067 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3068 return PackageManager.PERMISSION_GRANTED; 3069 } 3070 } 3071 } 3072 3073 return PackageManager.PERMISSION_DENIED; 3074 } 3075 3076 @Override 3077 public int checkUidPermission(String permName, int uid) { 3078 final int userId = UserHandle.getUserId(uid); 3079 3080 if (!sUserManager.exists(userId)) { 3081 return PackageManager.PERMISSION_DENIED; 3082 } 3083 3084 synchronized (mPackages) { 3085 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3086 if (obj != null) { 3087 final SettingBase ps = (SettingBase) obj; 3088 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3089 return PackageManager.PERMISSION_GRANTED; 3090 } 3091 } else { 3092 ArraySet<String> perms = mSystemPermissions.get(uid); 3093 if (perms != null && perms.contains(permName)) { 3094 return PackageManager.PERMISSION_GRANTED; 3095 } 3096 } 3097 } 3098 3099 return PackageManager.PERMISSION_DENIED; 3100 } 3101 3102 /** 3103 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3104 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3105 * @param checkShell TODO(yamasani): 3106 * @param message the message to log on security exception 3107 */ 3108 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3109 boolean checkShell, String message) { 3110 if (userId < 0) { 3111 throw new IllegalArgumentException("Invalid userId " + userId); 3112 } 3113 if (checkShell) { 3114 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3115 } 3116 if (userId == UserHandle.getUserId(callingUid)) return; 3117 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3118 if (requireFullPermission) { 3119 mContext.enforceCallingOrSelfPermission( 3120 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3121 } else { 3122 try { 3123 mContext.enforceCallingOrSelfPermission( 3124 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3125 } catch (SecurityException se) { 3126 mContext.enforceCallingOrSelfPermission( 3127 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3128 } 3129 } 3130 } 3131 } 3132 3133 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3134 if (callingUid == Process.SHELL_UID) { 3135 if (userHandle >= 0 3136 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3137 throw new SecurityException("Shell does not have permission to access user " 3138 + userHandle); 3139 } else if (userHandle < 0) { 3140 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3141 + Debug.getCallers(3)); 3142 } 3143 } 3144 } 3145 3146 private BasePermission findPermissionTreeLP(String permName) { 3147 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3148 if (permName.startsWith(bp.name) && 3149 permName.length() > bp.name.length() && 3150 permName.charAt(bp.name.length()) == '.') { 3151 return bp; 3152 } 3153 } 3154 return null; 3155 } 3156 3157 private BasePermission checkPermissionTreeLP(String permName) { 3158 if (permName != null) { 3159 BasePermission bp = findPermissionTreeLP(permName); 3160 if (bp != null) { 3161 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3162 return bp; 3163 } 3164 throw new SecurityException("Calling uid " 3165 + Binder.getCallingUid() 3166 + " is not allowed to add to permission tree " 3167 + bp.name + " owned by uid " + bp.uid); 3168 } 3169 } 3170 throw new SecurityException("No permission tree found for " + permName); 3171 } 3172 3173 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3174 if (s1 == null) { 3175 return s2 == null; 3176 } 3177 if (s2 == null) { 3178 return false; 3179 } 3180 if (s1.getClass() != s2.getClass()) { 3181 return false; 3182 } 3183 return s1.equals(s2); 3184 } 3185 3186 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3187 if (pi1.icon != pi2.icon) return false; 3188 if (pi1.logo != pi2.logo) return false; 3189 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3190 if (!compareStrings(pi1.name, pi2.name)) return false; 3191 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3192 // We'll take care of setting this one. 3193 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3194 // These are not currently stored in settings. 3195 //if (!compareStrings(pi1.group, pi2.group)) return false; 3196 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3197 //if (pi1.labelRes != pi2.labelRes) return false; 3198 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3199 return true; 3200 } 3201 3202 int permissionInfoFootprint(PermissionInfo info) { 3203 int size = info.name.length(); 3204 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3205 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3206 return size; 3207 } 3208 3209 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3210 int size = 0; 3211 for (BasePermission perm : mSettings.mPermissions.values()) { 3212 if (perm.uid == tree.uid) { 3213 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3214 } 3215 } 3216 return size; 3217 } 3218 3219 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3220 // We calculate the max size of permissions defined by this uid and throw 3221 // if that plus the size of 'info' would exceed our stated maximum. 3222 if (tree.uid != Process.SYSTEM_UID) { 3223 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3224 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3225 throw new SecurityException("Permission tree size cap exceeded"); 3226 } 3227 } 3228 } 3229 3230 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3231 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3232 throw new SecurityException("Label must be specified in permission"); 3233 } 3234 BasePermission tree = checkPermissionTreeLP(info.name); 3235 BasePermission bp = mSettings.mPermissions.get(info.name); 3236 boolean added = bp == null; 3237 boolean changed = true; 3238 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3239 if (added) { 3240 enforcePermissionCapLocked(info, tree); 3241 bp = new BasePermission(info.name, tree.sourcePackage, 3242 BasePermission.TYPE_DYNAMIC); 3243 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3244 throw new SecurityException( 3245 "Not allowed to modify non-dynamic permission " 3246 + info.name); 3247 } else { 3248 if (bp.protectionLevel == fixedLevel 3249 && bp.perm.owner.equals(tree.perm.owner) 3250 && bp.uid == tree.uid 3251 && comparePermissionInfos(bp.perm.info, info)) { 3252 changed = false; 3253 } 3254 } 3255 bp.protectionLevel = fixedLevel; 3256 info = new PermissionInfo(info); 3257 info.protectionLevel = fixedLevel; 3258 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3259 bp.perm.info.packageName = tree.perm.info.packageName; 3260 bp.uid = tree.uid; 3261 if (added) { 3262 mSettings.mPermissions.put(info.name, bp); 3263 } 3264 if (changed) { 3265 if (!async) { 3266 mSettings.writeLPr(); 3267 } else { 3268 scheduleWriteSettingsLocked(); 3269 } 3270 } 3271 return added; 3272 } 3273 3274 @Override 3275 public boolean addPermission(PermissionInfo info) { 3276 synchronized (mPackages) { 3277 return addPermissionLocked(info, false); 3278 } 3279 } 3280 3281 @Override 3282 public boolean addPermissionAsync(PermissionInfo info) { 3283 synchronized (mPackages) { 3284 return addPermissionLocked(info, true); 3285 } 3286 } 3287 3288 @Override 3289 public void removePermission(String name) { 3290 synchronized (mPackages) { 3291 checkPermissionTreeLP(name); 3292 BasePermission bp = mSettings.mPermissions.get(name); 3293 if (bp != null) { 3294 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3295 throw new SecurityException( 3296 "Not allowed to modify non-dynamic permission " 3297 + name); 3298 } 3299 mSettings.mPermissions.remove(name); 3300 mSettings.writeLPr(); 3301 } 3302 } 3303 } 3304 3305 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3306 BasePermission bp) { 3307 int index = pkg.requestedPermissions.indexOf(bp.name); 3308 if (index == -1) { 3309 throw new SecurityException("Package " + pkg.packageName 3310 + " has not requested permission " + bp.name); 3311 } 3312 if (!bp.isRuntime()) { 3313 throw new SecurityException("Permission " + bp.name 3314 + " is not a changeable permission type"); 3315 } 3316 } 3317 3318 @Override 3319 public void grantRuntimePermission(String packageName, String name, final int userId) { 3320 if (!sUserManager.exists(userId)) { 3321 Log.e(TAG, "No such user:" + userId); 3322 return; 3323 } 3324 3325 mContext.enforceCallingOrSelfPermission( 3326 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3327 "grantRuntimePermission"); 3328 3329 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3330 "grantRuntimePermission"); 3331 3332 final int uid; 3333 final SettingBase sb; 3334 3335 synchronized (mPackages) { 3336 final PackageParser.Package pkg = mPackages.get(packageName); 3337 if (pkg == null) { 3338 throw new IllegalArgumentException("Unknown package: " + packageName); 3339 } 3340 3341 final BasePermission bp = mSettings.mPermissions.get(name); 3342 if (bp == null) { 3343 throw new IllegalArgumentException("Unknown permission: " + name); 3344 } 3345 3346 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3347 3348 uid = pkg.applicationInfo.uid; 3349 sb = (SettingBase) pkg.mExtras; 3350 if (sb == null) { 3351 throw new IllegalArgumentException("Unknown package: " + packageName); 3352 } 3353 3354 final PermissionsState permissionsState = sb.getPermissionsState(); 3355 3356 final int flags = permissionsState.getPermissionFlags(name, userId); 3357 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3358 throw new SecurityException("Cannot grant system fixed permission: " 3359 + name + " for package: " + packageName); 3360 } 3361 3362 final int result = permissionsState.grantRuntimePermission(bp, userId); 3363 switch (result) { 3364 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3365 return; 3366 } 3367 3368 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3369 mHandler.post(new Runnable() { 3370 @Override 3371 public void run() { 3372 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3373 } 3374 }); 3375 } break; 3376 } 3377 3378 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3379 3380 // Not critical if that is lost - app has to request again. 3381 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3382 } 3383 3384 if (READ_EXTERNAL_STORAGE.equals(name) 3385 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3386 final long token = Binder.clearCallingIdentity(); 3387 try { 3388 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3389 storage.remountUid(uid); 3390 } finally { 3391 Binder.restoreCallingIdentity(token); 3392 } 3393 } 3394 } 3395 3396 @Override 3397 public void revokeRuntimePermission(String packageName, String name, int userId) { 3398 if (!sUserManager.exists(userId)) { 3399 Log.e(TAG, "No such user:" + userId); 3400 return; 3401 } 3402 3403 mContext.enforceCallingOrSelfPermission( 3404 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3405 "revokeRuntimePermission"); 3406 3407 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3408 "revokeRuntimePermission"); 3409 3410 final SettingBase sb; 3411 3412 synchronized (mPackages) { 3413 final PackageParser.Package pkg = mPackages.get(packageName); 3414 if (pkg == null) { 3415 throw new IllegalArgumentException("Unknown package: " + packageName); 3416 } 3417 3418 final BasePermission bp = mSettings.mPermissions.get(name); 3419 if (bp == null) { 3420 throw new IllegalArgumentException("Unknown permission: " + name); 3421 } 3422 3423 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3424 3425 sb = (SettingBase) pkg.mExtras; 3426 if (sb == null) { 3427 throw new IllegalArgumentException("Unknown package: " + packageName); 3428 } 3429 3430 final PermissionsState permissionsState = sb.getPermissionsState(); 3431 3432 final int flags = permissionsState.getPermissionFlags(name, userId); 3433 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3434 throw new SecurityException("Cannot revoke system fixed permission: " 3435 + name + " for package: " + packageName); 3436 } 3437 3438 if (permissionsState.revokeRuntimePermission(bp, userId) == 3439 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3440 return; 3441 } 3442 3443 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3444 3445 // Critical, after this call app should never have the permission. 3446 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3447 } 3448 3449 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3450 } 3451 3452 @Override 3453 public void resetRuntimePermissions() { 3454 mContext.enforceCallingOrSelfPermission( 3455 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3456 "revokeRuntimePermission"); 3457 3458 int callingUid = Binder.getCallingUid(); 3459 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3460 mContext.enforceCallingOrSelfPermission( 3461 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3462 "resetRuntimePermissions"); 3463 } 3464 3465 final int[] userIds; 3466 3467 synchronized (mPackages) { 3468 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3469 final int userCount = UserManagerService.getInstance().getUserIds().length; 3470 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3471 } 3472 3473 for (int userId : userIds) { 3474 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3475 } 3476 } 3477 3478 @Override 3479 public int getPermissionFlags(String name, String packageName, int userId) { 3480 if (!sUserManager.exists(userId)) { 3481 return 0; 3482 } 3483 3484 mContext.enforceCallingOrSelfPermission( 3485 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3486 "getPermissionFlags"); 3487 3488 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3489 "getPermissionFlags"); 3490 3491 synchronized (mPackages) { 3492 final PackageParser.Package pkg = mPackages.get(packageName); 3493 if (pkg == null) { 3494 throw new IllegalArgumentException("Unknown package: " + packageName); 3495 } 3496 3497 final BasePermission bp = mSettings.mPermissions.get(name); 3498 if (bp == null) { 3499 throw new IllegalArgumentException("Unknown permission: " + name); 3500 } 3501 3502 SettingBase sb = (SettingBase) pkg.mExtras; 3503 if (sb == null) { 3504 throw new IllegalArgumentException("Unknown package: " + packageName); 3505 } 3506 3507 PermissionsState permissionsState = sb.getPermissionsState(); 3508 return permissionsState.getPermissionFlags(name, userId); 3509 } 3510 } 3511 3512 @Override 3513 public void updatePermissionFlags(String name, String packageName, int flagMask, 3514 int flagValues, int userId) { 3515 if (!sUserManager.exists(userId)) { 3516 return; 3517 } 3518 3519 mContext.enforceCallingOrSelfPermission( 3520 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3521 "updatePermissionFlags"); 3522 3523 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3524 "updatePermissionFlags"); 3525 3526 // Only the system can change system fixed flags. 3527 if (getCallingUid() != Process.SYSTEM_UID) { 3528 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3529 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3530 } 3531 3532 synchronized (mPackages) { 3533 final PackageParser.Package pkg = mPackages.get(packageName); 3534 if (pkg == null) { 3535 throw new IllegalArgumentException("Unknown package: " + packageName); 3536 } 3537 3538 final BasePermission bp = mSettings.mPermissions.get(name); 3539 if (bp == null) { 3540 throw new IllegalArgumentException("Unknown permission: " + name); 3541 } 3542 3543 SettingBase sb = (SettingBase) pkg.mExtras; 3544 if (sb == null) { 3545 throw new IllegalArgumentException("Unknown package: " + packageName); 3546 } 3547 3548 PermissionsState permissionsState = sb.getPermissionsState(); 3549 3550 // Only the package manager can change flags for system component permissions. 3551 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3552 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3553 return; 3554 } 3555 3556 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3557 3558 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3559 // Install and runtime permissions are stored in different places, 3560 // so figure out what permission changed and persist the change. 3561 if (permissionsState.getInstallPermissionState(name) != null) { 3562 scheduleWriteSettingsLocked(); 3563 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3564 || hadState) { 3565 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3566 } 3567 } 3568 } 3569 } 3570 3571 /** 3572 * Update the permission flags for all packages and runtime permissions of a user in order 3573 * to allow device or profile owner to remove POLICY_FIXED. 3574 */ 3575 @Override 3576 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3577 if (!sUserManager.exists(userId)) { 3578 return; 3579 } 3580 3581 mContext.enforceCallingOrSelfPermission( 3582 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3583 "updatePermissionFlagsForAllApps"); 3584 3585 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3586 "updatePermissionFlagsForAllApps"); 3587 3588 // Only the system can change system fixed flags. 3589 if (getCallingUid() != Process.SYSTEM_UID) { 3590 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3591 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3592 } 3593 3594 synchronized (mPackages) { 3595 boolean changed = false; 3596 final int packageCount = mPackages.size(); 3597 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3598 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3599 SettingBase sb = (SettingBase) pkg.mExtras; 3600 if (sb == null) { 3601 continue; 3602 } 3603 PermissionsState permissionsState = sb.getPermissionsState(); 3604 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3605 userId, flagMask, flagValues); 3606 } 3607 if (changed) { 3608 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3609 } 3610 } 3611 } 3612 3613 @Override 3614 public boolean shouldShowRequestPermissionRationale(String permissionName, 3615 String packageName, int userId) { 3616 if (UserHandle.getCallingUserId() != userId) { 3617 mContext.enforceCallingPermission( 3618 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3619 "canShowRequestPermissionRationale for user " + userId); 3620 } 3621 3622 final int uid = getPackageUid(packageName, userId); 3623 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3624 return false; 3625 } 3626 3627 if (checkPermission(permissionName, packageName, userId) 3628 == PackageManager.PERMISSION_GRANTED) { 3629 return false; 3630 } 3631 3632 final int flags; 3633 3634 final long identity = Binder.clearCallingIdentity(); 3635 try { 3636 flags = getPermissionFlags(permissionName, 3637 packageName, userId); 3638 } finally { 3639 Binder.restoreCallingIdentity(identity); 3640 } 3641 3642 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3643 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3644 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3645 3646 if ((flags & fixedFlags) != 0) { 3647 return false; 3648 } 3649 3650 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3651 } 3652 3653 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3654 BasePermission bp = mSettings.mPermissions.get(permission); 3655 if (bp == null) { 3656 throw new SecurityException("Missing " + permission + " permission"); 3657 } 3658 3659 SettingBase sb = (SettingBase) pkg.mExtras; 3660 PermissionsState permissionsState = sb.getPermissionsState(); 3661 3662 if (permissionsState.grantInstallPermission(bp) != 3663 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3664 scheduleWriteSettingsLocked(); 3665 } 3666 } 3667 3668 @Override 3669 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3670 mContext.enforceCallingOrSelfPermission( 3671 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3672 "addOnPermissionsChangeListener"); 3673 3674 synchronized (mPackages) { 3675 mOnPermissionChangeListeners.addListenerLocked(listener); 3676 } 3677 } 3678 3679 @Override 3680 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3681 synchronized (mPackages) { 3682 mOnPermissionChangeListeners.removeListenerLocked(listener); 3683 } 3684 } 3685 3686 @Override 3687 public boolean isProtectedBroadcast(String actionName) { 3688 synchronized (mPackages) { 3689 return mProtectedBroadcasts.contains(actionName); 3690 } 3691 } 3692 3693 @Override 3694 public int checkSignatures(String pkg1, String pkg2) { 3695 synchronized (mPackages) { 3696 final PackageParser.Package p1 = mPackages.get(pkg1); 3697 final PackageParser.Package p2 = mPackages.get(pkg2); 3698 if (p1 == null || p1.mExtras == null 3699 || p2 == null || p2.mExtras == null) { 3700 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3701 } 3702 return compareSignatures(p1.mSignatures, p2.mSignatures); 3703 } 3704 } 3705 3706 @Override 3707 public int checkUidSignatures(int uid1, int uid2) { 3708 // Map to base uids. 3709 uid1 = UserHandle.getAppId(uid1); 3710 uid2 = UserHandle.getAppId(uid2); 3711 // reader 3712 synchronized (mPackages) { 3713 Signature[] s1; 3714 Signature[] s2; 3715 Object obj = mSettings.getUserIdLPr(uid1); 3716 if (obj != null) { 3717 if (obj instanceof SharedUserSetting) { 3718 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3719 } else if (obj instanceof PackageSetting) { 3720 s1 = ((PackageSetting)obj).signatures.mSignatures; 3721 } else { 3722 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3723 } 3724 } else { 3725 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3726 } 3727 obj = mSettings.getUserIdLPr(uid2); 3728 if (obj != null) { 3729 if (obj instanceof SharedUserSetting) { 3730 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3731 } else if (obj instanceof PackageSetting) { 3732 s2 = ((PackageSetting)obj).signatures.mSignatures; 3733 } else { 3734 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3735 } 3736 } else { 3737 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3738 } 3739 return compareSignatures(s1, s2); 3740 } 3741 } 3742 3743 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3744 final long identity = Binder.clearCallingIdentity(); 3745 try { 3746 if (sb instanceof SharedUserSetting) { 3747 SharedUserSetting sus = (SharedUserSetting) sb; 3748 final int packageCount = sus.packages.size(); 3749 for (int i = 0; i < packageCount; i++) { 3750 PackageSetting susPs = sus.packages.valueAt(i); 3751 if (userId == UserHandle.USER_ALL) { 3752 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3753 } else { 3754 final int uid = UserHandle.getUid(userId, susPs.appId); 3755 killUid(uid, reason); 3756 } 3757 } 3758 } else if (sb instanceof PackageSetting) { 3759 PackageSetting ps = (PackageSetting) sb; 3760 if (userId == UserHandle.USER_ALL) { 3761 killApplication(ps.pkg.packageName, ps.appId, reason); 3762 } else { 3763 final int uid = UserHandle.getUid(userId, ps.appId); 3764 killUid(uid, reason); 3765 } 3766 } 3767 } finally { 3768 Binder.restoreCallingIdentity(identity); 3769 } 3770 } 3771 3772 private static void killUid(int uid, String reason) { 3773 IActivityManager am = ActivityManagerNative.getDefault(); 3774 if (am != null) { 3775 try { 3776 am.killUid(uid, reason); 3777 } catch (RemoteException e) { 3778 /* ignore - same process */ 3779 } 3780 } 3781 } 3782 3783 /** 3784 * Compares two sets of signatures. Returns: 3785 * <br /> 3786 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3787 * <br /> 3788 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3789 * <br /> 3790 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3791 * <br /> 3792 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3793 * <br /> 3794 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3795 */ 3796 static int compareSignatures(Signature[] s1, Signature[] s2) { 3797 if (s1 == null) { 3798 return s2 == null 3799 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3800 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3801 } 3802 3803 if (s2 == null) { 3804 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3805 } 3806 3807 if (s1.length != s2.length) { 3808 return PackageManager.SIGNATURE_NO_MATCH; 3809 } 3810 3811 // Since both signature sets are of size 1, we can compare without HashSets. 3812 if (s1.length == 1) { 3813 return s1[0].equals(s2[0]) ? 3814 PackageManager.SIGNATURE_MATCH : 3815 PackageManager.SIGNATURE_NO_MATCH; 3816 } 3817 3818 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3819 for (Signature sig : s1) { 3820 set1.add(sig); 3821 } 3822 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3823 for (Signature sig : s2) { 3824 set2.add(sig); 3825 } 3826 // Make sure s2 contains all signatures in s1. 3827 if (set1.equals(set2)) { 3828 return PackageManager.SIGNATURE_MATCH; 3829 } 3830 return PackageManager.SIGNATURE_NO_MATCH; 3831 } 3832 3833 /** 3834 * If the database version for this type of package (internal storage or 3835 * external storage) is less than the version where package signatures 3836 * were updated, return true. 3837 */ 3838 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3839 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3840 DatabaseVersion.SIGNATURE_END_ENTITY)) 3841 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3842 DatabaseVersion.SIGNATURE_END_ENTITY)); 3843 } 3844 3845 /** 3846 * Used for backward compatibility to make sure any packages with 3847 * certificate chains get upgraded to the new style. {@code existingSigs} 3848 * will be in the old format (since they were stored on disk from before the 3849 * system upgrade) and {@code scannedSigs} will be in the newer format. 3850 */ 3851 private int compareSignaturesCompat(PackageSignatures existingSigs, 3852 PackageParser.Package scannedPkg) { 3853 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3854 return PackageManager.SIGNATURE_NO_MATCH; 3855 } 3856 3857 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3858 for (Signature sig : existingSigs.mSignatures) { 3859 existingSet.add(sig); 3860 } 3861 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3862 for (Signature sig : scannedPkg.mSignatures) { 3863 try { 3864 Signature[] chainSignatures = sig.getChainSignatures(); 3865 for (Signature chainSig : chainSignatures) { 3866 scannedCompatSet.add(chainSig); 3867 } 3868 } catch (CertificateEncodingException e) { 3869 scannedCompatSet.add(sig); 3870 } 3871 } 3872 /* 3873 * Make sure the expanded scanned set contains all signatures in the 3874 * existing one. 3875 */ 3876 if (scannedCompatSet.equals(existingSet)) { 3877 // Migrate the old signatures to the new scheme. 3878 existingSigs.assignSignatures(scannedPkg.mSignatures); 3879 // The new KeySets will be re-added later in the scanning process. 3880 synchronized (mPackages) { 3881 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3882 } 3883 return PackageManager.SIGNATURE_MATCH; 3884 } 3885 return PackageManager.SIGNATURE_NO_MATCH; 3886 } 3887 3888 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3889 if (isExternal(scannedPkg)) { 3890 return mSettings.isExternalDatabaseVersionOlderThan( 3891 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3892 } else { 3893 return mSettings.isInternalDatabaseVersionOlderThan( 3894 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3895 } 3896 } 3897 3898 private int compareSignaturesRecover(PackageSignatures existingSigs, 3899 PackageParser.Package scannedPkg) { 3900 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3901 return PackageManager.SIGNATURE_NO_MATCH; 3902 } 3903 3904 String msg = null; 3905 try { 3906 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3907 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3908 + scannedPkg.packageName); 3909 return PackageManager.SIGNATURE_MATCH; 3910 } 3911 } catch (CertificateException e) { 3912 msg = e.getMessage(); 3913 } 3914 3915 logCriticalInfo(Log.INFO, 3916 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3917 return PackageManager.SIGNATURE_NO_MATCH; 3918 } 3919 3920 @Override 3921 public String[] getPackagesForUid(int uid) { 3922 uid = UserHandle.getAppId(uid); 3923 // reader 3924 synchronized (mPackages) { 3925 Object obj = mSettings.getUserIdLPr(uid); 3926 if (obj instanceof SharedUserSetting) { 3927 final SharedUserSetting sus = (SharedUserSetting) obj; 3928 final int N = sus.packages.size(); 3929 final String[] res = new String[N]; 3930 final Iterator<PackageSetting> it = sus.packages.iterator(); 3931 int i = 0; 3932 while (it.hasNext()) { 3933 res[i++] = it.next().name; 3934 } 3935 return res; 3936 } else if (obj instanceof PackageSetting) { 3937 final PackageSetting ps = (PackageSetting) obj; 3938 return new String[] { ps.name }; 3939 } 3940 } 3941 return null; 3942 } 3943 3944 @Override 3945 public String getNameForUid(int uid) { 3946 // reader 3947 synchronized (mPackages) { 3948 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3949 if (obj instanceof SharedUserSetting) { 3950 final SharedUserSetting sus = (SharedUserSetting) obj; 3951 return sus.name + ":" + sus.userId; 3952 } else if (obj instanceof PackageSetting) { 3953 final PackageSetting ps = (PackageSetting) obj; 3954 return ps.name; 3955 } 3956 } 3957 return null; 3958 } 3959 3960 @Override 3961 public int getUidForSharedUser(String sharedUserName) { 3962 if(sharedUserName == null) { 3963 return -1; 3964 } 3965 // reader 3966 synchronized (mPackages) { 3967 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3968 if (suid == null) { 3969 return -1; 3970 } 3971 return suid.userId; 3972 } 3973 } 3974 3975 @Override 3976 public int getFlagsForUid(int uid) { 3977 synchronized (mPackages) { 3978 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3979 if (obj instanceof SharedUserSetting) { 3980 final SharedUserSetting sus = (SharedUserSetting) obj; 3981 return sus.pkgFlags; 3982 } else if (obj instanceof PackageSetting) { 3983 final PackageSetting ps = (PackageSetting) obj; 3984 return ps.pkgFlags; 3985 } 3986 } 3987 return 0; 3988 } 3989 3990 @Override 3991 public int getPrivateFlagsForUid(int uid) { 3992 synchronized (mPackages) { 3993 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3994 if (obj instanceof SharedUserSetting) { 3995 final SharedUserSetting sus = (SharedUserSetting) obj; 3996 return sus.pkgPrivateFlags; 3997 } else if (obj instanceof PackageSetting) { 3998 final PackageSetting ps = (PackageSetting) obj; 3999 return ps.pkgPrivateFlags; 4000 } 4001 } 4002 return 0; 4003 } 4004 4005 @Override 4006 public boolean isUidPrivileged(int uid) { 4007 uid = UserHandle.getAppId(uid); 4008 // reader 4009 synchronized (mPackages) { 4010 Object obj = mSettings.getUserIdLPr(uid); 4011 if (obj instanceof SharedUserSetting) { 4012 final SharedUserSetting sus = (SharedUserSetting) obj; 4013 final Iterator<PackageSetting> it = sus.packages.iterator(); 4014 while (it.hasNext()) { 4015 if (it.next().isPrivileged()) { 4016 return true; 4017 } 4018 } 4019 } else if (obj instanceof PackageSetting) { 4020 final PackageSetting ps = (PackageSetting) obj; 4021 return ps.isPrivileged(); 4022 } 4023 } 4024 return false; 4025 } 4026 4027 @Override 4028 public String[] getAppOpPermissionPackages(String permissionName) { 4029 synchronized (mPackages) { 4030 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4031 if (pkgs == null) { 4032 return null; 4033 } 4034 return pkgs.toArray(new String[pkgs.size()]); 4035 } 4036 } 4037 4038 @Override 4039 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4040 int flags, int userId) { 4041 if (!sUserManager.exists(userId)) return null; 4042 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4043 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4044 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4045 } 4046 4047 @Override 4048 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4049 IntentFilter filter, int match, ComponentName activity) { 4050 final int userId = UserHandle.getCallingUserId(); 4051 if (DEBUG_PREFERRED) { 4052 Log.v(TAG, "setLastChosenActivity intent=" + intent 4053 + " resolvedType=" + resolvedType 4054 + " flags=" + flags 4055 + " filter=" + filter 4056 + " match=" + match 4057 + " activity=" + activity); 4058 filter.dump(new PrintStreamPrinter(System.out), " "); 4059 } 4060 intent.setComponent(null); 4061 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4062 // Find any earlier preferred or last chosen entries and nuke them 4063 findPreferredActivity(intent, resolvedType, 4064 flags, query, 0, false, true, false, userId); 4065 // Add the new activity as the last chosen for this filter 4066 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4067 "Setting last chosen"); 4068 } 4069 4070 @Override 4071 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4072 final int userId = UserHandle.getCallingUserId(); 4073 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4074 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4075 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4076 false, false, false, userId); 4077 } 4078 4079 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4080 int flags, List<ResolveInfo> query, int userId) { 4081 if (query != null) { 4082 final int N = query.size(); 4083 if (N == 1) { 4084 return query.get(0); 4085 } else if (N > 1) { 4086 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4087 // If there is more than one activity with the same priority, 4088 // then let the user decide between them. 4089 ResolveInfo r0 = query.get(0); 4090 ResolveInfo r1 = query.get(1); 4091 if (DEBUG_INTENT_MATCHING || debug) { 4092 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4093 + r1.activityInfo.name + "=" + r1.priority); 4094 } 4095 // If the first activity has a higher priority, or a different 4096 // default, then it is always desireable to pick it. 4097 if (r0.priority != r1.priority 4098 || r0.preferredOrder != r1.preferredOrder 4099 || r0.isDefault != r1.isDefault) { 4100 return query.get(0); 4101 } 4102 // If we have saved a preference for a preferred activity for 4103 // this Intent, use that. 4104 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4105 flags, query, r0.priority, true, false, debug, userId); 4106 if (ri != null) { 4107 return ri; 4108 } 4109 if (userId != 0) { 4110 ri = new ResolveInfo(mResolveInfo); 4111 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4112 ri.activityInfo.applicationInfo = new ApplicationInfo( 4113 ri.activityInfo.applicationInfo); 4114 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4115 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4116 return ri; 4117 } 4118 return mResolveInfo; 4119 } 4120 } 4121 return null; 4122 } 4123 4124 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4125 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4126 final int N = query.size(); 4127 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4128 .get(userId); 4129 // Get the list of persistent preferred activities that handle the intent 4130 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4131 List<PersistentPreferredActivity> pprefs = ppir != null 4132 ? ppir.queryIntent(intent, resolvedType, 4133 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4134 : null; 4135 if (pprefs != null && pprefs.size() > 0) { 4136 final int M = pprefs.size(); 4137 for (int i=0; i<M; i++) { 4138 final PersistentPreferredActivity ppa = pprefs.get(i); 4139 if (DEBUG_PREFERRED || debug) { 4140 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4141 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4142 + "\n component=" + ppa.mComponent); 4143 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4144 } 4145 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4146 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4147 if (DEBUG_PREFERRED || debug) { 4148 Slog.v(TAG, "Found persistent preferred activity:"); 4149 if (ai != null) { 4150 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4151 } else { 4152 Slog.v(TAG, " null"); 4153 } 4154 } 4155 if (ai == null) { 4156 // This previously registered persistent preferred activity 4157 // component is no longer known. Ignore it and do NOT remove it. 4158 continue; 4159 } 4160 for (int j=0; j<N; j++) { 4161 final ResolveInfo ri = query.get(j); 4162 if (!ri.activityInfo.applicationInfo.packageName 4163 .equals(ai.applicationInfo.packageName)) { 4164 continue; 4165 } 4166 if (!ri.activityInfo.name.equals(ai.name)) { 4167 continue; 4168 } 4169 // Found a persistent preference that can handle the intent. 4170 if (DEBUG_PREFERRED || debug) { 4171 Slog.v(TAG, "Returning persistent preferred activity: " + 4172 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4173 } 4174 return ri; 4175 } 4176 } 4177 } 4178 return null; 4179 } 4180 4181 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4182 List<ResolveInfo> query, int priority, boolean always, 4183 boolean removeMatches, boolean debug, int userId) { 4184 if (!sUserManager.exists(userId)) return null; 4185 // writer 4186 synchronized (mPackages) { 4187 if (intent.getSelector() != null) { 4188 intent = intent.getSelector(); 4189 } 4190 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4191 4192 // Try to find a matching persistent preferred activity. 4193 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4194 debug, userId); 4195 4196 // If a persistent preferred activity matched, use it. 4197 if (pri != null) { 4198 return pri; 4199 } 4200 4201 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4202 // Get the list of preferred activities that handle the intent 4203 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4204 List<PreferredActivity> prefs = pir != null 4205 ? pir.queryIntent(intent, resolvedType, 4206 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4207 : null; 4208 if (prefs != null && prefs.size() > 0) { 4209 boolean changed = false; 4210 try { 4211 // First figure out how good the original match set is. 4212 // We will only allow preferred activities that came 4213 // from the same match quality. 4214 int match = 0; 4215 4216 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4217 4218 final int N = query.size(); 4219 for (int j=0; j<N; j++) { 4220 final ResolveInfo ri = query.get(j); 4221 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4222 + ": 0x" + Integer.toHexString(match)); 4223 if (ri.match > match) { 4224 match = ri.match; 4225 } 4226 } 4227 4228 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4229 + Integer.toHexString(match)); 4230 4231 match &= IntentFilter.MATCH_CATEGORY_MASK; 4232 final int M = prefs.size(); 4233 for (int i=0; i<M; i++) { 4234 final PreferredActivity pa = prefs.get(i); 4235 if (DEBUG_PREFERRED || debug) { 4236 Slog.v(TAG, "Checking PreferredActivity ds=" 4237 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4238 + "\n component=" + pa.mPref.mComponent); 4239 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4240 } 4241 if (pa.mPref.mMatch != match) { 4242 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4243 + Integer.toHexString(pa.mPref.mMatch)); 4244 continue; 4245 } 4246 // If it's not an "always" type preferred activity and that's what we're 4247 // looking for, skip it. 4248 if (always && !pa.mPref.mAlways) { 4249 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4250 continue; 4251 } 4252 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4253 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4254 if (DEBUG_PREFERRED || debug) { 4255 Slog.v(TAG, "Found preferred activity:"); 4256 if (ai != null) { 4257 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4258 } else { 4259 Slog.v(TAG, " null"); 4260 } 4261 } 4262 if (ai == null) { 4263 // This previously registered preferred activity 4264 // component is no longer known. Most likely an update 4265 // to the app was installed and in the new version this 4266 // component no longer exists. Clean it up by removing 4267 // it from the preferred activities list, and skip it. 4268 Slog.w(TAG, "Removing dangling preferred activity: " 4269 + pa.mPref.mComponent); 4270 pir.removeFilter(pa); 4271 changed = true; 4272 continue; 4273 } 4274 for (int j=0; j<N; j++) { 4275 final ResolveInfo ri = query.get(j); 4276 if (!ri.activityInfo.applicationInfo.packageName 4277 .equals(ai.applicationInfo.packageName)) { 4278 continue; 4279 } 4280 if (!ri.activityInfo.name.equals(ai.name)) { 4281 continue; 4282 } 4283 4284 if (removeMatches) { 4285 pir.removeFilter(pa); 4286 changed = true; 4287 if (DEBUG_PREFERRED) { 4288 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4289 } 4290 break; 4291 } 4292 4293 // Okay we found a previously set preferred or last chosen app. 4294 // If the result set is different from when this 4295 // was created, we need to clear it and re-ask the 4296 // user their preference, if we're looking for an "always" type entry. 4297 if (always && !pa.mPref.sameSet(query)) { 4298 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4299 + intent + " type " + resolvedType); 4300 if (DEBUG_PREFERRED) { 4301 Slog.v(TAG, "Removing preferred activity since set changed " 4302 + pa.mPref.mComponent); 4303 } 4304 pir.removeFilter(pa); 4305 // Re-add the filter as a "last chosen" entry (!always) 4306 PreferredActivity lastChosen = new PreferredActivity( 4307 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4308 pir.addFilter(lastChosen); 4309 changed = true; 4310 return null; 4311 } 4312 4313 // Yay! Either the set matched or we're looking for the last chosen 4314 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4315 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4316 return ri; 4317 } 4318 } 4319 } finally { 4320 if (changed) { 4321 if (DEBUG_PREFERRED) { 4322 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4323 } 4324 scheduleWritePackageRestrictionsLocked(userId); 4325 } 4326 } 4327 } 4328 } 4329 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4330 return null; 4331 } 4332 4333 /* 4334 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4335 */ 4336 @Override 4337 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4338 int targetUserId) { 4339 mContext.enforceCallingOrSelfPermission( 4340 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4341 List<CrossProfileIntentFilter> matches = 4342 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4343 if (matches != null) { 4344 int size = matches.size(); 4345 for (int i = 0; i < size; i++) { 4346 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4347 } 4348 } 4349 if (hasWebURI(intent)) { 4350 // cross-profile app linking works only towards the parent. 4351 final UserInfo parent = getProfileParent(sourceUserId); 4352 synchronized(mPackages) { 4353 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4354 parent.id) != null; 4355 } 4356 } 4357 return false; 4358 } 4359 4360 private UserInfo getProfileParent(int userId) { 4361 final long identity = Binder.clearCallingIdentity(); 4362 try { 4363 return sUserManager.getProfileParent(userId); 4364 } finally { 4365 Binder.restoreCallingIdentity(identity); 4366 } 4367 } 4368 4369 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4370 String resolvedType, int userId) { 4371 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4372 if (resolver != null) { 4373 return resolver.queryIntent(intent, resolvedType, false, userId); 4374 } 4375 return null; 4376 } 4377 4378 @Override 4379 public List<ResolveInfo> queryIntentActivities(Intent intent, 4380 String resolvedType, int flags, int userId) { 4381 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4382 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4383 ComponentName comp = intent.getComponent(); 4384 if (comp == null) { 4385 if (intent.getSelector() != null) { 4386 intent = intent.getSelector(); 4387 comp = intent.getComponent(); 4388 } 4389 } 4390 4391 if (comp != null) { 4392 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4393 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4394 if (ai != null) { 4395 final ResolveInfo ri = new ResolveInfo(); 4396 ri.activityInfo = ai; 4397 list.add(ri); 4398 } 4399 return list; 4400 } 4401 4402 // reader 4403 synchronized (mPackages) { 4404 final String pkgName = intent.getPackage(); 4405 if (pkgName == null) { 4406 List<CrossProfileIntentFilter> matchingFilters = 4407 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4408 // Check for results that need to skip the current profile. 4409 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4410 resolvedType, flags, userId); 4411 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4412 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4413 result.add(xpResolveInfo); 4414 return filterIfNotPrimaryUser(result, userId); 4415 } 4416 4417 // Check for results in the current profile. 4418 List<ResolveInfo> result = mActivities.queryIntent( 4419 intent, resolvedType, flags, userId); 4420 4421 // Check for cross profile results. 4422 xpResolveInfo = queryCrossProfileIntents( 4423 matchingFilters, intent, resolvedType, flags, userId); 4424 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4425 result.add(xpResolveInfo); 4426 Collections.sort(result, mResolvePrioritySorter); 4427 } 4428 result = filterIfNotPrimaryUser(result, userId); 4429 if (hasWebURI(intent)) { 4430 CrossProfileDomainInfo xpDomainInfo = null; 4431 final UserInfo parent = getProfileParent(userId); 4432 if (parent != null) { 4433 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4434 flags, userId, parent.id); 4435 } 4436 if (xpDomainInfo != null) { 4437 if (xpResolveInfo != null) { 4438 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4439 // in the result. 4440 result.remove(xpResolveInfo); 4441 } 4442 if (result.size() == 0) { 4443 result.add(xpDomainInfo.resolveInfo); 4444 return result; 4445 } 4446 } else if (result.size() <= 1) { 4447 return result; 4448 } 4449 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4450 xpDomainInfo); 4451 Collections.sort(result, mResolvePrioritySorter); 4452 } 4453 return result; 4454 } 4455 final PackageParser.Package pkg = mPackages.get(pkgName); 4456 if (pkg != null) { 4457 return filterIfNotPrimaryUser( 4458 mActivities.queryIntentForPackage( 4459 intent, resolvedType, flags, pkg.activities, userId), 4460 userId); 4461 } 4462 return new ArrayList<ResolveInfo>(); 4463 } 4464 } 4465 4466 private static class CrossProfileDomainInfo { 4467 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4468 ResolveInfo resolveInfo; 4469 /* Best domain verification status of the activities found in the other profile */ 4470 int bestDomainVerificationStatus; 4471 } 4472 4473 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4474 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4475 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4476 sourceUserId)) { 4477 return null; 4478 } 4479 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4480 resolvedType, flags, parentUserId); 4481 4482 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4483 return null; 4484 } 4485 CrossProfileDomainInfo result = null; 4486 int size = resultTargetUser.size(); 4487 for (int i = 0; i < size; i++) { 4488 ResolveInfo riTargetUser = resultTargetUser.get(i); 4489 // Intent filter verification is only for filters that specify a host. So don't return 4490 // those that handle all web uris. 4491 if (riTargetUser.handleAllWebDataURI) { 4492 continue; 4493 } 4494 String packageName = riTargetUser.activityInfo.packageName; 4495 PackageSetting ps = mSettings.mPackages.get(packageName); 4496 if (ps == null) { 4497 continue; 4498 } 4499 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4500 if (result == null) { 4501 result = new CrossProfileDomainInfo(); 4502 result.resolveInfo = 4503 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4504 result.bestDomainVerificationStatus = status; 4505 } else { 4506 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4507 result.bestDomainVerificationStatus); 4508 } 4509 } 4510 return result; 4511 } 4512 4513 /** 4514 * Verification statuses are ordered from the worse to the best, except for 4515 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4516 */ 4517 private int bestDomainVerificationStatus(int status1, int status2) { 4518 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4519 return status2; 4520 } 4521 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4522 return status1; 4523 } 4524 return (int) MathUtils.max(status1, status2); 4525 } 4526 4527 private boolean isUserEnabled(int userId) { 4528 long callingId = Binder.clearCallingIdentity(); 4529 try { 4530 UserInfo userInfo = sUserManager.getUserInfo(userId); 4531 return userInfo != null && userInfo.isEnabled(); 4532 } finally { 4533 Binder.restoreCallingIdentity(callingId); 4534 } 4535 } 4536 4537 /** 4538 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4539 * 4540 * @return filtered list 4541 */ 4542 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4543 if (userId == UserHandle.USER_OWNER) { 4544 return resolveInfos; 4545 } 4546 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4547 ResolveInfo info = resolveInfos.get(i); 4548 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4549 resolveInfos.remove(i); 4550 } 4551 } 4552 return resolveInfos; 4553 } 4554 4555 private static boolean hasWebURI(Intent intent) { 4556 if (intent.getData() == null) { 4557 return false; 4558 } 4559 final String scheme = intent.getScheme(); 4560 if (TextUtils.isEmpty(scheme)) { 4561 return false; 4562 } 4563 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4564 } 4565 4566 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4567 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4568 if (DEBUG_PREFERRED) { 4569 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4570 candidates.size()); 4571 } 4572 4573 final int userId = UserHandle.getCallingUserId(); 4574 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4575 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4576 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4577 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4578 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4579 4580 synchronized (mPackages) { 4581 final int count = candidates.size(); 4582 // First, try to use the domain preferred app. Partition the candidates into four lists: 4583 // one for the final results, one for the "do not use ever", one for "undefined status" 4584 // and finally one for "Browser App type". 4585 for (int n=0; n<count; n++) { 4586 ResolveInfo info = candidates.get(n); 4587 String packageName = info.activityInfo.packageName; 4588 PackageSetting ps = mSettings.mPackages.get(packageName); 4589 if (ps != null) { 4590 // Add to the special match all list (Browser use case) 4591 if (info.handleAllWebDataURI) { 4592 matchAllList.add(info); 4593 continue; 4594 } 4595 // Try to get the status from User settings first 4596 int status = getDomainVerificationStatusLPr(ps, userId); 4597 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4598 alwaysList.add(info); 4599 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4600 neverList.add(info); 4601 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4602 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4603 undefinedList.add(info); 4604 } 4605 } 4606 } 4607 // First try to add the "always" resolution for the current user if there is any 4608 if (alwaysList.size() > 0) { 4609 result.addAll(alwaysList); 4610 // if there is an "always" for the parent user, add it. 4611 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4612 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4613 result.add(xpDomainInfo.resolveInfo); 4614 } else { 4615 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4616 result.addAll(undefinedList); 4617 if (xpDomainInfo != null && ( 4618 xpDomainInfo.bestDomainVerificationStatus 4619 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4620 || xpDomainInfo.bestDomainVerificationStatus 4621 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4622 result.add(xpDomainInfo.resolveInfo); 4623 } 4624 // Also add Browsers (all of them or only the default one) 4625 if ((flags & MATCH_ALL) != 0) { 4626 result.addAll(matchAllList); 4627 } else { 4628 // Try to add the Default Browser if we can 4629 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4630 UserHandle.myUserId()); 4631 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4632 boolean defaultBrowserFound = false; 4633 final int browserCount = matchAllList.size(); 4634 for (int n=0; n<browserCount; n++) { 4635 ResolveInfo browser = matchAllList.get(n); 4636 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4637 result.add(browser); 4638 defaultBrowserFound = true; 4639 break; 4640 } 4641 } 4642 if (!defaultBrowserFound) { 4643 result.addAll(matchAllList); 4644 } 4645 } else { 4646 result.addAll(matchAllList); 4647 } 4648 } 4649 4650 // If there is nothing selected, add all candidates and remove the ones that the User 4651 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4652 if (result.size() == 0) { 4653 result.addAll(candidates); 4654 result.removeAll(neverList); 4655 } 4656 } 4657 } 4658 if (DEBUG_PREFERRED) { 4659 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4660 result.size()); 4661 } 4662 return result; 4663 } 4664 4665 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4666 int status = ps.getDomainVerificationStatusForUser(userId); 4667 // if none available, get the master status 4668 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4669 if (ps.getIntentFilterVerificationInfo() != null) { 4670 status = ps.getIntentFilterVerificationInfo().getStatus(); 4671 } 4672 } 4673 return status; 4674 } 4675 4676 private ResolveInfo querySkipCurrentProfileIntents( 4677 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4678 int flags, int sourceUserId) { 4679 if (matchingFilters != null) { 4680 int size = matchingFilters.size(); 4681 for (int i = 0; i < size; i ++) { 4682 CrossProfileIntentFilter filter = matchingFilters.get(i); 4683 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4684 // Checking if there are activities in the target user that can handle the 4685 // intent. 4686 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4687 flags, sourceUserId); 4688 if (resolveInfo != null) { 4689 return resolveInfo; 4690 } 4691 } 4692 } 4693 } 4694 return null; 4695 } 4696 4697 // Return matching ResolveInfo if any for skip current profile intent filters. 4698 private ResolveInfo queryCrossProfileIntents( 4699 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4700 int flags, int sourceUserId) { 4701 if (matchingFilters != null) { 4702 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4703 // match the same intent. For performance reasons, it is better not to 4704 // run queryIntent twice for the same userId 4705 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4706 int size = matchingFilters.size(); 4707 for (int i = 0; i < size; i++) { 4708 CrossProfileIntentFilter filter = matchingFilters.get(i); 4709 int targetUserId = filter.getTargetUserId(); 4710 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4711 && !alreadyTriedUserIds.get(targetUserId)) { 4712 // Checking if there are activities in the target user that can handle the 4713 // intent. 4714 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4715 flags, sourceUserId); 4716 if (resolveInfo != null) return resolveInfo; 4717 alreadyTriedUserIds.put(targetUserId, true); 4718 } 4719 } 4720 } 4721 return null; 4722 } 4723 4724 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4725 String resolvedType, int flags, int sourceUserId) { 4726 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4727 resolvedType, flags, filter.getTargetUserId()); 4728 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4729 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4730 } 4731 return null; 4732 } 4733 4734 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4735 int sourceUserId, int targetUserId) { 4736 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4737 String className; 4738 if (targetUserId == UserHandle.USER_OWNER) { 4739 className = FORWARD_INTENT_TO_USER_OWNER; 4740 } else { 4741 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4742 } 4743 ComponentName forwardingActivityComponentName = new ComponentName( 4744 mAndroidApplication.packageName, className); 4745 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4746 sourceUserId); 4747 if (targetUserId == UserHandle.USER_OWNER) { 4748 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4749 forwardingResolveInfo.noResourceId = true; 4750 } 4751 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4752 forwardingResolveInfo.priority = 0; 4753 forwardingResolveInfo.preferredOrder = 0; 4754 forwardingResolveInfo.match = 0; 4755 forwardingResolveInfo.isDefault = true; 4756 forwardingResolveInfo.filter = filter; 4757 forwardingResolveInfo.targetUserId = targetUserId; 4758 return forwardingResolveInfo; 4759 } 4760 4761 @Override 4762 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4763 Intent[] specifics, String[] specificTypes, Intent intent, 4764 String resolvedType, int flags, int userId) { 4765 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4766 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4767 false, "query intent activity options"); 4768 final String resultsAction = intent.getAction(); 4769 4770 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4771 | PackageManager.GET_RESOLVED_FILTER, userId); 4772 4773 if (DEBUG_INTENT_MATCHING) { 4774 Log.v(TAG, "Query " + intent + ": " + results); 4775 } 4776 4777 int specificsPos = 0; 4778 int N; 4779 4780 // todo: note that the algorithm used here is O(N^2). This 4781 // isn't a problem in our current environment, but if we start running 4782 // into situations where we have more than 5 or 10 matches then this 4783 // should probably be changed to something smarter... 4784 4785 // First we go through and resolve each of the specific items 4786 // that were supplied, taking care of removing any corresponding 4787 // duplicate items in the generic resolve list. 4788 if (specifics != null) { 4789 for (int i=0; i<specifics.length; i++) { 4790 final Intent sintent = specifics[i]; 4791 if (sintent == null) { 4792 continue; 4793 } 4794 4795 if (DEBUG_INTENT_MATCHING) { 4796 Log.v(TAG, "Specific #" + i + ": " + sintent); 4797 } 4798 4799 String action = sintent.getAction(); 4800 if (resultsAction != null && resultsAction.equals(action)) { 4801 // If this action was explicitly requested, then don't 4802 // remove things that have it. 4803 action = null; 4804 } 4805 4806 ResolveInfo ri = null; 4807 ActivityInfo ai = null; 4808 4809 ComponentName comp = sintent.getComponent(); 4810 if (comp == null) { 4811 ri = resolveIntent( 4812 sintent, 4813 specificTypes != null ? specificTypes[i] : null, 4814 flags, userId); 4815 if (ri == null) { 4816 continue; 4817 } 4818 if (ri == mResolveInfo) { 4819 // ACK! Must do something better with this. 4820 } 4821 ai = ri.activityInfo; 4822 comp = new ComponentName(ai.applicationInfo.packageName, 4823 ai.name); 4824 } else { 4825 ai = getActivityInfo(comp, flags, userId); 4826 if (ai == null) { 4827 continue; 4828 } 4829 } 4830 4831 // Look for any generic query activities that are duplicates 4832 // of this specific one, and remove them from the results. 4833 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4834 N = results.size(); 4835 int j; 4836 for (j=specificsPos; j<N; j++) { 4837 ResolveInfo sri = results.get(j); 4838 if ((sri.activityInfo.name.equals(comp.getClassName()) 4839 && sri.activityInfo.applicationInfo.packageName.equals( 4840 comp.getPackageName())) 4841 || (action != null && sri.filter.matchAction(action))) { 4842 results.remove(j); 4843 if (DEBUG_INTENT_MATCHING) Log.v( 4844 TAG, "Removing duplicate item from " + j 4845 + " due to specific " + specificsPos); 4846 if (ri == null) { 4847 ri = sri; 4848 } 4849 j--; 4850 N--; 4851 } 4852 } 4853 4854 // Add this specific item to its proper place. 4855 if (ri == null) { 4856 ri = new ResolveInfo(); 4857 ri.activityInfo = ai; 4858 } 4859 results.add(specificsPos, ri); 4860 ri.specificIndex = i; 4861 specificsPos++; 4862 } 4863 } 4864 4865 // Now we go through the remaining generic results and remove any 4866 // duplicate actions that are found here. 4867 N = results.size(); 4868 for (int i=specificsPos; i<N-1; i++) { 4869 final ResolveInfo rii = results.get(i); 4870 if (rii.filter == null) { 4871 continue; 4872 } 4873 4874 // Iterate over all of the actions of this result's intent 4875 // filter... typically this should be just one. 4876 final Iterator<String> it = rii.filter.actionsIterator(); 4877 if (it == null) { 4878 continue; 4879 } 4880 while (it.hasNext()) { 4881 final String action = it.next(); 4882 if (resultsAction != null && resultsAction.equals(action)) { 4883 // If this action was explicitly requested, then don't 4884 // remove things that have it. 4885 continue; 4886 } 4887 for (int j=i+1; j<N; j++) { 4888 final ResolveInfo rij = results.get(j); 4889 if (rij.filter != null && rij.filter.hasAction(action)) { 4890 results.remove(j); 4891 if (DEBUG_INTENT_MATCHING) Log.v( 4892 TAG, "Removing duplicate item from " + j 4893 + " due to action " + action + " at " + i); 4894 j--; 4895 N--; 4896 } 4897 } 4898 } 4899 4900 // If the caller didn't request filter information, drop it now 4901 // so we don't have to marshall/unmarshall it. 4902 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4903 rii.filter = null; 4904 } 4905 } 4906 4907 // Filter out the caller activity if so requested. 4908 if (caller != null) { 4909 N = results.size(); 4910 for (int i=0; i<N; i++) { 4911 ActivityInfo ainfo = results.get(i).activityInfo; 4912 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4913 && caller.getClassName().equals(ainfo.name)) { 4914 results.remove(i); 4915 break; 4916 } 4917 } 4918 } 4919 4920 // If the caller didn't request filter information, 4921 // drop them now so we don't have to 4922 // marshall/unmarshall it. 4923 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4924 N = results.size(); 4925 for (int i=0; i<N; i++) { 4926 results.get(i).filter = null; 4927 } 4928 } 4929 4930 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4931 return results; 4932 } 4933 4934 @Override 4935 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4936 int userId) { 4937 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4938 ComponentName comp = intent.getComponent(); 4939 if (comp == null) { 4940 if (intent.getSelector() != null) { 4941 intent = intent.getSelector(); 4942 comp = intent.getComponent(); 4943 } 4944 } 4945 if (comp != null) { 4946 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4947 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4948 if (ai != null) { 4949 ResolveInfo ri = new ResolveInfo(); 4950 ri.activityInfo = ai; 4951 list.add(ri); 4952 } 4953 return list; 4954 } 4955 4956 // reader 4957 synchronized (mPackages) { 4958 String pkgName = intent.getPackage(); 4959 if (pkgName == null) { 4960 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4961 } 4962 final PackageParser.Package pkg = mPackages.get(pkgName); 4963 if (pkg != null) { 4964 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4965 userId); 4966 } 4967 return null; 4968 } 4969 } 4970 4971 @Override 4972 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4973 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4974 if (!sUserManager.exists(userId)) return null; 4975 if (query != null) { 4976 if (query.size() >= 1) { 4977 // If there is more than one service with the same priority, 4978 // just arbitrarily pick the first one. 4979 return query.get(0); 4980 } 4981 } 4982 return null; 4983 } 4984 4985 @Override 4986 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4987 int userId) { 4988 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4989 ComponentName comp = intent.getComponent(); 4990 if (comp == null) { 4991 if (intent.getSelector() != null) { 4992 intent = intent.getSelector(); 4993 comp = intent.getComponent(); 4994 } 4995 } 4996 if (comp != null) { 4997 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4998 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4999 if (si != null) { 5000 final ResolveInfo ri = new ResolveInfo(); 5001 ri.serviceInfo = si; 5002 list.add(ri); 5003 } 5004 return list; 5005 } 5006 5007 // reader 5008 synchronized (mPackages) { 5009 String pkgName = intent.getPackage(); 5010 if (pkgName == null) { 5011 return mServices.queryIntent(intent, resolvedType, flags, userId); 5012 } 5013 final PackageParser.Package pkg = mPackages.get(pkgName); 5014 if (pkg != null) { 5015 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5016 userId); 5017 } 5018 return null; 5019 } 5020 } 5021 5022 @Override 5023 public List<ResolveInfo> queryIntentContentProviders( 5024 Intent intent, String resolvedType, int flags, int userId) { 5025 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5026 ComponentName comp = intent.getComponent(); 5027 if (comp == null) { 5028 if (intent.getSelector() != null) { 5029 intent = intent.getSelector(); 5030 comp = intent.getComponent(); 5031 } 5032 } 5033 if (comp != null) { 5034 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5035 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5036 if (pi != null) { 5037 final ResolveInfo ri = new ResolveInfo(); 5038 ri.providerInfo = pi; 5039 list.add(ri); 5040 } 5041 return list; 5042 } 5043 5044 // reader 5045 synchronized (mPackages) { 5046 String pkgName = intent.getPackage(); 5047 if (pkgName == null) { 5048 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5049 } 5050 final PackageParser.Package pkg = mPackages.get(pkgName); 5051 if (pkg != null) { 5052 return mProviders.queryIntentForPackage( 5053 intent, resolvedType, flags, pkg.providers, userId); 5054 } 5055 return null; 5056 } 5057 } 5058 5059 @Override 5060 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5061 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5062 5063 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5064 5065 // writer 5066 synchronized (mPackages) { 5067 ArrayList<PackageInfo> list; 5068 if (listUninstalled) { 5069 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5070 for (PackageSetting ps : mSettings.mPackages.values()) { 5071 PackageInfo pi; 5072 if (ps.pkg != null) { 5073 pi = generatePackageInfo(ps.pkg, flags, userId); 5074 } else { 5075 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5076 } 5077 if (pi != null) { 5078 list.add(pi); 5079 } 5080 } 5081 } else { 5082 list = new ArrayList<PackageInfo>(mPackages.size()); 5083 for (PackageParser.Package p : mPackages.values()) { 5084 PackageInfo pi = generatePackageInfo(p, flags, userId); 5085 if (pi != null) { 5086 list.add(pi); 5087 } 5088 } 5089 } 5090 5091 return new ParceledListSlice<PackageInfo>(list); 5092 } 5093 } 5094 5095 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5096 String[] permissions, boolean[] tmp, int flags, int userId) { 5097 int numMatch = 0; 5098 final PermissionsState permissionsState = ps.getPermissionsState(); 5099 for (int i=0; i<permissions.length; i++) { 5100 final String permission = permissions[i]; 5101 if (permissionsState.hasPermission(permission, userId)) { 5102 tmp[i] = true; 5103 numMatch++; 5104 } else { 5105 tmp[i] = false; 5106 } 5107 } 5108 if (numMatch == 0) { 5109 return; 5110 } 5111 PackageInfo pi; 5112 if (ps.pkg != null) { 5113 pi = generatePackageInfo(ps.pkg, flags, userId); 5114 } else { 5115 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5116 } 5117 // The above might return null in cases of uninstalled apps or install-state 5118 // skew across users/profiles. 5119 if (pi != null) { 5120 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5121 if (numMatch == permissions.length) { 5122 pi.requestedPermissions = permissions; 5123 } else { 5124 pi.requestedPermissions = new String[numMatch]; 5125 numMatch = 0; 5126 for (int i=0; i<permissions.length; i++) { 5127 if (tmp[i]) { 5128 pi.requestedPermissions[numMatch] = permissions[i]; 5129 numMatch++; 5130 } 5131 } 5132 } 5133 } 5134 list.add(pi); 5135 } 5136 } 5137 5138 @Override 5139 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5140 String[] permissions, int flags, int userId) { 5141 if (!sUserManager.exists(userId)) return null; 5142 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5143 5144 // writer 5145 synchronized (mPackages) { 5146 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5147 boolean[] tmpBools = new boolean[permissions.length]; 5148 if (listUninstalled) { 5149 for (PackageSetting ps : mSettings.mPackages.values()) { 5150 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5151 } 5152 } else { 5153 for (PackageParser.Package pkg : mPackages.values()) { 5154 PackageSetting ps = (PackageSetting)pkg.mExtras; 5155 if (ps != null) { 5156 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5157 userId); 5158 } 5159 } 5160 } 5161 5162 return new ParceledListSlice<PackageInfo>(list); 5163 } 5164 } 5165 5166 @Override 5167 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5168 if (!sUserManager.exists(userId)) return null; 5169 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5170 5171 // writer 5172 synchronized (mPackages) { 5173 ArrayList<ApplicationInfo> list; 5174 if (listUninstalled) { 5175 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5176 for (PackageSetting ps : mSettings.mPackages.values()) { 5177 ApplicationInfo ai; 5178 if (ps.pkg != null) { 5179 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5180 ps.readUserState(userId), userId); 5181 } else { 5182 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5183 } 5184 if (ai != null) { 5185 list.add(ai); 5186 } 5187 } 5188 } else { 5189 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5190 for (PackageParser.Package p : mPackages.values()) { 5191 if (p.mExtras != null) { 5192 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5193 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5194 if (ai != null) { 5195 list.add(ai); 5196 } 5197 } 5198 } 5199 } 5200 5201 return new ParceledListSlice<ApplicationInfo>(list); 5202 } 5203 } 5204 5205 public List<ApplicationInfo> getPersistentApplications(int flags) { 5206 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5207 5208 // reader 5209 synchronized (mPackages) { 5210 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5211 final int userId = UserHandle.getCallingUserId(); 5212 while (i.hasNext()) { 5213 final PackageParser.Package p = i.next(); 5214 if (p.applicationInfo != null 5215 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5216 && (!mSafeMode || isSystemApp(p))) { 5217 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5218 if (ps != null) { 5219 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5220 ps.readUserState(userId), userId); 5221 if (ai != null) { 5222 finalList.add(ai); 5223 } 5224 } 5225 } 5226 } 5227 } 5228 5229 return finalList; 5230 } 5231 5232 @Override 5233 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5234 if (!sUserManager.exists(userId)) return null; 5235 // reader 5236 synchronized (mPackages) { 5237 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5238 PackageSetting ps = provider != null 5239 ? mSettings.mPackages.get(provider.owner.packageName) 5240 : null; 5241 return ps != null 5242 && mSettings.isEnabledLPr(provider.info, flags, userId) 5243 && (!mSafeMode || (provider.info.applicationInfo.flags 5244 &ApplicationInfo.FLAG_SYSTEM) != 0) 5245 ? PackageParser.generateProviderInfo(provider, flags, 5246 ps.readUserState(userId), userId) 5247 : null; 5248 } 5249 } 5250 5251 /** 5252 * @deprecated 5253 */ 5254 @Deprecated 5255 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5256 // reader 5257 synchronized (mPackages) { 5258 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5259 .entrySet().iterator(); 5260 final int userId = UserHandle.getCallingUserId(); 5261 while (i.hasNext()) { 5262 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5263 PackageParser.Provider p = entry.getValue(); 5264 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5265 5266 if (ps != null && p.syncable 5267 && (!mSafeMode || (p.info.applicationInfo.flags 5268 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5269 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5270 ps.readUserState(userId), userId); 5271 if (info != null) { 5272 outNames.add(entry.getKey()); 5273 outInfo.add(info); 5274 } 5275 } 5276 } 5277 } 5278 } 5279 5280 @Override 5281 public List<ProviderInfo> queryContentProviders(String processName, 5282 int uid, int flags) { 5283 ArrayList<ProviderInfo> finalList = null; 5284 // reader 5285 synchronized (mPackages) { 5286 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5287 final int userId = processName != null ? 5288 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5289 while (i.hasNext()) { 5290 final PackageParser.Provider p = i.next(); 5291 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5292 if (ps != null && p.info.authority != null 5293 && (processName == null 5294 || (p.info.processName.equals(processName) 5295 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5296 && mSettings.isEnabledLPr(p.info, flags, userId) 5297 && (!mSafeMode 5298 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5299 if (finalList == null) { 5300 finalList = new ArrayList<ProviderInfo>(3); 5301 } 5302 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5303 ps.readUserState(userId), userId); 5304 if (info != null) { 5305 finalList.add(info); 5306 } 5307 } 5308 } 5309 } 5310 5311 if (finalList != null) { 5312 Collections.sort(finalList, mProviderInitOrderSorter); 5313 } 5314 5315 return finalList; 5316 } 5317 5318 @Override 5319 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5320 int flags) { 5321 // reader 5322 synchronized (mPackages) { 5323 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5324 return PackageParser.generateInstrumentationInfo(i, flags); 5325 } 5326 } 5327 5328 @Override 5329 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5330 int flags) { 5331 ArrayList<InstrumentationInfo> finalList = 5332 new ArrayList<InstrumentationInfo>(); 5333 5334 // reader 5335 synchronized (mPackages) { 5336 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5337 while (i.hasNext()) { 5338 final PackageParser.Instrumentation p = i.next(); 5339 if (targetPackage == null 5340 || targetPackage.equals(p.info.targetPackage)) { 5341 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5342 flags); 5343 if (ii != null) { 5344 finalList.add(ii); 5345 } 5346 } 5347 } 5348 } 5349 5350 return finalList; 5351 } 5352 5353 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5354 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5355 if (overlays == null) { 5356 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5357 return; 5358 } 5359 for (PackageParser.Package opkg : overlays.values()) { 5360 // Not much to do if idmap fails: we already logged the error 5361 // and we certainly don't want to abort installation of pkg simply 5362 // because an overlay didn't fit properly. For these reasons, 5363 // ignore the return value of createIdmapForPackagePairLI. 5364 createIdmapForPackagePairLI(pkg, opkg); 5365 } 5366 } 5367 5368 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5369 PackageParser.Package opkg) { 5370 if (!opkg.mTrustedOverlay) { 5371 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5372 opkg.baseCodePath + ": overlay not trusted"); 5373 return false; 5374 } 5375 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5376 if (overlaySet == null) { 5377 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5378 opkg.baseCodePath + " but target package has no known overlays"); 5379 return false; 5380 } 5381 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5382 // TODO: generate idmap for split APKs 5383 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5384 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5385 + opkg.baseCodePath); 5386 return false; 5387 } 5388 PackageParser.Package[] overlayArray = 5389 overlaySet.values().toArray(new PackageParser.Package[0]); 5390 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5391 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5392 return p1.mOverlayPriority - p2.mOverlayPriority; 5393 } 5394 }; 5395 Arrays.sort(overlayArray, cmp); 5396 5397 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5398 int i = 0; 5399 for (PackageParser.Package p : overlayArray) { 5400 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5401 } 5402 return true; 5403 } 5404 5405 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5406 final File[] files = dir.listFiles(); 5407 if (ArrayUtils.isEmpty(files)) { 5408 Log.d(TAG, "No files in app dir " + dir); 5409 return; 5410 } 5411 5412 if (DEBUG_PACKAGE_SCANNING) { 5413 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5414 + " flags=0x" + Integer.toHexString(parseFlags)); 5415 } 5416 5417 for (File file : files) { 5418 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5419 && !PackageInstallerService.isStageName(file.getName()); 5420 if (!isPackage) { 5421 // Ignore entries which are not packages 5422 continue; 5423 } 5424 try { 5425 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5426 scanFlags, currentTime, null); 5427 } catch (PackageManagerException e) { 5428 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5429 5430 // Delete invalid userdata apps 5431 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5432 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5433 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5434 if (file.isDirectory()) { 5435 mInstaller.rmPackageDir(file.getAbsolutePath()); 5436 } else { 5437 file.delete(); 5438 } 5439 } 5440 } 5441 } 5442 } 5443 5444 private static File getSettingsProblemFile() { 5445 File dataDir = Environment.getDataDirectory(); 5446 File systemDir = new File(dataDir, "system"); 5447 File fname = new File(systemDir, "uiderrors.txt"); 5448 return fname; 5449 } 5450 5451 static void reportSettingsProblem(int priority, String msg) { 5452 logCriticalInfo(priority, msg); 5453 } 5454 5455 static void logCriticalInfo(int priority, String msg) { 5456 Slog.println(priority, TAG, msg); 5457 EventLogTags.writePmCriticalInfo(msg); 5458 try { 5459 File fname = getSettingsProblemFile(); 5460 FileOutputStream out = new FileOutputStream(fname, true); 5461 PrintWriter pw = new FastPrintWriter(out); 5462 SimpleDateFormat formatter = new SimpleDateFormat(); 5463 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5464 pw.println(dateString + ": " + msg); 5465 pw.close(); 5466 FileUtils.setPermissions( 5467 fname.toString(), 5468 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5469 -1, -1); 5470 } catch (java.io.IOException e) { 5471 } 5472 } 5473 5474 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5475 PackageParser.Package pkg, File srcFile, int parseFlags) 5476 throws PackageManagerException { 5477 if (ps != null 5478 && ps.codePath.equals(srcFile) 5479 && ps.timeStamp == srcFile.lastModified() 5480 && !isCompatSignatureUpdateNeeded(pkg) 5481 && !isRecoverSignatureUpdateNeeded(pkg)) { 5482 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5483 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5484 ArraySet<PublicKey> signingKs; 5485 synchronized (mPackages) { 5486 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5487 } 5488 if (ps.signatures.mSignatures != null 5489 && ps.signatures.mSignatures.length != 0 5490 && signingKs != null) { 5491 // Optimization: reuse the existing cached certificates 5492 // if the package appears to be unchanged. 5493 pkg.mSignatures = ps.signatures.mSignatures; 5494 pkg.mSigningKeys = signingKs; 5495 return; 5496 } 5497 5498 Slog.w(TAG, "PackageSetting for " + ps.name 5499 + " is missing signatures. Collecting certs again to recover them."); 5500 } else { 5501 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5502 } 5503 5504 try { 5505 pp.collectCertificates(pkg, parseFlags); 5506 pp.collectManifestDigest(pkg); 5507 } catch (PackageParserException e) { 5508 throw PackageManagerException.from(e); 5509 } 5510 } 5511 5512 /* 5513 * Scan a package and return the newly parsed package. 5514 * Returns null in case of errors and the error code is stored in mLastScanError 5515 */ 5516 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5517 long currentTime, UserHandle user) throws PackageManagerException { 5518 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5519 parseFlags |= mDefParseFlags; 5520 PackageParser pp = new PackageParser(); 5521 pp.setSeparateProcesses(mSeparateProcesses); 5522 pp.setOnlyCoreApps(mOnlyCore); 5523 pp.setDisplayMetrics(mMetrics); 5524 5525 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5526 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5527 } 5528 5529 final PackageParser.Package pkg; 5530 try { 5531 pkg = pp.parsePackage(scanFile, parseFlags); 5532 } catch (PackageParserException e) { 5533 throw PackageManagerException.from(e); 5534 } 5535 5536 PackageSetting ps = null; 5537 PackageSetting updatedPkg; 5538 // reader 5539 synchronized (mPackages) { 5540 // Look to see if we already know about this package. 5541 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5542 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5543 // This package has been renamed to its original name. Let's 5544 // use that. 5545 ps = mSettings.peekPackageLPr(oldName); 5546 } 5547 // If there was no original package, see one for the real package name. 5548 if (ps == null) { 5549 ps = mSettings.peekPackageLPr(pkg.packageName); 5550 } 5551 // Check to see if this package could be hiding/updating a system 5552 // package. Must look for it either under the original or real 5553 // package name depending on our state. 5554 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5555 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5556 } 5557 boolean updatedPkgBetter = false; 5558 // First check if this is a system package that may involve an update 5559 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5560 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5561 // it needs to drop FLAG_PRIVILEGED. 5562 if (locationIsPrivileged(scanFile)) { 5563 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5564 } else { 5565 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5566 } 5567 5568 if (ps != null && !ps.codePath.equals(scanFile)) { 5569 // The path has changed from what was last scanned... check the 5570 // version of the new path against what we have stored to determine 5571 // what to do. 5572 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5573 if (pkg.mVersionCode <= ps.versionCode) { 5574 // The system package has been updated and the code path does not match 5575 // Ignore entry. Skip it. 5576 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5577 + " ignored: updated version " + ps.versionCode 5578 + " better than this " + pkg.mVersionCode); 5579 if (!updatedPkg.codePath.equals(scanFile)) { 5580 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5581 + ps.name + " changing from " + updatedPkg.codePathString 5582 + " to " + scanFile); 5583 updatedPkg.codePath = scanFile; 5584 updatedPkg.codePathString = scanFile.toString(); 5585 updatedPkg.resourcePath = scanFile; 5586 updatedPkg.resourcePathString = scanFile.toString(); 5587 } 5588 updatedPkg.pkg = pkg; 5589 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5590 } else { 5591 // The current app on the system partition is better than 5592 // what we have updated to on the data partition; switch 5593 // back to the system partition version. 5594 // At this point, its safely assumed that package installation for 5595 // apps in system partition will go through. If not there won't be a working 5596 // version of the app 5597 // writer 5598 synchronized (mPackages) { 5599 // Just remove the loaded entries from package lists. 5600 mPackages.remove(ps.name); 5601 } 5602 5603 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5604 + " reverting from " + ps.codePathString 5605 + ": new version " + pkg.mVersionCode 5606 + " better than installed " + ps.versionCode); 5607 5608 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5609 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5610 synchronized (mInstallLock) { 5611 args.cleanUpResourcesLI(); 5612 } 5613 synchronized (mPackages) { 5614 mSettings.enableSystemPackageLPw(ps.name); 5615 } 5616 updatedPkgBetter = true; 5617 } 5618 } 5619 } 5620 5621 if (updatedPkg != null) { 5622 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5623 // initially 5624 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5625 5626 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5627 // flag set initially 5628 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5629 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5630 } 5631 } 5632 5633 // Verify certificates against what was last scanned 5634 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5635 5636 /* 5637 * A new system app appeared, but we already had a non-system one of the 5638 * same name installed earlier. 5639 */ 5640 boolean shouldHideSystemApp = false; 5641 if (updatedPkg == null && ps != null 5642 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5643 /* 5644 * Check to make sure the signatures match first. If they don't, 5645 * wipe the installed application and its data. 5646 */ 5647 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5648 != PackageManager.SIGNATURE_MATCH) { 5649 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5650 + " signatures don't match existing userdata copy; removing"); 5651 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5652 ps = null; 5653 } else { 5654 /* 5655 * If the newly-added system app is an older version than the 5656 * already installed version, hide it. It will be scanned later 5657 * and re-added like an update. 5658 */ 5659 if (pkg.mVersionCode <= ps.versionCode) { 5660 shouldHideSystemApp = true; 5661 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5662 + " but new version " + pkg.mVersionCode + " better than installed " 5663 + ps.versionCode + "; hiding system"); 5664 } else { 5665 /* 5666 * The newly found system app is a newer version that the 5667 * one previously installed. Simply remove the 5668 * already-installed application and replace it with our own 5669 * while keeping the application data. 5670 */ 5671 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5672 + " reverting from " + ps.codePathString + ": new version " 5673 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5674 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5675 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5676 synchronized (mInstallLock) { 5677 args.cleanUpResourcesLI(); 5678 } 5679 } 5680 } 5681 } 5682 5683 // The apk is forward locked (not public) if its code and resources 5684 // are kept in different files. (except for app in either system or 5685 // vendor path). 5686 // TODO grab this value from PackageSettings 5687 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5688 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5689 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5690 } 5691 } 5692 5693 // TODO: extend to support forward-locked splits 5694 String resourcePath = null; 5695 String baseResourcePath = null; 5696 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5697 if (ps != null && ps.resourcePathString != null) { 5698 resourcePath = ps.resourcePathString; 5699 baseResourcePath = ps.resourcePathString; 5700 } else { 5701 // Should not happen at all. Just log an error. 5702 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5703 } 5704 } else { 5705 resourcePath = pkg.codePath; 5706 baseResourcePath = pkg.baseCodePath; 5707 } 5708 5709 // Set application objects path explicitly. 5710 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5711 pkg.applicationInfo.setCodePath(pkg.codePath); 5712 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5713 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5714 pkg.applicationInfo.setResourcePath(resourcePath); 5715 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5716 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5717 5718 // Note that we invoke the following method only if we are about to unpack an application 5719 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5720 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5721 5722 /* 5723 * If the system app should be overridden by a previously installed 5724 * data, hide the system app now and let the /data/app scan pick it up 5725 * again. 5726 */ 5727 if (shouldHideSystemApp) { 5728 synchronized (mPackages) { 5729 /* 5730 * We have to grant systems permissions before we hide, because 5731 * grantPermissions will assume the package update is trying to 5732 * expand its permissions. 5733 */ 5734 grantPermissionsLPw(pkg, true, pkg.packageName); 5735 mSettings.disableSystemPackageLPw(pkg.packageName); 5736 } 5737 } 5738 5739 return scannedPkg; 5740 } 5741 5742 private static String fixProcessName(String defProcessName, 5743 String processName, int uid) { 5744 if (processName == null) { 5745 return defProcessName; 5746 } 5747 return processName; 5748 } 5749 5750 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5751 throws PackageManagerException { 5752 if (pkgSetting.signatures.mSignatures != null) { 5753 // Already existing package. Make sure signatures match 5754 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5755 == PackageManager.SIGNATURE_MATCH; 5756 if (!match) { 5757 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5758 == PackageManager.SIGNATURE_MATCH; 5759 } 5760 if (!match) { 5761 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5762 == PackageManager.SIGNATURE_MATCH; 5763 } 5764 if (!match) { 5765 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5766 + pkg.packageName + " signatures do not match the " 5767 + "previously installed version; ignoring!"); 5768 } 5769 } 5770 5771 // Check for shared user signatures 5772 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5773 // Already existing package. Make sure signatures match 5774 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5775 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5776 if (!match) { 5777 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5778 == PackageManager.SIGNATURE_MATCH; 5779 } 5780 if (!match) { 5781 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5782 == PackageManager.SIGNATURE_MATCH; 5783 } 5784 if (!match) { 5785 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5786 "Package " + pkg.packageName 5787 + " has no signatures that match those in shared user " 5788 + pkgSetting.sharedUser.name + "; ignoring!"); 5789 } 5790 } 5791 } 5792 5793 /** 5794 * Enforces that only the system UID or root's UID can call a method exposed 5795 * via Binder. 5796 * 5797 * @param message used as message if SecurityException is thrown 5798 * @throws SecurityException if the caller is not system or root 5799 */ 5800 private static final void enforceSystemOrRoot(String message) { 5801 final int uid = Binder.getCallingUid(); 5802 if (uid != Process.SYSTEM_UID && uid != 0) { 5803 throw new SecurityException(message); 5804 } 5805 } 5806 5807 @Override 5808 public void performBootDexOpt() { 5809 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5810 5811 // Before everything else, see whether we need to fstrim. 5812 try { 5813 IMountService ms = PackageHelper.getMountService(); 5814 if (ms != null) { 5815 final boolean isUpgrade = isUpgrade(); 5816 boolean doTrim = isUpgrade; 5817 if (doTrim) { 5818 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5819 } else { 5820 final long interval = android.provider.Settings.Global.getLong( 5821 mContext.getContentResolver(), 5822 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5823 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5824 if (interval > 0) { 5825 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5826 if (timeSinceLast > interval) { 5827 doTrim = true; 5828 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5829 + "; running immediately"); 5830 } 5831 } 5832 } 5833 if (doTrim) { 5834 if (!isFirstBoot()) { 5835 try { 5836 ActivityManagerNative.getDefault().showBootMessage( 5837 mContext.getResources().getString( 5838 R.string.android_upgrading_fstrim), true); 5839 } catch (RemoteException e) { 5840 } 5841 } 5842 ms.runMaintenance(); 5843 } 5844 } else { 5845 Slog.e(TAG, "Mount service unavailable!"); 5846 } 5847 } catch (RemoteException e) { 5848 // Can't happen; MountService is local 5849 } 5850 5851 final ArraySet<PackageParser.Package> pkgs; 5852 synchronized (mPackages) { 5853 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5854 } 5855 5856 if (pkgs != null) { 5857 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5858 // in case the device runs out of space. 5859 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5860 // Give priority to core apps. 5861 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5862 PackageParser.Package pkg = it.next(); 5863 if (pkg.coreApp) { 5864 if (DEBUG_DEXOPT) { 5865 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5866 } 5867 sortedPkgs.add(pkg); 5868 it.remove(); 5869 } 5870 } 5871 // Give priority to system apps that listen for pre boot complete. 5872 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5873 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5874 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5875 PackageParser.Package pkg = it.next(); 5876 if (pkgNames.contains(pkg.packageName)) { 5877 if (DEBUG_DEXOPT) { 5878 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5879 } 5880 sortedPkgs.add(pkg); 5881 it.remove(); 5882 } 5883 } 5884 // Give priority to system apps. 5885 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5886 PackageParser.Package pkg = it.next(); 5887 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5888 if (DEBUG_DEXOPT) { 5889 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5890 } 5891 sortedPkgs.add(pkg); 5892 it.remove(); 5893 } 5894 } 5895 // Give priority to updated system apps. 5896 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5897 PackageParser.Package pkg = it.next(); 5898 if (pkg.isUpdatedSystemApp()) { 5899 if (DEBUG_DEXOPT) { 5900 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5901 } 5902 sortedPkgs.add(pkg); 5903 it.remove(); 5904 } 5905 } 5906 // Give priority to apps that listen for boot complete. 5907 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5908 pkgNames = getPackageNamesForIntent(intent); 5909 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5910 PackageParser.Package pkg = it.next(); 5911 if (pkgNames.contains(pkg.packageName)) { 5912 if (DEBUG_DEXOPT) { 5913 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5914 } 5915 sortedPkgs.add(pkg); 5916 it.remove(); 5917 } 5918 } 5919 // Filter out packages that aren't recently used. 5920 filterRecentlyUsedApps(pkgs); 5921 // Add all remaining apps. 5922 for (PackageParser.Package pkg : pkgs) { 5923 if (DEBUG_DEXOPT) { 5924 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5925 } 5926 sortedPkgs.add(pkg); 5927 } 5928 5929 // If we want to be lazy, filter everything that wasn't recently used. 5930 if (mLazyDexOpt) { 5931 filterRecentlyUsedApps(sortedPkgs); 5932 } 5933 5934 int i = 0; 5935 int total = sortedPkgs.size(); 5936 File dataDir = Environment.getDataDirectory(); 5937 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5938 if (lowThreshold == 0) { 5939 throw new IllegalStateException("Invalid low memory threshold"); 5940 } 5941 for (PackageParser.Package pkg : sortedPkgs) { 5942 long usableSpace = dataDir.getUsableSpace(); 5943 if (usableSpace < lowThreshold) { 5944 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5945 break; 5946 } 5947 performBootDexOpt(pkg, ++i, total); 5948 } 5949 } 5950 } 5951 5952 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5953 // Filter out packages that aren't recently used. 5954 // 5955 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5956 // should do a full dexopt. 5957 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5958 int total = pkgs.size(); 5959 int skipped = 0; 5960 long now = System.currentTimeMillis(); 5961 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5962 PackageParser.Package pkg = i.next(); 5963 long then = pkg.mLastPackageUsageTimeInMills; 5964 if (then + mDexOptLRUThresholdInMills < now) { 5965 if (DEBUG_DEXOPT) { 5966 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5967 ((then == 0) ? "never" : new Date(then))); 5968 } 5969 i.remove(); 5970 skipped++; 5971 } 5972 } 5973 if (DEBUG_DEXOPT) { 5974 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5975 } 5976 } 5977 } 5978 5979 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5980 List<ResolveInfo> ris = null; 5981 try { 5982 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5983 intent, null, 0, UserHandle.USER_OWNER); 5984 } catch (RemoteException e) { 5985 } 5986 ArraySet<String> pkgNames = new ArraySet<String>(); 5987 if (ris != null) { 5988 for (ResolveInfo ri : ris) { 5989 pkgNames.add(ri.activityInfo.packageName); 5990 } 5991 } 5992 return pkgNames; 5993 } 5994 5995 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5996 if (DEBUG_DEXOPT) { 5997 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5998 } 5999 if (!isFirstBoot()) { 6000 try { 6001 ActivityManagerNative.getDefault().showBootMessage( 6002 mContext.getResources().getString(R.string.android_upgrading_apk, 6003 curr, total), true); 6004 } catch (RemoteException e) { 6005 } 6006 } 6007 PackageParser.Package p = pkg; 6008 synchronized (mInstallLock) { 6009 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6010 false /* force dex */, false /* defer */, true /* include dependencies */); 6011 } 6012 } 6013 6014 @Override 6015 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6016 return performDexOpt(packageName, instructionSet, false); 6017 } 6018 6019 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6020 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6021 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6022 if (!dexopt && !updateUsage) { 6023 // We aren't going to dexopt or update usage, so bail early. 6024 return false; 6025 } 6026 PackageParser.Package p; 6027 final String targetInstructionSet; 6028 synchronized (mPackages) { 6029 p = mPackages.get(packageName); 6030 if (p == null) { 6031 return false; 6032 } 6033 if (updateUsage) { 6034 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6035 } 6036 mPackageUsage.write(false); 6037 if (!dexopt) { 6038 // We aren't going to dexopt, so bail early. 6039 return false; 6040 } 6041 6042 targetInstructionSet = instructionSet != null ? instructionSet : 6043 getPrimaryInstructionSet(p.applicationInfo); 6044 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6045 return false; 6046 } 6047 } 6048 6049 synchronized (mInstallLock) { 6050 final String[] instructionSets = new String[] { targetInstructionSet }; 6051 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6052 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6053 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6054 } 6055 } 6056 6057 public ArraySet<String> getPackagesThatNeedDexOpt() { 6058 ArraySet<String> pkgs = null; 6059 synchronized (mPackages) { 6060 for (PackageParser.Package p : mPackages.values()) { 6061 if (DEBUG_DEXOPT) { 6062 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6063 } 6064 if (!p.mDexOptPerformed.isEmpty()) { 6065 continue; 6066 } 6067 if (pkgs == null) { 6068 pkgs = new ArraySet<String>(); 6069 } 6070 pkgs.add(p.packageName); 6071 } 6072 } 6073 return pkgs; 6074 } 6075 6076 public void shutdown() { 6077 mPackageUsage.write(true); 6078 } 6079 6080 @Override 6081 public void forceDexOpt(String packageName) { 6082 enforceSystemOrRoot("forceDexOpt"); 6083 6084 PackageParser.Package pkg; 6085 synchronized (mPackages) { 6086 pkg = mPackages.get(packageName); 6087 if (pkg == null) { 6088 throw new IllegalArgumentException("Missing package: " + packageName); 6089 } 6090 } 6091 6092 synchronized (mInstallLock) { 6093 final String[] instructionSets = new String[] { 6094 getPrimaryInstructionSet(pkg.applicationInfo) }; 6095 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6096 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6097 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6098 throw new IllegalStateException("Failed to dexopt: " + res); 6099 } 6100 } 6101 } 6102 6103 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6104 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6105 Slog.w(TAG, "Unable to update from " + oldPkg.name 6106 + " to " + newPkg.packageName 6107 + ": old package not in system partition"); 6108 return false; 6109 } else if (mPackages.get(oldPkg.name) != null) { 6110 Slog.w(TAG, "Unable to update from " + oldPkg.name 6111 + " to " + newPkg.packageName 6112 + ": old package still exists"); 6113 return false; 6114 } 6115 return true; 6116 } 6117 6118 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6119 int[] users = sUserManager.getUserIds(); 6120 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6121 if (res < 0) { 6122 return res; 6123 } 6124 for (int user : users) { 6125 if (user != 0) { 6126 res = mInstaller.createUserData(volumeUuid, packageName, 6127 UserHandle.getUid(user, uid), user, seinfo); 6128 if (res < 0) { 6129 return res; 6130 } 6131 } 6132 } 6133 return res; 6134 } 6135 6136 private int removeDataDirsLI(String volumeUuid, String packageName) { 6137 int[] users = sUserManager.getUserIds(); 6138 int res = 0; 6139 for (int user : users) { 6140 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6141 if (resInner < 0) { 6142 res = resInner; 6143 } 6144 } 6145 6146 return res; 6147 } 6148 6149 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6150 int[] users = sUserManager.getUserIds(); 6151 int res = 0; 6152 for (int user : users) { 6153 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6154 if (resInner < 0) { 6155 res = resInner; 6156 } 6157 } 6158 return res; 6159 } 6160 6161 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6162 PackageParser.Package changingLib) { 6163 if (file.path != null) { 6164 usesLibraryFiles.add(file.path); 6165 return; 6166 } 6167 PackageParser.Package p = mPackages.get(file.apk); 6168 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6169 // If we are doing this while in the middle of updating a library apk, 6170 // then we need to make sure to use that new apk for determining the 6171 // dependencies here. (We haven't yet finished committing the new apk 6172 // to the package manager state.) 6173 if (p == null || p.packageName.equals(changingLib.packageName)) { 6174 p = changingLib; 6175 } 6176 } 6177 if (p != null) { 6178 usesLibraryFiles.addAll(p.getAllCodePaths()); 6179 } 6180 } 6181 6182 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6183 PackageParser.Package changingLib) throws PackageManagerException { 6184 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6185 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6186 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6187 for (int i=0; i<N; i++) { 6188 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6189 if (file == null) { 6190 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6191 "Package " + pkg.packageName + " requires unavailable shared library " 6192 + pkg.usesLibraries.get(i) + "; failing!"); 6193 } 6194 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6195 } 6196 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6197 for (int i=0; i<N; i++) { 6198 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6199 if (file == null) { 6200 Slog.w(TAG, "Package " + pkg.packageName 6201 + " desires unavailable shared library " 6202 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6203 } else { 6204 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6205 } 6206 } 6207 N = usesLibraryFiles.size(); 6208 if (N > 0) { 6209 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6210 } else { 6211 pkg.usesLibraryFiles = null; 6212 } 6213 } 6214 } 6215 6216 private static boolean hasString(List<String> list, List<String> which) { 6217 if (list == null) { 6218 return false; 6219 } 6220 for (int i=list.size()-1; i>=0; i--) { 6221 for (int j=which.size()-1; j>=0; j--) { 6222 if (which.get(j).equals(list.get(i))) { 6223 return true; 6224 } 6225 } 6226 } 6227 return false; 6228 } 6229 6230 private void updateAllSharedLibrariesLPw() { 6231 for (PackageParser.Package pkg : mPackages.values()) { 6232 try { 6233 updateSharedLibrariesLPw(pkg, null); 6234 } catch (PackageManagerException e) { 6235 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6236 } 6237 } 6238 } 6239 6240 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6241 PackageParser.Package changingPkg) { 6242 ArrayList<PackageParser.Package> res = null; 6243 for (PackageParser.Package pkg : mPackages.values()) { 6244 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6245 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6246 if (res == null) { 6247 res = new ArrayList<PackageParser.Package>(); 6248 } 6249 res.add(pkg); 6250 try { 6251 updateSharedLibrariesLPw(pkg, changingPkg); 6252 } catch (PackageManagerException e) { 6253 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6254 } 6255 } 6256 } 6257 return res; 6258 } 6259 6260 /** 6261 * Derive the value of the {@code cpuAbiOverride} based on the provided 6262 * value and an optional stored value from the package settings. 6263 */ 6264 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6265 String cpuAbiOverride = null; 6266 6267 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6268 cpuAbiOverride = null; 6269 } else if (abiOverride != null) { 6270 cpuAbiOverride = abiOverride; 6271 } else if (settings != null) { 6272 cpuAbiOverride = settings.cpuAbiOverrideString; 6273 } 6274 6275 return cpuAbiOverride; 6276 } 6277 6278 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6279 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6280 boolean success = false; 6281 try { 6282 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6283 currentTime, user); 6284 success = true; 6285 return res; 6286 } finally { 6287 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6288 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6289 } 6290 } 6291 } 6292 6293 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6294 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6295 final File scanFile = new File(pkg.codePath); 6296 if (pkg.applicationInfo.getCodePath() == null || 6297 pkg.applicationInfo.getResourcePath() == null) { 6298 // Bail out. The resource and code paths haven't been set. 6299 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6300 "Code and resource paths haven't been set correctly"); 6301 } 6302 6303 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6304 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6305 } else { 6306 // Only allow system apps to be flagged as core apps. 6307 pkg.coreApp = false; 6308 } 6309 6310 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6311 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6312 } 6313 6314 if (mCustomResolverComponentName != null && 6315 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6316 setUpCustomResolverActivity(pkg); 6317 } 6318 6319 if (pkg.packageName.equals("android")) { 6320 synchronized (mPackages) { 6321 if (mAndroidApplication != null) { 6322 Slog.w(TAG, "*************************************************"); 6323 Slog.w(TAG, "Core android package being redefined. Skipping."); 6324 Slog.w(TAG, " file=" + scanFile); 6325 Slog.w(TAG, "*************************************************"); 6326 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6327 "Core android package being redefined. Skipping."); 6328 } 6329 6330 // Set up information for our fall-back user intent resolution activity. 6331 mPlatformPackage = pkg; 6332 pkg.mVersionCode = mSdkVersion; 6333 mAndroidApplication = pkg.applicationInfo; 6334 6335 if (!mResolverReplaced) { 6336 mResolveActivity.applicationInfo = mAndroidApplication; 6337 mResolveActivity.name = ResolverActivity.class.getName(); 6338 mResolveActivity.packageName = mAndroidApplication.packageName; 6339 mResolveActivity.processName = "system:ui"; 6340 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6341 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6342 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6343 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6344 mResolveActivity.exported = true; 6345 mResolveActivity.enabled = true; 6346 mResolveInfo.activityInfo = mResolveActivity; 6347 mResolveInfo.priority = 0; 6348 mResolveInfo.preferredOrder = 0; 6349 mResolveInfo.match = 0; 6350 mResolveComponentName = new ComponentName( 6351 mAndroidApplication.packageName, mResolveActivity.name); 6352 } 6353 } 6354 } 6355 6356 if (DEBUG_PACKAGE_SCANNING) { 6357 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6358 Log.d(TAG, "Scanning package " + pkg.packageName); 6359 } 6360 6361 if (mPackages.containsKey(pkg.packageName) 6362 || mSharedLibraries.containsKey(pkg.packageName)) { 6363 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6364 "Application package " + pkg.packageName 6365 + " already installed. Skipping duplicate."); 6366 } 6367 6368 // If we're only installing presumed-existing packages, require that the 6369 // scanned APK is both already known and at the path previously established 6370 // for it. Previously unknown packages we pick up normally, but if we have an 6371 // a priori expectation about this package's install presence, enforce it. 6372 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6373 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6374 if (known != null) { 6375 if (DEBUG_PACKAGE_SCANNING) { 6376 Log.d(TAG, "Examining " + pkg.codePath 6377 + " and requiring known paths " + known.codePathString 6378 + " & " + known.resourcePathString); 6379 } 6380 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6381 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6382 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6383 "Application package " + pkg.packageName 6384 + " found at " + pkg.applicationInfo.getCodePath() 6385 + " but expected at " + known.codePathString + "; ignoring."); 6386 } 6387 } 6388 } 6389 6390 // Initialize package source and resource directories 6391 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6392 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6393 6394 SharedUserSetting suid = null; 6395 PackageSetting pkgSetting = null; 6396 6397 if (!isSystemApp(pkg)) { 6398 // Only system apps can use these features. 6399 pkg.mOriginalPackages = null; 6400 pkg.mRealPackage = null; 6401 pkg.mAdoptPermissions = null; 6402 } 6403 6404 // writer 6405 synchronized (mPackages) { 6406 if (pkg.mSharedUserId != null) { 6407 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6408 if (suid == null) { 6409 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6410 "Creating application package " + pkg.packageName 6411 + " for shared user failed"); 6412 } 6413 if (DEBUG_PACKAGE_SCANNING) { 6414 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6415 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6416 + "): packages=" + suid.packages); 6417 } 6418 } 6419 6420 // Check if we are renaming from an original package name. 6421 PackageSetting origPackage = null; 6422 String realName = null; 6423 if (pkg.mOriginalPackages != null) { 6424 // This package may need to be renamed to a previously 6425 // installed name. Let's check on that... 6426 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6427 if (pkg.mOriginalPackages.contains(renamed)) { 6428 // This package had originally been installed as the 6429 // original name, and we have already taken care of 6430 // transitioning to the new one. Just update the new 6431 // one to continue using the old name. 6432 realName = pkg.mRealPackage; 6433 if (!pkg.packageName.equals(renamed)) { 6434 // Callers into this function may have already taken 6435 // care of renaming the package; only do it here if 6436 // it is not already done. 6437 pkg.setPackageName(renamed); 6438 } 6439 6440 } else { 6441 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6442 if ((origPackage = mSettings.peekPackageLPr( 6443 pkg.mOriginalPackages.get(i))) != null) { 6444 // We do have the package already installed under its 6445 // original name... should we use it? 6446 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6447 // New package is not compatible with original. 6448 origPackage = null; 6449 continue; 6450 } else if (origPackage.sharedUser != null) { 6451 // Make sure uid is compatible between packages. 6452 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6453 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6454 + " to " + pkg.packageName + ": old uid " 6455 + origPackage.sharedUser.name 6456 + " differs from " + pkg.mSharedUserId); 6457 origPackage = null; 6458 continue; 6459 } 6460 } else { 6461 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6462 + pkg.packageName + " to old name " + origPackage.name); 6463 } 6464 break; 6465 } 6466 } 6467 } 6468 } 6469 6470 if (mTransferedPackages.contains(pkg.packageName)) { 6471 Slog.w(TAG, "Package " + pkg.packageName 6472 + " was transferred to another, but its .apk remains"); 6473 } 6474 6475 // Just create the setting, don't add it yet. For already existing packages 6476 // the PkgSetting exists already and doesn't have to be created. 6477 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6478 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6479 pkg.applicationInfo.primaryCpuAbi, 6480 pkg.applicationInfo.secondaryCpuAbi, 6481 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6482 user, false); 6483 if (pkgSetting == null) { 6484 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6485 "Creating application package " + pkg.packageName + " failed"); 6486 } 6487 6488 if (pkgSetting.origPackage != null) { 6489 // If we are first transitioning from an original package, 6490 // fix up the new package's name now. We need to do this after 6491 // looking up the package under its new name, so getPackageLP 6492 // can take care of fiddling things correctly. 6493 pkg.setPackageName(origPackage.name); 6494 6495 // File a report about this. 6496 String msg = "New package " + pkgSetting.realName 6497 + " renamed to replace old package " + pkgSetting.name; 6498 reportSettingsProblem(Log.WARN, msg); 6499 6500 // Make a note of it. 6501 mTransferedPackages.add(origPackage.name); 6502 6503 // No longer need to retain this. 6504 pkgSetting.origPackage = null; 6505 } 6506 6507 if (realName != null) { 6508 // Make a note of it. 6509 mTransferedPackages.add(pkg.packageName); 6510 } 6511 6512 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6513 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6514 } 6515 6516 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6517 // Check all shared libraries and map to their actual file path. 6518 // We only do this here for apps not on a system dir, because those 6519 // are the only ones that can fail an install due to this. We 6520 // will take care of the system apps by updating all of their 6521 // library paths after the scan is done. 6522 updateSharedLibrariesLPw(pkg, null); 6523 } 6524 6525 if (mFoundPolicyFile) { 6526 SELinuxMMAC.assignSeinfoValue(pkg); 6527 } 6528 6529 pkg.applicationInfo.uid = pkgSetting.appId; 6530 pkg.mExtras = pkgSetting; 6531 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6532 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6533 // We just determined the app is signed correctly, so bring 6534 // over the latest parsed certs. 6535 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6536 } else { 6537 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6538 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6539 "Package " + pkg.packageName + " upgrade keys do not match the " 6540 + "previously installed version"); 6541 } else { 6542 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6543 String msg = "System package " + pkg.packageName 6544 + " signature changed; retaining data."; 6545 reportSettingsProblem(Log.WARN, msg); 6546 } 6547 } 6548 } else { 6549 try { 6550 verifySignaturesLP(pkgSetting, pkg); 6551 // We just determined the app is signed correctly, so bring 6552 // over the latest parsed certs. 6553 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6554 } catch (PackageManagerException e) { 6555 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6556 throw e; 6557 } 6558 // The signature has changed, but this package is in the system 6559 // image... let's recover! 6560 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6561 // However... if this package is part of a shared user, but it 6562 // doesn't match the signature of the shared user, let's fail. 6563 // What this means is that you can't change the signatures 6564 // associated with an overall shared user, which doesn't seem all 6565 // that unreasonable. 6566 if (pkgSetting.sharedUser != null) { 6567 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6568 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6569 throw new PackageManagerException( 6570 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6571 "Signature mismatch for shared user : " 6572 + pkgSetting.sharedUser); 6573 } 6574 } 6575 // File a report about this. 6576 String msg = "System package " + pkg.packageName 6577 + " signature changed; retaining data."; 6578 reportSettingsProblem(Log.WARN, msg); 6579 } 6580 } 6581 // Verify that this new package doesn't have any content providers 6582 // that conflict with existing packages. Only do this if the 6583 // package isn't already installed, since we don't want to break 6584 // things that are installed. 6585 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6586 final int N = pkg.providers.size(); 6587 int i; 6588 for (i=0; i<N; i++) { 6589 PackageParser.Provider p = pkg.providers.get(i); 6590 if (p.info.authority != null) { 6591 String names[] = p.info.authority.split(";"); 6592 for (int j = 0; j < names.length; j++) { 6593 if (mProvidersByAuthority.containsKey(names[j])) { 6594 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6595 final String otherPackageName = 6596 ((other != null && other.getComponentName() != null) ? 6597 other.getComponentName().getPackageName() : "?"); 6598 throw new PackageManagerException( 6599 INSTALL_FAILED_CONFLICTING_PROVIDER, 6600 "Can't install because provider name " + names[j] 6601 + " (in package " + pkg.applicationInfo.packageName 6602 + ") is already used by " + otherPackageName); 6603 } 6604 } 6605 } 6606 } 6607 } 6608 6609 if (pkg.mAdoptPermissions != null) { 6610 // This package wants to adopt ownership of permissions from 6611 // another package. 6612 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6613 final String origName = pkg.mAdoptPermissions.get(i); 6614 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6615 if (orig != null) { 6616 if (verifyPackageUpdateLPr(orig, pkg)) { 6617 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6618 + pkg.packageName); 6619 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6620 } 6621 } 6622 } 6623 } 6624 } 6625 6626 final String pkgName = pkg.packageName; 6627 6628 final long scanFileTime = scanFile.lastModified(); 6629 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6630 pkg.applicationInfo.processName = fixProcessName( 6631 pkg.applicationInfo.packageName, 6632 pkg.applicationInfo.processName, 6633 pkg.applicationInfo.uid); 6634 6635 File dataPath; 6636 if (mPlatformPackage == pkg) { 6637 // The system package is special. 6638 dataPath = new File(Environment.getDataDirectory(), "system"); 6639 6640 pkg.applicationInfo.dataDir = dataPath.getPath(); 6641 6642 } else { 6643 // This is a normal package, need to make its data directory. 6644 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6645 UserHandle.USER_OWNER, pkg.packageName); 6646 6647 boolean uidError = false; 6648 if (dataPath.exists()) { 6649 int currentUid = 0; 6650 try { 6651 StructStat stat = Os.stat(dataPath.getPath()); 6652 currentUid = stat.st_uid; 6653 } catch (ErrnoException e) { 6654 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6655 } 6656 6657 // If we have mismatched owners for the data path, we have a problem. 6658 if (currentUid != pkg.applicationInfo.uid) { 6659 boolean recovered = false; 6660 if (currentUid == 0) { 6661 // The directory somehow became owned by root. Wow. 6662 // This is probably because the system was stopped while 6663 // installd was in the middle of messing with its libs 6664 // directory. Ask installd to fix that. 6665 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6666 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6667 if (ret >= 0) { 6668 recovered = true; 6669 String msg = "Package " + pkg.packageName 6670 + " unexpectedly changed to uid 0; recovered to " + 6671 + pkg.applicationInfo.uid; 6672 reportSettingsProblem(Log.WARN, msg); 6673 } 6674 } 6675 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6676 || (scanFlags&SCAN_BOOTING) != 0)) { 6677 // If this is a system app, we can at least delete its 6678 // current data so the application will still work. 6679 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6680 if (ret >= 0) { 6681 // TODO: Kill the processes first 6682 // Old data gone! 6683 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6684 ? "System package " : "Third party package "; 6685 String msg = prefix + pkg.packageName 6686 + " has changed from uid: " 6687 + currentUid + " to " 6688 + pkg.applicationInfo.uid + "; old data erased"; 6689 reportSettingsProblem(Log.WARN, msg); 6690 recovered = true; 6691 6692 // And now re-install the app. 6693 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6694 pkg.applicationInfo.seinfo); 6695 if (ret == -1) { 6696 // Ack should not happen! 6697 msg = prefix + pkg.packageName 6698 + " could not have data directory re-created after delete."; 6699 reportSettingsProblem(Log.WARN, msg); 6700 throw new PackageManagerException( 6701 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6702 } 6703 } 6704 if (!recovered) { 6705 mHasSystemUidErrors = true; 6706 } 6707 } else if (!recovered) { 6708 // If we allow this install to proceed, we will be broken. 6709 // Abort, abort! 6710 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6711 "scanPackageLI"); 6712 } 6713 if (!recovered) { 6714 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6715 + pkg.applicationInfo.uid + "/fs_" 6716 + currentUid; 6717 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6718 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6719 String msg = "Package " + pkg.packageName 6720 + " has mismatched uid: " 6721 + currentUid + " on disk, " 6722 + pkg.applicationInfo.uid + " in settings"; 6723 // writer 6724 synchronized (mPackages) { 6725 mSettings.mReadMessages.append(msg); 6726 mSettings.mReadMessages.append('\n'); 6727 uidError = true; 6728 if (!pkgSetting.uidError) { 6729 reportSettingsProblem(Log.ERROR, msg); 6730 } 6731 } 6732 } 6733 } 6734 pkg.applicationInfo.dataDir = dataPath.getPath(); 6735 if (mShouldRestoreconData) { 6736 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6737 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6738 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6739 } 6740 } else { 6741 if (DEBUG_PACKAGE_SCANNING) { 6742 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6743 Log.v(TAG, "Want this data dir: " + dataPath); 6744 } 6745 //invoke installer to do the actual installation 6746 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6747 pkg.applicationInfo.seinfo); 6748 if (ret < 0) { 6749 // Error from installer 6750 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6751 "Unable to create data dirs [errorCode=" + ret + "]"); 6752 } 6753 6754 if (dataPath.exists()) { 6755 pkg.applicationInfo.dataDir = dataPath.getPath(); 6756 } else { 6757 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6758 pkg.applicationInfo.dataDir = null; 6759 } 6760 } 6761 6762 pkgSetting.uidError = uidError; 6763 } 6764 6765 final String path = scanFile.getPath(); 6766 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6767 6768 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6769 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6770 6771 // Some system apps still use directory structure for native libraries 6772 // in which case we might end up not detecting abi solely based on apk 6773 // structure. Try to detect abi based on directory structure. 6774 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6775 pkg.applicationInfo.primaryCpuAbi == null) { 6776 setBundledAppAbisAndRoots(pkg, pkgSetting); 6777 setNativeLibraryPaths(pkg); 6778 } 6779 6780 } else { 6781 if ((scanFlags & SCAN_MOVE) != 0) { 6782 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6783 // but we already have this packages package info in the PackageSetting. We just 6784 // use that and derive the native library path based on the new codepath. 6785 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6786 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6787 } 6788 6789 // Set native library paths again. For moves, the path will be updated based on the 6790 // ABIs we've determined above. For non-moves, the path will be updated based on the 6791 // ABIs we determined during compilation, but the path will depend on the final 6792 // package path (after the rename away from the stage path). 6793 setNativeLibraryPaths(pkg); 6794 } 6795 6796 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6797 final int[] userIds = sUserManager.getUserIds(); 6798 synchronized (mInstallLock) { 6799 // Make sure all user data directories are ready to roll; we're okay 6800 // if they already exist 6801 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6802 for (int userId : userIds) { 6803 if (userId != 0) { 6804 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6805 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6806 pkg.applicationInfo.seinfo); 6807 } 6808 } 6809 } 6810 6811 // Create a native library symlink only if we have native libraries 6812 // and if the native libraries are 32 bit libraries. We do not provide 6813 // this symlink for 64 bit libraries. 6814 if (pkg.applicationInfo.primaryCpuAbi != null && 6815 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6816 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6817 for (int userId : userIds) { 6818 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6819 nativeLibPath, userId) < 0) { 6820 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6821 "Failed linking native library dir (user=" + userId + ")"); 6822 } 6823 } 6824 } 6825 } 6826 6827 // This is a special case for the "system" package, where the ABI is 6828 // dictated by the zygote configuration (and init.rc). We should keep track 6829 // of this ABI so that we can deal with "normal" applications that run under 6830 // the same UID correctly. 6831 if (mPlatformPackage == pkg) { 6832 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6833 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6834 } 6835 6836 // If there's a mismatch between the abi-override in the package setting 6837 // and the abiOverride specified for the install. Warn about this because we 6838 // would've already compiled the app without taking the package setting into 6839 // account. 6840 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6841 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6842 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6843 " for package: " + pkg.packageName); 6844 } 6845 } 6846 6847 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6848 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6849 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6850 6851 // Copy the derived override back to the parsed package, so that we can 6852 // update the package settings accordingly. 6853 pkg.cpuAbiOverride = cpuAbiOverride; 6854 6855 if (DEBUG_ABI_SELECTION) { 6856 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6857 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6858 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6859 } 6860 6861 // Push the derived path down into PackageSettings so we know what to 6862 // clean up at uninstall time. 6863 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6864 6865 if (DEBUG_ABI_SELECTION) { 6866 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6867 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6868 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6869 } 6870 6871 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6872 // We don't do this here during boot because we can do it all 6873 // at once after scanning all existing packages. 6874 // 6875 // We also do this *before* we perform dexopt on this package, so that 6876 // we can avoid redundant dexopts, and also to make sure we've got the 6877 // code and package path correct. 6878 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6879 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6880 } 6881 6882 if ((scanFlags & SCAN_NO_DEX) == 0) { 6883 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6884 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6885 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6886 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6887 } 6888 } 6889 if (mFactoryTest && pkg.requestedPermissions.contains( 6890 android.Manifest.permission.FACTORY_TEST)) { 6891 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6892 } 6893 6894 ArrayList<PackageParser.Package> clientLibPkgs = null; 6895 6896 // writer 6897 synchronized (mPackages) { 6898 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6899 // Only system apps can add new shared libraries. 6900 if (pkg.libraryNames != null) { 6901 for (int i=0; i<pkg.libraryNames.size(); i++) { 6902 String name = pkg.libraryNames.get(i); 6903 boolean allowed = false; 6904 if (pkg.isUpdatedSystemApp()) { 6905 // New library entries can only be added through the 6906 // system image. This is important to get rid of a lot 6907 // of nasty edge cases: for example if we allowed a non- 6908 // system update of the app to add a library, then uninstalling 6909 // the update would make the library go away, and assumptions 6910 // we made such as through app install filtering would now 6911 // have allowed apps on the device which aren't compatible 6912 // with it. Better to just have the restriction here, be 6913 // conservative, and create many fewer cases that can negatively 6914 // impact the user experience. 6915 final PackageSetting sysPs = mSettings 6916 .getDisabledSystemPkgLPr(pkg.packageName); 6917 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6918 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6919 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6920 allowed = true; 6921 allowed = true; 6922 break; 6923 } 6924 } 6925 } 6926 } else { 6927 allowed = true; 6928 } 6929 if (allowed) { 6930 if (!mSharedLibraries.containsKey(name)) { 6931 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6932 } else if (!name.equals(pkg.packageName)) { 6933 Slog.w(TAG, "Package " + pkg.packageName + " library " 6934 + name + " already exists; skipping"); 6935 } 6936 } else { 6937 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6938 + name + " that is not declared on system image; skipping"); 6939 } 6940 } 6941 if ((scanFlags&SCAN_BOOTING) == 0) { 6942 // If we are not booting, we need to update any applications 6943 // that are clients of our shared library. If we are booting, 6944 // this will all be done once the scan is complete. 6945 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6946 } 6947 } 6948 } 6949 } 6950 6951 // We also need to dexopt any apps that are dependent on this library. Note that 6952 // if these fail, we should abort the install since installing the library will 6953 // result in some apps being broken. 6954 if (clientLibPkgs != null) { 6955 if ((scanFlags & SCAN_NO_DEX) == 0) { 6956 for (int i = 0; i < clientLibPkgs.size(); i++) { 6957 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6958 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6959 null /* instruction sets */, forceDex, 6960 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6961 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6962 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6963 "scanPackageLI failed to dexopt clientLibPkgs"); 6964 } 6965 } 6966 } 6967 } 6968 6969 // Also need to kill any apps that are dependent on the library. 6970 if (clientLibPkgs != null) { 6971 for (int i=0; i<clientLibPkgs.size(); i++) { 6972 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6973 killApplication(clientPkg.applicationInfo.packageName, 6974 clientPkg.applicationInfo.uid, "update lib"); 6975 } 6976 } 6977 6978 // Make sure we're not adding any bogus keyset info 6979 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6980 ksms.assertScannedPackageValid(pkg); 6981 6982 // writer 6983 synchronized (mPackages) { 6984 // We don't expect installation to fail beyond this point 6985 6986 // Add the new setting to mSettings 6987 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6988 // Add the new setting to mPackages 6989 mPackages.put(pkg.applicationInfo.packageName, pkg); 6990 // Make sure we don't accidentally delete its data. 6991 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6992 while (iter.hasNext()) { 6993 PackageCleanItem item = iter.next(); 6994 if (pkgName.equals(item.packageName)) { 6995 iter.remove(); 6996 } 6997 } 6998 6999 // Take care of first install / last update times. 7000 if (currentTime != 0) { 7001 if (pkgSetting.firstInstallTime == 0) { 7002 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7003 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7004 pkgSetting.lastUpdateTime = currentTime; 7005 } 7006 } else if (pkgSetting.firstInstallTime == 0) { 7007 // We need *something*. Take time time stamp of the file. 7008 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7009 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7010 if (scanFileTime != pkgSetting.timeStamp) { 7011 // A package on the system image has changed; consider this 7012 // to be an update. 7013 pkgSetting.lastUpdateTime = scanFileTime; 7014 } 7015 } 7016 7017 // Add the package's KeySets to the global KeySetManagerService 7018 ksms.addScannedPackageLPw(pkg); 7019 7020 int N = pkg.providers.size(); 7021 StringBuilder r = null; 7022 int i; 7023 for (i=0; i<N; i++) { 7024 PackageParser.Provider p = pkg.providers.get(i); 7025 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7026 p.info.processName, pkg.applicationInfo.uid); 7027 mProviders.addProvider(p); 7028 p.syncable = p.info.isSyncable; 7029 if (p.info.authority != null) { 7030 String names[] = p.info.authority.split(";"); 7031 p.info.authority = null; 7032 for (int j = 0; j < names.length; j++) { 7033 if (j == 1 && p.syncable) { 7034 // We only want the first authority for a provider to possibly be 7035 // syncable, so if we already added this provider using a different 7036 // authority clear the syncable flag. We copy the provider before 7037 // changing it because the mProviders object contains a reference 7038 // to a provider that we don't want to change. 7039 // Only do this for the second authority since the resulting provider 7040 // object can be the same for all future authorities for this provider. 7041 p = new PackageParser.Provider(p); 7042 p.syncable = false; 7043 } 7044 if (!mProvidersByAuthority.containsKey(names[j])) { 7045 mProvidersByAuthority.put(names[j], p); 7046 if (p.info.authority == null) { 7047 p.info.authority = names[j]; 7048 } else { 7049 p.info.authority = p.info.authority + ";" + names[j]; 7050 } 7051 if (DEBUG_PACKAGE_SCANNING) { 7052 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7053 Log.d(TAG, "Registered content provider: " + names[j] 7054 + ", className = " + p.info.name + ", isSyncable = " 7055 + p.info.isSyncable); 7056 } 7057 } else { 7058 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7059 Slog.w(TAG, "Skipping provider name " + names[j] + 7060 " (in package " + pkg.applicationInfo.packageName + 7061 "): name already used by " 7062 + ((other != null && other.getComponentName() != null) 7063 ? other.getComponentName().getPackageName() : "?")); 7064 } 7065 } 7066 } 7067 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7068 if (r == null) { 7069 r = new StringBuilder(256); 7070 } else { 7071 r.append(' '); 7072 } 7073 r.append(p.info.name); 7074 } 7075 } 7076 if (r != null) { 7077 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7078 } 7079 7080 N = pkg.services.size(); 7081 r = null; 7082 for (i=0; i<N; i++) { 7083 PackageParser.Service s = pkg.services.get(i); 7084 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7085 s.info.processName, pkg.applicationInfo.uid); 7086 mServices.addService(s); 7087 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7088 if (r == null) { 7089 r = new StringBuilder(256); 7090 } else { 7091 r.append(' '); 7092 } 7093 r.append(s.info.name); 7094 } 7095 } 7096 if (r != null) { 7097 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7098 } 7099 7100 N = pkg.receivers.size(); 7101 r = null; 7102 for (i=0; i<N; i++) { 7103 PackageParser.Activity a = pkg.receivers.get(i); 7104 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7105 a.info.processName, pkg.applicationInfo.uid); 7106 mReceivers.addActivity(a, "receiver"); 7107 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7108 if (r == null) { 7109 r = new StringBuilder(256); 7110 } else { 7111 r.append(' '); 7112 } 7113 r.append(a.info.name); 7114 } 7115 } 7116 if (r != null) { 7117 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7118 } 7119 7120 N = pkg.activities.size(); 7121 r = null; 7122 for (i=0; i<N; i++) { 7123 PackageParser.Activity a = pkg.activities.get(i); 7124 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7125 a.info.processName, pkg.applicationInfo.uid); 7126 mActivities.addActivity(a, "activity"); 7127 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7128 if (r == null) { 7129 r = new StringBuilder(256); 7130 } else { 7131 r.append(' '); 7132 } 7133 r.append(a.info.name); 7134 } 7135 } 7136 if (r != null) { 7137 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7138 } 7139 7140 N = pkg.permissionGroups.size(); 7141 r = null; 7142 for (i=0; i<N; i++) { 7143 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7144 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7145 if (cur == null) { 7146 mPermissionGroups.put(pg.info.name, pg); 7147 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7148 if (r == null) { 7149 r = new StringBuilder(256); 7150 } else { 7151 r.append(' '); 7152 } 7153 r.append(pg.info.name); 7154 } 7155 } else { 7156 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7157 + pg.info.packageName + " ignored: original from " 7158 + cur.info.packageName); 7159 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7160 if (r == null) { 7161 r = new StringBuilder(256); 7162 } else { 7163 r.append(' '); 7164 } 7165 r.append("DUP:"); 7166 r.append(pg.info.name); 7167 } 7168 } 7169 } 7170 if (r != null) { 7171 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7172 } 7173 7174 N = pkg.permissions.size(); 7175 r = null; 7176 for (i=0; i<N; i++) { 7177 PackageParser.Permission p = pkg.permissions.get(i); 7178 7179 // Now that permission groups have a special meaning, we ignore permission 7180 // groups for legacy apps to prevent unexpected behavior. In particular, 7181 // permissions for one app being granted to someone just becuase they happen 7182 // to be in a group defined by another app (before this had no implications). 7183 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7184 p.group = mPermissionGroups.get(p.info.group); 7185 // Warn for a permission in an unknown group. 7186 if (p.info.group != null && p.group == null) { 7187 Slog.w(TAG, "Permission " + p.info.name + " from package " 7188 + p.info.packageName + " in an unknown group " + p.info.group); 7189 } 7190 } 7191 7192 ArrayMap<String, BasePermission> permissionMap = 7193 p.tree ? mSettings.mPermissionTrees 7194 : mSettings.mPermissions; 7195 BasePermission bp = permissionMap.get(p.info.name); 7196 7197 // Allow system apps to redefine non-system permissions 7198 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7199 final boolean currentOwnerIsSystem = (bp.perm != null 7200 && isSystemApp(bp.perm.owner)); 7201 if (isSystemApp(p.owner)) { 7202 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7203 // It's a built-in permission and no owner, take ownership now 7204 bp.packageSetting = pkgSetting; 7205 bp.perm = p; 7206 bp.uid = pkg.applicationInfo.uid; 7207 bp.sourcePackage = p.info.packageName; 7208 } else if (!currentOwnerIsSystem) { 7209 String msg = "New decl " + p.owner + " of permission " 7210 + p.info.name + " is system; overriding " + bp.sourcePackage; 7211 reportSettingsProblem(Log.WARN, msg); 7212 bp = null; 7213 } 7214 } 7215 } 7216 7217 if (bp == null) { 7218 bp = new BasePermission(p.info.name, p.info.packageName, 7219 BasePermission.TYPE_NORMAL); 7220 permissionMap.put(p.info.name, bp); 7221 } 7222 7223 if (bp.perm == null) { 7224 if (bp.sourcePackage == null 7225 || bp.sourcePackage.equals(p.info.packageName)) { 7226 BasePermission tree = findPermissionTreeLP(p.info.name); 7227 if (tree == null 7228 || tree.sourcePackage.equals(p.info.packageName)) { 7229 bp.packageSetting = pkgSetting; 7230 bp.perm = p; 7231 bp.uid = pkg.applicationInfo.uid; 7232 bp.sourcePackage = p.info.packageName; 7233 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7234 if (r == null) { 7235 r = new StringBuilder(256); 7236 } else { 7237 r.append(' '); 7238 } 7239 r.append(p.info.name); 7240 } 7241 } else { 7242 Slog.w(TAG, "Permission " + p.info.name + " from package " 7243 + p.info.packageName + " ignored: base tree " 7244 + tree.name + " is from package " 7245 + tree.sourcePackage); 7246 } 7247 } else { 7248 Slog.w(TAG, "Permission " + p.info.name + " from package " 7249 + p.info.packageName + " ignored: original from " 7250 + bp.sourcePackage); 7251 } 7252 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7253 if (r == null) { 7254 r = new StringBuilder(256); 7255 } else { 7256 r.append(' '); 7257 } 7258 r.append("DUP:"); 7259 r.append(p.info.name); 7260 } 7261 if (bp.perm == p) { 7262 bp.protectionLevel = p.info.protectionLevel; 7263 } 7264 } 7265 7266 if (r != null) { 7267 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7268 } 7269 7270 N = pkg.instrumentation.size(); 7271 r = null; 7272 for (i=0; i<N; i++) { 7273 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7274 a.info.packageName = pkg.applicationInfo.packageName; 7275 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7276 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7277 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7278 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7279 a.info.dataDir = pkg.applicationInfo.dataDir; 7280 7281 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7282 // need other information about the application, like the ABI and what not ? 7283 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7284 mInstrumentation.put(a.getComponentName(), a); 7285 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7286 if (r == null) { 7287 r = new StringBuilder(256); 7288 } else { 7289 r.append(' '); 7290 } 7291 r.append(a.info.name); 7292 } 7293 } 7294 if (r != null) { 7295 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7296 } 7297 7298 if (pkg.protectedBroadcasts != null) { 7299 N = pkg.protectedBroadcasts.size(); 7300 for (i=0; i<N; i++) { 7301 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7302 } 7303 } 7304 7305 pkgSetting.setTimeStamp(scanFileTime); 7306 7307 // Create idmap files for pairs of (packages, overlay packages). 7308 // Note: "android", ie framework-res.apk, is handled by native layers. 7309 if (pkg.mOverlayTarget != null) { 7310 // This is an overlay package. 7311 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7312 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7313 mOverlays.put(pkg.mOverlayTarget, 7314 new ArrayMap<String, PackageParser.Package>()); 7315 } 7316 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7317 map.put(pkg.packageName, pkg); 7318 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7319 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7320 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7321 "scanPackageLI failed to createIdmap"); 7322 } 7323 } 7324 } else if (mOverlays.containsKey(pkg.packageName) && 7325 !pkg.packageName.equals("android")) { 7326 // This is a regular package, with one or more known overlay packages. 7327 createIdmapsForPackageLI(pkg); 7328 } 7329 } 7330 7331 return pkg; 7332 } 7333 7334 /** 7335 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7336 * is derived purely on the basis of the contents of {@code scanFile} and 7337 * {@code cpuAbiOverride}. 7338 * 7339 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7340 */ 7341 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7342 String cpuAbiOverride, boolean extractLibs) 7343 throws PackageManagerException { 7344 // TODO: We can probably be smarter about this stuff. For installed apps, 7345 // we can calculate this information at install time once and for all. For 7346 // system apps, we can probably assume that this information doesn't change 7347 // after the first boot scan. As things stand, we do lots of unnecessary work. 7348 7349 // Give ourselves some initial paths; we'll come back for another 7350 // pass once we've determined ABI below. 7351 setNativeLibraryPaths(pkg); 7352 7353 // We would never need to extract libs for forward-locked and external packages, 7354 // since the container service will do it for us. We shouldn't attempt to 7355 // extract libs from system app when it was not updated. 7356 if (pkg.isForwardLocked() || isExternal(pkg) || 7357 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7358 extractLibs = false; 7359 } 7360 7361 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7362 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7363 7364 NativeLibraryHelper.Handle handle = null; 7365 try { 7366 handle = NativeLibraryHelper.Handle.create(scanFile); 7367 // TODO(multiArch): This can be null for apps that didn't go through the 7368 // usual installation process. We can calculate it again, like we 7369 // do during install time. 7370 // 7371 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7372 // unnecessary. 7373 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7374 7375 // Null out the abis so that they can be recalculated. 7376 pkg.applicationInfo.primaryCpuAbi = null; 7377 pkg.applicationInfo.secondaryCpuAbi = null; 7378 if (isMultiArch(pkg.applicationInfo)) { 7379 // Warn if we've set an abiOverride for multi-lib packages.. 7380 // By definition, we need to copy both 32 and 64 bit libraries for 7381 // such packages. 7382 if (pkg.cpuAbiOverride != null 7383 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7384 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7385 } 7386 7387 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7388 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7389 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7390 if (extractLibs) { 7391 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7392 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7393 useIsaSpecificSubdirs); 7394 } else { 7395 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7396 } 7397 } 7398 7399 maybeThrowExceptionForMultiArchCopy( 7400 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7401 7402 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7403 if (extractLibs) { 7404 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7405 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7406 useIsaSpecificSubdirs); 7407 } else { 7408 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7409 } 7410 } 7411 7412 maybeThrowExceptionForMultiArchCopy( 7413 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7414 7415 if (abi64 >= 0) { 7416 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7417 } 7418 7419 if (abi32 >= 0) { 7420 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7421 if (abi64 >= 0) { 7422 pkg.applicationInfo.secondaryCpuAbi = abi; 7423 } else { 7424 pkg.applicationInfo.primaryCpuAbi = abi; 7425 } 7426 } 7427 } else { 7428 String[] abiList = (cpuAbiOverride != null) ? 7429 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7430 7431 // Enable gross and lame hacks for apps that are built with old 7432 // SDK tools. We must scan their APKs for renderscript bitcode and 7433 // not launch them if it's present. Don't bother checking on devices 7434 // that don't have 64 bit support. 7435 boolean needsRenderScriptOverride = false; 7436 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7437 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7438 abiList = Build.SUPPORTED_32_BIT_ABIS; 7439 needsRenderScriptOverride = true; 7440 } 7441 7442 final int copyRet; 7443 if (extractLibs) { 7444 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7445 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7446 } else { 7447 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7448 } 7449 7450 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7451 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7452 "Error unpackaging native libs for app, errorCode=" + copyRet); 7453 } 7454 7455 if (copyRet >= 0) { 7456 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7457 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7458 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7459 } else if (needsRenderScriptOverride) { 7460 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7461 } 7462 } 7463 } catch (IOException ioe) { 7464 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7465 } finally { 7466 IoUtils.closeQuietly(handle); 7467 } 7468 7469 // Now that we've calculated the ABIs and determined if it's an internal app, 7470 // we will go ahead and populate the nativeLibraryPath. 7471 setNativeLibraryPaths(pkg); 7472 } 7473 7474 /** 7475 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7476 * i.e, so that all packages can be run inside a single process if required. 7477 * 7478 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7479 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7480 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7481 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7482 * updating a package that belongs to a shared user. 7483 * 7484 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7485 * adds unnecessary complexity. 7486 */ 7487 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7488 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7489 String requiredInstructionSet = null; 7490 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7491 requiredInstructionSet = VMRuntime.getInstructionSet( 7492 scannedPackage.applicationInfo.primaryCpuAbi); 7493 } 7494 7495 PackageSetting requirer = null; 7496 for (PackageSetting ps : packagesForUser) { 7497 // If packagesForUser contains scannedPackage, we skip it. This will happen 7498 // when scannedPackage is an update of an existing package. Without this check, 7499 // we will never be able to change the ABI of any package belonging to a shared 7500 // user, even if it's compatible with other packages. 7501 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7502 if (ps.primaryCpuAbiString == null) { 7503 continue; 7504 } 7505 7506 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7507 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7508 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7509 // this but there's not much we can do. 7510 String errorMessage = "Instruction set mismatch, " 7511 + ((requirer == null) ? "[caller]" : requirer) 7512 + " requires " + requiredInstructionSet + " whereas " + ps 7513 + " requires " + instructionSet; 7514 Slog.w(TAG, errorMessage); 7515 } 7516 7517 if (requiredInstructionSet == null) { 7518 requiredInstructionSet = instructionSet; 7519 requirer = ps; 7520 } 7521 } 7522 } 7523 7524 if (requiredInstructionSet != null) { 7525 String adjustedAbi; 7526 if (requirer != null) { 7527 // requirer != null implies that either scannedPackage was null or that scannedPackage 7528 // did not require an ABI, in which case we have to adjust scannedPackage to match 7529 // the ABI of the set (which is the same as requirer's ABI) 7530 adjustedAbi = requirer.primaryCpuAbiString; 7531 if (scannedPackage != null) { 7532 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7533 } 7534 } else { 7535 // requirer == null implies that we're updating all ABIs in the set to 7536 // match scannedPackage. 7537 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7538 } 7539 7540 for (PackageSetting ps : packagesForUser) { 7541 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7542 if (ps.primaryCpuAbiString != null) { 7543 continue; 7544 } 7545 7546 ps.primaryCpuAbiString = adjustedAbi; 7547 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7548 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7549 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7550 7551 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7552 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7553 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7554 ps.primaryCpuAbiString = null; 7555 ps.pkg.applicationInfo.primaryCpuAbi = null; 7556 return; 7557 } else { 7558 mInstaller.rmdex(ps.codePathString, 7559 getDexCodeInstructionSet(getPreferredInstructionSet())); 7560 } 7561 } 7562 } 7563 } 7564 } 7565 } 7566 7567 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7568 synchronized (mPackages) { 7569 mResolverReplaced = true; 7570 // Set up information for custom user intent resolution activity. 7571 mResolveActivity.applicationInfo = pkg.applicationInfo; 7572 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7573 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7574 mResolveActivity.processName = pkg.applicationInfo.packageName; 7575 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7576 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7577 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7578 mResolveActivity.theme = 0; 7579 mResolveActivity.exported = true; 7580 mResolveActivity.enabled = true; 7581 mResolveInfo.activityInfo = mResolveActivity; 7582 mResolveInfo.priority = 0; 7583 mResolveInfo.preferredOrder = 0; 7584 mResolveInfo.match = 0; 7585 mResolveComponentName = mCustomResolverComponentName; 7586 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7587 mResolveComponentName); 7588 } 7589 } 7590 7591 private static String calculateBundledApkRoot(final String codePathString) { 7592 final File codePath = new File(codePathString); 7593 final File codeRoot; 7594 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7595 codeRoot = Environment.getRootDirectory(); 7596 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7597 codeRoot = Environment.getOemDirectory(); 7598 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7599 codeRoot = Environment.getVendorDirectory(); 7600 } else { 7601 // Unrecognized code path; take its top real segment as the apk root: 7602 // e.g. /something/app/blah.apk => /something 7603 try { 7604 File f = codePath.getCanonicalFile(); 7605 File parent = f.getParentFile(); // non-null because codePath is a file 7606 File tmp; 7607 while ((tmp = parent.getParentFile()) != null) { 7608 f = parent; 7609 parent = tmp; 7610 } 7611 codeRoot = f; 7612 Slog.w(TAG, "Unrecognized code path " 7613 + codePath + " - using " + codeRoot); 7614 } catch (IOException e) { 7615 // Can't canonicalize the code path -- shenanigans? 7616 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7617 return Environment.getRootDirectory().getPath(); 7618 } 7619 } 7620 return codeRoot.getPath(); 7621 } 7622 7623 /** 7624 * Derive and set the location of native libraries for the given package, 7625 * which varies depending on where and how the package was installed. 7626 */ 7627 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7628 final ApplicationInfo info = pkg.applicationInfo; 7629 final String codePath = pkg.codePath; 7630 final File codeFile = new File(codePath); 7631 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7632 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7633 7634 info.nativeLibraryRootDir = null; 7635 info.nativeLibraryRootRequiresIsa = false; 7636 info.nativeLibraryDir = null; 7637 info.secondaryNativeLibraryDir = null; 7638 7639 if (isApkFile(codeFile)) { 7640 // Monolithic install 7641 if (bundledApp) { 7642 // If "/system/lib64/apkname" exists, assume that is the per-package 7643 // native library directory to use; otherwise use "/system/lib/apkname". 7644 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7645 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7646 getPrimaryInstructionSet(info)); 7647 7648 // This is a bundled system app so choose the path based on the ABI. 7649 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7650 // is just the default path. 7651 final String apkName = deriveCodePathName(codePath); 7652 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7653 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7654 apkName).getAbsolutePath(); 7655 7656 if (info.secondaryCpuAbi != null) { 7657 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7658 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7659 secondaryLibDir, apkName).getAbsolutePath(); 7660 } 7661 } else if (asecApp) { 7662 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7663 .getAbsolutePath(); 7664 } else { 7665 final String apkName = deriveCodePathName(codePath); 7666 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7667 .getAbsolutePath(); 7668 } 7669 7670 info.nativeLibraryRootRequiresIsa = false; 7671 info.nativeLibraryDir = info.nativeLibraryRootDir; 7672 } else { 7673 // Cluster install 7674 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7675 info.nativeLibraryRootRequiresIsa = true; 7676 7677 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7678 getPrimaryInstructionSet(info)).getAbsolutePath(); 7679 7680 if (info.secondaryCpuAbi != null) { 7681 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7682 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7683 } 7684 } 7685 } 7686 7687 /** 7688 * Calculate the abis and roots for a bundled app. These can uniquely 7689 * be determined from the contents of the system partition, i.e whether 7690 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7691 * of this information, and instead assume that the system was built 7692 * sensibly. 7693 */ 7694 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7695 PackageSetting pkgSetting) { 7696 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7697 7698 // If "/system/lib64/apkname" exists, assume that is the per-package 7699 // native library directory to use; otherwise use "/system/lib/apkname". 7700 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7701 setBundledAppAbi(pkg, apkRoot, apkName); 7702 // pkgSetting might be null during rescan following uninstall of updates 7703 // to a bundled app, so accommodate that possibility. The settings in 7704 // that case will be established later from the parsed package. 7705 // 7706 // If the settings aren't null, sync them up with what we've just derived. 7707 // note that apkRoot isn't stored in the package settings. 7708 if (pkgSetting != null) { 7709 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7710 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7711 } 7712 } 7713 7714 /** 7715 * Deduces the ABI of a bundled app and sets the relevant fields on the 7716 * parsed pkg object. 7717 * 7718 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7719 * under which system libraries are installed. 7720 * @param apkName the name of the installed package. 7721 */ 7722 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7723 final File codeFile = new File(pkg.codePath); 7724 7725 final boolean has64BitLibs; 7726 final boolean has32BitLibs; 7727 if (isApkFile(codeFile)) { 7728 // Monolithic install 7729 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7730 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7731 } else { 7732 // Cluster install 7733 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7734 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7735 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7736 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7737 has64BitLibs = (new File(rootDir, isa)).exists(); 7738 } else { 7739 has64BitLibs = false; 7740 } 7741 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7742 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7743 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7744 has32BitLibs = (new File(rootDir, isa)).exists(); 7745 } else { 7746 has32BitLibs = false; 7747 } 7748 } 7749 7750 if (has64BitLibs && !has32BitLibs) { 7751 // The package has 64 bit libs, but not 32 bit libs. Its primary 7752 // ABI should be 64 bit. We can safely assume here that the bundled 7753 // native libraries correspond to the most preferred ABI in the list. 7754 7755 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7756 pkg.applicationInfo.secondaryCpuAbi = null; 7757 } else if (has32BitLibs && !has64BitLibs) { 7758 // The package has 32 bit libs but not 64 bit libs. Its primary 7759 // ABI should be 32 bit. 7760 7761 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7762 pkg.applicationInfo.secondaryCpuAbi = null; 7763 } else if (has32BitLibs && has64BitLibs) { 7764 // The application has both 64 and 32 bit bundled libraries. We check 7765 // here that the app declares multiArch support, and warn if it doesn't. 7766 // 7767 // We will be lenient here and record both ABIs. The primary will be the 7768 // ABI that's higher on the list, i.e, a device that's configured to prefer 7769 // 64 bit apps will see a 64 bit primary ABI, 7770 7771 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7772 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7773 } 7774 7775 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7776 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7777 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7778 } else { 7779 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7780 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7781 } 7782 } else { 7783 pkg.applicationInfo.primaryCpuAbi = null; 7784 pkg.applicationInfo.secondaryCpuAbi = null; 7785 } 7786 } 7787 7788 private void killApplication(String pkgName, int appId, String reason) { 7789 // Request the ActivityManager to kill the process(only for existing packages) 7790 // so that we do not end up in a confused state while the user is still using the older 7791 // version of the application while the new one gets installed. 7792 IActivityManager am = ActivityManagerNative.getDefault(); 7793 if (am != null) { 7794 try { 7795 am.killApplicationWithAppId(pkgName, appId, reason); 7796 } catch (RemoteException e) { 7797 } 7798 } 7799 } 7800 7801 void removePackageLI(PackageSetting ps, boolean chatty) { 7802 if (DEBUG_INSTALL) { 7803 if (chatty) 7804 Log.d(TAG, "Removing package " + ps.name); 7805 } 7806 7807 // writer 7808 synchronized (mPackages) { 7809 mPackages.remove(ps.name); 7810 final PackageParser.Package pkg = ps.pkg; 7811 if (pkg != null) { 7812 cleanPackageDataStructuresLILPw(pkg, chatty); 7813 } 7814 } 7815 } 7816 7817 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7818 if (DEBUG_INSTALL) { 7819 if (chatty) 7820 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7821 } 7822 7823 // writer 7824 synchronized (mPackages) { 7825 mPackages.remove(pkg.applicationInfo.packageName); 7826 cleanPackageDataStructuresLILPw(pkg, chatty); 7827 } 7828 } 7829 7830 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7831 int N = pkg.providers.size(); 7832 StringBuilder r = null; 7833 int i; 7834 for (i=0; i<N; i++) { 7835 PackageParser.Provider p = pkg.providers.get(i); 7836 mProviders.removeProvider(p); 7837 if (p.info.authority == null) { 7838 7839 /* There was another ContentProvider with this authority when 7840 * this app was installed so this authority is null, 7841 * Ignore it as we don't have to unregister the provider. 7842 */ 7843 continue; 7844 } 7845 String names[] = p.info.authority.split(";"); 7846 for (int j = 0; j < names.length; j++) { 7847 if (mProvidersByAuthority.get(names[j]) == p) { 7848 mProvidersByAuthority.remove(names[j]); 7849 if (DEBUG_REMOVE) { 7850 if (chatty) 7851 Log.d(TAG, "Unregistered content provider: " + names[j] 7852 + ", className = " + p.info.name + ", isSyncable = " 7853 + p.info.isSyncable); 7854 } 7855 } 7856 } 7857 if (DEBUG_REMOVE && chatty) { 7858 if (r == null) { 7859 r = new StringBuilder(256); 7860 } else { 7861 r.append(' '); 7862 } 7863 r.append(p.info.name); 7864 } 7865 } 7866 if (r != null) { 7867 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7868 } 7869 7870 N = pkg.services.size(); 7871 r = null; 7872 for (i=0; i<N; i++) { 7873 PackageParser.Service s = pkg.services.get(i); 7874 mServices.removeService(s); 7875 if (chatty) { 7876 if (r == null) { 7877 r = new StringBuilder(256); 7878 } else { 7879 r.append(' '); 7880 } 7881 r.append(s.info.name); 7882 } 7883 } 7884 if (r != null) { 7885 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7886 } 7887 7888 N = pkg.receivers.size(); 7889 r = null; 7890 for (i=0; i<N; i++) { 7891 PackageParser.Activity a = pkg.receivers.get(i); 7892 mReceivers.removeActivity(a, "receiver"); 7893 if (DEBUG_REMOVE && chatty) { 7894 if (r == null) { 7895 r = new StringBuilder(256); 7896 } else { 7897 r.append(' '); 7898 } 7899 r.append(a.info.name); 7900 } 7901 } 7902 if (r != null) { 7903 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7904 } 7905 7906 N = pkg.activities.size(); 7907 r = null; 7908 for (i=0; i<N; i++) { 7909 PackageParser.Activity a = pkg.activities.get(i); 7910 mActivities.removeActivity(a, "activity"); 7911 if (DEBUG_REMOVE && chatty) { 7912 if (r == null) { 7913 r = new StringBuilder(256); 7914 } else { 7915 r.append(' '); 7916 } 7917 r.append(a.info.name); 7918 } 7919 } 7920 if (r != null) { 7921 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7922 } 7923 7924 N = pkg.permissions.size(); 7925 r = null; 7926 for (i=0; i<N; i++) { 7927 PackageParser.Permission p = pkg.permissions.get(i); 7928 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7929 if (bp == null) { 7930 bp = mSettings.mPermissionTrees.get(p.info.name); 7931 } 7932 if (bp != null && bp.perm == p) { 7933 bp.perm = null; 7934 if (DEBUG_REMOVE && chatty) { 7935 if (r == null) { 7936 r = new StringBuilder(256); 7937 } else { 7938 r.append(' '); 7939 } 7940 r.append(p.info.name); 7941 } 7942 } 7943 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7944 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7945 if (appOpPerms != null) { 7946 appOpPerms.remove(pkg.packageName); 7947 } 7948 } 7949 } 7950 if (r != null) { 7951 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7952 } 7953 7954 N = pkg.requestedPermissions.size(); 7955 r = null; 7956 for (i=0; i<N; i++) { 7957 String perm = pkg.requestedPermissions.get(i); 7958 BasePermission bp = mSettings.mPermissions.get(perm); 7959 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7960 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7961 if (appOpPerms != null) { 7962 appOpPerms.remove(pkg.packageName); 7963 if (appOpPerms.isEmpty()) { 7964 mAppOpPermissionPackages.remove(perm); 7965 } 7966 } 7967 } 7968 } 7969 if (r != null) { 7970 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7971 } 7972 7973 N = pkg.instrumentation.size(); 7974 r = null; 7975 for (i=0; i<N; i++) { 7976 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7977 mInstrumentation.remove(a.getComponentName()); 7978 if (DEBUG_REMOVE && chatty) { 7979 if (r == null) { 7980 r = new StringBuilder(256); 7981 } else { 7982 r.append(' '); 7983 } 7984 r.append(a.info.name); 7985 } 7986 } 7987 if (r != null) { 7988 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7989 } 7990 7991 r = null; 7992 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7993 // Only system apps can hold shared libraries. 7994 if (pkg.libraryNames != null) { 7995 for (i=0; i<pkg.libraryNames.size(); i++) { 7996 String name = pkg.libraryNames.get(i); 7997 SharedLibraryEntry cur = mSharedLibraries.get(name); 7998 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7999 mSharedLibraries.remove(name); 8000 if (DEBUG_REMOVE && chatty) { 8001 if (r == null) { 8002 r = new StringBuilder(256); 8003 } else { 8004 r.append(' '); 8005 } 8006 r.append(name); 8007 } 8008 } 8009 } 8010 } 8011 } 8012 if (r != null) { 8013 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8014 } 8015 } 8016 8017 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8018 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8019 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8020 return true; 8021 } 8022 } 8023 return false; 8024 } 8025 8026 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8027 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8028 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8029 8030 private void updatePermissionsLPw(String changingPkg, 8031 PackageParser.Package pkgInfo, int flags) { 8032 // Make sure there are no dangling permission trees. 8033 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8034 while (it.hasNext()) { 8035 final BasePermission bp = it.next(); 8036 if (bp.packageSetting == null) { 8037 // We may not yet have parsed the package, so just see if 8038 // we still know about its settings. 8039 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8040 } 8041 if (bp.packageSetting == null) { 8042 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8043 + " from package " + bp.sourcePackage); 8044 it.remove(); 8045 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8046 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8047 Slog.i(TAG, "Removing old permission tree: " + bp.name 8048 + " from package " + bp.sourcePackage); 8049 flags |= UPDATE_PERMISSIONS_ALL; 8050 it.remove(); 8051 } 8052 } 8053 } 8054 8055 // Make sure all dynamic permissions have been assigned to a package, 8056 // and make sure there are no dangling permissions. 8057 it = mSettings.mPermissions.values().iterator(); 8058 while (it.hasNext()) { 8059 final BasePermission bp = it.next(); 8060 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8061 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8062 + bp.name + " pkg=" + bp.sourcePackage 8063 + " info=" + bp.pendingInfo); 8064 if (bp.packageSetting == null && bp.pendingInfo != null) { 8065 final BasePermission tree = findPermissionTreeLP(bp.name); 8066 if (tree != null && tree.perm != null) { 8067 bp.packageSetting = tree.packageSetting; 8068 bp.perm = new PackageParser.Permission(tree.perm.owner, 8069 new PermissionInfo(bp.pendingInfo)); 8070 bp.perm.info.packageName = tree.perm.info.packageName; 8071 bp.perm.info.name = bp.name; 8072 bp.uid = tree.uid; 8073 } 8074 } 8075 } 8076 if (bp.packageSetting == null) { 8077 // We may not yet have parsed the package, so just see if 8078 // we still know about its settings. 8079 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8080 } 8081 if (bp.packageSetting == null) { 8082 Slog.w(TAG, "Removing dangling permission: " + bp.name 8083 + " from package " + bp.sourcePackage); 8084 it.remove(); 8085 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8086 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8087 Slog.i(TAG, "Removing old permission: " + bp.name 8088 + " from package " + bp.sourcePackage); 8089 flags |= UPDATE_PERMISSIONS_ALL; 8090 it.remove(); 8091 } 8092 } 8093 } 8094 8095 // Now update the permissions for all packages, in particular 8096 // replace the granted permissions of the system packages. 8097 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8098 for (PackageParser.Package pkg : mPackages.values()) { 8099 if (pkg != pkgInfo) { 8100 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8101 changingPkg); 8102 } 8103 } 8104 } 8105 8106 if (pkgInfo != null) { 8107 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8108 } 8109 } 8110 8111 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8112 String packageOfInterest) { 8113 // IMPORTANT: There are two types of permissions: install and runtime. 8114 // Install time permissions are granted when the app is installed to 8115 // all device users and users added in the future. Runtime permissions 8116 // are granted at runtime explicitly to specific users. Normal and signature 8117 // protected permissions are install time permissions. Dangerous permissions 8118 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8119 // otherwise they are runtime permissions. This function does not manage 8120 // runtime permissions except for the case an app targeting Lollipop MR1 8121 // being upgraded to target a newer SDK, in which case dangerous permissions 8122 // are transformed from install time to runtime ones. 8123 8124 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8125 if (ps == null) { 8126 return; 8127 } 8128 8129 PermissionsState permissionsState = ps.getPermissionsState(); 8130 PermissionsState origPermissions = permissionsState; 8131 8132 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8133 8134 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8135 8136 boolean changedInstallPermission = false; 8137 8138 if (replace) { 8139 ps.installPermissionsFixed = false; 8140 if (!ps.isSharedUser()) { 8141 origPermissions = new PermissionsState(permissionsState); 8142 permissionsState.reset(); 8143 } 8144 } 8145 8146 permissionsState.setGlobalGids(mGlobalGids); 8147 8148 final int N = pkg.requestedPermissions.size(); 8149 for (int i=0; i<N; i++) { 8150 final String name = pkg.requestedPermissions.get(i); 8151 final BasePermission bp = mSettings.mPermissions.get(name); 8152 8153 if (DEBUG_INSTALL) { 8154 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8155 } 8156 8157 if (bp == null || bp.packageSetting == null) { 8158 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8159 Slog.w(TAG, "Unknown permission " + name 8160 + " in package " + pkg.packageName); 8161 } 8162 continue; 8163 } 8164 8165 final String perm = bp.name; 8166 boolean allowedSig = false; 8167 int grant = GRANT_DENIED; 8168 8169 // Keep track of app op permissions. 8170 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8171 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8172 if (pkgs == null) { 8173 pkgs = new ArraySet<>(); 8174 mAppOpPermissionPackages.put(bp.name, pkgs); 8175 } 8176 pkgs.add(pkg.packageName); 8177 } 8178 8179 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8180 switch (level) { 8181 case PermissionInfo.PROTECTION_NORMAL: { 8182 // For all apps normal permissions are install time ones. 8183 grant = GRANT_INSTALL; 8184 } break; 8185 8186 case PermissionInfo.PROTECTION_DANGEROUS: { 8187 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8188 // For legacy apps dangerous permissions are install time ones. 8189 grant = GRANT_INSTALL_LEGACY; 8190 } else if (origPermissions.hasInstallPermission(bp.name)) { 8191 // For legacy apps that became modern, install becomes runtime. 8192 grant = GRANT_UPGRADE; 8193 } else { 8194 // For modern apps keep runtime permissions unchanged. 8195 grant = GRANT_RUNTIME; 8196 } 8197 } break; 8198 8199 case PermissionInfo.PROTECTION_SIGNATURE: { 8200 // For all apps signature permissions are install time ones. 8201 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8202 if (allowedSig) { 8203 grant = GRANT_INSTALL; 8204 } 8205 } break; 8206 } 8207 8208 if (DEBUG_INSTALL) { 8209 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8210 } 8211 8212 if (grant != GRANT_DENIED) { 8213 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8214 // If this is an existing, non-system package, then 8215 // we can't add any new permissions to it. 8216 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8217 // Except... if this is a permission that was added 8218 // to the platform (note: need to only do this when 8219 // updating the platform). 8220 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8221 grant = GRANT_DENIED; 8222 } 8223 } 8224 } 8225 8226 switch (grant) { 8227 case GRANT_INSTALL: { 8228 // Revoke this as runtime permission to handle the case of 8229 // a runtime permission being downgraded to an install one. 8230 for (int userId : UserManagerService.getInstance().getUserIds()) { 8231 if (origPermissions.getRuntimePermissionState( 8232 bp.name, userId) != null) { 8233 // Revoke the runtime permission and clear the flags. 8234 origPermissions.revokeRuntimePermission(bp, userId); 8235 origPermissions.updatePermissionFlags(bp, userId, 8236 PackageManager.MASK_PERMISSION_FLAGS, 0); 8237 // If we revoked a permission permission, we have to write. 8238 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8239 changedRuntimePermissionUserIds, userId); 8240 } 8241 } 8242 // Grant an install permission. 8243 if (permissionsState.grantInstallPermission(bp) != 8244 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8245 changedInstallPermission = true; 8246 } 8247 } break; 8248 8249 case GRANT_INSTALL_LEGACY: { 8250 // Grant an install permission. 8251 if (permissionsState.grantInstallPermission(bp) != 8252 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8253 changedInstallPermission = true; 8254 } 8255 } break; 8256 8257 case GRANT_RUNTIME: { 8258 // Grant previously granted runtime permissions. 8259 for (int userId : UserManagerService.getInstance().getUserIds()) { 8260 PermissionState permissionState = origPermissions 8261 .getRuntimePermissionState(bp.name, userId); 8262 final int flags = permissionState != null 8263 ? permissionState.getFlags() : 0; 8264 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8265 if (permissionsState.grantRuntimePermission(bp, userId) == 8266 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8267 // If we cannot put the permission as it was, we have to write. 8268 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8269 changedRuntimePermissionUserIds, userId); 8270 } 8271 } 8272 // Propagate the permission flags. 8273 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8274 } 8275 } break; 8276 8277 case GRANT_UPGRADE: { 8278 // Grant runtime permissions for a previously held install permission. 8279 PermissionState permissionState = origPermissions 8280 .getInstallPermissionState(bp.name); 8281 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8282 8283 if (origPermissions.revokeInstallPermission(bp) 8284 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8285 // We will be transferring the permission flags, so clear them. 8286 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8287 PackageManager.MASK_PERMISSION_FLAGS, 0); 8288 changedInstallPermission = true; 8289 } 8290 8291 // If the permission is not to be promoted to runtime we ignore it and 8292 // also its other flags as they are not applicable to install permissions. 8293 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8294 for (int userId : currentUserIds) { 8295 if (permissionsState.grantRuntimePermission(bp, userId) != 8296 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8297 // Transfer the permission flags. 8298 permissionsState.updatePermissionFlags(bp, userId, 8299 flags, flags); 8300 // If we granted the permission, we have to write. 8301 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8302 changedRuntimePermissionUserIds, userId); 8303 } 8304 } 8305 } 8306 } break; 8307 8308 default: { 8309 if (packageOfInterest == null 8310 || packageOfInterest.equals(pkg.packageName)) { 8311 Slog.w(TAG, "Not granting permission " + perm 8312 + " to package " + pkg.packageName 8313 + " because it was previously installed without"); 8314 } 8315 } break; 8316 } 8317 } else { 8318 if (permissionsState.revokeInstallPermission(bp) != 8319 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8320 // Also drop the permission flags. 8321 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8322 PackageManager.MASK_PERMISSION_FLAGS, 0); 8323 changedInstallPermission = true; 8324 Slog.i(TAG, "Un-granting permission " + perm 8325 + " from package " + pkg.packageName 8326 + " (protectionLevel=" + bp.protectionLevel 8327 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8328 + ")"); 8329 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8330 // Don't print warning for app op permissions, since it is fine for them 8331 // not to be granted, there is a UI for the user to decide. 8332 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8333 Slog.w(TAG, "Not granting permission " + perm 8334 + " to package " + pkg.packageName 8335 + " (protectionLevel=" + bp.protectionLevel 8336 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8337 + ")"); 8338 } 8339 } 8340 } 8341 } 8342 8343 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8344 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8345 // This is the first that we have heard about this package, so the 8346 // permissions we have now selected are fixed until explicitly 8347 // changed. 8348 ps.installPermissionsFixed = true; 8349 } 8350 8351 // Persist the runtime permissions state for users with changes. 8352 for (int userId : changedRuntimePermissionUserIds) { 8353 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8354 } 8355 } 8356 8357 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8358 boolean allowed = false; 8359 final int NP = PackageParser.NEW_PERMISSIONS.length; 8360 for (int ip=0; ip<NP; ip++) { 8361 final PackageParser.NewPermissionInfo npi 8362 = PackageParser.NEW_PERMISSIONS[ip]; 8363 if (npi.name.equals(perm) 8364 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8365 allowed = true; 8366 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8367 + pkg.packageName); 8368 break; 8369 } 8370 } 8371 return allowed; 8372 } 8373 8374 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8375 BasePermission bp, PermissionsState origPermissions) { 8376 boolean allowed; 8377 allowed = (compareSignatures( 8378 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8379 == PackageManager.SIGNATURE_MATCH) 8380 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8381 == PackageManager.SIGNATURE_MATCH); 8382 if (!allowed && (bp.protectionLevel 8383 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8384 if (isSystemApp(pkg)) { 8385 // For updated system applications, a system permission 8386 // is granted only if it had been defined by the original application. 8387 if (pkg.isUpdatedSystemApp()) { 8388 final PackageSetting sysPs = mSettings 8389 .getDisabledSystemPkgLPr(pkg.packageName); 8390 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8391 // If the original was granted this permission, we take 8392 // that grant decision as read and propagate it to the 8393 // update. 8394 if (sysPs.isPrivileged()) { 8395 allowed = true; 8396 } 8397 } else { 8398 // The system apk may have been updated with an older 8399 // version of the one on the data partition, but which 8400 // granted a new system permission that it didn't have 8401 // before. In this case we do want to allow the app to 8402 // now get the new permission if the ancestral apk is 8403 // privileged to get it. 8404 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8405 for (int j=0; 8406 j<sysPs.pkg.requestedPermissions.size(); j++) { 8407 if (perm.equals( 8408 sysPs.pkg.requestedPermissions.get(j))) { 8409 allowed = true; 8410 break; 8411 } 8412 } 8413 } 8414 } 8415 } else { 8416 allowed = isPrivilegedApp(pkg); 8417 } 8418 } 8419 } 8420 if (!allowed && (bp.protectionLevel 8421 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8422 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8423 // If this was a previously normal/dangerous permission that got moved 8424 // to a system permission as part of the runtime permission redesign, then 8425 // we still want to blindly grant it to old apps. 8426 allowed = true; 8427 } 8428 if (!allowed && (bp.protectionLevel 8429 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8430 // For development permissions, a development permission 8431 // is granted only if it was already granted. 8432 allowed = origPermissions.hasInstallPermission(perm); 8433 } 8434 return allowed; 8435 } 8436 8437 final class ActivityIntentResolver 8438 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8439 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8440 boolean defaultOnly, int userId) { 8441 if (!sUserManager.exists(userId)) return null; 8442 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8443 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8444 } 8445 8446 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8447 int userId) { 8448 if (!sUserManager.exists(userId)) return null; 8449 mFlags = flags; 8450 return super.queryIntent(intent, resolvedType, 8451 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8452 } 8453 8454 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8455 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8456 if (!sUserManager.exists(userId)) return null; 8457 if (packageActivities == null) { 8458 return null; 8459 } 8460 mFlags = flags; 8461 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8462 final int N = packageActivities.size(); 8463 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8464 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8465 8466 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8467 for (int i = 0; i < N; ++i) { 8468 intentFilters = packageActivities.get(i).intents; 8469 if (intentFilters != null && intentFilters.size() > 0) { 8470 PackageParser.ActivityIntentInfo[] array = 8471 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8472 intentFilters.toArray(array); 8473 listCut.add(array); 8474 } 8475 } 8476 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8477 } 8478 8479 public final void addActivity(PackageParser.Activity a, String type) { 8480 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8481 mActivities.put(a.getComponentName(), a); 8482 if (DEBUG_SHOW_INFO) 8483 Log.v( 8484 TAG, " " + type + " " + 8485 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8486 if (DEBUG_SHOW_INFO) 8487 Log.v(TAG, " Class=" + a.info.name); 8488 final int NI = a.intents.size(); 8489 for (int j=0; j<NI; j++) { 8490 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8491 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8492 intent.setPriority(0); 8493 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8494 + a.className + " with priority > 0, forcing to 0"); 8495 } 8496 if (DEBUG_SHOW_INFO) { 8497 Log.v(TAG, " IntentFilter:"); 8498 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8499 } 8500 if (!intent.debugCheck()) { 8501 Log.w(TAG, "==> For Activity " + a.info.name); 8502 } 8503 addFilter(intent); 8504 } 8505 } 8506 8507 public final void removeActivity(PackageParser.Activity a, String type) { 8508 mActivities.remove(a.getComponentName()); 8509 if (DEBUG_SHOW_INFO) { 8510 Log.v(TAG, " " + type + " " 8511 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8512 : a.info.name) + ":"); 8513 Log.v(TAG, " Class=" + a.info.name); 8514 } 8515 final int NI = a.intents.size(); 8516 for (int j=0; j<NI; j++) { 8517 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8518 if (DEBUG_SHOW_INFO) { 8519 Log.v(TAG, " IntentFilter:"); 8520 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8521 } 8522 removeFilter(intent); 8523 } 8524 } 8525 8526 @Override 8527 protected boolean allowFilterResult( 8528 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8529 ActivityInfo filterAi = filter.activity.info; 8530 for (int i=dest.size()-1; i>=0; i--) { 8531 ActivityInfo destAi = dest.get(i).activityInfo; 8532 if (destAi.name == filterAi.name 8533 && destAi.packageName == filterAi.packageName) { 8534 return false; 8535 } 8536 } 8537 return true; 8538 } 8539 8540 @Override 8541 protected ActivityIntentInfo[] newArray(int size) { 8542 return new ActivityIntentInfo[size]; 8543 } 8544 8545 @Override 8546 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8547 if (!sUserManager.exists(userId)) return true; 8548 PackageParser.Package p = filter.activity.owner; 8549 if (p != null) { 8550 PackageSetting ps = (PackageSetting)p.mExtras; 8551 if (ps != null) { 8552 // System apps are never considered stopped for purposes of 8553 // filtering, because there may be no way for the user to 8554 // actually re-launch them. 8555 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8556 && ps.getStopped(userId); 8557 } 8558 } 8559 return false; 8560 } 8561 8562 @Override 8563 protected boolean isPackageForFilter(String packageName, 8564 PackageParser.ActivityIntentInfo info) { 8565 return packageName.equals(info.activity.owner.packageName); 8566 } 8567 8568 @Override 8569 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8570 int match, int userId) { 8571 if (!sUserManager.exists(userId)) return null; 8572 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8573 return null; 8574 } 8575 final PackageParser.Activity activity = info.activity; 8576 if (mSafeMode && (activity.info.applicationInfo.flags 8577 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8578 return null; 8579 } 8580 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8581 if (ps == null) { 8582 return null; 8583 } 8584 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8585 ps.readUserState(userId), userId); 8586 if (ai == null) { 8587 return null; 8588 } 8589 final ResolveInfo res = new ResolveInfo(); 8590 res.activityInfo = ai; 8591 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8592 res.filter = info; 8593 } 8594 if (info != null) { 8595 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8596 } 8597 res.priority = info.getPriority(); 8598 res.preferredOrder = activity.owner.mPreferredOrder; 8599 //System.out.println("Result: " + res.activityInfo.className + 8600 // " = " + res.priority); 8601 res.match = match; 8602 res.isDefault = info.hasDefault; 8603 res.labelRes = info.labelRes; 8604 res.nonLocalizedLabel = info.nonLocalizedLabel; 8605 if (userNeedsBadging(userId)) { 8606 res.noResourceId = true; 8607 } else { 8608 res.icon = info.icon; 8609 } 8610 res.iconResourceId = info.icon; 8611 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8612 return res; 8613 } 8614 8615 @Override 8616 protected void sortResults(List<ResolveInfo> results) { 8617 Collections.sort(results, mResolvePrioritySorter); 8618 } 8619 8620 @Override 8621 protected void dumpFilter(PrintWriter out, String prefix, 8622 PackageParser.ActivityIntentInfo filter) { 8623 out.print(prefix); out.print( 8624 Integer.toHexString(System.identityHashCode(filter.activity))); 8625 out.print(' '); 8626 filter.activity.printComponentShortName(out); 8627 out.print(" filter "); 8628 out.println(Integer.toHexString(System.identityHashCode(filter))); 8629 } 8630 8631 @Override 8632 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8633 return filter.activity; 8634 } 8635 8636 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8637 PackageParser.Activity activity = (PackageParser.Activity)label; 8638 out.print(prefix); out.print( 8639 Integer.toHexString(System.identityHashCode(activity))); 8640 out.print(' '); 8641 activity.printComponentShortName(out); 8642 if (count > 1) { 8643 out.print(" ("); out.print(count); out.print(" filters)"); 8644 } 8645 out.println(); 8646 } 8647 8648// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8649// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8650// final List<ResolveInfo> retList = Lists.newArrayList(); 8651// while (i.hasNext()) { 8652// final ResolveInfo resolveInfo = i.next(); 8653// if (isEnabledLP(resolveInfo.activityInfo)) { 8654// retList.add(resolveInfo); 8655// } 8656// } 8657// return retList; 8658// } 8659 8660 // Keys are String (activity class name), values are Activity. 8661 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8662 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8663 private int mFlags; 8664 } 8665 8666 private final class ServiceIntentResolver 8667 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8668 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8669 boolean defaultOnly, int userId) { 8670 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8671 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8672 } 8673 8674 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8675 int userId) { 8676 if (!sUserManager.exists(userId)) return null; 8677 mFlags = flags; 8678 return super.queryIntent(intent, resolvedType, 8679 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8680 } 8681 8682 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8683 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8684 if (!sUserManager.exists(userId)) return null; 8685 if (packageServices == null) { 8686 return null; 8687 } 8688 mFlags = flags; 8689 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8690 final int N = packageServices.size(); 8691 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8692 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8693 8694 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8695 for (int i = 0; i < N; ++i) { 8696 intentFilters = packageServices.get(i).intents; 8697 if (intentFilters != null && intentFilters.size() > 0) { 8698 PackageParser.ServiceIntentInfo[] array = 8699 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8700 intentFilters.toArray(array); 8701 listCut.add(array); 8702 } 8703 } 8704 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8705 } 8706 8707 public final void addService(PackageParser.Service s) { 8708 mServices.put(s.getComponentName(), s); 8709 if (DEBUG_SHOW_INFO) { 8710 Log.v(TAG, " " 8711 + (s.info.nonLocalizedLabel != null 8712 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8713 Log.v(TAG, " Class=" + s.info.name); 8714 } 8715 final int NI = s.intents.size(); 8716 int j; 8717 for (j=0; j<NI; j++) { 8718 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8719 if (DEBUG_SHOW_INFO) { 8720 Log.v(TAG, " IntentFilter:"); 8721 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8722 } 8723 if (!intent.debugCheck()) { 8724 Log.w(TAG, "==> For Service " + s.info.name); 8725 } 8726 addFilter(intent); 8727 } 8728 } 8729 8730 public final void removeService(PackageParser.Service s) { 8731 mServices.remove(s.getComponentName()); 8732 if (DEBUG_SHOW_INFO) { 8733 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8734 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8735 Log.v(TAG, " Class=" + s.info.name); 8736 } 8737 final int NI = s.intents.size(); 8738 int j; 8739 for (j=0; j<NI; j++) { 8740 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8741 if (DEBUG_SHOW_INFO) { 8742 Log.v(TAG, " IntentFilter:"); 8743 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8744 } 8745 removeFilter(intent); 8746 } 8747 } 8748 8749 @Override 8750 protected boolean allowFilterResult( 8751 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8752 ServiceInfo filterSi = filter.service.info; 8753 for (int i=dest.size()-1; i>=0; i--) { 8754 ServiceInfo destAi = dest.get(i).serviceInfo; 8755 if (destAi.name == filterSi.name 8756 && destAi.packageName == filterSi.packageName) { 8757 return false; 8758 } 8759 } 8760 return true; 8761 } 8762 8763 @Override 8764 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8765 return new PackageParser.ServiceIntentInfo[size]; 8766 } 8767 8768 @Override 8769 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8770 if (!sUserManager.exists(userId)) return true; 8771 PackageParser.Package p = filter.service.owner; 8772 if (p != null) { 8773 PackageSetting ps = (PackageSetting)p.mExtras; 8774 if (ps != null) { 8775 // System apps are never considered stopped for purposes of 8776 // filtering, because there may be no way for the user to 8777 // actually re-launch them. 8778 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8779 && ps.getStopped(userId); 8780 } 8781 } 8782 return false; 8783 } 8784 8785 @Override 8786 protected boolean isPackageForFilter(String packageName, 8787 PackageParser.ServiceIntentInfo info) { 8788 return packageName.equals(info.service.owner.packageName); 8789 } 8790 8791 @Override 8792 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8793 int match, int userId) { 8794 if (!sUserManager.exists(userId)) return null; 8795 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8796 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8797 return null; 8798 } 8799 final PackageParser.Service service = info.service; 8800 if (mSafeMode && (service.info.applicationInfo.flags 8801 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8802 return null; 8803 } 8804 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8805 if (ps == null) { 8806 return null; 8807 } 8808 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8809 ps.readUserState(userId), userId); 8810 if (si == null) { 8811 return null; 8812 } 8813 final ResolveInfo res = new ResolveInfo(); 8814 res.serviceInfo = si; 8815 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8816 res.filter = filter; 8817 } 8818 res.priority = info.getPriority(); 8819 res.preferredOrder = service.owner.mPreferredOrder; 8820 res.match = match; 8821 res.isDefault = info.hasDefault; 8822 res.labelRes = info.labelRes; 8823 res.nonLocalizedLabel = info.nonLocalizedLabel; 8824 res.icon = info.icon; 8825 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8826 return res; 8827 } 8828 8829 @Override 8830 protected void sortResults(List<ResolveInfo> results) { 8831 Collections.sort(results, mResolvePrioritySorter); 8832 } 8833 8834 @Override 8835 protected void dumpFilter(PrintWriter out, String prefix, 8836 PackageParser.ServiceIntentInfo filter) { 8837 out.print(prefix); out.print( 8838 Integer.toHexString(System.identityHashCode(filter.service))); 8839 out.print(' '); 8840 filter.service.printComponentShortName(out); 8841 out.print(" filter "); 8842 out.println(Integer.toHexString(System.identityHashCode(filter))); 8843 } 8844 8845 @Override 8846 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8847 return filter.service; 8848 } 8849 8850 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8851 PackageParser.Service service = (PackageParser.Service)label; 8852 out.print(prefix); out.print( 8853 Integer.toHexString(System.identityHashCode(service))); 8854 out.print(' '); 8855 service.printComponentShortName(out); 8856 if (count > 1) { 8857 out.print(" ("); out.print(count); out.print(" filters)"); 8858 } 8859 out.println(); 8860 } 8861 8862// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8863// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8864// final List<ResolveInfo> retList = Lists.newArrayList(); 8865// while (i.hasNext()) { 8866// final ResolveInfo resolveInfo = (ResolveInfo) i; 8867// if (isEnabledLP(resolveInfo.serviceInfo)) { 8868// retList.add(resolveInfo); 8869// } 8870// } 8871// return retList; 8872// } 8873 8874 // Keys are String (activity class name), values are Activity. 8875 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8876 = new ArrayMap<ComponentName, PackageParser.Service>(); 8877 private int mFlags; 8878 }; 8879 8880 private final class ProviderIntentResolver 8881 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8882 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8883 boolean defaultOnly, int userId) { 8884 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8885 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8886 } 8887 8888 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8889 int userId) { 8890 if (!sUserManager.exists(userId)) 8891 return null; 8892 mFlags = flags; 8893 return super.queryIntent(intent, resolvedType, 8894 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8895 } 8896 8897 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8898 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8899 if (!sUserManager.exists(userId)) 8900 return null; 8901 if (packageProviders == null) { 8902 return null; 8903 } 8904 mFlags = flags; 8905 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8906 final int N = packageProviders.size(); 8907 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8908 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8909 8910 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8911 for (int i = 0; i < N; ++i) { 8912 intentFilters = packageProviders.get(i).intents; 8913 if (intentFilters != null && intentFilters.size() > 0) { 8914 PackageParser.ProviderIntentInfo[] array = 8915 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8916 intentFilters.toArray(array); 8917 listCut.add(array); 8918 } 8919 } 8920 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8921 } 8922 8923 public final void addProvider(PackageParser.Provider p) { 8924 if (mProviders.containsKey(p.getComponentName())) { 8925 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8926 return; 8927 } 8928 8929 mProviders.put(p.getComponentName(), p); 8930 if (DEBUG_SHOW_INFO) { 8931 Log.v(TAG, " " 8932 + (p.info.nonLocalizedLabel != null 8933 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8934 Log.v(TAG, " Class=" + p.info.name); 8935 } 8936 final int NI = p.intents.size(); 8937 int j; 8938 for (j = 0; j < NI; j++) { 8939 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8940 if (DEBUG_SHOW_INFO) { 8941 Log.v(TAG, " IntentFilter:"); 8942 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8943 } 8944 if (!intent.debugCheck()) { 8945 Log.w(TAG, "==> For Provider " + p.info.name); 8946 } 8947 addFilter(intent); 8948 } 8949 } 8950 8951 public final void removeProvider(PackageParser.Provider p) { 8952 mProviders.remove(p.getComponentName()); 8953 if (DEBUG_SHOW_INFO) { 8954 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8955 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8956 Log.v(TAG, " Class=" + p.info.name); 8957 } 8958 final int NI = p.intents.size(); 8959 int j; 8960 for (j = 0; j < NI; j++) { 8961 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8962 if (DEBUG_SHOW_INFO) { 8963 Log.v(TAG, " IntentFilter:"); 8964 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8965 } 8966 removeFilter(intent); 8967 } 8968 } 8969 8970 @Override 8971 protected boolean allowFilterResult( 8972 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8973 ProviderInfo filterPi = filter.provider.info; 8974 for (int i = dest.size() - 1; i >= 0; i--) { 8975 ProviderInfo destPi = dest.get(i).providerInfo; 8976 if (destPi.name == filterPi.name 8977 && destPi.packageName == filterPi.packageName) { 8978 return false; 8979 } 8980 } 8981 return true; 8982 } 8983 8984 @Override 8985 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8986 return new PackageParser.ProviderIntentInfo[size]; 8987 } 8988 8989 @Override 8990 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8991 if (!sUserManager.exists(userId)) 8992 return true; 8993 PackageParser.Package p = filter.provider.owner; 8994 if (p != null) { 8995 PackageSetting ps = (PackageSetting) p.mExtras; 8996 if (ps != null) { 8997 // System apps are never considered stopped for purposes of 8998 // filtering, because there may be no way for the user to 8999 // actually re-launch them. 9000 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9001 && ps.getStopped(userId); 9002 } 9003 } 9004 return false; 9005 } 9006 9007 @Override 9008 protected boolean isPackageForFilter(String packageName, 9009 PackageParser.ProviderIntentInfo info) { 9010 return packageName.equals(info.provider.owner.packageName); 9011 } 9012 9013 @Override 9014 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9015 int match, int userId) { 9016 if (!sUserManager.exists(userId)) 9017 return null; 9018 final PackageParser.ProviderIntentInfo info = filter; 9019 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9020 return null; 9021 } 9022 final PackageParser.Provider provider = info.provider; 9023 if (mSafeMode && (provider.info.applicationInfo.flags 9024 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9025 return null; 9026 } 9027 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9028 if (ps == null) { 9029 return null; 9030 } 9031 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9032 ps.readUserState(userId), userId); 9033 if (pi == null) { 9034 return null; 9035 } 9036 final ResolveInfo res = new ResolveInfo(); 9037 res.providerInfo = pi; 9038 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9039 res.filter = filter; 9040 } 9041 res.priority = info.getPriority(); 9042 res.preferredOrder = provider.owner.mPreferredOrder; 9043 res.match = match; 9044 res.isDefault = info.hasDefault; 9045 res.labelRes = info.labelRes; 9046 res.nonLocalizedLabel = info.nonLocalizedLabel; 9047 res.icon = info.icon; 9048 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9049 return res; 9050 } 9051 9052 @Override 9053 protected void sortResults(List<ResolveInfo> results) { 9054 Collections.sort(results, mResolvePrioritySorter); 9055 } 9056 9057 @Override 9058 protected void dumpFilter(PrintWriter out, String prefix, 9059 PackageParser.ProviderIntentInfo filter) { 9060 out.print(prefix); 9061 out.print( 9062 Integer.toHexString(System.identityHashCode(filter.provider))); 9063 out.print(' '); 9064 filter.provider.printComponentShortName(out); 9065 out.print(" filter "); 9066 out.println(Integer.toHexString(System.identityHashCode(filter))); 9067 } 9068 9069 @Override 9070 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9071 return filter.provider; 9072 } 9073 9074 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9075 PackageParser.Provider provider = (PackageParser.Provider)label; 9076 out.print(prefix); out.print( 9077 Integer.toHexString(System.identityHashCode(provider))); 9078 out.print(' '); 9079 provider.printComponentShortName(out); 9080 if (count > 1) { 9081 out.print(" ("); out.print(count); out.print(" filters)"); 9082 } 9083 out.println(); 9084 } 9085 9086 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9087 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9088 private int mFlags; 9089 }; 9090 9091 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9092 new Comparator<ResolveInfo>() { 9093 public int compare(ResolveInfo r1, ResolveInfo r2) { 9094 int v1 = r1.priority; 9095 int v2 = r2.priority; 9096 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9097 if (v1 != v2) { 9098 return (v1 > v2) ? -1 : 1; 9099 } 9100 v1 = r1.preferredOrder; 9101 v2 = r2.preferredOrder; 9102 if (v1 != v2) { 9103 return (v1 > v2) ? -1 : 1; 9104 } 9105 if (r1.isDefault != r2.isDefault) { 9106 return r1.isDefault ? -1 : 1; 9107 } 9108 v1 = r1.match; 9109 v2 = r2.match; 9110 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9111 if (v1 != v2) { 9112 return (v1 > v2) ? -1 : 1; 9113 } 9114 if (r1.system != r2.system) { 9115 return r1.system ? -1 : 1; 9116 } 9117 return 0; 9118 } 9119 }; 9120 9121 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9122 new Comparator<ProviderInfo>() { 9123 public int compare(ProviderInfo p1, ProviderInfo p2) { 9124 final int v1 = p1.initOrder; 9125 final int v2 = p2.initOrder; 9126 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9127 } 9128 }; 9129 9130 final void sendPackageBroadcast(final String action, final String pkg, 9131 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9132 final int[] userIds) { 9133 mHandler.post(new Runnable() { 9134 @Override 9135 public void run() { 9136 try { 9137 final IActivityManager am = ActivityManagerNative.getDefault(); 9138 if (am == null) return; 9139 final int[] resolvedUserIds; 9140 if (userIds == null) { 9141 resolvedUserIds = am.getRunningUserIds(); 9142 } else { 9143 resolvedUserIds = userIds; 9144 } 9145 for (int id : resolvedUserIds) { 9146 final Intent intent = new Intent(action, 9147 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9148 if (extras != null) { 9149 intent.putExtras(extras); 9150 } 9151 if (targetPkg != null) { 9152 intent.setPackage(targetPkg); 9153 } 9154 // Modify the UID when posting to other users 9155 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9156 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9157 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9158 intent.putExtra(Intent.EXTRA_UID, uid); 9159 } 9160 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9161 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9162 if (DEBUG_BROADCASTS) { 9163 RuntimeException here = new RuntimeException("here"); 9164 here.fillInStackTrace(); 9165 Slog.d(TAG, "Sending to user " + id + ": " 9166 + intent.toShortString(false, true, false, false) 9167 + " " + intent.getExtras(), here); 9168 } 9169 am.broadcastIntent(null, intent, null, finishedReceiver, 9170 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9171 null, finishedReceiver != null, false, id); 9172 } 9173 } catch (RemoteException ex) { 9174 } 9175 } 9176 }); 9177 } 9178 9179 /** 9180 * Check if the external storage media is available. This is true if there 9181 * is a mounted external storage medium or if the external storage is 9182 * emulated. 9183 */ 9184 private boolean isExternalMediaAvailable() { 9185 return mMediaMounted || Environment.isExternalStorageEmulated(); 9186 } 9187 9188 @Override 9189 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9190 // writer 9191 synchronized (mPackages) { 9192 if (!isExternalMediaAvailable()) { 9193 // If the external storage is no longer mounted at this point, 9194 // the caller may not have been able to delete all of this 9195 // packages files and can not delete any more. Bail. 9196 return null; 9197 } 9198 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9199 if (lastPackage != null) { 9200 pkgs.remove(lastPackage); 9201 } 9202 if (pkgs.size() > 0) { 9203 return pkgs.get(0); 9204 } 9205 } 9206 return null; 9207 } 9208 9209 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9210 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9211 userId, andCode ? 1 : 0, packageName); 9212 if (mSystemReady) { 9213 msg.sendToTarget(); 9214 } else { 9215 if (mPostSystemReadyMessages == null) { 9216 mPostSystemReadyMessages = new ArrayList<>(); 9217 } 9218 mPostSystemReadyMessages.add(msg); 9219 } 9220 } 9221 9222 void startCleaningPackages() { 9223 // reader 9224 synchronized (mPackages) { 9225 if (!isExternalMediaAvailable()) { 9226 return; 9227 } 9228 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9229 return; 9230 } 9231 } 9232 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9233 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9234 IActivityManager am = ActivityManagerNative.getDefault(); 9235 if (am != null) { 9236 try { 9237 am.startService(null, intent, null, mContext.getOpPackageName(), 9238 UserHandle.USER_OWNER); 9239 } catch (RemoteException e) { 9240 } 9241 } 9242 } 9243 9244 @Override 9245 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9246 int installFlags, String installerPackageName, VerificationParams verificationParams, 9247 String packageAbiOverride) { 9248 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9249 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9250 } 9251 9252 @Override 9253 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9254 int installFlags, String installerPackageName, VerificationParams verificationParams, 9255 String packageAbiOverride, int userId) { 9256 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9257 9258 final int callingUid = Binder.getCallingUid(); 9259 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9260 9261 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9262 try { 9263 if (observer != null) { 9264 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9265 } 9266 } catch (RemoteException re) { 9267 } 9268 return; 9269 } 9270 9271 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9272 installFlags |= PackageManager.INSTALL_FROM_ADB; 9273 9274 } else { 9275 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9276 // about installerPackageName. 9277 9278 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9279 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9280 } 9281 9282 UserHandle user; 9283 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9284 user = UserHandle.ALL; 9285 } else { 9286 user = new UserHandle(userId); 9287 } 9288 9289 // Only system components can circumvent runtime permissions when installing. 9290 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9291 && mContext.checkCallingOrSelfPermission(Manifest.permission 9292 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9293 throw new SecurityException("You need the " 9294 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9295 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9296 } 9297 9298 verificationParams.setInstallerUid(callingUid); 9299 9300 final File originFile = new File(originPath); 9301 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9302 9303 final Message msg = mHandler.obtainMessage(INIT_COPY); 9304 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9305 null, verificationParams, user, packageAbiOverride); 9306 mHandler.sendMessage(msg); 9307 } 9308 9309 void installStage(String packageName, File stagedDir, String stagedCid, 9310 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9311 String installerPackageName, int installerUid, UserHandle user) { 9312 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9313 params.referrerUri, installerUid, null); 9314 verifParams.setInstallerUid(installerUid); 9315 9316 final OriginInfo origin; 9317 if (stagedDir != null) { 9318 origin = OriginInfo.fromStagedFile(stagedDir); 9319 } else { 9320 origin = OriginInfo.fromStagedContainer(stagedCid); 9321 } 9322 9323 final Message msg = mHandler.obtainMessage(INIT_COPY); 9324 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9325 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9326 mHandler.sendMessage(msg); 9327 } 9328 9329 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9330 Bundle extras = new Bundle(1); 9331 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9332 9333 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9334 packageName, extras, null, null, new int[] {userId}); 9335 try { 9336 IActivityManager am = ActivityManagerNative.getDefault(); 9337 final boolean isSystem = 9338 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9339 if (isSystem && am.isUserRunning(userId, false)) { 9340 // The just-installed/enabled app is bundled on the system, so presumed 9341 // to be able to run automatically without needing an explicit launch. 9342 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9343 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9344 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9345 .setPackage(packageName); 9346 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9347 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9348 } 9349 } catch (RemoteException e) { 9350 // shouldn't happen 9351 Slog.w(TAG, "Unable to bootstrap installed package", e); 9352 } 9353 } 9354 9355 @Override 9356 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9357 int userId) { 9358 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9359 PackageSetting pkgSetting; 9360 final int uid = Binder.getCallingUid(); 9361 enforceCrossUserPermission(uid, userId, true, true, 9362 "setApplicationHiddenSetting for user " + userId); 9363 9364 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9365 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9366 return false; 9367 } 9368 9369 long callingId = Binder.clearCallingIdentity(); 9370 try { 9371 boolean sendAdded = false; 9372 boolean sendRemoved = false; 9373 // writer 9374 synchronized (mPackages) { 9375 pkgSetting = mSettings.mPackages.get(packageName); 9376 if (pkgSetting == null) { 9377 return false; 9378 } 9379 if (pkgSetting.getHidden(userId) != hidden) { 9380 pkgSetting.setHidden(hidden, userId); 9381 mSettings.writePackageRestrictionsLPr(userId); 9382 if (hidden) { 9383 sendRemoved = true; 9384 } else { 9385 sendAdded = true; 9386 } 9387 } 9388 } 9389 if (sendAdded) { 9390 sendPackageAddedForUser(packageName, pkgSetting, userId); 9391 return true; 9392 } 9393 if (sendRemoved) { 9394 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9395 "hiding pkg"); 9396 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9397 } 9398 } finally { 9399 Binder.restoreCallingIdentity(callingId); 9400 } 9401 return false; 9402 } 9403 9404 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9405 int userId) { 9406 final PackageRemovedInfo info = new PackageRemovedInfo(); 9407 info.removedPackage = packageName; 9408 info.removedUsers = new int[] {userId}; 9409 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9410 info.sendBroadcast(false, false, false); 9411 } 9412 9413 /** 9414 * Returns true if application is not found or there was an error. Otherwise it returns 9415 * the hidden state of the package for the given user. 9416 */ 9417 @Override 9418 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9420 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9421 false, "getApplicationHidden for user " + userId); 9422 PackageSetting pkgSetting; 9423 long callingId = Binder.clearCallingIdentity(); 9424 try { 9425 // writer 9426 synchronized (mPackages) { 9427 pkgSetting = mSettings.mPackages.get(packageName); 9428 if (pkgSetting == null) { 9429 return true; 9430 } 9431 return pkgSetting.getHidden(userId); 9432 } 9433 } finally { 9434 Binder.restoreCallingIdentity(callingId); 9435 } 9436 } 9437 9438 /** 9439 * @hide 9440 */ 9441 @Override 9442 public int installExistingPackageAsUser(String packageName, int userId) { 9443 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9444 null); 9445 PackageSetting pkgSetting; 9446 final int uid = Binder.getCallingUid(); 9447 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9448 + userId); 9449 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9450 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9451 } 9452 9453 long callingId = Binder.clearCallingIdentity(); 9454 try { 9455 boolean sendAdded = false; 9456 9457 // writer 9458 synchronized (mPackages) { 9459 pkgSetting = mSettings.mPackages.get(packageName); 9460 if (pkgSetting == null) { 9461 return PackageManager.INSTALL_FAILED_INVALID_URI; 9462 } 9463 if (!pkgSetting.getInstalled(userId)) { 9464 pkgSetting.setInstalled(true, userId); 9465 pkgSetting.setHidden(false, userId); 9466 mSettings.writePackageRestrictionsLPr(userId); 9467 sendAdded = true; 9468 } 9469 } 9470 9471 if (sendAdded) { 9472 sendPackageAddedForUser(packageName, pkgSetting, userId); 9473 } 9474 } finally { 9475 Binder.restoreCallingIdentity(callingId); 9476 } 9477 9478 return PackageManager.INSTALL_SUCCEEDED; 9479 } 9480 9481 boolean isUserRestricted(int userId, String restrictionKey) { 9482 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9483 if (restrictions.getBoolean(restrictionKey, false)) { 9484 Log.w(TAG, "User is restricted: " + restrictionKey); 9485 return true; 9486 } 9487 return false; 9488 } 9489 9490 @Override 9491 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9492 mContext.enforceCallingOrSelfPermission( 9493 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9494 "Only package verification agents can verify applications"); 9495 9496 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9497 final PackageVerificationResponse response = new PackageVerificationResponse( 9498 verificationCode, Binder.getCallingUid()); 9499 msg.arg1 = id; 9500 msg.obj = response; 9501 mHandler.sendMessage(msg); 9502 } 9503 9504 @Override 9505 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9506 long millisecondsToDelay) { 9507 mContext.enforceCallingOrSelfPermission( 9508 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9509 "Only package verification agents can extend verification timeouts"); 9510 9511 final PackageVerificationState state = mPendingVerification.get(id); 9512 final PackageVerificationResponse response = new PackageVerificationResponse( 9513 verificationCodeAtTimeout, Binder.getCallingUid()); 9514 9515 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9516 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9517 } 9518 if (millisecondsToDelay < 0) { 9519 millisecondsToDelay = 0; 9520 } 9521 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9522 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9523 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9524 } 9525 9526 if ((state != null) && !state.timeoutExtended()) { 9527 state.extendTimeout(); 9528 9529 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9530 msg.arg1 = id; 9531 msg.obj = response; 9532 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9533 } 9534 } 9535 9536 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9537 int verificationCode, UserHandle user) { 9538 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9539 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9540 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9541 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9542 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9543 9544 mContext.sendBroadcastAsUser(intent, user, 9545 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9546 } 9547 9548 private ComponentName matchComponentForVerifier(String packageName, 9549 List<ResolveInfo> receivers) { 9550 ActivityInfo targetReceiver = null; 9551 9552 final int NR = receivers.size(); 9553 for (int i = 0; i < NR; i++) { 9554 final ResolveInfo info = receivers.get(i); 9555 if (info.activityInfo == null) { 9556 continue; 9557 } 9558 9559 if (packageName.equals(info.activityInfo.packageName)) { 9560 targetReceiver = info.activityInfo; 9561 break; 9562 } 9563 } 9564 9565 if (targetReceiver == null) { 9566 return null; 9567 } 9568 9569 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9570 } 9571 9572 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9573 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9574 if (pkgInfo.verifiers.length == 0) { 9575 return null; 9576 } 9577 9578 final int N = pkgInfo.verifiers.length; 9579 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9580 for (int i = 0; i < N; i++) { 9581 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9582 9583 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9584 receivers); 9585 if (comp == null) { 9586 continue; 9587 } 9588 9589 final int verifierUid = getUidForVerifier(verifierInfo); 9590 if (verifierUid == -1) { 9591 continue; 9592 } 9593 9594 if (DEBUG_VERIFY) { 9595 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9596 + " with the correct signature"); 9597 } 9598 sufficientVerifiers.add(comp); 9599 verificationState.addSufficientVerifier(verifierUid); 9600 } 9601 9602 return sufficientVerifiers; 9603 } 9604 9605 private int getUidForVerifier(VerifierInfo verifierInfo) { 9606 synchronized (mPackages) { 9607 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9608 if (pkg == null) { 9609 return -1; 9610 } else if (pkg.mSignatures.length != 1) { 9611 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9612 + " has more than one signature; ignoring"); 9613 return -1; 9614 } 9615 9616 /* 9617 * If the public key of the package's signature does not match 9618 * our expected public key, then this is a different package and 9619 * we should skip. 9620 */ 9621 9622 final byte[] expectedPublicKey; 9623 try { 9624 final Signature verifierSig = pkg.mSignatures[0]; 9625 final PublicKey publicKey = verifierSig.getPublicKey(); 9626 expectedPublicKey = publicKey.getEncoded(); 9627 } catch (CertificateException e) { 9628 return -1; 9629 } 9630 9631 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9632 9633 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9634 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9635 + " does not have the expected public key; ignoring"); 9636 return -1; 9637 } 9638 9639 return pkg.applicationInfo.uid; 9640 } 9641 } 9642 9643 @Override 9644 public void finishPackageInstall(int token) { 9645 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9646 9647 if (DEBUG_INSTALL) { 9648 Slog.v(TAG, "BM finishing package install for " + token); 9649 } 9650 9651 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9652 mHandler.sendMessage(msg); 9653 } 9654 9655 /** 9656 * Get the verification agent timeout. 9657 * 9658 * @return verification timeout in milliseconds 9659 */ 9660 private long getVerificationTimeout() { 9661 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9662 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9663 DEFAULT_VERIFICATION_TIMEOUT); 9664 } 9665 9666 /** 9667 * Get the default verification agent response code. 9668 * 9669 * @return default verification response code 9670 */ 9671 private int getDefaultVerificationResponse() { 9672 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9673 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9674 DEFAULT_VERIFICATION_RESPONSE); 9675 } 9676 9677 /** 9678 * Check whether or not package verification has been enabled. 9679 * 9680 * @return true if verification should be performed 9681 */ 9682 private boolean isVerificationEnabled(int userId, int installFlags) { 9683 if (!DEFAULT_VERIFY_ENABLE) { 9684 return false; 9685 } 9686 9687 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9688 9689 // Check if installing from ADB 9690 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9691 // Do not run verification in a test harness environment 9692 if (ActivityManager.isRunningInTestHarness()) { 9693 return false; 9694 } 9695 if (ensureVerifyAppsEnabled) { 9696 return true; 9697 } 9698 // Check if the developer does not want package verification for ADB installs 9699 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9700 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9701 return false; 9702 } 9703 } 9704 9705 if (ensureVerifyAppsEnabled) { 9706 return true; 9707 } 9708 9709 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9710 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9711 } 9712 9713 @Override 9714 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9715 throws RemoteException { 9716 mContext.enforceCallingOrSelfPermission( 9717 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9718 "Only intentfilter verification agents can verify applications"); 9719 9720 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9721 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9722 Binder.getCallingUid(), verificationCode, failedDomains); 9723 msg.arg1 = id; 9724 msg.obj = response; 9725 mHandler.sendMessage(msg); 9726 } 9727 9728 @Override 9729 public int getIntentVerificationStatus(String packageName, int userId) { 9730 synchronized (mPackages) { 9731 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9732 } 9733 } 9734 9735 @Override 9736 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9737 mContext.enforceCallingOrSelfPermission( 9738 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9739 9740 boolean result = false; 9741 synchronized (mPackages) { 9742 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9743 } 9744 if (result) { 9745 scheduleWritePackageRestrictionsLocked(userId); 9746 } 9747 return result; 9748 } 9749 9750 @Override 9751 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9752 synchronized (mPackages) { 9753 return mSettings.getIntentFilterVerificationsLPr(packageName); 9754 } 9755 } 9756 9757 @Override 9758 public List<IntentFilter> getAllIntentFilters(String packageName) { 9759 if (TextUtils.isEmpty(packageName)) { 9760 return Collections.<IntentFilter>emptyList(); 9761 } 9762 synchronized (mPackages) { 9763 PackageParser.Package pkg = mPackages.get(packageName); 9764 if (pkg == null || pkg.activities == null) { 9765 return Collections.<IntentFilter>emptyList(); 9766 } 9767 final int count = pkg.activities.size(); 9768 ArrayList<IntentFilter> result = new ArrayList<>(); 9769 for (int n=0; n<count; n++) { 9770 PackageParser.Activity activity = pkg.activities.get(n); 9771 if (activity.intents != null || activity.intents.size() > 0) { 9772 result.addAll(activity.intents); 9773 } 9774 } 9775 return result; 9776 } 9777 } 9778 9779 @Override 9780 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9781 mContext.enforceCallingOrSelfPermission( 9782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9783 9784 synchronized (mPackages) { 9785 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9786 if (packageName != null) { 9787 result |= updateIntentVerificationStatus(packageName, 9788 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9789 UserHandle.myUserId()); 9790 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9791 packageName, userId); 9792 } 9793 return result; 9794 } 9795 } 9796 9797 @Override 9798 public String getDefaultBrowserPackageName(int userId) { 9799 synchronized (mPackages) { 9800 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9801 } 9802 } 9803 9804 /** 9805 * Get the "allow unknown sources" setting. 9806 * 9807 * @return the current "allow unknown sources" setting 9808 */ 9809 private int getUnknownSourcesSettings() { 9810 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9811 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9812 -1); 9813 } 9814 9815 @Override 9816 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9817 final int uid = Binder.getCallingUid(); 9818 // writer 9819 synchronized (mPackages) { 9820 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9821 if (targetPackageSetting == null) { 9822 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9823 } 9824 9825 PackageSetting installerPackageSetting; 9826 if (installerPackageName != null) { 9827 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9828 if (installerPackageSetting == null) { 9829 throw new IllegalArgumentException("Unknown installer package: " 9830 + installerPackageName); 9831 } 9832 } else { 9833 installerPackageSetting = null; 9834 } 9835 9836 Signature[] callerSignature; 9837 Object obj = mSettings.getUserIdLPr(uid); 9838 if (obj != null) { 9839 if (obj instanceof SharedUserSetting) { 9840 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9841 } else if (obj instanceof PackageSetting) { 9842 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9843 } else { 9844 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9845 } 9846 } else { 9847 throw new SecurityException("Unknown calling uid " + uid); 9848 } 9849 9850 // Verify: can't set installerPackageName to a package that is 9851 // not signed with the same cert as the caller. 9852 if (installerPackageSetting != null) { 9853 if (compareSignatures(callerSignature, 9854 installerPackageSetting.signatures.mSignatures) 9855 != PackageManager.SIGNATURE_MATCH) { 9856 throw new SecurityException( 9857 "Caller does not have same cert as new installer package " 9858 + installerPackageName); 9859 } 9860 } 9861 9862 // Verify: if target already has an installer package, it must 9863 // be signed with the same cert as the caller. 9864 if (targetPackageSetting.installerPackageName != null) { 9865 PackageSetting setting = mSettings.mPackages.get( 9866 targetPackageSetting.installerPackageName); 9867 // If the currently set package isn't valid, then it's always 9868 // okay to change it. 9869 if (setting != null) { 9870 if (compareSignatures(callerSignature, 9871 setting.signatures.mSignatures) 9872 != PackageManager.SIGNATURE_MATCH) { 9873 throw new SecurityException( 9874 "Caller does not have same cert as old installer package " 9875 + targetPackageSetting.installerPackageName); 9876 } 9877 } 9878 } 9879 9880 // Okay! 9881 targetPackageSetting.installerPackageName = installerPackageName; 9882 scheduleWriteSettingsLocked(); 9883 } 9884 } 9885 9886 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9887 // Queue up an async operation since the package installation may take a little while. 9888 mHandler.post(new Runnable() { 9889 public void run() { 9890 mHandler.removeCallbacks(this); 9891 // Result object to be returned 9892 PackageInstalledInfo res = new PackageInstalledInfo(); 9893 res.returnCode = currentStatus; 9894 res.uid = -1; 9895 res.pkg = null; 9896 res.removedInfo = new PackageRemovedInfo(); 9897 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9898 args.doPreInstall(res.returnCode); 9899 synchronized (mInstallLock) { 9900 installPackageLI(args, res); 9901 } 9902 args.doPostInstall(res.returnCode, res.uid); 9903 } 9904 9905 // A restore should be performed at this point if (a) the install 9906 // succeeded, (b) the operation is not an update, and (c) the new 9907 // package has not opted out of backup participation. 9908 final boolean update = res.removedInfo.removedPackage != null; 9909 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9910 boolean doRestore = !update 9911 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9912 9913 // Set up the post-install work request bookkeeping. This will be used 9914 // and cleaned up by the post-install event handling regardless of whether 9915 // there's a restore pass performed. Token values are >= 1. 9916 int token; 9917 if (mNextInstallToken < 0) mNextInstallToken = 1; 9918 token = mNextInstallToken++; 9919 9920 PostInstallData data = new PostInstallData(args, res); 9921 mRunningInstalls.put(token, data); 9922 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9923 9924 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9925 // Pass responsibility to the Backup Manager. It will perform a 9926 // restore if appropriate, then pass responsibility back to the 9927 // Package Manager to run the post-install observer callbacks 9928 // and broadcasts. 9929 IBackupManager bm = IBackupManager.Stub.asInterface( 9930 ServiceManager.getService(Context.BACKUP_SERVICE)); 9931 if (bm != null) { 9932 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9933 + " to BM for possible restore"); 9934 try { 9935 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9936 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9937 } else { 9938 doRestore = false; 9939 } 9940 } catch (RemoteException e) { 9941 // can't happen; the backup manager is local 9942 } catch (Exception e) { 9943 Slog.e(TAG, "Exception trying to enqueue restore", e); 9944 doRestore = false; 9945 } 9946 } else { 9947 Slog.e(TAG, "Backup Manager not found!"); 9948 doRestore = false; 9949 } 9950 } 9951 9952 if (!doRestore) { 9953 // No restore possible, or the Backup Manager was mysteriously not 9954 // available -- just fire the post-install work request directly. 9955 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9956 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9957 mHandler.sendMessage(msg); 9958 } 9959 } 9960 }); 9961 } 9962 9963 private abstract class HandlerParams { 9964 private static final int MAX_RETRIES = 4; 9965 9966 /** 9967 * Number of times startCopy() has been attempted and had a non-fatal 9968 * error. 9969 */ 9970 private int mRetries = 0; 9971 9972 /** User handle for the user requesting the information or installation. */ 9973 private final UserHandle mUser; 9974 9975 HandlerParams(UserHandle user) { 9976 mUser = user; 9977 } 9978 9979 UserHandle getUser() { 9980 return mUser; 9981 } 9982 9983 final boolean startCopy() { 9984 boolean res; 9985 try { 9986 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9987 9988 if (++mRetries > MAX_RETRIES) { 9989 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9990 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9991 handleServiceError(); 9992 return false; 9993 } else { 9994 handleStartCopy(); 9995 res = true; 9996 } 9997 } catch (RemoteException e) { 9998 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9999 mHandler.sendEmptyMessage(MCS_RECONNECT); 10000 res = false; 10001 } 10002 handleReturnCode(); 10003 return res; 10004 } 10005 10006 final void serviceError() { 10007 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10008 handleServiceError(); 10009 handleReturnCode(); 10010 } 10011 10012 abstract void handleStartCopy() throws RemoteException; 10013 abstract void handleServiceError(); 10014 abstract void handleReturnCode(); 10015 } 10016 10017 class MeasureParams extends HandlerParams { 10018 private final PackageStats mStats; 10019 private boolean mSuccess; 10020 10021 private final IPackageStatsObserver mObserver; 10022 10023 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10024 super(new UserHandle(stats.userHandle)); 10025 mObserver = observer; 10026 mStats = stats; 10027 } 10028 10029 @Override 10030 public String toString() { 10031 return "MeasureParams{" 10032 + Integer.toHexString(System.identityHashCode(this)) 10033 + " " + mStats.packageName + "}"; 10034 } 10035 10036 @Override 10037 void handleStartCopy() throws RemoteException { 10038 synchronized (mInstallLock) { 10039 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10040 } 10041 10042 if (mSuccess) { 10043 final boolean mounted; 10044 if (Environment.isExternalStorageEmulated()) { 10045 mounted = true; 10046 } else { 10047 final String status = Environment.getExternalStorageState(); 10048 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10049 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10050 } 10051 10052 if (mounted) { 10053 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10054 10055 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10056 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10057 10058 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10059 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10060 10061 // Always subtract cache size, since it's a subdirectory 10062 mStats.externalDataSize -= mStats.externalCacheSize; 10063 10064 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10065 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10066 10067 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10068 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10069 } 10070 } 10071 } 10072 10073 @Override 10074 void handleReturnCode() { 10075 if (mObserver != null) { 10076 try { 10077 mObserver.onGetStatsCompleted(mStats, mSuccess); 10078 } catch (RemoteException e) { 10079 Slog.i(TAG, "Observer no longer exists."); 10080 } 10081 } 10082 } 10083 10084 @Override 10085 void handleServiceError() { 10086 Slog.e(TAG, "Could not measure application " + mStats.packageName 10087 + " external storage"); 10088 } 10089 } 10090 10091 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10092 throws RemoteException { 10093 long result = 0; 10094 for (File path : paths) { 10095 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10096 } 10097 return result; 10098 } 10099 10100 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10101 for (File path : paths) { 10102 try { 10103 mcs.clearDirectory(path.getAbsolutePath()); 10104 } catch (RemoteException e) { 10105 } 10106 } 10107 } 10108 10109 static class OriginInfo { 10110 /** 10111 * Location where install is coming from, before it has been 10112 * copied/renamed into place. This could be a single monolithic APK 10113 * file, or a cluster directory. This location may be untrusted. 10114 */ 10115 final File file; 10116 final String cid; 10117 10118 /** 10119 * Flag indicating that {@link #file} or {@link #cid} has already been 10120 * staged, meaning downstream users don't need to defensively copy the 10121 * contents. 10122 */ 10123 final boolean staged; 10124 10125 /** 10126 * Flag indicating that {@link #file} or {@link #cid} is an already 10127 * installed app that is being moved. 10128 */ 10129 final boolean existing; 10130 10131 final String resolvedPath; 10132 final File resolvedFile; 10133 10134 static OriginInfo fromNothing() { 10135 return new OriginInfo(null, null, false, false); 10136 } 10137 10138 static OriginInfo fromUntrustedFile(File file) { 10139 return new OriginInfo(file, null, false, false); 10140 } 10141 10142 static OriginInfo fromExistingFile(File file) { 10143 return new OriginInfo(file, null, false, true); 10144 } 10145 10146 static OriginInfo fromStagedFile(File file) { 10147 return new OriginInfo(file, null, true, false); 10148 } 10149 10150 static OriginInfo fromStagedContainer(String cid) { 10151 return new OriginInfo(null, cid, true, false); 10152 } 10153 10154 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10155 this.file = file; 10156 this.cid = cid; 10157 this.staged = staged; 10158 this.existing = existing; 10159 10160 if (cid != null) { 10161 resolvedPath = PackageHelper.getSdDir(cid); 10162 resolvedFile = new File(resolvedPath); 10163 } else if (file != null) { 10164 resolvedPath = file.getAbsolutePath(); 10165 resolvedFile = file; 10166 } else { 10167 resolvedPath = null; 10168 resolvedFile = null; 10169 } 10170 } 10171 } 10172 10173 class MoveInfo { 10174 final int moveId; 10175 final String fromUuid; 10176 final String toUuid; 10177 final String packageName; 10178 final String dataAppName; 10179 final int appId; 10180 final String seinfo; 10181 10182 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10183 String dataAppName, int appId, String seinfo) { 10184 this.moveId = moveId; 10185 this.fromUuid = fromUuid; 10186 this.toUuid = toUuid; 10187 this.packageName = packageName; 10188 this.dataAppName = dataAppName; 10189 this.appId = appId; 10190 this.seinfo = seinfo; 10191 } 10192 } 10193 10194 class InstallParams extends HandlerParams { 10195 final OriginInfo origin; 10196 final MoveInfo move; 10197 final IPackageInstallObserver2 observer; 10198 int installFlags; 10199 final String installerPackageName; 10200 final String volumeUuid; 10201 final VerificationParams verificationParams; 10202 private InstallArgs mArgs; 10203 private int mRet; 10204 final String packageAbiOverride; 10205 10206 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10207 int installFlags, String installerPackageName, String volumeUuid, 10208 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10209 super(user); 10210 this.origin = origin; 10211 this.move = move; 10212 this.observer = observer; 10213 this.installFlags = installFlags; 10214 this.installerPackageName = installerPackageName; 10215 this.volumeUuid = volumeUuid; 10216 this.verificationParams = verificationParams; 10217 this.packageAbiOverride = packageAbiOverride; 10218 } 10219 10220 @Override 10221 public String toString() { 10222 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10223 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10224 } 10225 10226 public ManifestDigest getManifestDigest() { 10227 if (verificationParams == null) { 10228 return null; 10229 } 10230 return verificationParams.getManifestDigest(); 10231 } 10232 10233 private int installLocationPolicy(PackageInfoLite pkgLite) { 10234 String packageName = pkgLite.packageName; 10235 int installLocation = pkgLite.installLocation; 10236 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10237 // reader 10238 synchronized (mPackages) { 10239 PackageParser.Package pkg = mPackages.get(packageName); 10240 if (pkg != null) { 10241 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10242 // Check for downgrading. 10243 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10244 try { 10245 checkDowngrade(pkg, pkgLite); 10246 } catch (PackageManagerException e) { 10247 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10248 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10249 } 10250 } 10251 // Check for updated system application. 10252 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10253 if (onSd) { 10254 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10255 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10256 } 10257 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10258 } else { 10259 if (onSd) { 10260 // Install flag overrides everything. 10261 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10262 } 10263 // If current upgrade specifies particular preference 10264 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10265 // Application explicitly specified internal. 10266 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10267 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10268 // App explictly prefers external. Let policy decide 10269 } else { 10270 // Prefer previous location 10271 if (isExternal(pkg)) { 10272 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10273 } 10274 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10275 } 10276 } 10277 } else { 10278 // Invalid install. Return error code 10279 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10280 } 10281 } 10282 } 10283 // All the special cases have been taken care of. 10284 // Return result based on recommended install location. 10285 if (onSd) { 10286 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10287 } 10288 return pkgLite.recommendedInstallLocation; 10289 } 10290 10291 /* 10292 * Invoke remote method to get package information and install 10293 * location values. Override install location based on default 10294 * policy if needed and then create install arguments based 10295 * on the install location. 10296 */ 10297 public void handleStartCopy() throws RemoteException { 10298 int ret = PackageManager.INSTALL_SUCCEEDED; 10299 10300 // If we're already staged, we've firmly committed to an install location 10301 if (origin.staged) { 10302 if (origin.file != null) { 10303 installFlags |= PackageManager.INSTALL_INTERNAL; 10304 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10305 } else if (origin.cid != null) { 10306 installFlags |= PackageManager.INSTALL_EXTERNAL; 10307 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10308 } else { 10309 throw new IllegalStateException("Invalid stage location"); 10310 } 10311 } 10312 10313 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10314 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10315 10316 PackageInfoLite pkgLite = null; 10317 10318 if (onInt && onSd) { 10319 // Check if both bits are set. 10320 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10321 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10322 } else { 10323 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10324 packageAbiOverride); 10325 10326 /* 10327 * If we have too little free space, try to free cache 10328 * before giving up. 10329 */ 10330 if (!origin.staged && pkgLite.recommendedInstallLocation 10331 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10332 // TODO: focus freeing disk space on the target device 10333 final StorageManager storage = StorageManager.from(mContext); 10334 final long lowThreshold = storage.getStorageLowBytes( 10335 Environment.getDataDirectory()); 10336 10337 final long sizeBytes = mContainerService.calculateInstalledSize( 10338 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10339 10340 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10341 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10342 installFlags, packageAbiOverride); 10343 } 10344 10345 /* 10346 * The cache free must have deleted the file we 10347 * downloaded to install. 10348 * 10349 * TODO: fix the "freeCache" call to not delete 10350 * the file we care about. 10351 */ 10352 if (pkgLite.recommendedInstallLocation 10353 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10354 pkgLite.recommendedInstallLocation 10355 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10356 } 10357 } 10358 } 10359 10360 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10361 int loc = pkgLite.recommendedInstallLocation; 10362 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10363 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10364 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10365 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10366 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10367 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10368 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10369 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10370 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10371 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10372 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10373 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10374 } else { 10375 // Override with defaults if needed. 10376 loc = installLocationPolicy(pkgLite); 10377 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10378 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10379 } else if (!onSd && !onInt) { 10380 // Override install location with flags 10381 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10382 // Set the flag to install on external media. 10383 installFlags |= PackageManager.INSTALL_EXTERNAL; 10384 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10385 } else { 10386 // Make sure the flag for installing on external 10387 // media is unset 10388 installFlags |= PackageManager.INSTALL_INTERNAL; 10389 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10390 } 10391 } 10392 } 10393 } 10394 10395 final InstallArgs args = createInstallArgs(this); 10396 mArgs = args; 10397 10398 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10399 /* 10400 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10401 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10402 */ 10403 int userIdentifier = getUser().getIdentifier(); 10404 if (userIdentifier == UserHandle.USER_ALL 10405 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10406 userIdentifier = UserHandle.USER_OWNER; 10407 } 10408 10409 /* 10410 * Determine if we have any installed package verifiers. If we 10411 * do, then we'll defer to them to verify the packages. 10412 */ 10413 final int requiredUid = mRequiredVerifierPackage == null ? -1 10414 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10415 if (!origin.existing && requiredUid != -1 10416 && isVerificationEnabled(userIdentifier, installFlags)) { 10417 final Intent verification = new Intent( 10418 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10419 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10420 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10421 PACKAGE_MIME_TYPE); 10422 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10423 10424 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10425 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10426 0 /* TODO: Which userId? */); 10427 10428 if (DEBUG_VERIFY) { 10429 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10430 + verification.toString() + " with " + pkgLite.verifiers.length 10431 + " optional verifiers"); 10432 } 10433 10434 final int verificationId = mPendingVerificationToken++; 10435 10436 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10437 10438 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10439 installerPackageName); 10440 10441 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10442 installFlags); 10443 10444 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10445 pkgLite.packageName); 10446 10447 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10448 pkgLite.versionCode); 10449 10450 if (verificationParams != null) { 10451 if (verificationParams.getVerificationURI() != null) { 10452 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10453 verificationParams.getVerificationURI()); 10454 } 10455 if (verificationParams.getOriginatingURI() != null) { 10456 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10457 verificationParams.getOriginatingURI()); 10458 } 10459 if (verificationParams.getReferrer() != null) { 10460 verification.putExtra(Intent.EXTRA_REFERRER, 10461 verificationParams.getReferrer()); 10462 } 10463 if (verificationParams.getOriginatingUid() >= 0) { 10464 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10465 verificationParams.getOriginatingUid()); 10466 } 10467 if (verificationParams.getInstallerUid() >= 0) { 10468 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10469 verificationParams.getInstallerUid()); 10470 } 10471 } 10472 10473 final PackageVerificationState verificationState = new PackageVerificationState( 10474 requiredUid, args); 10475 10476 mPendingVerification.append(verificationId, verificationState); 10477 10478 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10479 receivers, verificationState); 10480 10481 /* 10482 * If any sufficient verifiers were listed in the package 10483 * manifest, attempt to ask them. 10484 */ 10485 if (sufficientVerifiers != null) { 10486 final int N = sufficientVerifiers.size(); 10487 if (N == 0) { 10488 Slog.i(TAG, "Additional verifiers required, but none installed."); 10489 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10490 } else { 10491 for (int i = 0; i < N; i++) { 10492 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10493 10494 final Intent sufficientIntent = new Intent(verification); 10495 sufficientIntent.setComponent(verifierComponent); 10496 10497 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10498 } 10499 } 10500 } 10501 10502 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10503 mRequiredVerifierPackage, receivers); 10504 if (ret == PackageManager.INSTALL_SUCCEEDED 10505 && mRequiredVerifierPackage != null) { 10506 /* 10507 * Send the intent to the required verification agent, 10508 * but only start the verification timeout after the 10509 * target BroadcastReceivers have run. 10510 */ 10511 verification.setComponent(requiredVerifierComponent); 10512 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10513 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10514 new BroadcastReceiver() { 10515 @Override 10516 public void onReceive(Context context, Intent intent) { 10517 final Message msg = mHandler 10518 .obtainMessage(CHECK_PENDING_VERIFICATION); 10519 msg.arg1 = verificationId; 10520 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10521 } 10522 }, null, 0, null, null); 10523 10524 /* 10525 * We don't want the copy to proceed until verification 10526 * succeeds, so null out this field. 10527 */ 10528 mArgs = null; 10529 } 10530 } else { 10531 /* 10532 * No package verification is enabled, so immediately start 10533 * the remote call to initiate copy using temporary file. 10534 */ 10535 ret = args.copyApk(mContainerService, true); 10536 } 10537 } 10538 10539 mRet = ret; 10540 } 10541 10542 @Override 10543 void handleReturnCode() { 10544 // If mArgs is null, then MCS couldn't be reached. When it 10545 // reconnects, it will try again to install. At that point, this 10546 // will succeed. 10547 if (mArgs != null) { 10548 processPendingInstall(mArgs, mRet); 10549 } 10550 } 10551 10552 @Override 10553 void handleServiceError() { 10554 mArgs = createInstallArgs(this); 10555 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10556 } 10557 10558 public boolean isForwardLocked() { 10559 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10560 } 10561 } 10562 10563 /** 10564 * Used during creation of InstallArgs 10565 * 10566 * @param installFlags package installation flags 10567 * @return true if should be installed on external storage 10568 */ 10569 private static boolean installOnExternalAsec(int installFlags) { 10570 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10571 return false; 10572 } 10573 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10574 return true; 10575 } 10576 return false; 10577 } 10578 10579 /** 10580 * Used during creation of InstallArgs 10581 * 10582 * @param installFlags package installation flags 10583 * @return true if should be installed as forward locked 10584 */ 10585 private static boolean installForwardLocked(int installFlags) { 10586 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10587 } 10588 10589 private InstallArgs createInstallArgs(InstallParams params) { 10590 if (params.move != null) { 10591 return new MoveInstallArgs(params); 10592 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10593 return new AsecInstallArgs(params); 10594 } else { 10595 return new FileInstallArgs(params); 10596 } 10597 } 10598 10599 /** 10600 * Create args that describe an existing installed package. Typically used 10601 * when cleaning up old installs, or used as a move source. 10602 */ 10603 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10604 String resourcePath, String[] instructionSets) { 10605 final boolean isInAsec; 10606 if (installOnExternalAsec(installFlags)) { 10607 /* Apps on SD card are always in ASEC containers. */ 10608 isInAsec = true; 10609 } else if (installForwardLocked(installFlags) 10610 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10611 /* 10612 * Forward-locked apps are only in ASEC containers if they're the 10613 * new style 10614 */ 10615 isInAsec = true; 10616 } else { 10617 isInAsec = false; 10618 } 10619 10620 if (isInAsec) { 10621 return new AsecInstallArgs(codePath, instructionSets, 10622 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10623 } else { 10624 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10625 } 10626 } 10627 10628 static abstract class InstallArgs { 10629 /** @see InstallParams#origin */ 10630 final OriginInfo origin; 10631 /** @see InstallParams#move */ 10632 final MoveInfo move; 10633 10634 final IPackageInstallObserver2 observer; 10635 // Always refers to PackageManager flags only 10636 final int installFlags; 10637 final String installerPackageName; 10638 final String volumeUuid; 10639 final ManifestDigest manifestDigest; 10640 final UserHandle user; 10641 final String abiOverride; 10642 10643 // The list of instruction sets supported by this app. This is currently 10644 // only used during the rmdex() phase to clean up resources. We can get rid of this 10645 // if we move dex files under the common app path. 10646 /* nullable */ String[] instructionSets; 10647 10648 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10649 int installFlags, String installerPackageName, String volumeUuid, 10650 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10651 String abiOverride) { 10652 this.origin = origin; 10653 this.move = move; 10654 this.installFlags = installFlags; 10655 this.observer = observer; 10656 this.installerPackageName = installerPackageName; 10657 this.volumeUuid = volumeUuid; 10658 this.manifestDigest = manifestDigest; 10659 this.user = user; 10660 this.instructionSets = instructionSets; 10661 this.abiOverride = abiOverride; 10662 } 10663 10664 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10665 abstract int doPreInstall(int status); 10666 10667 /** 10668 * Rename package into final resting place. All paths on the given 10669 * scanned package should be updated to reflect the rename. 10670 */ 10671 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10672 abstract int doPostInstall(int status, int uid); 10673 10674 /** @see PackageSettingBase#codePathString */ 10675 abstract String getCodePath(); 10676 /** @see PackageSettingBase#resourcePathString */ 10677 abstract String getResourcePath(); 10678 10679 // Need installer lock especially for dex file removal. 10680 abstract void cleanUpResourcesLI(); 10681 abstract boolean doPostDeleteLI(boolean delete); 10682 10683 /** 10684 * Called before the source arguments are copied. This is used mostly 10685 * for MoveParams when it needs to read the source file to put it in the 10686 * destination. 10687 */ 10688 int doPreCopy() { 10689 return PackageManager.INSTALL_SUCCEEDED; 10690 } 10691 10692 /** 10693 * Called after the source arguments are copied. This is used mostly for 10694 * MoveParams when it needs to read the source file to put it in the 10695 * destination. 10696 * 10697 * @return 10698 */ 10699 int doPostCopy(int uid) { 10700 return PackageManager.INSTALL_SUCCEEDED; 10701 } 10702 10703 protected boolean isFwdLocked() { 10704 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10705 } 10706 10707 protected boolean isExternalAsec() { 10708 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10709 } 10710 10711 UserHandle getUser() { 10712 return user; 10713 } 10714 } 10715 10716 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10717 if (!allCodePaths.isEmpty()) { 10718 if (instructionSets == null) { 10719 throw new IllegalStateException("instructionSet == null"); 10720 } 10721 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10722 for (String codePath : allCodePaths) { 10723 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10724 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10725 if (retCode < 0) { 10726 Slog.w(TAG, "Couldn't remove dex file for package: " 10727 + " at location " + codePath + ", retcode=" + retCode); 10728 // we don't consider this to be a failure of the core package deletion 10729 } 10730 } 10731 } 10732 } 10733 } 10734 10735 /** 10736 * Logic to handle installation of non-ASEC applications, including copying 10737 * and renaming logic. 10738 */ 10739 class FileInstallArgs extends InstallArgs { 10740 private File codeFile; 10741 private File resourceFile; 10742 10743 // Example topology: 10744 // /data/app/com.example/base.apk 10745 // /data/app/com.example/split_foo.apk 10746 // /data/app/com.example/lib/arm/libfoo.so 10747 // /data/app/com.example/lib/arm64/libfoo.so 10748 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10749 10750 /** New install */ 10751 FileInstallArgs(InstallParams params) { 10752 super(params.origin, params.move, params.observer, params.installFlags, 10753 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10754 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10755 if (isFwdLocked()) { 10756 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10757 } 10758 } 10759 10760 /** Existing install */ 10761 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10762 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10763 null); 10764 this.codeFile = (codePath != null) ? new File(codePath) : null; 10765 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10766 } 10767 10768 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10769 if (origin.staged) { 10770 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10771 codeFile = origin.file; 10772 resourceFile = origin.file; 10773 return PackageManager.INSTALL_SUCCEEDED; 10774 } 10775 10776 try { 10777 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10778 codeFile = tempDir; 10779 resourceFile = tempDir; 10780 } catch (IOException e) { 10781 Slog.w(TAG, "Failed to create copy file: " + e); 10782 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10783 } 10784 10785 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10786 @Override 10787 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10788 if (!FileUtils.isValidExtFilename(name)) { 10789 throw new IllegalArgumentException("Invalid filename: " + name); 10790 } 10791 try { 10792 final File file = new File(codeFile, name); 10793 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10794 O_RDWR | O_CREAT, 0644); 10795 Os.chmod(file.getAbsolutePath(), 0644); 10796 return new ParcelFileDescriptor(fd); 10797 } catch (ErrnoException e) { 10798 throw new RemoteException("Failed to open: " + e.getMessage()); 10799 } 10800 } 10801 }; 10802 10803 int ret = PackageManager.INSTALL_SUCCEEDED; 10804 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10805 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10806 Slog.e(TAG, "Failed to copy package"); 10807 return ret; 10808 } 10809 10810 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10811 NativeLibraryHelper.Handle handle = null; 10812 try { 10813 handle = NativeLibraryHelper.Handle.create(codeFile); 10814 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10815 abiOverride); 10816 } catch (IOException e) { 10817 Slog.e(TAG, "Copying native libraries failed", e); 10818 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10819 } finally { 10820 IoUtils.closeQuietly(handle); 10821 } 10822 10823 return ret; 10824 } 10825 10826 int doPreInstall(int status) { 10827 if (status != PackageManager.INSTALL_SUCCEEDED) { 10828 cleanUp(); 10829 } 10830 return status; 10831 } 10832 10833 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10834 if (status != PackageManager.INSTALL_SUCCEEDED) { 10835 cleanUp(); 10836 return false; 10837 } 10838 10839 final File targetDir = codeFile.getParentFile(); 10840 final File beforeCodeFile = codeFile; 10841 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10842 10843 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10844 try { 10845 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10846 } catch (ErrnoException e) { 10847 Slog.w(TAG, "Failed to rename", e); 10848 return false; 10849 } 10850 10851 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10852 Slog.w(TAG, "Failed to restorecon"); 10853 return false; 10854 } 10855 10856 // Reflect the rename internally 10857 codeFile = afterCodeFile; 10858 resourceFile = afterCodeFile; 10859 10860 // Reflect the rename in scanned details 10861 pkg.codePath = afterCodeFile.getAbsolutePath(); 10862 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10863 pkg.baseCodePath); 10864 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10865 pkg.splitCodePaths); 10866 10867 // Reflect the rename in app info 10868 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10869 pkg.applicationInfo.setCodePath(pkg.codePath); 10870 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10871 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10872 pkg.applicationInfo.setResourcePath(pkg.codePath); 10873 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10874 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10875 10876 return true; 10877 } 10878 10879 int doPostInstall(int status, int uid) { 10880 if (status != PackageManager.INSTALL_SUCCEEDED) { 10881 cleanUp(); 10882 } 10883 return status; 10884 } 10885 10886 @Override 10887 String getCodePath() { 10888 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10889 } 10890 10891 @Override 10892 String getResourcePath() { 10893 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10894 } 10895 10896 private boolean cleanUp() { 10897 if (codeFile == null || !codeFile.exists()) { 10898 return false; 10899 } 10900 10901 if (codeFile.isDirectory()) { 10902 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10903 } else { 10904 codeFile.delete(); 10905 } 10906 10907 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10908 resourceFile.delete(); 10909 } 10910 10911 return true; 10912 } 10913 10914 void cleanUpResourcesLI() { 10915 // Try enumerating all code paths before deleting 10916 List<String> allCodePaths = Collections.EMPTY_LIST; 10917 if (codeFile != null && codeFile.exists()) { 10918 try { 10919 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10920 allCodePaths = pkg.getAllCodePaths(); 10921 } catch (PackageParserException e) { 10922 // Ignored; we tried our best 10923 } 10924 } 10925 10926 cleanUp(); 10927 removeDexFiles(allCodePaths, instructionSets); 10928 } 10929 10930 boolean doPostDeleteLI(boolean delete) { 10931 // XXX err, shouldn't we respect the delete flag? 10932 cleanUpResourcesLI(); 10933 return true; 10934 } 10935 } 10936 10937 private boolean isAsecExternal(String cid) { 10938 final String asecPath = PackageHelper.getSdFilesystem(cid); 10939 return !asecPath.startsWith(mAsecInternalPath); 10940 } 10941 10942 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10943 PackageManagerException { 10944 if (copyRet < 0) { 10945 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10946 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10947 throw new PackageManagerException(copyRet, message); 10948 } 10949 } 10950 } 10951 10952 /** 10953 * Extract the MountService "container ID" from the full code path of an 10954 * .apk. 10955 */ 10956 static String cidFromCodePath(String fullCodePath) { 10957 int eidx = fullCodePath.lastIndexOf("/"); 10958 String subStr1 = fullCodePath.substring(0, eidx); 10959 int sidx = subStr1.lastIndexOf("/"); 10960 return subStr1.substring(sidx+1, eidx); 10961 } 10962 10963 /** 10964 * Logic to handle installation of ASEC applications, including copying and 10965 * renaming logic. 10966 */ 10967 class AsecInstallArgs extends InstallArgs { 10968 static final String RES_FILE_NAME = "pkg.apk"; 10969 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10970 10971 String cid; 10972 String packagePath; 10973 String resourcePath; 10974 10975 /** New install */ 10976 AsecInstallArgs(InstallParams params) { 10977 super(params.origin, params.move, params.observer, params.installFlags, 10978 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10979 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10980 } 10981 10982 /** Existing install */ 10983 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10984 boolean isExternal, boolean isForwardLocked) { 10985 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10986 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10987 instructionSets, null); 10988 // Hackily pretend we're still looking at a full code path 10989 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10990 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10991 } 10992 10993 // Extract cid from fullCodePath 10994 int eidx = fullCodePath.lastIndexOf("/"); 10995 String subStr1 = fullCodePath.substring(0, eidx); 10996 int sidx = subStr1.lastIndexOf("/"); 10997 cid = subStr1.substring(sidx+1, eidx); 10998 setMountPath(subStr1); 10999 } 11000 11001 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11002 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11003 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11004 instructionSets, null); 11005 this.cid = cid; 11006 setMountPath(PackageHelper.getSdDir(cid)); 11007 } 11008 11009 void createCopyFile() { 11010 cid = mInstallerService.allocateExternalStageCidLegacy(); 11011 } 11012 11013 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11014 if (origin.staged) { 11015 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11016 cid = origin.cid; 11017 setMountPath(PackageHelper.getSdDir(cid)); 11018 return PackageManager.INSTALL_SUCCEEDED; 11019 } 11020 11021 if (temp) { 11022 createCopyFile(); 11023 } else { 11024 /* 11025 * Pre-emptively destroy the container since it's destroyed if 11026 * copying fails due to it existing anyway. 11027 */ 11028 PackageHelper.destroySdDir(cid); 11029 } 11030 11031 final String newMountPath = imcs.copyPackageToContainer( 11032 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11033 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11034 11035 if (newMountPath != null) { 11036 setMountPath(newMountPath); 11037 return PackageManager.INSTALL_SUCCEEDED; 11038 } else { 11039 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11040 } 11041 } 11042 11043 @Override 11044 String getCodePath() { 11045 return packagePath; 11046 } 11047 11048 @Override 11049 String getResourcePath() { 11050 return resourcePath; 11051 } 11052 11053 int doPreInstall(int status) { 11054 if (status != PackageManager.INSTALL_SUCCEEDED) { 11055 // Destroy container 11056 PackageHelper.destroySdDir(cid); 11057 } else { 11058 boolean mounted = PackageHelper.isContainerMounted(cid); 11059 if (!mounted) { 11060 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11061 Process.SYSTEM_UID); 11062 if (newMountPath != null) { 11063 setMountPath(newMountPath); 11064 } else { 11065 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11066 } 11067 } 11068 } 11069 return status; 11070 } 11071 11072 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11073 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11074 String newMountPath = null; 11075 if (PackageHelper.isContainerMounted(cid)) { 11076 // Unmount the container 11077 if (!PackageHelper.unMountSdDir(cid)) { 11078 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11079 return false; 11080 } 11081 } 11082 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11083 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11084 " which might be stale. Will try to clean up."); 11085 // Clean up the stale container and proceed to recreate. 11086 if (!PackageHelper.destroySdDir(newCacheId)) { 11087 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11088 return false; 11089 } 11090 // Successfully cleaned up stale container. Try to rename again. 11091 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11092 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11093 + " inspite of cleaning it up."); 11094 return false; 11095 } 11096 } 11097 if (!PackageHelper.isContainerMounted(newCacheId)) { 11098 Slog.w(TAG, "Mounting container " + newCacheId); 11099 newMountPath = PackageHelper.mountSdDir(newCacheId, 11100 getEncryptKey(), Process.SYSTEM_UID); 11101 } else { 11102 newMountPath = PackageHelper.getSdDir(newCacheId); 11103 } 11104 if (newMountPath == null) { 11105 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11106 return false; 11107 } 11108 Log.i(TAG, "Succesfully renamed " + cid + 11109 " to " + newCacheId + 11110 " at new path: " + newMountPath); 11111 cid = newCacheId; 11112 11113 final File beforeCodeFile = new File(packagePath); 11114 setMountPath(newMountPath); 11115 final File afterCodeFile = new File(packagePath); 11116 11117 // Reflect the rename in scanned details 11118 pkg.codePath = afterCodeFile.getAbsolutePath(); 11119 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11120 pkg.baseCodePath); 11121 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11122 pkg.splitCodePaths); 11123 11124 // Reflect the rename in app info 11125 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11126 pkg.applicationInfo.setCodePath(pkg.codePath); 11127 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11128 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11129 pkg.applicationInfo.setResourcePath(pkg.codePath); 11130 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11131 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11132 11133 return true; 11134 } 11135 11136 private void setMountPath(String mountPath) { 11137 final File mountFile = new File(mountPath); 11138 11139 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11140 if (monolithicFile.exists()) { 11141 packagePath = monolithicFile.getAbsolutePath(); 11142 if (isFwdLocked()) { 11143 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11144 } else { 11145 resourcePath = packagePath; 11146 } 11147 } else { 11148 packagePath = mountFile.getAbsolutePath(); 11149 resourcePath = packagePath; 11150 } 11151 } 11152 11153 int doPostInstall(int status, int uid) { 11154 if (status != PackageManager.INSTALL_SUCCEEDED) { 11155 cleanUp(); 11156 } else { 11157 final int groupOwner; 11158 final String protectedFile; 11159 if (isFwdLocked()) { 11160 groupOwner = UserHandle.getSharedAppGid(uid); 11161 protectedFile = RES_FILE_NAME; 11162 } else { 11163 groupOwner = -1; 11164 protectedFile = null; 11165 } 11166 11167 if (uid < Process.FIRST_APPLICATION_UID 11168 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11169 Slog.e(TAG, "Failed to finalize " + cid); 11170 PackageHelper.destroySdDir(cid); 11171 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11172 } 11173 11174 boolean mounted = PackageHelper.isContainerMounted(cid); 11175 if (!mounted) { 11176 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11177 } 11178 } 11179 return status; 11180 } 11181 11182 private void cleanUp() { 11183 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11184 11185 // Destroy secure container 11186 PackageHelper.destroySdDir(cid); 11187 } 11188 11189 private List<String> getAllCodePaths() { 11190 final File codeFile = new File(getCodePath()); 11191 if (codeFile != null && codeFile.exists()) { 11192 try { 11193 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11194 return pkg.getAllCodePaths(); 11195 } catch (PackageParserException e) { 11196 // Ignored; we tried our best 11197 } 11198 } 11199 return Collections.EMPTY_LIST; 11200 } 11201 11202 void cleanUpResourcesLI() { 11203 // Enumerate all code paths before deleting 11204 cleanUpResourcesLI(getAllCodePaths()); 11205 } 11206 11207 private void cleanUpResourcesLI(List<String> allCodePaths) { 11208 cleanUp(); 11209 removeDexFiles(allCodePaths, instructionSets); 11210 } 11211 11212 String getPackageName() { 11213 return getAsecPackageName(cid); 11214 } 11215 11216 boolean doPostDeleteLI(boolean delete) { 11217 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11218 final List<String> allCodePaths = getAllCodePaths(); 11219 boolean mounted = PackageHelper.isContainerMounted(cid); 11220 if (mounted) { 11221 // Unmount first 11222 if (PackageHelper.unMountSdDir(cid)) { 11223 mounted = false; 11224 } 11225 } 11226 if (!mounted && delete) { 11227 cleanUpResourcesLI(allCodePaths); 11228 } 11229 return !mounted; 11230 } 11231 11232 @Override 11233 int doPreCopy() { 11234 if (isFwdLocked()) { 11235 if (!PackageHelper.fixSdPermissions(cid, 11236 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11237 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11238 } 11239 } 11240 11241 return PackageManager.INSTALL_SUCCEEDED; 11242 } 11243 11244 @Override 11245 int doPostCopy(int uid) { 11246 if (isFwdLocked()) { 11247 if (uid < Process.FIRST_APPLICATION_UID 11248 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11249 RES_FILE_NAME)) { 11250 Slog.e(TAG, "Failed to finalize " + cid); 11251 PackageHelper.destroySdDir(cid); 11252 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11253 } 11254 } 11255 11256 return PackageManager.INSTALL_SUCCEEDED; 11257 } 11258 } 11259 11260 /** 11261 * Logic to handle movement of existing installed applications. 11262 */ 11263 class MoveInstallArgs extends InstallArgs { 11264 private File codeFile; 11265 private File resourceFile; 11266 11267 /** New install */ 11268 MoveInstallArgs(InstallParams params) { 11269 super(params.origin, params.move, params.observer, params.installFlags, 11270 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11271 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11272 } 11273 11274 int copyApk(IMediaContainerService imcs, boolean temp) { 11275 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11276 + move.fromUuid + " to " + move.toUuid); 11277 synchronized (mInstaller) { 11278 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11279 move.dataAppName, move.appId, move.seinfo) != 0) { 11280 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11281 } 11282 } 11283 11284 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11285 resourceFile = codeFile; 11286 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11287 11288 return PackageManager.INSTALL_SUCCEEDED; 11289 } 11290 11291 int doPreInstall(int status) { 11292 if (status != PackageManager.INSTALL_SUCCEEDED) { 11293 cleanUp(); 11294 } 11295 return status; 11296 } 11297 11298 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11299 if (status != PackageManager.INSTALL_SUCCEEDED) { 11300 cleanUp(); 11301 return false; 11302 } 11303 11304 // Reflect the move in app info 11305 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11306 pkg.applicationInfo.setCodePath(pkg.codePath); 11307 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11308 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11309 pkg.applicationInfo.setResourcePath(pkg.codePath); 11310 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11311 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11312 11313 return true; 11314 } 11315 11316 int doPostInstall(int status, int uid) { 11317 if (status != PackageManager.INSTALL_SUCCEEDED) { 11318 cleanUp(); 11319 } 11320 return status; 11321 } 11322 11323 @Override 11324 String getCodePath() { 11325 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11326 } 11327 11328 @Override 11329 String getResourcePath() { 11330 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11331 } 11332 11333 private boolean cleanUp() { 11334 if (codeFile == null || !codeFile.exists()) { 11335 return false; 11336 } 11337 11338 if (codeFile.isDirectory()) { 11339 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11340 } else { 11341 codeFile.delete(); 11342 } 11343 11344 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11345 resourceFile.delete(); 11346 } 11347 11348 return true; 11349 } 11350 11351 void cleanUpResourcesLI() { 11352 cleanUp(); 11353 } 11354 11355 boolean doPostDeleteLI(boolean delete) { 11356 // XXX err, shouldn't we respect the delete flag? 11357 cleanUpResourcesLI(); 11358 return true; 11359 } 11360 } 11361 11362 static String getAsecPackageName(String packageCid) { 11363 int idx = packageCid.lastIndexOf("-"); 11364 if (idx == -1) { 11365 return packageCid; 11366 } 11367 return packageCid.substring(0, idx); 11368 } 11369 11370 // Utility method used to create code paths based on package name and available index. 11371 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11372 String idxStr = ""; 11373 int idx = 1; 11374 // Fall back to default value of idx=1 if prefix is not 11375 // part of oldCodePath 11376 if (oldCodePath != null) { 11377 String subStr = oldCodePath; 11378 // Drop the suffix right away 11379 if (suffix != null && subStr.endsWith(suffix)) { 11380 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11381 } 11382 // If oldCodePath already contains prefix find out the 11383 // ending index to either increment or decrement. 11384 int sidx = subStr.lastIndexOf(prefix); 11385 if (sidx != -1) { 11386 subStr = subStr.substring(sidx + prefix.length()); 11387 if (subStr != null) { 11388 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11389 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11390 } 11391 try { 11392 idx = Integer.parseInt(subStr); 11393 if (idx <= 1) { 11394 idx++; 11395 } else { 11396 idx--; 11397 } 11398 } catch(NumberFormatException e) { 11399 } 11400 } 11401 } 11402 } 11403 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11404 return prefix + idxStr; 11405 } 11406 11407 private File getNextCodePath(File targetDir, String packageName) { 11408 int suffix = 1; 11409 File result; 11410 do { 11411 result = new File(targetDir, packageName + "-" + suffix); 11412 suffix++; 11413 } while (result.exists()); 11414 return result; 11415 } 11416 11417 // Utility method that returns the relative package path with respect 11418 // to the installation directory. Like say for /data/data/com.test-1.apk 11419 // string com.test-1 is returned. 11420 static String deriveCodePathName(String codePath) { 11421 if (codePath == null) { 11422 return null; 11423 } 11424 final File codeFile = new File(codePath); 11425 final String name = codeFile.getName(); 11426 if (codeFile.isDirectory()) { 11427 return name; 11428 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11429 final int lastDot = name.lastIndexOf('.'); 11430 return name.substring(0, lastDot); 11431 } else { 11432 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11433 return null; 11434 } 11435 } 11436 11437 class PackageInstalledInfo { 11438 String name; 11439 int uid; 11440 // The set of users that originally had this package installed. 11441 int[] origUsers; 11442 // The set of users that now have this package installed. 11443 int[] newUsers; 11444 PackageParser.Package pkg; 11445 int returnCode; 11446 String returnMsg; 11447 PackageRemovedInfo removedInfo; 11448 11449 public void setError(int code, String msg) { 11450 returnCode = code; 11451 returnMsg = msg; 11452 Slog.w(TAG, msg); 11453 } 11454 11455 public void setError(String msg, PackageParserException e) { 11456 returnCode = e.error; 11457 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11458 Slog.w(TAG, msg, e); 11459 } 11460 11461 public void setError(String msg, PackageManagerException e) { 11462 returnCode = e.error; 11463 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11464 Slog.w(TAG, msg, e); 11465 } 11466 11467 // In some error cases we want to convey more info back to the observer 11468 String origPackage; 11469 String origPermission; 11470 } 11471 11472 /* 11473 * Install a non-existing package. 11474 */ 11475 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11476 UserHandle user, String installerPackageName, String volumeUuid, 11477 PackageInstalledInfo res) { 11478 // Remember this for later, in case we need to rollback this install 11479 String pkgName = pkg.packageName; 11480 11481 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11482 final boolean dataDirExists = Environment 11483 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11484 synchronized(mPackages) { 11485 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11486 // A package with the same name is already installed, though 11487 // it has been renamed to an older name. The package we 11488 // are trying to install should be installed as an update to 11489 // the existing one, but that has not been requested, so bail. 11490 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11491 + " without first uninstalling package running as " 11492 + mSettings.mRenamedPackages.get(pkgName)); 11493 return; 11494 } 11495 if (mPackages.containsKey(pkgName)) { 11496 // Don't allow installation over an existing package with the same name. 11497 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11498 + " without first uninstalling."); 11499 return; 11500 } 11501 } 11502 11503 try { 11504 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11505 System.currentTimeMillis(), user); 11506 11507 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11508 // delete the partially installed application. the data directory will have to be 11509 // restored if it was already existing 11510 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11511 // remove package from internal structures. Note that we want deletePackageX to 11512 // delete the package data and cache directories that it created in 11513 // scanPackageLocked, unless those directories existed before we even tried to 11514 // install. 11515 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11516 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11517 res.removedInfo, true); 11518 } 11519 11520 } catch (PackageManagerException e) { 11521 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11522 } 11523 } 11524 11525 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11526 // Can't rotate keys during boot or if sharedUser. 11527 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11528 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11529 return false; 11530 } 11531 // app is using upgradeKeySets; make sure all are valid 11532 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11533 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11534 for (int i = 0; i < upgradeKeySets.length; i++) { 11535 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11536 Slog.wtf(TAG, "Package " 11537 + (oldPs.name != null ? oldPs.name : "<null>") 11538 + " contains upgrade-key-set reference to unknown key-set: " 11539 + upgradeKeySets[i] 11540 + " reverting to signatures check."); 11541 return false; 11542 } 11543 } 11544 return true; 11545 } 11546 11547 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11548 // Upgrade keysets are being used. Determine if new package has a superset of the 11549 // required keys. 11550 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11551 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11552 for (int i = 0; i < upgradeKeySets.length; i++) { 11553 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11554 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11555 return true; 11556 } 11557 } 11558 return false; 11559 } 11560 11561 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11562 UserHandle user, String installerPackageName, String volumeUuid, 11563 PackageInstalledInfo res) { 11564 final PackageParser.Package oldPackage; 11565 final String pkgName = pkg.packageName; 11566 final int[] allUsers; 11567 final boolean[] perUserInstalled; 11568 final boolean weFroze; 11569 11570 // First find the old package info and check signatures 11571 synchronized(mPackages) { 11572 oldPackage = mPackages.get(pkgName); 11573 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11574 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11575 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11576 if(!checkUpgradeKeySetLP(ps, pkg)) { 11577 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11578 "New package not signed by keys specified by upgrade-keysets: " 11579 + pkgName); 11580 return; 11581 } 11582 } else { 11583 // default to original signature matching 11584 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11585 != PackageManager.SIGNATURE_MATCH) { 11586 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11587 "New package has a different signature: " + pkgName); 11588 return; 11589 } 11590 } 11591 11592 // In case of rollback, remember per-user/profile install state 11593 allUsers = sUserManager.getUserIds(); 11594 perUserInstalled = new boolean[allUsers.length]; 11595 for (int i = 0; i < allUsers.length; i++) { 11596 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11597 } 11598 11599 // Mark the app as frozen to prevent launching during the upgrade 11600 // process, and then kill all running instances 11601 if (!ps.frozen) { 11602 ps.frozen = true; 11603 weFroze = true; 11604 } else { 11605 weFroze = false; 11606 } 11607 } 11608 11609 // Now that we're guarded by frozen state, kill app during upgrade 11610 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11611 11612 try { 11613 boolean sysPkg = (isSystemApp(oldPackage)); 11614 if (sysPkg) { 11615 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11616 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11617 } else { 11618 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11619 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11620 } 11621 } finally { 11622 // Regardless of success or failure of upgrade steps above, always 11623 // unfreeze the package if we froze it 11624 if (weFroze) { 11625 unfreezePackage(pkgName); 11626 } 11627 } 11628 } 11629 11630 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11631 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11632 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11633 String volumeUuid, PackageInstalledInfo res) { 11634 String pkgName = deletedPackage.packageName; 11635 boolean deletedPkg = true; 11636 boolean updatedSettings = false; 11637 11638 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11639 + deletedPackage); 11640 long origUpdateTime; 11641 if (pkg.mExtras != null) { 11642 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11643 } else { 11644 origUpdateTime = 0; 11645 } 11646 11647 // First delete the existing package while retaining the data directory 11648 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11649 res.removedInfo, true)) { 11650 // If the existing package wasn't successfully deleted 11651 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11652 deletedPkg = false; 11653 } else { 11654 // Successfully deleted the old package; proceed with replace. 11655 11656 // If deleted package lived in a container, give users a chance to 11657 // relinquish resources before killing. 11658 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11659 if (DEBUG_INSTALL) { 11660 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11661 } 11662 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11663 final ArrayList<String> pkgList = new ArrayList<String>(1); 11664 pkgList.add(deletedPackage.applicationInfo.packageName); 11665 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11666 } 11667 11668 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11669 try { 11670 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11671 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11672 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11673 perUserInstalled, res, user); 11674 updatedSettings = true; 11675 } catch (PackageManagerException e) { 11676 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11677 } 11678 } 11679 11680 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11681 // remove package from internal structures. Note that we want deletePackageX to 11682 // delete the package data and cache directories that it created in 11683 // scanPackageLocked, unless those directories existed before we even tried to 11684 // install. 11685 if(updatedSettings) { 11686 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11687 deletePackageLI( 11688 pkgName, null, true, allUsers, perUserInstalled, 11689 PackageManager.DELETE_KEEP_DATA, 11690 res.removedInfo, true); 11691 } 11692 // Since we failed to install the new package we need to restore the old 11693 // package that we deleted. 11694 if (deletedPkg) { 11695 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11696 File restoreFile = new File(deletedPackage.codePath); 11697 // Parse old package 11698 boolean oldExternal = isExternal(deletedPackage); 11699 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11700 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11701 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11702 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11703 try { 11704 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11705 } catch (PackageManagerException e) { 11706 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11707 + e.getMessage()); 11708 return; 11709 } 11710 // Restore of old package succeeded. Update permissions. 11711 // writer 11712 synchronized (mPackages) { 11713 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11714 UPDATE_PERMISSIONS_ALL); 11715 // can downgrade to reader 11716 mSettings.writeLPr(); 11717 } 11718 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11719 } 11720 } 11721 } 11722 11723 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11724 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11725 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11726 String volumeUuid, PackageInstalledInfo res) { 11727 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11728 + ", old=" + deletedPackage); 11729 boolean disabledSystem = false; 11730 boolean updatedSettings = false; 11731 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11732 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11733 != 0) { 11734 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11735 } 11736 String packageName = deletedPackage.packageName; 11737 if (packageName == null) { 11738 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11739 "Attempt to delete null packageName."); 11740 return; 11741 } 11742 PackageParser.Package oldPkg; 11743 PackageSetting oldPkgSetting; 11744 // reader 11745 synchronized (mPackages) { 11746 oldPkg = mPackages.get(packageName); 11747 oldPkgSetting = mSettings.mPackages.get(packageName); 11748 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11749 (oldPkgSetting == null)) { 11750 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11751 "Couldn't find package:" + packageName + " information"); 11752 return; 11753 } 11754 } 11755 11756 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11757 res.removedInfo.removedPackage = packageName; 11758 // Remove existing system package 11759 removePackageLI(oldPkgSetting, true); 11760 // writer 11761 synchronized (mPackages) { 11762 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11763 if (!disabledSystem && deletedPackage != null) { 11764 // We didn't need to disable the .apk as a current system package, 11765 // which means we are replacing another update that is already 11766 // installed. We need to make sure to delete the older one's .apk. 11767 res.removedInfo.args = createInstallArgsForExisting(0, 11768 deletedPackage.applicationInfo.getCodePath(), 11769 deletedPackage.applicationInfo.getResourcePath(), 11770 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11771 } else { 11772 res.removedInfo.args = null; 11773 } 11774 } 11775 11776 // Successfully disabled the old package. Now proceed with re-installation 11777 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11778 11779 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11780 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11781 11782 PackageParser.Package newPackage = null; 11783 try { 11784 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11785 if (newPackage.mExtras != null) { 11786 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11787 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11788 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11789 11790 // is the update attempting to change shared user? that isn't going to work... 11791 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11792 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11793 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11794 + " to " + newPkgSetting.sharedUser); 11795 updatedSettings = true; 11796 } 11797 } 11798 11799 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11800 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11801 perUserInstalled, res, user); 11802 updatedSettings = true; 11803 } 11804 11805 } catch (PackageManagerException e) { 11806 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11807 } 11808 11809 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11810 // Re installation failed. Restore old information 11811 // Remove new pkg information 11812 if (newPackage != null) { 11813 removeInstalledPackageLI(newPackage, true); 11814 } 11815 // Add back the old system package 11816 try { 11817 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11818 } catch (PackageManagerException e) { 11819 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11820 } 11821 // Restore the old system information in Settings 11822 synchronized (mPackages) { 11823 if (disabledSystem) { 11824 mSettings.enableSystemPackageLPw(packageName); 11825 } 11826 if (updatedSettings) { 11827 mSettings.setInstallerPackageName(packageName, 11828 oldPkgSetting.installerPackageName); 11829 } 11830 mSettings.writeLPr(); 11831 } 11832 } 11833 } 11834 11835 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11836 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11837 UserHandle user) { 11838 String pkgName = newPackage.packageName; 11839 synchronized (mPackages) { 11840 //write settings. the installStatus will be incomplete at this stage. 11841 //note that the new package setting would have already been 11842 //added to mPackages. It hasn't been persisted yet. 11843 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11844 mSettings.writeLPr(); 11845 } 11846 11847 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11848 11849 synchronized (mPackages) { 11850 updatePermissionsLPw(newPackage.packageName, newPackage, 11851 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11852 ? UPDATE_PERMISSIONS_ALL : 0)); 11853 // For system-bundled packages, we assume that installing an upgraded version 11854 // of the package implies that the user actually wants to run that new code, 11855 // so we enable the package. 11856 PackageSetting ps = mSettings.mPackages.get(pkgName); 11857 if (ps != null) { 11858 if (isSystemApp(newPackage)) { 11859 // NB: implicit assumption that system package upgrades apply to all users 11860 if (DEBUG_INSTALL) { 11861 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11862 } 11863 if (res.origUsers != null) { 11864 for (int userHandle : res.origUsers) { 11865 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11866 userHandle, installerPackageName); 11867 } 11868 } 11869 // Also convey the prior install/uninstall state 11870 if (allUsers != null && perUserInstalled != null) { 11871 for (int i = 0; i < allUsers.length; i++) { 11872 if (DEBUG_INSTALL) { 11873 Slog.d(TAG, " user " + allUsers[i] 11874 + " => " + perUserInstalled[i]); 11875 } 11876 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11877 } 11878 // these install state changes will be persisted in the 11879 // upcoming call to mSettings.writeLPr(). 11880 } 11881 } 11882 // It's implied that when a user requests installation, they want the app to be 11883 // installed and enabled. 11884 int userId = user.getIdentifier(); 11885 if (userId != UserHandle.USER_ALL) { 11886 ps.setInstalled(true, userId); 11887 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11888 } 11889 } 11890 res.name = pkgName; 11891 res.uid = newPackage.applicationInfo.uid; 11892 res.pkg = newPackage; 11893 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11894 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11895 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11896 //to update install status 11897 mSettings.writeLPr(); 11898 } 11899 } 11900 11901 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11902 final int installFlags = args.installFlags; 11903 final String installerPackageName = args.installerPackageName; 11904 final String volumeUuid = args.volumeUuid; 11905 final File tmpPackageFile = new File(args.getCodePath()); 11906 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11907 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11908 || (args.volumeUuid != null)); 11909 boolean replace = false; 11910 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11911 if (args.move != null) { 11912 // moving a complete application; perfom an initial scan on the new install location 11913 scanFlags |= SCAN_INITIAL; 11914 } 11915 // Result object to be returned 11916 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11917 11918 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11919 // Retrieve PackageSettings and parse package 11920 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11921 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11922 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11923 PackageParser pp = new PackageParser(); 11924 pp.setSeparateProcesses(mSeparateProcesses); 11925 pp.setDisplayMetrics(mMetrics); 11926 11927 final PackageParser.Package pkg; 11928 try { 11929 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11930 } catch (PackageParserException e) { 11931 res.setError("Failed parse during installPackageLI", e); 11932 return; 11933 } 11934 11935 // Mark that we have an install time CPU ABI override. 11936 pkg.cpuAbiOverride = args.abiOverride; 11937 11938 String pkgName = res.name = pkg.packageName; 11939 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11940 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11941 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11942 return; 11943 } 11944 } 11945 11946 try { 11947 pp.collectCertificates(pkg, parseFlags); 11948 pp.collectManifestDigest(pkg); 11949 } catch (PackageParserException e) { 11950 res.setError("Failed collect during installPackageLI", e); 11951 return; 11952 } 11953 11954 /* If the installer passed in a manifest digest, compare it now. */ 11955 if (args.manifestDigest != null) { 11956 if (DEBUG_INSTALL) { 11957 final String parsedManifest = pkg.manifestDigest == null ? "null" 11958 : pkg.manifestDigest.toString(); 11959 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11960 + parsedManifest); 11961 } 11962 11963 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11964 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11965 return; 11966 } 11967 } else if (DEBUG_INSTALL) { 11968 final String parsedManifest = pkg.manifestDigest == null 11969 ? "null" : pkg.manifestDigest.toString(); 11970 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11971 } 11972 11973 // Get rid of all references to package scan path via parser. 11974 pp = null; 11975 String oldCodePath = null; 11976 boolean systemApp = false; 11977 synchronized (mPackages) { 11978 // Check if installing already existing package 11979 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11980 String oldName = mSettings.mRenamedPackages.get(pkgName); 11981 if (pkg.mOriginalPackages != null 11982 && pkg.mOriginalPackages.contains(oldName) 11983 && mPackages.containsKey(oldName)) { 11984 // This package is derived from an original package, 11985 // and this device has been updating from that original 11986 // name. We must continue using the original name, so 11987 // rename the new package here. 11988 pkg.setPackageName(oldName); 11989 pkgName = pkg.packageName; 11990 replace = true; 11991 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11992 + oldName + " pkgName=" + pkgName); 11993 } else if (mPackages.containsKey(pkgName)) { 11994 // This package, under its official name, already exists 11995 // on the device; we should replace it. 11996 replace = true; 11997 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11998 } 11999 12000 // Prevent apps opting out from runtime permissions 12001 if (replace) { 12002 PackageParser.Package oldPackage = mPackages.get(pkgName); 12003 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12004 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12005 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12006 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12007 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12008 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12009 + " doesn't support runtime permissions but the old" 12010 + " target SDK " + oldTargetSdk + " does."); 12011 return; 12012 } 12013 } 12014 } 12015 12016 PackageSetting ps = mSettings.mPackages.get(pkgName); 12017 if (ps != null) { 12018 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12019 12020 // Quick sanity check that we're signed correctly if updating; 12021 // we'll check this again later when scanning, but we want to 12022 // bail early here before tripping over redefined permissions. 12023 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12024 if (!checkUpgradeKeySetLP(ps, pkg)) { 12025 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12026 + pkg.packageName + " upgrade keys do not match the " 12027 + "previously installed version"); 12028 return; 12029 } 12030 } else { 12031 try { 12032 verifySignaturesLP(ps, pkg); 12033 } catch (PackageManagerException e) { 12034 res.setError(e.error, e.getMessage()); 12035 return; 12036 } 12037 } 12038 12039 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12040 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12041 systemApp = (ps.pkg.applicationInfo.flags & 12042 ApplicationInfo.FLAG_SYSTEM) != 0; 12043 } 12044 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12045 } 12046 12047 // Check whether the newly-scanned package wants to define an already-defined perm 12048 int N = pkg.permissions.size(); 12049 for (int i = N-1; i >= 0; i--) { 12050 PackageParser.Permission perm = pkg.permissions.get(i); 12051 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12052 if (bp != null) { 12053 // If the defining package is signed with our cert, it's okay. This 12054 // also includes the "updating the same package" case, of course. 12055 // "updating same package" could also involve key-rotation. 12056 final boolean sigsOk; 12057 if (bp.sourcePackage.equals(pkg.packageName) 12058 && (bp.packageSetting instanceof PackageSetting) 12059 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12060 scanFlags))) { 12061 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12062 } else { 12063 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12064 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12065 } 12066 if (!sigsOk) { 12067 // If the owning package is the system itself, we log but allow 12068 // install to proceed; we fail the install on all other permission 12069 // redefinitions. 12070 if (!bp.sourcePackage.equals("android")) { 12071 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12072 + pkg.packageName + " attempting to redeclare permission " 12073 + perm.info.name + " already owned by " + bp.sourcePackage); 12074 res.origPermission = perm.info.name; 12075 res.origPackage = bp.sourcePackage; 12076 return; 12077 } else { 12078 Slog.w(TAG, "Package " + pkg.packageName 12079 + " attempting to redeclare system permission " 12080 + perm.info.name + "; ignoring new declaration"); 12081 pkg.permissions.remove(i); 12082 } 12083 } 12084 } 12085 } 12086 12087 } 12088 12089 if (systemApp && onExternal) { 12090 // Disable updates to system apps on sdcard 12091 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12092 "Cannot install updates to system apps on sdcard"); 12093 return; 12094 } 12095 12096 if (args.move != null) { 12097 // We did an in-place move, so dex is ready to roll 12098 scanFlags |= SCAN_NO_DEX; 12099 scanFlags |= SCAN_MOVE; 12100 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12101 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12102 scanFlags |= SCAN_NO_DEX; 12103 12104 try { 12105 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12106 true /* extract libs */); 12107 } catch (PackageManagerException pme) { 12108 Slog.e(TAG, "Error deriving application ABI", pme); 12109 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12110 return; 12111 } 12112 12113 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12114 int result = mPackageDexOptimizer 12115 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12116 false /* defer */, false /* inclDependencies */); 12117 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12118 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12119 return; 12120 } 12121 } 12122 12123 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12124 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12125 return; 12126 } 12127 12128 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12129 12130 if (replace) { 12131 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12132 installerPackageName, volumeUuid, res); 12133 } else { 12134 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12135 args.user, installerPackageName, volumeUuid, res); 12136 } 12137 synchronized (mPackages) { 12138 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12139 if (ps != null) { 12140 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12141 } 12142 } 12143 } 12144 12145 private void startIntentFilterVerifications(int userId, boolean replacing, 12146 PackageParser.Package pkg) { 12147 if (mIntentFilterVerifierComponent == null) { 12148 Slog.w(TAG, "No IntentFilter verification will not be done as " 12149 + "there is no IntentFilterVerifier available!"); 12150 return; 12151 } 12152 12153 final int verifierUid = getPackageUid( 12154 mIntentFilterVerifierComponent.getPackageName(), 12155 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12156 12157 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12158 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12159 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12160 mHandler.sendMessage(msg); 12161 } 12162 12163 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12164 PackageParser.Package pkg) { 12165 int size = pkg.activities.size(); 12166 if (size == 0) { 12167 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12168 "No activity, so no need to verify any IntentFilter!"); 12169 return; 12170 } 12171 12172 final boolean hasDomainURLs = hasDomainURLs(pkg); 12173 if (!hasDomainURLs) { 12174 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12175 "No domain URLs, so no need to verify any IntentFilter!"); 12176 return; 12177 } 12178 12179 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12180 + " if any IntentFilter from the " + size 12181 + " Activities needs verification ..."); 12182 12183 int count = 0; 12184 final String packageName = pkg.packageName; 12185 12186 synchronized (mPackages) { 12187 // If this is a new install and we see that we've already run verification for this 12188 // package, we have nothing to do: it means the state was restored from backup. 12189 if (!replacing) { 12190 IntentFilterVerificationInfo ivi = 12191 mSettings.getIntentFilterVerificationLPr(packageName); 12192 if (ivi != null) { 12193 if (DEBUG_DOMAIN_VERIFICATION) { 12194 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12195 + ivi.getStatusString()); 12196 } 12197 return; 12198 } 12199 } 12200 12201 // If any filters need to be verified, then all need to be. 12202 boolean needToVerify = false; 12203 for (PackageParser.Activity a : pkg.activities) { 12204 for (ActivityIntentInfo filter : a.intents) { 12205 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12206 if (DEBUG_DOMAIN_VERIFICATION) { 12207 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12208 } 12209 needToVerify = true; 12210 break; 12211 } 12212 } 12213 } 12214 12215 if (needToVerify) { 12216 final int verificationId = mIntentFilterVerificationToken++; 12217 for (PackageParser.Activity a : pkg.activities) { 12218 for (ActivityIntentInfo filter : a.intents) { 12219 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12220 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12221 "Verification needed for IntentFilter:" + filter.toString()); 12222 mIntentFilterVerifier.addOneIntentFilterVerification( 12223 verifierUid, userId, verificationId, filter, packageName); 12224 count++; 12225 } 12226 } 12227 } 12228 } 12229 } 12230 12231 if (count > 0) { 12232 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12233 + " IntentFilter verification" + (count > 1 ? "s" : "") 12234 + " for userId:" + userId); 12235 mIntentFilterVerifier.startVerifications(userId); 12236 } else { 12237 if (DEBUG_DOMAIN_VERIFICATION) { 12238 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12239 } 12240 } 12241 } 12242 12243 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12244 final ComponentName cn = filter.activity.getComponentName(); 12245 final String packageName = cn.getPackageName(); 12246 12247 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12248 packageName); 12249 if (ivi == null) { 12250 return true; 12251 } 12252 int status = ivi.getStatus(); 12253 switch (status) { 12254 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12255 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12256 return true; 12257 12258 default: 12259 // Nothing to do 12260 return false; 12261 } 12262 } 12263 12264 private static boolean isMultiArch(PackageSetting ps) { 12265 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12266 } 12267 12268 private static boolean isMultiArch(ApplicationInfo info) { 12269 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12270 } 12271 12272 private static boolean isExternal(PackageParser.Package pkg) { 12273 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12274 } 12275 12276 private static boolean isExternal(PackageSetting ps) { 12277 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12278 } 12279 12280 private static boolean isExternal(ApplicationInfo info) { 12281 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12282 } 12283 12284 private static boolean isSystemApp(PackageParser.Package pkg) { 12285 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12286 } 12287 12288 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12289 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12290 } 12291 12292 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12293 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12294 } 12295 12296 private static boolean isSystemApp(PackageSetting ps) { 12297 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12298 } 12299 12300 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12301 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12302 } 12303 12304 private int packageFlagsToInstallFlags(PackageSetting ps) { 12305 int installFlags = 0; 12306 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12307 // This existing package was an external ASEC install when we have 12308 // the external flag without a UUID 12309 installFlags |= PackageManager.INSTALL_EXTERNAL; 12310 } 12311 if (ps.isForwardLocked()) { 12312 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12313 } 12314 return installFlags; 12315 } 12316 12317 private void deleteTempPackageFiles() { 12318 final FilenameFilter filter = new FilenameFilter() { 12319 public boolean accept(File dir, String name) { 12320 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12321 } 12322 }; 12323 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12324 file.delete(); 12325 } 12326 } 12327 12328 @Override 12329 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12330 int flags) { 12331 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12332 flags); 12333 } 12334 12335 @Override 12336 public void deletePackage(final String packageName, 12337 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12338 mContext.enforceCallingOrSelfPermission( 12339 android.Manifest.permission.DELETE_PACKAGES, null); 12340 Preconditions.checkNotNull(packageName); 12341 Preconditions.checkNotNull(observer); 12342 final int uid = Binder.getCallingUid(); 12343 if (UserHandle.getUserId(uid) != userId) { 12344 mContext.enforceCallingPermission( 12345 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12346 "deletePackage for user " + userId); 12347 } 12348 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12349 try { 12350 observer.onPackageDeleted(packageName, 12351 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12352 } catch (RemoteException re) { 12353 } 12354 return; 12355 } 12356 12357 boolean uninstallBlocked = false; 12358 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12359 int[] users = sUserManager.getUserIds(); 12360 for (int i = 0; i < users.length; ++i) { 12361 if (getBlockUninstallForUser(packageName, users[i])) { 12362 uninstallBlocked = true; 12363 break; 12364 } 12365 } 12366 } else { 12367 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12368 } 12369 if (uninstallBlocked) { 12370 try { 12371 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12372 null); 12373 } catch (RemoteException re) { 12374 } 12375 return; 12376 } 12377 12378 if (DEBUG_REMOVE) { 12379 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12380 } 12381 // Queue up an async operation since the package deletion may take a little while. 12382 mHandler.post(new Runnable() { 12383 public void run() { 12384 mHandler.removeCallbacks(this); 12385 final int returnCode = deletePackageX(packageName, userId, flags); 12386 if (observer != null) { 12387 try { 12388 observer.onPackageDeleted(packageName, returnCode, null); 12389 } catch (RemoteException e) { 12390 Log.i(TAG, "Observer no longer exists."); 12391 } //end catch 12392 } //end if 12393 } //end run 12394 }); 12395 } 12396 12397 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12398 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12399 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12400 try { 12401 if (dpm != null) { 12402 if (dpm.isDeviceOwner(packageName)) { 12403 return true; 12404 } 12405 int[] users; 12406 if (userId == UserHandle.USER_ALL) { 12407 users = sUserManager.getUserIds(); 12408 } else { 12409 users = new int[]{userId}; 12410 } 12411 for (int i = 0; i < users.length; ++i) { 12412 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12413 return true; 12414 } 12415 } 12416 } 12417 } catch (RemoteException e) { 12418 } 12419 return false; 12420 } 12421 12422 /** 12423 * This method is an internal method that could be get invoked either 12424 * to delete an installed package or to clean up a failed installation. 12425 * After deleting an installed package, a broadcast is sent to notify any 12426 * listeners that the package has been installed. For cleaning up a failed 12427 * installation, the broadcast is not necessary since the package's 12428 * installation wouldn't have sent the initial broadcast either 12429 * The key steps in deleting a package are 12430 * deleting the package information in internal structures like mPackages, 12431 * deleting the packages base directories through installd 12432 * updating mSettings to reflect current status 12433 * persisting settings for later use 12434 * sending a broadcast if necessary 12435 */ 12436 private int deletePackageX(String packageName, int userId, int flags) { 12437 final PackageRemovedInfo info = new PackageRemovedInfo(); 12438 final boolean res; 12439 12440 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12441 ? UserHandle.ALL : new UserHandle(userId); 12442 12443 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12444 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12445 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12446 } 12447 12448 boolean removedForAllUsers = false; 12449 boolean systemUpdate = false; 12450 12451 // for the uninstall-updates case and restricted profiles, remember the per- 12452 // userhandle installed state 12453 int[] allUsers; 12454 boolean[] perUserInstalled; 12455 synchronized (mPackages) { 12456 PackageSetting ps = mSettings.mPackages.get(packageName); 12457 allUsers = sUserManager.getUserIds(); 12458 perUserInstalled = new boolean[allUsers.length]; 12459 for (int i = 0; i < allUsers.length; i++) { 12460 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12461 } 12462 } 12463 12464 synchronized (mInstallLock) { 12465 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12466 res = deletePackageLI(packageName, removeForUser, 12467 true, allUsers, perUserInstalled, 12468 flags | REMOVE_CHATTY, info, true); 12469 systemUpdate = info.isRemovedPackageSystemUpdate; 12470 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12471 removedForAllUsers = true; 12472 } 12473 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12474 + " removedForAllUsers=" + removedForAllUsers); 12475 } 12476 12477 if (res) { 12478 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12479 12480 // If the removed package was a system update, the old system package 12481 // was re-enabled; we need to broadcast this information 12482 if (systemUpdate) { 12483 Bundle extras = new Bundle(1); 12484 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12485 ? info.removedAppId : info.uid); 12486 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12487 12488 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12489 extras, null, null, null); 12490 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12491 extras, null, null, null); 12492 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12493 null, packageName, null, null); 12494 } 12495 } 12496 // Force a gc here. 12497 Runtime.getRuntime().gc(); 12498 // Delete the resources here after sending the broadcast to let 12499 // other processes clean up before deleting resources. 12500 if (info.args != null) { 12501 synchronized (mInstallLock) { 12502 info.args.doPostDeleteLI(true); 12503 } 12504 } 12505 12506 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12507 } 12508 12509 class PackageRemovedInfo { 12510 String removedPackage; 12511 int uid = -1; 12512 int removedAppId = -1; 12513 int[] removedUsers = null; 12514 boolean isRemovedPackageSystemUpdate = false; 12515 // Clean up resources deleted packages. 12516 InstallArgs args = null; 12517 12518 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12519 Bundle extras = new Bundle(1); 12520 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12521 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12522 if (replacing) { 12523 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12524 } 12525 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12526 if (removedPackage != null) { 12527 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12528 extras, null, null, removedUsers); 12529 if (fullRemove && !replacing) { 12530 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12531 extras, null, null, removedUsers); 12532 } 12533 } 12534 if (removedAppId >= 0) { 12535 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12536 removedUsers); 12537 } 12538 } 12539 } 12540 12541 /* 12542 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12543 * flag is not set, the data directory is removed as well. 12544 * make sure this flag is set for partially installed apps. If not its meaningless to 12545 * delete a partially installed application. 12546 */ 12547 private void removePackageDataLI(PackageSetting ps, 12548 int[] allUserHandles, boolean[] perUserInstalled, 12549 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12550 String packageName = ps.name; 12551 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12552 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12553 // Retrieve object to delete permissions for shared user later on 12554 final PackageSetting deletedPs; 12555 // reader 12556 synchronized (mPackages) { 12557 deletedPs = mSettings.mPackages.get(packageName); 12558 if (outInfo != null) { 12559 outInfo.removedPackage = packageName; 12560 outInfo.removedUsers = deletedPs != null 12561 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12562 : null; 12563 } 12564 } 12565 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12566 removeDataDirsLI(ps.volumeUuid, packageName); 12567 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12568 } 12569 // writer 12570 synchronized (mPackages) { 12571 if (deletedPs != null) { 12572 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12573 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12574 clearDefaultBrowserIfNeeded(packageName); 12575 if (outInfo != null) { 12576 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12577 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12578 } 12579 updatePermissionsLPw(deletedPs.name, null, 0); 12580 if (deletedPs.sharedUser != null) { 12581 // Remove permissions associated with package. Since runtime 12582 // permissions are per user we have to kill the removed package 12583 // or packages running under the shared user of the removed 12584 // package if revoking the permissions requested only by the removed 12585 // package is successful and this causes a change in gids. 12586 for (int userId : UserManagerService.getInstance().getUserIds()) { 12587 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12588 userId); 12589 if (userIdToKill == UserHandle.USER_ALL 12590 || userIdToKill >= UserHandle.USER_OWNER) { 12591 // If gids changed for this user, kill all affected packages. 12592 mHandler.post(new Runnable() { 12593 @Override 12594 public void run() { 12595 // This has to happen with no lock held. 12596 killSettingPackagesForUser(deletedPs, userIdToKill, 12597 KILL_APP_REASON_GIDS_CHANGED); 12598 } 12599 }); 12600 break; 12601 } 12602 } 12603 } 12604 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12605 } 12606 // make sure to preserve per-user disabled state if this removal was just 12607 // a downgrade of a system app to the factory package 12608 if (allUserHandles != null && perUserInstalled != null) { 12609 if (DEBUG_REMOVE) { 12610 Slog.d(TAG, "Propagating install state across downgrade"); 12611 } 12612 for (int i = 0; i < allUserHandles.length; i++) { 12613 if (DEBUG_REMOVE) { 12614 Slog.d(TAG, " user " + allUserHandles[i] 12615 + " => " + perUserInstalled[i]); 12616 } 12617 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12618 } 12619 } 12620 } 12621 // can downgrade to reader 12622 if (writeSettings) { 12623 // Save settings now 12624 mSettings.writeLPr(); 12625 } 12626 } 12627 if (outInfo != null) { 12628 // A user ID was deleted here. Go through all users and remove it 12629 // from KeyStore. 12630 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12631 } 12632 } 12633 12634 static boolean locationIsPrivileged(File path) { 12635 try { 12636 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12637 .getCanonicalPath(); 12638 return path.getCanonicalPath().startsWith(privilegedAppDir); 12639 } catch (IOException e) { 12640 Slog.e(TAG, "Unable to access code path " + path); 12641 } 12642 return false; 12643 } 12644 12645 /* 12646 * Tries to delete system package. 12647 */ 12648 private boolean deleteSystemPackageLI(PackageSetting newPs, 12649 int[] allUserHandles, boolean[] perUserInstalled, 12650 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12651 final boolean applyUserRestrictions 12652 = (allUserHandles != null) && (perUserInstalled != null); 12653 PackageSetting disabledPs = null; 12654 // Confirm if the system package has been updated 12655 // An updated system app can be deleted. This will also have to restore 12656 // the system pkg from system partition 12657 // reader 12658 synchronized (mPackages) { 12659 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12660 } 12661 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12662 + " disabledPs=" + disabledPs); 12663 if (disabledPs == null) { 12664 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12665 return false; 12666 } else if (DEBUG_REMOVE) { 12667 Slog.d(TAG, "Deleting system pkg from data partition"); 12668 } 12669 if (DEBUG_REMOVE) { 12670 if (applyUserRestrictions) { 12671 Slog.d(TAG, "Remembering install states:"); 12672 for (int i = 0; i < allUserHandles.length; i++) { 12673 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12674 } 12675 } 12676 } 12677 // Delete the updated package 12678 outInfo.isRemovedPackageSystemUpdate = true; 12679 if (disabledPs.versionCode < newPs.versionCode) { 12680 // Delete data for downgrades 12681 flags &= ~PackageManager.DELETE_KEEP_DATA; 12682 } else { 12683 // Preserve data by setting flag 12684 flags |= PackageManager.DELETE_KEEP_DATA; 12685 } 12686 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12687 allUserHandles, perUserInstalled, outInfo, writeSettings); 12688 if (!ret) { 12689 return false; 12690 } 12691 // writer 12692 synchronized (mPackages) { 12693 // Reinstate the old system package 12694 mSettings.enableSystemPackageLPw(newPs.name); 12695 // Remove any native libraries from the upgraded package. 12696 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12697 } 12698 // Install the system package 12699 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12700 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12701 if (locationIsPrivileged(disabledPs.codePath)) { 12702 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12703 } 12704 12705 final PackageParser.Package newPkg; 12706 try { 12707 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12708 } catch (PackageManagerException e) { 12709 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12710 return false; 12711 } 12712 12713 // writer 12714 synchronized (mPackages) { 12715 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12716 updatePermissionsLPw(newPkg.packageName, newPkg, 12717 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12718 if (applyUserRestrictions) { 12719 if (DEBUG_REMOVE) { 12720 Slog.d(TAG, "Propagating install state across reinstall"); 12721 } 12722 for (int i = 0; i < allUserHandles.length; i++) { 12723 if (DEBUG_REMOVE) { 12724 Slog.d(TAG, " user " + allUserHandles[i] 12725 + " => " + perUserInstalled[i]); 12726 } 12727 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12728 } 12729 // Regardless of writeSettings we need to ensure that this restriction 12730 // state propagation is persisted 12731 mSettings.writeAllUsersPackageRestrictionsLPr(); 12732 } 12733 // can downgrade to reader here 12734 if (writeSettings) { 12735 mSettings.writeLPr(); 12736 } 12737 } 12738 return true; 12739 } 12740 12741 private boolean deleteInstalledPackageLI(PackageSetting ps, 12742 boolean deleteCodeAndResources, int flags, 12743 int[] allUserHandles, boolean[] perUserInstalled, 12744 PackageRemovedInfo outInfo, boolean writeSettings) { 12745 if (outInfo != null) { 12746 outInfo.uid = ps.appId; 12747 } 12748 12749 // Delete package data from internal structures and also remove data if flag is set 12750 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12751 12752 // Delete application code and resources 12753 if (deleteCodeAndResources && (outInfo != null)) { 12754 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12755 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12756 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12757 } 12758 return true; 12759 } 12760 12761 @Override 12762 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12763 int userId) { 12764 mContext.enforceCallingOrSelfPermission( 12765 android.Manifest.permission.DELETE_PACKAGES, null); 12766 synchronized (mPackages) { 12767 PackageSetting ps = mSettings.mPackages.get(packageName); 12768 if (ps == null) { 12769 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12770 return false; 12771 } 12772 if (!ps.getInstalled(userId)) { 12773 // Can't block uninstall for an app that is not installed or enabled. 12774 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12775 return false; 12776 } 12777 ps.setBlockUninstall(blockUninstall, userId); 12778 mSettings.writePackageRestrictionsLPr(userId); 12779 } 12780 return true; 12781 } 12782 12783 @Override 12784 public boolean getBlockUninstallForUser(String packageName, int userId) { 12785 synchronized (mPackages) { 12786 PackageSetting ps = mSettings.mPackages.get(packageName); 12787 if (ps == null) { 12788 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12789 return false; 12790 } 12791 return ps.getBlockUninstall(userId); 12792 } 12793 } 12794 12795 /* 12796 * This method handles package deletion in general 12797 */ 12798 private boolean deletePackageLI(String packageName, UserHandle user, 12799 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12800 int flags, PackageRemovedInfo outInfo, 12801 boolean writeSettings) { 12802 if (packageName == null) { 12803 Slog.w(TAG, "Attempt to delete null packageName."); 12804 return false; 12805 } 12806 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12807 PackageSetting ps; 12808 boolean dataOnly = false; 12809 int removeUser = -1; 12810 int appId = -1; 12811 synchronized (mPackages) { 12812 ps = mSettings.mPackages.get(packageName); 12813 if (ps == null) { 12814 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12815 return false; 12816 } 12817 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12818 && user.getIdentifier() != UserHandle.USER_ALL) { 12819 // The caller is asking that the package only be deleted for a single 12820 // user. To do this, we just mark its uninstalled state and delete 12821 // its data. If this is a system app, we only allow this to happen if 12822 // they have set the special DELETE_SYSTEM_APP which requests different 12823 // semantics than normal for uninstalling system apps. 12824 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12825 ps.setUserState(user.getIdentifier(), 12826 COMPONENT_ENABLED_STATE_DEFAULT, 12827 false, //installed 12828 true, //stopped 12829 true, //notLaunched 12830 false, //hidden 12831 null, null, null, 12832 false, // blockUninstall 12833 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12834 if (!isSystemApp(ps)) { 12835 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12836 // Other user still have this package installed, so all 12837 // we need to do is clear this user's data and save that 12838 // it is uninstalled. 12839 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12840 removeUser = user.getIdentifier(); 12841 appId = ps.appId; 12842 scheduleWritePackageRestrictionsLocked(removeUser); 12843 } else { 12844 // We need to set it back to 'installed' so the uninstall 12845 // broadcasts will be sent correctly. 12846 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12847 ps.setInstalled(true, user.getIdentifier()); 12848 } 12849 } else { 12850 // This is a system app, so we assume that the 12851 // other users still have this package installed, so all 12852 // we need to do is clear this user's data and save that 12853 // it is uninstalled. 12854 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12855 removeUser = user.getIdentifier(); 12856 appId = ps.appId; 12857 scheduleWritePackageRestrictionsLocked(removeUser); 12858 } 12859 } 12860 } 12861 12862 if (removeUser >= 0) { 12863 // From above, we determined that we are deleting this only 12864 // for a single user. Continue the work here. 12865 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12866 if (outInfo != null) { 12867 outInfo.removedPackage = packageName; 12868 outInfo.removedAppId = appId; 12869 outInfo.removedUsers = new int[] {removeUser}; 12870 } 12871 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12872 removeKeystoreDataIfNeeded(removeUser, appId); 12873 schedulePackageCleaning(packageName, removeUser, false); 12874 synchronized (mPackages) { 12875 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12876 scheduleWritePackageRestrictionsLocked(removeUser); 12877 } 12878 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12879 removeUser); 12880 } 12881 return true; 12882 } 12883 12884 if (dataOnly) { 12885 // Delete application data first 12886 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12887 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12888 return true; 12889 } 12890 12891 boolean ret = false; 12892 if (isSystemApp(ps)) { 12893 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12894 // When an updated system application is deleted we delete the existing resources as well and 12895 // fall back to existing code in system partition 12896 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12897 flags, outInfo, writeSettings); 12898 } else { 12899 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12900 // Kill application pre-emptively especially for apps on sd. 12901 killApplication(packageName, ps.appId, "uninstall pkg"); 12902 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12903 allUserHandles, perUserInstalled, 12904 outInfo, writeSettings); 12905 } 12906 12907 return ret; 12908 } 12909 12910 private final class ClearStorageConnection implements ServiceConnection { 12911 IMediaContainerService mContainerService; 12912 12913 @Override 12914 public void onServiceConnected(ComponentName name, IBinder service) { 12915 synchronized (this) { 12916 mContainerService = IMediaContainerService.Stub.asInterface(service); 12917 notifyAll(); 12918 } 12919 } 12920 12921 @Override 12922 public void onServiceDisconnected(ComponentName name) { 12923 } 12924 } 12925 12926 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12927 final boolean mounted; 12928 if (Environment.isExternalStorageEmulated()) { 12929 mounted = true; 12930 } else { 12931 final String status = Environment.getExternalStorageState(); 12932 12933 mounted = status.equals(Environment.MEDIA_MOUNTED) 12934 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12935 } 12936 12937 if (!mounted) { 12938 return; 12939 } 12940 12941 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12942 int[] users; 12943 if (userId == UserHandle.USER_ALL) { 12944 users = sUserManager.getUserIds(); 12945 } else { 12946 users = new int[] { userId }; 12947 } 12948 final ClearStorageConnection conn = new ClearStorageConnection(); 12949 if (mContext.bindServiceAsUser( 12950 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12951 try { 12952 for (int curUser : users) { 12953 long timeout = SystemClock.uptimeMillis() + 5000; 12954 synchronized (conn) { 12955 long now = SystemClock.uptimeMillis(); 12956 while (conn.mContainerService == null && now < timeout) { 12957 try { 12958 conn.wait(timeout - now); 12959 } catch (InterruptedException e) { 12960 } 12961 } 12962 } 12963 if (conn.mContainerService == null) { 12964 return; 12965 } 12966 12967 final UserEnvironment userEnv = new UserEnvironment(curUser); 12968 clearDirectory(conn.mContainerService, 12969 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12970 if (allData) { 12971 clearDirectory(conn.mContainerService, 12972 userEnv.buildExternalStorageAppDataDirs(packageName)); 12973 clearDirectory(conn.mContainerService, 12974 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12975 } 12976 } 12977 } finally { 12978 mContext.unbindService(conn); 12979 } 12980 } 12981 } 12982 12983 @Override 12984 public void clearApplicationUserData(final String packageName, 12985 final IPackageDataObserver observer, final int userId) { 12986 mContext.enforceCallingOrSelfPermission( 12987 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12988 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12989 // Queue up an async operation since the package deletion may take a little while. 12990 mHandler.post(new Runnable() { 12991 public void run() { 12992 mHandler.removeCallbacks(this); 12993 final boolean succeeded; 12994 synchronized (mInstallLock) { 12995 succeeded = clearApplicationUserDataLI(packageName, userId); 12996 } 12997 clearExternalStorageDataSync(packageName, userId, true); 12998 if (succeeded) { 12999 // invoke DeviceStorageMonitor's update method to clear any notifications 13000 DeviceStorageMonitorInternal 13001 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13002 if (dsm != null) { 13003 dsm.checkMemory(); 13004 } 13005 } 13006 if(observer != null) { 13007 try { 13008 observer.onRemoveCompleted(packageName, succeeded); 13009 } catch (RemoteException e) { 13010 Log.i(TAG, "Observer no longer exists."); 13011 } 13012 } //end if observer 13013 } //end run 13014 }); 13015 } 13016 13017 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13018 if (packageName == null) { 13019 Slog.w(TAG, "Attempt to delete null packageName."); 13020 return false; 13021 } 13022 13023 // Try finding details about the requested package 13024 PackageParser.Package pkg; 13025 synchronized (mPackages) { 13026 pkg = mPackages.get(packageName); 13027 if (pkg == null) { 13028 final PackageSetting ps = mSettings.mPackages.get(packageName); 13029 if (ps != null) { 13030 pkg = ps.pkg; 13031 } 13032 } 13033 13034 if (pkg == null) { 13035 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13036 return false; 13037 } 13038 13039 PackageSetting ps = (PackageSetting) pkg.mExtras; 13040 PermissionsState permissionsState = ps.getPermissionsState(); 13041 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 13042 } 13043 13044 // Always delete data directories for package, even if we found no other 13045 // record of app. This helps users recover from UID mismatches without 13046 // resorting to a full data wipe. 13047 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13048 if (retCode < 0) { 13049 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13050 return false; 13051 } 13052 13053 final int appId = pkg.applicationInfo.uid; 13054 removeKeystoreDataIfNeeded(userId, appId); 13055 13056 // Create a native library symlink only if we have native libraries 13057 // and if the native libraries are 32 bit libraries. We do not provide 13058 // this symlink for 64 bit libraries. 13059 if (pkg.applicationInfo.primaryCpuAbi != null && 13060 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13061 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13062 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13063 nativeLibPath, userId) < 0) { 13064 Slog.w(TAG, "Failed linking native library dir"); 13065 return false; 13066 } 13067 } 13068 13069 return true; 13070 } 13071 13072 13073 /** 13074 * Revokes granted runtime permissions and clears resettable flags 13075 * which are flags that can be set by a user interaction. 13076 * 13077 * @param permissionsState The permission state to reset. 13078 * @param userId The device user for which to do a reset. 13079 */ 13080 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 13081 PermissionsState permissionsState, int userId) { 13082 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 13083 | PackageManager.FLAG_PERMISSION_USER_FIXED 13084 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13085 13086 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 13087 } 13088 13089 /** 13090 * Revokes granted runtime permissions and clears all flags. 13091 * 13092 * @param permissionsState The permission state to reset. 13093 * @param userId The device user for which to do a reset. 13094 */ 13095 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 13096 PermissionsState permissionsState, int userId) { 13097 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 13098 PackageManager.MASK_PERMISSION_FLAGS); 13099 } 13100 13101 /** 13102 * Revokes granted runtime permissions and clears certain flags. 13103 * 13104 * @param permissionsState The permission state to reset. 13105 * @param userId The device user for which to do a reset. 13106 * @param flags The flags that is going to be reset. 13107 */ 13108 private void revokeRuntimePermissionsAndClearFlagsLocked( 13109 PermissionsState permissionsState, final int userId, int flags) { 13110 boolean needsWrite = false; 13111 13112 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 13113 BasePermission bp = mSettings.mPermissions.get(state.getName()); 13114 if (bp != null) { 13115 permissionsState.revokeRuntimePermission(bp, userId); 13116 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 13117 needsWrite = true; 13118 } 13119 } 13120 13121 // Ensure default permissions are never cleared. 13122 mHandler.post(new Runnable() { 13123 @Override 13124 public void run() { 13125 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13126 } 13127 }); 13128 13129 if (needsWrite) { 13130 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13131 } 13132 } 13133 13134 /** 13135 * Remove entries from the keystore daemon. Will only remove it if the 13136 * {@code appId} is valid. 13137 */ 13138 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13139 if (appId < 0) { 13140 return; 13141 } 13142 13143 final KeyStore keyStore = KeyStore.getInstance(); 13144 if (keyStore != null) { 13145 if (userId == UserHandle.USER_ALL) { 13146 for (final int individual : sUserManager.getUserIds()) { 13147 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13148 } 13149 } else { 13150 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13151 } 13152 } else { 13153 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13154 } 13155 } 13156 13157 @Override 13158 public void deleteApplicationCacheFiles(final String packageName, 13159 final IPackageDataObserver observer) { 13160 mContext.enforceCallingOrSelfPermission( 13161 android.Manifest.permission.DELETE_CACHE_FILES, null); 13162 // Queue up an async operation since the package deletion may take a little while. 13163 final int userId = UserHandle.getCallingUserId(); 13164 mHandler.post(new Runnable() { 13165 public void run() { 13166 mHandler.removeCallbacks(this); 13167 final boolean succeded; 13168 synchronized (mInstallLock) { 13169 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13170 } 13171 clearExternalStorageDataSync(packageName, userId, false); 13172 if (observer != null) { 13173 try { 13174 observer.onRemoveCompleted(packageName, succeded); 13175 } catch (RemoteException e) { 13176 Log.i(TAG, "Observer no longer exists."); 13177 } 13178 } //end if observer 13179 } //end run 13180 }); 13181 } 13182 13183 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13184 if (packageName == null) { 13185 Slog.w(TAG, "Attempt to delete null packageName."); 13186 return false; 13187 } 13188 PackageParser.Package p; 13189 synchronized (mPackages) { 13190 p = mPackages.get(packageName); 13191 } 13192 if (p == null) { 13193 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13194 return false; 13195 } 13196 final ApplicationInfo applicationInfo = p.applicationInfo; 13197 if (applicationInfo == null) { 13198 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13199 return false; 13200 } 13201 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13202 if (retCode < 0) { 13203 Slog.w(TAG, "Couldn't remove cache files for package: " 13204 + packageName + " u" + userId); 13205 return false; 13206 } 13207 return true; 13208 } 13209 13210 @Override 13211 public void getPackageSizeInfo(final String packageName, int userHandle, 13212 final IPackageStatsObserver observer) { 13213 mContext.enforceCallingOrSelfPermission( 13214 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13215 if (packageName == null) { 13216 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13217 } 13218 13219 PackageStats stats = new PackageStats(packageName, userHandle); 13220 13221 /* 13222 * Queue up an async operation since the package measurement may take a 13223 * little while. 13224 */ 13225 Message msg = mHandler.obtainMessage(INIT_COPY); 13226 msg.obj = new MeasureParams(stats, observer); 13227 mHandler.sendMessage(msg); 13228 } 13229 13230 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13231 PackageStats pStats) { 13232 if (packageName == null) { 13233 Slog.w(TAG, "Attempt to get size of null packageName."); 13234 return false; 13235 } 13236 PackageParser.Package p; 13237 boolean dataOnly = false; 13238 String libDirRoot = null; 13239 String asecPath = null; 13240 PackageSetting ps = null; 13241 synchronized (mPackages) { 13242 p = mPackages.get(packageName); 13243 ps = mSettings.mPackages.get(packageName); 13244 if(p == null) { 13245 dataOnly = true; 13246 if((ps == null) || (ps.pkg == null)) { 13247 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13248 return false; 13249 } 13250 p = ps.pkg; 13251 } 13252 if (ps != null) { 13253 libDirRoot = ps.legacyNativeLibraryPathString; 13254 } 13255 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13256 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13257 if (secureContainerId != null) { 13258 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13259 } 13260 } 13261 } 13262 String publicSrcDir = null; 13263 if(!dataOnly) { 13264 final ApplicationInfo applicationInfo = p.applicationInfo; 13265 if (applicationInfo == null) { 13266 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13267 return false; 13268 } 13269 if (p.isForwardLocked()) { 13270 publicSrcDir = applicationInfo.getBaseResourcePath(); 13271 } 13272 } 13273 // TODO: extend to measure size of split APKs 13274 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13275 // not just the first level. 13276 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13277 // just the primary. 13278 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13279 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13280 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13281 if (res < 0) { 13282 return false; 13283 } 13284 13285 // Fix-up for forward-locked applications in ASEC containers. 13286 if (!isExternal(p)) { 13287 pStats.codeSize += pStats.externalCodeSize; 13288 pStats.externalCodeSize = 0L; 13289 } 13290 13291 return true; 13292 } 13293 13294 13295 @Override 13296 public void addPackageToPreferred(String packageName) { 13297 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13298 } 13299 13300 @Override 13301 public void removePackageFromPreferred(String packageName) { 13302 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13303 } 13304 13305 @Override 13306 public List<PackageInfo> getPreferredPackages(int flags) { 13307 return new ArrayList<PackageInfo>(); 13308 } 13309 13310 private int getUidTargetSdkVersionLockedLPr(int uid) { 13311 Object obj = mSettings.getUserIdLPr(uid); 13312 if (obj instanceof SharedUserSetting) { 13313 final SharedUserSetting sus = (SharedUserSetting) obj; 13314 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13315 final Iterator<PackageSetting> it = sus.packages.iterator(); 13316 while (it.hasNext()) { 13317 final PackageSetting ps = it.next(); 13318 if (ps.pkg != null) { 13319 int v = ps.pkg.applicationInfo.targetSdkVersion; 13320 if (v < vers) vers = v; 13321 } 13322 } 13323 return vers; 13324 } else if (obj instanceof PackageSetting) { 13325 final PackageSetting ps = (PackageSetting) obj; 13326 if (ps.pkg != null) { 13327 return ps.pkg.applicationInfo.targetSdkVersion; 13328 } 13329 } 13330 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13331 } 13332 13333 @Override 13334 public void addPreferredActivity(IntentFilter filter, int match, 13335 ComponentName[] set, ComponentName activity, int userId) { 13336 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13337 "Adding preferred"); 13338 } 13339 13340 private void addPreferredActivityInternal(IntentFilter filter, int match, 13341 ComponentName[] set, ComponentName activity, boolean always, int userId, 13342 String opname) { 13343 // writer 13344 int callingUid = Binder.getCallingUid(); 13345 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13346 if (filter.countActions() == 0) { 13347 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13348 return; 13349 } 13350 synchronized (mPackages) { 13351 if (mContext.checkCallingOrSelfPermission( 13352 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13353 != PackageManager.PERMISSION_GRANTED) { 13354 if (getUidTargetSdkVersionLockedLPr(callingUid) 13355 < Build.VERSION_CODES.FROYO) { 13356 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13357 + callingUid); 13358 return; 13359 } 13360 mContext.enforceCallingOrSelfPermission( 13361 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13362 } 13363 13364 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13365 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13366 + userId + ":"); 13367 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13368 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13369 scheduleWritePackageRestrictionsLocked(userId); 13370 } 13371 } 13372 13373 @Override 13374 public void replacePreferredActivity(IntentFilter filter, int match, 13375 ComponentName[] set, ComponentName activity, int userId) { 13376 if (filter.countActions() != 1) { 13377 throw new IllegalArgumentException( 13378 "replacePreferredActivity expects filter to have only 1 action."); 13379 } 13380 if (filter.countDataAuthorities() != 0 13381 || filter.countDataPaths() != 0 13382 || filter.countDataSchemes() > 1 13383 || filter.countDataTypes() != 0) { 13384 throw new IllegalArgumentException( 13385 "replacePreferredActivity expects filter to have no data authorities, " + 13386 "paths, or types; and at most one scheme."); 13387 } 13388 13389 final int callingUid = Binder.getCallingUid(); 13390 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13391 synchronized (mPackages) { 13392 if (mContext.checkCallingOrSelfPermission( 13393 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13394 != PackageManager.PERMISSION_GRANTED) { 13395 if (getUidTargetSdkVersionLockedLPr(callingUid) 13396 < Build.VERSION_CODES.FROYO) { 13397 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13398 + Binder.getCallingUid()); 13399 return; 13400 } 13401 mContext.enforceCallingOrSelfPermission( 13402 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13403 } 13404 13405 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13406 if (pir != null) { 13407 // Get all of the existing entries that exactly match this filter. 13408 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13409 if (existing != null && existing.size() == 1) { 13410 PreferredActivity cur = existing.get(0); 13411 if (DEBUG_PREFERRED) { 13412 Slog.i(TAG, "Checking replace of preferred:"); 13413 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13414 if (!cur.mPref.mAlways) { 13415 Slog.i(TAG, " -- CUR; not mAlways!"); 13416 } else { 13417 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13418 Slog.i(TAG, " -- CUR: mSet=" 13419 + Arrays.toString(cur.mPref.mSetComponents)); 13420 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13421 Slog.i(TAG, " -- NEW: mMatch=" 13422 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13423 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13424 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13425 } 13426 } 13427 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13428 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13429 && cur.mPref.sameSet(set)) { 13430 // Setting the preferred activity to what it happens to be already 13431 if (DEBUG_PREFERRED) { 13432 Slog.i(TAG, "Replacing with same preferred activity " 13433 + cur.mPref.mShortComponent + " for user " 13434 + userId + ":"); 13435 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13436 } 13437 return; 13438 } 13439 } 13440 13441 if (existing != null) { 13442 if (DEBUG_PREFERRED) { 13443 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13444 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13445 } 13446 for (int i = 0; i < existing.size(); i++) { 13447 PreferredActivity pa = existing.get(i); 13448 if (DEBUG_PREFERRED) { 13449 Slog.i(TAG, "Removing existing preferred activity " 13450 + pa.mPref.mComponent + ":"); 13451 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13452 } 13453 pir.removeFilter(pa); 13454 } 13455 } 13456 } 13457 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13458 "Replacing preferred"); 13459 } 13460 } 13461 13462 @Override 13463 public void clearPackagePreferredActivities(String packageName) { 13464 final int uid = Binder.getCallingUid(); 13465 // writer 13466 synchronized (mPackages) { 13467 PackageParser.Package pkg = mPackages.get(packageName); 13468 if (pkg == null || pkg.applicationInfo.uid != uid) { 13469 if (mContext.checkCallingOrSelfPermission( 13470 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13471 != PackageManager.PERMISSION_GRANTED) { 13472 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13473 < Build.VERSION_CODES.FROYO) { 13474 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13475 + Binder.getCallingUid()); 13476 return; 13477 } 13478 mContext.enforceCallingOrSelfPermission( 13479 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13480 } 13481 } 13482 13483 int user = UserHandle.getCallingUserId(); 13484 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13485 scheduleWritePackageRestrictionsLocked(user); 13486 } 13487 } 13488 } 13489 13490 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13491 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13492 ArrayList<PreferredActivity> removed = null; 13493 boolean changed = false; 13494 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13495 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13496 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13497 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13498 continue; 13499 } 13500 Iterator<PreferredActivity> it = pir.filterIterator(); 13501 while (it.hasNext()) { 13502 PreferredActivity pa = it.next(); 13503 // Mark entry for removal only if it matches the package name 13504 // and the entry is of type "always". 13505 if (packageName == null || 13506 (pa.mPref.mComponent.getPackageName().equals(packageName) 13507 && pa.mPref.mAlways)) { 13508 if (removed == null) { 13509 removed = new ArrayList<PreferredActivity>(); 13510 } 13511 removed.add(pa); 13512 } 13513 } 13514 if (removed != null) { 13515 for (int j=0; j<removed.size(); j++) { 13516 PreferredActivity pa = removed.get(j); 13517 pir.removeFilter(pa); 13518 } 13519 changed = true; 13520 } 13521 } 13522 return changed; 13523 } 13524 13525 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13526 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13527 if (userId == UserHandle.USER_ALL) { 13528 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13529 sUserManager.getUserIds())) { 13530 for (int oneUserId : sUserManager.getUserIds()) { 13531 scheduleWritePackageRestrictionsLocked(oneUserId); 13532 } 13533 } 13534 } else { 13535 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13536 scheduleWritePackageRestrictionsLocked(userId); 13537 } 13538 } 13539 } 13540 13541 13542 void clearDefaultBrowserIfNeeded(String packageName) { 13543 for (int oneUserId : sUserManager.getUserIds()) { 13544 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13545 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13546 if (packageName.equals(defaultBrowserPackageName)) { 13547 setDefaultBrowserPackageName(null, oneUserId); 13548 } 13549 } 13550 } 13551 13552 @Override 13553 public void resetPreferredActivities(int userId) { 13554 mContext.enforceCallingOrSelfPermission( 13555 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13556 // writer 13557 synchronized (mPackages) { 13558 clearPackagePreferredActivitiesLPw(null, userId); 13559 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13560 applyFactoryDefaultBrowserLPw(userId); 13561 13562 scheduleWritePackageRestrictionsLocked(userId); 13563 } 13564 } 13565 13566 @Override 13567 public int getPreferredActivities(List<IntentFilter> outFilters, 13568 List<ComponentName> outActivities, String packageName) { 13569 13570 int num = 0; 13571 final int userId = UserHandle.getCallingUserId(); 13572 // reader 13573 synchronized (mPackages) { 13574 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13575 if (pir != null) { 13576 final Iterator<PreferredActivity> it = pir.filterIterator(); 13577 while (it.hasNext()) { 13578 final PreferredActivity pa = it.next(); 13579 if (packageName == null 13580 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13581 && pa.mPref.mAlways)) { 13582 if (outFilters != null) { 13583 outFilters.add(new IntentFilter(pa)); 13584 } 13585 if (outActivities != null) { 13586 outActivities.add(pa.mPref.mComponent); 13587 } 13588 } 13589 } 13590 } 13591 } 13592 13593 return num; 13594 } 13595 13596 @Override 13597 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13598 int userId) { 13599 int callingUid = Binder.getCallingUid(); 13600 if (callingUid != Process.SYSTEM_UID) { 13601 throw new SecurityException( 13602 "addPersistentPreferredActivity can only be run by the system"); 13603 } 13604 if (filter.countActions() == 0) { 13605 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13606 return; 13607 } 13608 synchronized (mPackages) { 13609 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13610 " :"); 13611 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13612 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13613 new PersistentPreferredActivity(filter, activity)); 13614 scheduleWritePackageRestrictionsLocked(userId); 13615 } 13616 } 13617 13618 @Override 13619 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13620 int callingUid = Binder.getCallingUid(); 13621 if (callingUid != Process.SYSTEM_UID) { 13622 throw new SecurityException( 13623 "clearPackagePersistentPreferredActivities can only be run by the system"); 13624 } 13625 ArrayList<PersistentPreferredActivity> removed = null; 13626 boolean changed = false; 13627 synchronized (mPackages) { 13628 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13629 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13630 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13631 .valueAt(i); 13632 if (userId != thisUserId) { 13633 continue; 13634 } 13635 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13636 while (it.hasNext()) { 13637 PersistentPreferredActivity ppa = it.next(); 13638 // Mark entry for removal only if it matches the package name. 13639 if (ppa.mComponent.getPackageName().equals(packageName)) { 13640 if (removed == null) { 13641 removed = new ArrayList<PersistentPreferredActivity>(); 13642 } 13643 removed.add(ppa); 13644 } 13645 } 13646 if (removed != null) { 13647 for (int j=0; j<removed.size(); j++) { 13648 PersistentPreferredActivity ppa = removed.get(j); 13649 ppir.removeFilter(ppa); 13650 } 13651 changed = true; 13652 } 13653 } 13654 13655 if (changed) { 13656 scheduleWritePackageRestrictionsLocked(userId); 13657 } 13658 } 13659 } 13660 13661 /** 13662 * Common machinery for picking apart a restored XML blob and passing 13663 * it to a caller-supplied functor to be applied to the running system. 13664 */ 13665 private void restoreFromXml(XmlPullParser parser, int userId, 13666 String expectedStartTag, BlobXmlRestorer functor) 13667 throws IOException, XmlPullParserException { 13668 int type; 13669 while ((type = parser.next()) != XmlPullParser.START_TAG 13670 && type != XmlPullParser.END_DOCUMENT) { 13671 } 13672 if (type != XmlPullParser.START_TAG) { 13673 // oops didn't find a start tag?! 13674 if (DEBUG_BACKUP) { 13675 Slog.e(TAG, "Didn't find start tag during restore"); 13676 } 13677 return; 13678 } 13679 13680 // this is supposed to be TAG_PREFERRED_BACKUP 13681 if (!expectedStartTag.equals(parser.getName())) { 13682 if (DEBUG_BACKUP) { 13683 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13684 } 13685 return; 13686 } 13687 13688 // skip interfering stuff, then we're aligned with the backing implementation 13689 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13690 functor.apply(parser, userId); 13691 } 13692 13693 private interface BlobXmlRestorer { 13694 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13695 } 13696 13697 /** 13698 * Non-Binder method, support for the backup/restore mechanism: write the 13699 * full set of preferred activities in its canonical XML format. Returns the 13700 * XML output as a byte array, or null if there is none. 13701 */ 13702 @Override 13703 public byte[] getPreferredActivityBackup(int userId) { 13704 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13705 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13706 } 13707 13708 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13709 try { 13710 final XmlSerializer serializer = new FastXmlSerializer(); 13711 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13712 serializer.startDocument(null, true); 13713 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13714 13715 synchronized (mPackages) { 13716 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13717 } 13718 13719 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13720 serializer.endDocument(); 13721 serializer.flush(); 13722 } catch (Exception e) { 13723 if (DEBUG_BACKUP) { 13724 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13725 } 13726 return null; 13727 } 13728 13729 return dataStream.toByteArray(); 13730 } 13731 13732 @Override 13733 public void restorePreferredActivities(byte[] backup, int userId) { 13734 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13735 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13736 } 13737 13738 try { 13739 final XmlPullParser parser = Xml.newPullParser(); 13740 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13741 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13742 new BlobXmlRestorer() { 13743 @Override 13744 public void apply(XmlPullParser parser, int userId) 13745 throws XmlPullParserException, IOException { 13746 synchronized (mPackages) { 13747 mSettings.readPreferredActivitiesLPw(parser, userId); 13748 } 13749 } 13750 } ); 13751 } catch (Exception e) { 13752 if (DEBUG_BACKUP) { 13753 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13754 } 13755 } 13756 } 13757 13758 /** 13759 * Non-Binder method, support for the backup/restore mechanism: write the 13760 * default browser (etc) settings in its canonical XML format. Returns the default 13761 * browser XML representation as a byte array, or null if there is none. 13762 */ 13763 @Override 13764 public byte[] getDefaultAppsBackup(int userId) { 13765 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13766 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13767 } 13768 13769 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13770 try { 13771 final XmlSerializer serializer = new FastXmlSerializer(); 13772 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13773 serializer.startDocument(null, true); 13774 serializer.startTag(null, TAG_DEFAULT_APPS); 13775 13776 synchronized (mPackages) { 13777 mSettings.writeDefaultAppsLPr(serializer, userId); 13778 } 13779 13780 serializer.endTag(null, TAG_DEFAULT_APPS); 13781 serializer.endDocument(); 13782 serializer.flush(); 13783 } catch (Exception e) { 13784 if (DEBUG_BACKUP) { 13785 Slog.e(TAG, "Unable to write default apps for backup", e); 13786 } 13787 return null; 13788 } 13789 13790 return dataStream.toByteArray(); 13791 } 13792 13793 @Override 13794 public void restoreDefaultApps(byte[] backup, int userId) { 13795 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13796 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13797 } 13798 13799 try { 13800 final XmlPullParser parser = Xml.newPullParser(); 13801 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13802 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13803 new BlobXmlRestorer() { 13804 @Override 13805 public void apply(XmlPullParser parser, int userId) 13806 throws XmlPullParserException, IOException { 13807 synchronized (mPackages) { 13808 mSettings.readDefaultAppsLPw(parser, userId); 13809 } 13810 } 13811 } ); 13812 } catch (Exception e) { 13813 if (DEBUG_BACKUP) { 13814 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13815 } 13816 } 13817 } 13818 13819 @Override 13820 public byte[] getIntentFilterVerificationBackup(int userId) { 13821 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13822 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13823 } 13824 13825 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13826 try { 13827 final XmlSerializer serializer = new FastXmlSerializer(); 13828 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13829 serializer.startDocument(null, true); 13830 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13831 13832 synchronized (mPackages) { 13833 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13834 } 13835 13836 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13837 serializer.endDocument(); 13838 serializer.flush(); 13839 } catch (Exception e) { 13840 if (DEBUG_BACKUP) { 13841 Slog.e(TAG, "Unable to write default apps for backup", e); 13842 } 13843 return null; 13844 } 13845 13846 return dataStream.toByteArray(); 13847 } 13848 13849 @Override 13850 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13851 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13852 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13853 } 13854 13855 try { 13856 final XmlPullParser parser = Xml.newPullParser(); 13857 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13858 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13859 new BlobXmlRestorer() { 13860 @Override 13861 public void apply(XmlPullParser parser, int userId) 13862 throws XmlPullParserException, IOException { 13863 synchronized (mPackages) { 13864 mSettings.readAllDomainVerificationsLPr(parser, userId); 13865 mSettings.writeLPr(); 13866 } 13867 } 13868 } ); 13869 } catch (Exception e) { 13870 if (DEBUG_BACKUP) { 13871 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13872 } 13873 } 13874 } 13875 13876 @Override 13877 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13878 int sourceUserId, int targetUserId, int flags) { 13879 mContext.enforceCallingOrSelfPermission( 13880 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13881 int callingUid = Binder.getCallingUid(); 13882 enforceOwnerRights(ownerPackage, callingUid); 13883 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13884 if (intentFilter.countActions() == 0) { 13885 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13886 return; 13887 } 13888 synchronized (mPackages) { 13889 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13890 ownerPackage, targetUserId, flags); 13891 CrossProfileIntentResolver resolver = 13892 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13893 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13894 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13895 if (existing != null) { 13896 int size = existing.size(); 13897 for (int i = 0; i < size; i++) { 13898 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13899 return; 13900 } 13901 } 13902 } 13903 resolver.addFilter(newFilter); 13904 scheduleWritePackageRestrictionsLocked(sourceUserId); 13905 } 13906 } 13907 13908 @Override 13909 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13910 mContext.enforceCallingOrSelfPermission( 13911 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13912 int callingUid = Binder.getCallingUid(); 13913 enforceOwnerRights(ownerPackage, callingUid); 13914 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13915 synchronized (mPackages) { 13916 CrossProfileIntentResolver resolver = 13917 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13918 ArraySet<CrossProfileIntentFilter> set = 13919 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13920 for (CrossProfileIntentFilter filter : set) { 13921 if (filter.getOwnerPackage().equals(ownerPackage)) { 13922 resolver.removeFilter(filter); 13923 } 13924 } 13925 scheduleWritePackageRestrictionsLocked(sourceUserId); 13926 } 13927 } 13928 13929 // Enforcing that callingUid is owning pkg on userId 13930 private void enforceOwnerRights(String pkg, int callingUid) { 13931 // The system owns everything. 13932 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13933 return; 13934 } 13935 int callingUserId = UserHandle.getUserId(callingUid); 13936 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13937 if (pi == null) { 13938 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13939 + callingUserId); 13940 } 13941 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13942 throw new SecurityException("Calling uid " + callingUid 13943 + " does not own package " + pkg); 13944 } 13945 } 13946 13947 @Override 13948 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13949 Intent intent = new Intent(Intent.ACTION_MAIN); 13950 intent.addCategory(Intent.CATEGORY_HOME); 13951 13952 final int callingUserId = UserHandle.getCallingUserId(); 13953 List<ResolveInfo> list = queryIntentActivities(intent, null, 13954 PackageManager.GET_META_DATA, callingUserId); 13955 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13956 true, false, false, callingUserId); 13957 13958 allHomeCandidates.clear(); 13959 if (list != null) { 13960 for (ResolveInfo ri : list) { 13961 allHomeCandidates.add(ri); 13962 } 13963 } 13964 return (preferred == null || preferred.activityInfo == null) 13965 ? null 13966 : new ComponentName(preferred.activityInfo.packageName, 13967 preferred.activityInfo.name); 13968 } 13969 13970 @Override 13971 public void setApplicationEnabledSetting(String appPackageName, 13972 int newState, int flags, int userId, String callingPackage) { 13973 if (!sUserManager.exists(userId)) return; 13974 if (callingPackage == null) { 13975 callingPackage = Integer.toString(Binder.getCallingUid()); 13976 } 13977 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13978 } 13979 13980 @Override 13981 public void setComponentEnabledSetting(ComponentName componentName, 13982 int newState, int flags, int userId) { 13983 if (!sUserManager.exists(userId)) return; 13984 setEnabledSetting(componentName.getPackageName(), 13985 componentName.getClassName(), newState, flags, userId, null); 13986 } 13987 13988 private void setEnabledSetting(final String packageName, String className, int newState, 13989 final int flags, int userId, String callingPackage) { 13990 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13991 || newState == COMPONENT_ENABLED_STATE_ENABLED 13992 || newState == COMPONENT_ENABLED_STATE_DISABLED 13993 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13994 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13995 throw new IllegalArgumentException("Invalid new component state: " 13996 + newState); 13997 } 13998 PackageSetting pkgSetting; 13999 final int uid = Binder.getCallingUid(); 14000 final int permission = mContext.checkCallingOrSelfPermission( 14001 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14002 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14003 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14004 boolean sendNow = false; 14005 boolean isApp = (className == null); 14006 String componentName = isApp ? packageName : className; 14007 int packageUid = -1; 14008 ArrayList<String> components; 14009 14010 // writer 14011 synchronized (mPackages) { 14012 pkgSetting = mSettings.mPackages.get(packageName); 14013 if (pkgSetting == null) { 14014 if (className == null) { 14015 throw new IllegalArgumentException( 14016 "Unknown package: " + packageName); 14017 } 14018 throw new IllegalArgumentException( 14019 "Unknown component: " + packageName 14020 + "/" + className); 14021 } 14022 // Allow root and verify that userId is not being specified by a different user 14023 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14024 throw new SecurityException( 14025 "Permission Denial: attempt to change component state from pid=" 14026 + Binder.getCallingPid() 14027 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14028 } 14029 if (className == null) { 14030 // We're dealing with an application/package level state change 14031 if (pkgSetting.getEnabled(userId) == newState) { 14032 // Nothing to do 14033 return; 14034 } 14035 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14036 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14037 // Don't care about who enables an app. 14038 callingPackage = null; 14039 } 14040 pkgSetting.setEnabled(newState, userId, callingPackage); 14041 // pkgSetting.pkg.mSetEnabled = newState; 14042 } else { 14043 // We're dealing with a component level state change 14044 // First, verify that this is a valid class name. 14045 PackageParser.Package pkg = pkgSetting.pkg; 14046 if (pkg == null || !pkg.hasComponentClassName(className)) { 14047 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14048 throw new IllegalArgumentException("Component class " + className 14049 + " does not exist in " + packageName); 14050 } else { 14051 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14052 + className + " does not exist in " + packageName); 14053 } 14054 } 14055 switch (newState) { 14056 case COMPONENT_ENABLED_STATE_ENABLED: 14057 if (!pkgSetting.enableComponentLPw(className, userId)) { 14058 return; 14059 } 14060 break; 14061 case COMPONENT_ENABLED_STATE_DISABLED: 14062 if (!pkgSetting.disableComponentLPw(className, userId)) { 14063 return; 14064 } 14065 break; 14066 case COMPONENT_ENABLED_STATE_DEFAULT: 14067 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14068 return; 14069 } 14070 break; 14071 default: 14072 Slog.e(TAG, "Invalid new component state: " + newState); 14073 return; 14074 } 14075 } 14076 scheduleWritePackageRestrictionsLocked(userId); 14077 components = mPendingBroadcasts.get(userId, packageName); 14078 final boolean newPackage = components == null; 14079 if (newPackage) { 14080 components = new ArrayList<String>(); 14081 } 14082 if (!components.contains(componentName)) { 14083 components.add(componentName); 14084 } 14085 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14086 sendNow = true; 14087 // Purge entry from pending broadcast list if another one exists already 14088 // since we are sending one right away. 14089 mPendingBroadcasts.remove(userId, packageName); 14090 } else { 14091 if (newPackage) { 14092 mPendingBroadcasts.put(userId, packageName, components); 14093 } 14094 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14095 // Schedule a message 14096 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14097 } 14098 } 14099 } 14100 14101 long callingId = Binder.clearCallingIdentity(); 14102 try { 14103 if (sendNow) { 14104 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14105 sendPackageChangedBroadcast(packageName, 14106 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14107 } 14108 } finally { 14109 Binder.restoreCallingIdentity(callingId); 14110 } 14111 } 14112 14113 private void sendPackageChangedBroadcast(String packageName, 14114 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14115 if (DEBUG_INSTALL) 14116 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14117 + componentNames); 14118 Bundle extras = new Bundle(4); 14119 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14120 String nameList[] = new String[componentNames.size()]; 14121 componentNames.toArray(nameList); 14122 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14123 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14124 extras.putInt(Intent.EXTRA_UID, packageUid); 14125 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14126 new int[] {UserHandle.getUserId(packageUid)}); 14127 } 14128 14129 @Override 14130 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14131 if (!sUserManager.exists(userId)) return; 14132 final int uid = Binder.getCallingUid(); 14133 final int permission = mContext.checkCallingOrSelfPermission( 14134 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14135 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14136 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14137 // writer 14138 synchronized (mPackages) { 14139 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14140 allowedByPermission, uid, userId)) { 14141 scheduleWritePackageRestrictionsLocked(userId); 14142 } 14143 } 14144 } 14145 14146 @Override 14147 public String getInstallerPackageName(String packageName) { 14148 // reader 14149 synchronized (mPackages) { 14150 return mSettings.getInstallerPackageNameLPr(packageName); 14151 } 14152 } 14153 14154 @Override 14155 public int getApplicationEnabledSetting(String packageName, int userId) { 14156 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14157 int uid = Binder.getCallingUid(); 14158 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14159 // reader 14160 synchronized (mPackages) { 14161 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14162 } 14163 } 14164 14165 @Override 14166 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14167 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14168 int uid = Binder.getCallingUid(); 14169 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14170 // reader 14171 synchronized (mPackages) { 14172 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14173 } 14174 } 14175 14176 @Override 14177 public void enterSafeMode() { 14178 enforceSystemOrRoot("Only the system can request entering safe mode"); 14179 14180 if (!mSystemReady) { 14181 mSafeMode = true; 14182 } 14183 } 14184 14185 @Override 14186 public void systemReady() { 14187 mSystemReady = true; 14188 14189 // Read the compatibilty setting when the system is ready. 14190 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14191 mContext.getContentResolver(), 14192 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14193 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14194 if (DEBUG_SETTINGS) { 14195 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14196 } 14197 14198 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14199 14200 synchronized (mPackages) { 14201 // Verify that all of the preferred activity components actually 14202 // exist. It is possible for applications to be updated and at 14203 // that point remove a previously declared activity component that 14204 // had been set as a preferred activity. We try to clean this up 14205 // the next time we encounter that preferred activity, but it is 14206 // possible for the user flow to never be able to return to that 14207 // situation so here we do a sanity check to make sure we haven't 14208 // left any junk around. 14209 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14210 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14211 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14212 removed.clear(); 14213 for (PreferredActivity pa : pir.filterSet()) { 14214 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14215 removed.add(pa); 14216 } 14217 } 14218 if (removed.size() > 0) { 14219 for (int r=0; r<removed.size(); r++) { 14220 PreferredActivity pa = removed.get(r); 14221 Slog.w(TAG, "Removing dangling preferred activity: " 14222 + pa.mPref.mComponent); 14223 pir.removeFilter(pa); 14224 } 14225 mSettings.writePackageRestrictionsLPr( 14226 mSettings.mPreferredActivities.keyAt(i)); 14227 } 14228 } 14229 14230 for (int userId : UserManagerService.getInstance().getUserIds()) { 14231 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14232 grantPermissionsUserIds = ArrayUtils.appendInt( 14233 grantPermissionsUserIds, userId); 14234 } 14235 } 14236 } 14237 sUserManager.systemReady(); 14238 14239 // If we upgraded grant all default permissions before kicking off. 14240 for (int userId : grantPermissionsUserIds) { 14241 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14242 } 14243 14244 // Kick off any messages waiting for system ready 14245 if (mPostSystemReadyMessages != null) { 14246 for (Message msg : mPostSystemReadyMessages) { 14247 msg.sendToTarget(); 14248 } 14249 mPostSystemReadyMessages = null; 14250 } 14251 14252 // Watch for external volumes that come and go over time 14253 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14254 storage.registerListener(mStorageListener); 14255 14256 mInstallerService.systemReady(); 14257 mPackageDexOptimizer.systemReady(); 14258 } 14259 14260 @Override 14261 public boolean isSafeMode() { 14262 return mSafeMode; 14263 } 14264 14265 @Override 14266 public boolean hasSystemUidErrors() { 14267 return mHasSystemUidErrors; 14268 } 14269 14270 static String arrayToString(int[] array) { 14271 StringBuffer buf = new StringBuffer(128); 14272 buf.append('['); 14273 if (array != null) { 14274 for (int i=0; i<array.length; i++) { 14275 if (i > 0) buf.append(", "); 14276 buf.append(array[i]); 14277 } 14278 } 14279 buf.append(']'); 14280 return buf.toString(); 14281 } 14282 14283 static class DumpState { 14284 public static final int DUMP_LIBS = 1 << 0; 14285 public static final int DUMP_FEATURES = 1 << 1; 14286 public static final int DUMP_RESOLVERS = 1 << 2; 14287 public static final int DUMP_PERMISSIONS = 1 << 3; 14288 public static final int DUMP_PACKAGES = 1 << 4; 14289 public static final int DUMP_SHARED_USERS = 1 << 5; 14290 public static final int DUMP_MESSAGES = 1 << 6; 14291 public static final int DUMP_PROVIDERS = 1 << 7; 14292 public static final int DUMP_VERIFIERS = 1 << 8; 14293 public static final int DUMP_PREFERRED = 1 << 9; 14294 public static final int DUMP_PREFERRED_XML = 1 << 10; 14295 public static final int DUMP_KEYSETS = 1 << 11; 14296 public static final int DUMP_VERSION = 1 << 12; 14297 public static final int DUMP_INSTALLS = 1 << 13; 14298 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14299 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14300 14301 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14302 14303 private int mTypes; 14304 14305 private int mOptions; 14306 14307 private boolean mTitlePrinted; 14308 14309 private SharedUserSetting mSharedUser; 14310 14311 public boolean isDumping(int type) { 14312 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14313 return true; 14314 } 14315 14316 return (mTypes & type) != 0; 14317 } 14318 14319 public void setDump(int type) { 14320 mTypes |= type; 14321 } 14322 14323 public boolean isOptionEnabled(int option) { 14324 return (mOptions & option) != 0; 14325 } 14326 14327 public void setOptionEnabled(int option) { 14328 mOptions |= option; 14329 } 14330 14331 public boolean onTitlePrinted() { 14332 final boolean printed = mTitlePrinted; 14333 mTitlePrinted = true; 14334 return printed; 14335 } 14336 14337 public boolean getTitlePrinted() { 14338 return mTitlePrinted; 14339 } 14340 14341 public void setTitlePrinted(boolean enabled) { 14342 mTitlePrinted = enabled; 14343 } 14344 14345 public SharedUserSetting getSharedUser() { 14346 return mSharedUser; 14347 } 14348 14349 public void setSharedUser(SharedUserSetting user) { 14350 mSharedUser = user; 14351 } 14352 } 14353 14354 @Override 14355 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14356 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14357 != PackageManager.PERMISSION_GRANTED) { 14358 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14359 + Binder.getCallingPid() 14360 + ", uid=" + Binder.getCallingUid() 14361 + " without permission " 14362 + android.Manifest.permission.DUMP); 14363 return; 14364 } 14365 14366 DumpState dumpState = new DumpState(); 14367 boolean fullPreferred = false; 14368 boolean checkin = false; 14369 14370 String packageName = null; 14371 ArraySet<String> permissionNames = null; 14372 14373 int opti = 0; 14374 while (opti < args.length) { 14375 String opt = args[opti]; 14376 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14377 break; 14378 } 14379 opti++; 14380 14381 if ("-a".equals(opt)) { 14382 // Right now we only know how to print all. 14383 } else if ("-h".equals(opt)) { 14384 pw.println("Package manager dump options:"); 14385 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14386 pw.println(" --checkin: dump for a checkin"); 14387 pw.println(" -f: print details of intent filters"); 14388 pw.println(" -h: print this help"); 14389 pw.println(" cmd may be one of:"); 14390 pw.println(" l[ibraries]: list known shared libraries"); 14391 pw.println(" f[ibraries]: list device features"); 14392 pw.println(" k[eysets]: print known keysets"); 14393 pw.println(" r[esolvers]: dump intent resolvers"); 14394 pw.println(" perm[issions]: dump permissions"); 14395 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14396 pw.println(" pref[erred]: print preferred package settings"); 14397 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14398 pw.println(" prov[iders]: dump content providers"); 14399 pw.println(" p[ackages]: dump installed packages"); 14400 pw.println(" s[hared-users]: dump shared user IDs"); 14401 pw.println(" m[essages]: print collected runtime messages"); 14402 pw.println(" v[erifiers]: print package verifier info"); 14403 pw.println(" version: print database version info"); 14404 pw.println(" write: write current settings now"); 14405 pw.println(" <package.name>: info about given package"); 14406 pw.println(" installs: details about install sessions"); 14407 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14408 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14409 return; 14410 } else if ("--checkin".equals(opt)) { 14411 checkin = true; 14412 } else if ("-f".equals(opt)) { 14413 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14414 } else { 14415 pw.println("Unknown argument: " + opt + "; use -h for help"); 14416 } 14417 } 14418 14419 // Is the caller requesting to dump a particular piece of data? 14420 if (opti < args.length) { 14421 String cmd = args[opti]; 14422 opti++; 14423 // Is this a package name? 14424 if ("android".equals(cmd) || cmd.contains(".")) { 14425 packageName = cmd; 14426 // When dumping a single package, we always dump all of its 14427 // filter information since the amount of data will be reasonable. 14428 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14429 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14430 dumpState.setDump(DumpState.DUMP_LIBS); 14431 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14432 dumpState.setDump(DumpState.DUMP_FEATURES); 14433 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14434 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14435 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14436 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14437 } else if ("permission".equals(cmd)) { 14438 if (opti >= args.length) { 14439 pw.println("Error: permission requires permission name"); 14440 return; 14441 } 14442 permissionNames = new ArraySet<>(); 14443 while (opti < args.length) { 14444 permissionNames.add(args[opti]); 14445 opti++; 14446 } 14447 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14448 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14449 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14450 dumpState.setDump(DumpState.DUMP_PREFERRED); 14451 } else if ("preferred-xml".equals(cmd)) { 14452 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14453 if (opti < args.length && "--full".equals(args[opti])) { 14454 fullPreferred = true; 14455 opti++; 14456 } 14457 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14458 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14459 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14460 dumpState.setDump(DumpState.DUMP_PACKAGES); 14461 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14462 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14463 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14464 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14465 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14466 dumpState.setDump(DumpState.DUMP_MESSAGES); 14467 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14468 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14469 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14470 || "intent-filter-verifiers".equals(cmd)) { 14471 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14472 } else if ("version".equals(cmd)) { 14473 dumpState.setDump(DumpState.DUMP_VERSION); 14474 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14475 dumpState.setDump(DumpState.DUMP_KEYSETS); 14476 } else if ("installs".equals(cmd)) { 14477 dumpState.setDump(DumpState.DUMP_INSTALLS); 14478 } else if ("write".equals(cmd)) { 14479 synchronized (mPackages) { 14480 mSettings.writeLPr(); 14481 pw.println("Settings written."); 14482 return; 14483 } 14484 } 14485 } 14486 14487 if (checkin) { 14488 pw.println("vers,1"); 14489 } 14490 14491 // reader 14492 synchronized (mPackages) { 14493 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14494 if (!checkin) { 14495 if (dumpState.onTitlePrinted()) 14496 pw.println(); 14497 pw.println("Database versions:"); 14498 pw.print(" SDK Version:"); 14499 pw.print(" internal="); 14500 pw.print(mSettings.mInternalSdkPlatform); 14501 pw.print(" external="); 14502 pw.println(mSettings.mExternalSdkPlatform); 14503 pw.print(" DB Version:"); 14504 pw.print(" internal="); 14505 pw.print(mSettings.mInternalDatabaseVersion); 14506 pw.print(" external="); 14507 pw.println(mSettings.mExternalDatabaseVersion); 14508 } 14509 } 14510 14511 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14512 if (!checkin) { 14513 if (dumpState.onTitlePrinted()) 14514 pw.println(); 14515 pw.println("Verifiers:"); 14516 pw.print(" Required: "); 14517 pw.print(mRequiredVerifierPackage); 14518 pw.print(" (uid="); 14519 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14520 pw.println(")"); 14521 } else if (mRequiredVerifierPackage != null) { 14522 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14523 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14524 } 14525 } 14526 14527 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14528 packageName == null) { 14529 if (mIntentFilterVerifierComponent != null) { 14530 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14531 if (!checkin) { 14532 if (dumpState.onTitlePrinted()) 14533 pw.println(); 14534 pw.println("Intent Filter Verifier:"); 14535 pw.print(" Using: "); 14536 pw.print(verifierPackageName); 14537 pw.print(" (uid="); 14538 pw.print(getPackageUid(verifierPackageName, 0)); 14539 pw.println(")"); 14540 } else if (verifierPackageName != null) { 14541 pw.print("ifv,"); pw.print(verifierPackageName); 14542 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14543 } 14544 } else { 14545 pw.println(); 14546 pw.println("No Intent Filter Verifier available!"); 14547 } 14548 } 14549 14550 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14551 boolean printedHeader = false; 14552 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14553 while (it.hasNext()) { 14554 String name = it.next(); 14555 SharedLibraryEntry ent = mSharedLibraries.get(name); 14556 if (!checkin) { 14557 if (!printedHeader) { 14558 if (dumpState.onTitlePrinted()) 14559 pw.println(); 14560 pw.println("Libraries:"); 14561 printedHeader = true; 14562 } 14563 pw.print(" "); 14564 } else { 14565 pw.print("lib,"); 14566 } 14567 pw.print(name); 14568 if (!checkin) { 14569 pw.print(" -> "); 14570 } 14571 if (ent.path != null) { 14572 if (!checkin) { 14573 pw.print("(jar) "); 14574 pw.print(ent.path); 14575 } else { 14576 pw.print(",jar,"); 14577 pw.print(ent.path); 14578 } 14579 } else { 14580 if (!checkin) { 14581 pw.print("(apk) "); 14582 pw.print(ent.apk); 14583 } else { 14584 pw.print(",apk,"); 14585 pw.print(ent.apk); 14586 } 14587 } 14588 pw.println(); 14589 } 14590 } 14591 14592 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14593 if (dumpState.onTitlePrinted()) 14594 pw.println(); 14595 if (!checkin) { 14596 pw.println("Features:"); 14597 } 14598 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14599 while (it.hasNext()) { 14600 String name = it.next(); 14601 if (!checkin) { 14602 pw.print(" "); 14603 } else { 14604 pw.print("feat,"); 14605 } 14606 pw.println(name); 14607 } 14608 } 14609 14610 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14611 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14612 : "Activity Resolver Table:", " ", packageName, 14613 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14614 dumpState.setTitlePrinted(true); 14615 } 14616 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14617 : "Receiver Resolver Table:", " ", packageName, 14618 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14619 dumpState.setTitlePrinted(true); 14620 } 14621 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14622 : "Service Resolver Table:", " ", packageName, 14623 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14624 dumpState.setTitlePrinted(true); 14625 } 14626 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14627 : "Provider Resolver Table:", " ", packageName, 14628 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14629 dumpState.setTitlePrinted(true); 14630 } 14631 } 14632 14633 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14634 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14635 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14636 int user = mSettings.mPreferredActivities.keyAt(i); 14637 if (pir.dump(pw, 14638 dumpState.getTitlePrinted() 14639 ? "\nPreferred Activities User " + user + ":" 14640 : "Preferred Activities User " + user + ":", " ", 14641 packageName, true, false)) { 14642 dumpState.setTitlePrinted(true); 14643 } 14644 } 14645 } 14646 14647 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14648 pw.flush(); 14649 FileOutputStream fout = new FileOutputStream(fd); 14650 BufferedOutputStream str = new BufferedOutputStream(fout); 14651 XmlSerializer serializer = new FastXmlSerializer(); 14652 try { 14653 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14654 serializer.startDocument(null, true); 14655 serializer.setFeature( 14656 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14657 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14658 serializer.endDocument(); 14659 serializer.flush(); 14660 } catch (IllegalArgumentException e) { 14661 pw.println("Failed writing: " + e); 14662 } catch (IllegalStateException e) { 14663 pw.println("Failed writing: " + e); 14664 } catch (IOException e) { 14665 pw.println("Failed writing: " + e); 14666 } 14667 } 14668 14669 if (!checkin 14670 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14671 && packageName == null) { 14672 pw.println(); 14673 int count = mSettings.mPackages.size(); 14674 if (count == 0) { 14675 pw.println("No domain preferred apps!"); 14676 pw.println(); 14677 } else { 14678 final String prefix = " "; 14679 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14680 if (allPackageSettings.size() == 0) { 14681 pw.println("No domain preferred apps!"); 14682 pw.println(); 14683 } else { 14684 pw.println("Domain preferred apps status:"); 14685 pw.println(); 14686 count = 0; 14687 for (PackageSetting ps : allPackageSettings) { 14688 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14689 if (ivi == null || ivi.getPackageName() == null) continue; 14690 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14691 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14692 pw.println(prefix + "Status: " + ivi.getStatusString()); 14693 pw.println(); 14694 count++; 14695 } 14696 if (count == 0) { 14697 pw.println(prefix + "No domain preferred app status!"); 14698 pw.println(); 14699 } 14700 for (int userId : sUserManager.getUserIds()) { 14701 pw.println("Domain preferred apps for User " + userId + ":"); 14702 pw.println(); 14703 count = 0; 14704 for (PackageSetting ps : allPackageSettings) { 14705 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14706 if (ivi == null || ivi.getPackageName() == null) { 14707 continue; 14708 } 14709 final int status = ps.getDomainVerificationStatusForUser(userId); 14710 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14711 continue; 14712 } 14713 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14714 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14715 String statusStr = IntentFilterVerificationInfo. 14716 getStatusStringFromValue(status); 14717 pw.println(prefix + "Status: " + statusStr); 14718 pw.println(); 14719 count++; 14720 } 14721 if (count == 0) { 14722 pw.println(prefix + "No domain preferred apps!"); 14723 pw.println(); 14724 } 14725 } 14726 } 14727 } 14728 } 14729 14730 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14731 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14732 if (packageName == null && permissionNames == null) { 14733 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14734 if (iperm == 0) { 14735 if (dumpState.onTitlePrinted()) 14736 pw.println(); 14737 pw.println("AppOp Permissions:"); 14738 } 14739 pw.print(" AppOp Permission "); 14740 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14741 pw.println(":"); 14742 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14743 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14744 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14745 } 14746 } 14747 } 14748 } 14749 14750 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14751 boolean printedSomething = false; 14752 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14753 if (packageName != null && !packageName.equals(p.info.packageName)) { 14754 continue; 14755 } 14756 if (!printedSomething) { 14757 if (dumpState.onTitlePrinted()) 14758 pw.println(); 14759 pw.println("Registered ContentProviders:"); 14760 printedSomething = true; 14761 } 14762 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14763 pw.print(" "); pw.println(p.toString()); 14764 } 14765 printedSomething = false; 14766 for (Map.Entry<String, PackageParser.Provider> entry : 14767 mProvidersByAuthority.entrySet()) { 14768 PackageParser.Provider p = entry.getValue(); 14769 if (packageName != null && !packageName.equals(p.info.packageName)) { 14770 continue; 14771 } 14772 if (!printedSomething) { 14773 if (dumpState.onTitlePrinted()) 14774 pw.println(); 14775 pw.println("ContentProvider Authorities:"); 14776 printedSomething = true; 14777 } 14778 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14779 pw.print(" "); pw.println(p.toString()); 14780 if (p.info != null && p.info.applicationInfo != null) { 14781 final String appInfo = p.info.applicationInfo.toString(); 14782 pw.print(" applicationInfo="); pw.println(appInfo); 14783 } 14784 } 14785 } 14786 14787 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14788 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14789 } 14790 14791 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14792 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14793 } 14794 14795 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14796 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14797 } 14798 14799 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14800 // XXX should handle packageName != null by dumping only install data that 14801 // the given package is involved with. 14802 if (dumpState.onTitlePrinted()) pw.println(); 14803 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14804 } 14805 14806 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14807 if (dumpState.onTitlePrinted()) pw.println(); 14808 mSettings.dumpReadMessagesLPr(pw, dumpState); 14809 14810 pw.println(); 14811 pw.println("Package warning messages:"); 14812 BufferedReader in = null; 14813 String line = null; 14814 try { 14815 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14816 while ((line = in.readLine()) != null) { 14817 if (line.contains("ignored: updated version")) continue; 14818 pw.println(line); 14819 } 14820 } catch (IOException ignored) { 14821 } finally { 14822 IoUtils.closeQuietly(in); 14823 } 14824 } 14825 14826 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14827 BufferedReader in = null; 14828 String line = null; 14829 try { 14830 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14831 while ((line = in.readLine()) != null) { 14832 if (line.contains("ignored: updated version")) continue; 14833 pw.print("msg,"); 14834 pw.println(line); 14835 } 14836 } catch (IOException ignored) { 14837 } finally { 14838 IoUtils.closeQuietly(in); 14839 } 14840 } 14841 } 14842 } 14843 14844 // ------- apps on sdcard specific code ------- 14845 static final boolean DEBUG_SD_INSTALL = false; 14846 14847 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14848 14849 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14850 14851 private boolean mMediaMounted = false; 14852 14853 static String getEncryptKey() { 14854 try { 14855 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14856 SD_ENCRYPTION_KEYSTORE_NAME); 14857 if (sdEncKey == null) { 14858 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14859 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14860 if (sdEncKey == null) { 14861 Slog.e(TAG, "Failed to create encryption keys"); 14862 return null; 14863 } 14864 } 14865 return sdEncKey; 14866 } catch (NoSuchAlgorithmException nsae) { 14867 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14868 return null; 14869 } catch (IOException ioe) { 14870 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14871 return null; 14872 } 14873 } 14874 14875 /* 14876 * Update media status on PackageManager. 14877 */ 14878 @Override 14879 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14880 int callingUid = Binder.getCallingUid(); 14881 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14882 throw new SecurityException("Media status can only be updated by the system"); 14883 } 14884 // reader; this apparently protects mMediaMounted, but should probably 14885 // be a different lock in that case. 14886 synchronized (mPackages) { 14887 Log.i(TAG, "Updating external media status from " 14888 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14889 + (mediaStatus ? "mounted" : "unmounted")); 14890 if (DEBUG_SD_INSTALL) 14891 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14892 + ", mMediaMounted=" + mMediaMounted); 14893 if (mediaStatus == mMediaMounted) { 14894 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14895 : 0, -1); 14896 mHandler.sendMessage(msg); 14897 return; 14898 } 14899 mMediaMounted = mediaStatus; 14900 } 14901 // Queue up an async operation since the package installation may take a 14902 // little while. 14903 mHandler.post(new Runnable() { 14904 public void run() { 14905 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14906 } 14907 }); 14908 } 14909 14910 /** 14911 * Called by MountService when the initial ASECs to scan are available. 14912 * Should block until all the ASEC containers are finished being scanned. 14913 */ 14914 public void scanAvailableAsecs() { 14915 updateExternalMediaStatusInner(true, false, false); 14916 if (mShouldRestoreconData) { 14917 SELinuxMMAC.setRestoreconDone(); 14918 mShouldRestoreconData = false; 14919 } 14920 } 14921 14922 /* 14923 * Collect information of applications on external media, map them against 14924 * existing containers and update information based on current mount status. 14925 * Please note that we always have to report status if reportStatus has been 14926 * set to true especially when unloading packages. 14927 */ 14928 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14929 boolean externalStorage) { 14930 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14931 int[] uidArr = EmptyArray.INT; 14932 14933 final String[] list = PackageHelper.getSecureContainerList(); 14934 if (ArrayUtils.isEmpty(list)) { 14935 Log.i(TAG, "No secure containers found"); 14936 } else { 14937 // Process list of secure containers and categorize them 14938 // as active or stale based on their package internal state. 14939 14940 // reader 14941 synchronized (mPackages) { 14942 for (String cid : list) { 14943 // Leave stages untouched for now; installer service owns them 14944 if (PackageInstallerService.isStageName(cid)) continue; 14945 14946 if (DEBUG_SD_INSTALL) 14947 Log.i(TAG, "Processing container " + cid); 14948 String pkgName = getAsecPackageName(cid); 14949 if (pkgName == null) { 14950 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14951 continue; 14952 } 14953 if (DEBUG_SD_INSTALL) 14954 Log.i(TAG, "Looking for pkg : " + pkgName); 14955 14956 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14957 if (ps == null) { 14958 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14959 continue; 14960 } 14961 14962 /* 14963 * Skip packages that are not external if we're unmounting 14964 * external storage. 14965 */ 14966 if (externalStorage && !isMounted && !isExternal(ps)) { 14967 continue; 14968 } 14969 14970 final AsecInstallArgs args = new AsecInstallArgs(cid, 14971 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14972 // The package status is changed only if the code path 14973 // matches between settings and the container id. 14974 if (ps.codePathString != null 14975 && ps.codePathString.startsWith(args.getCodePath())) { 14976 if (DEBUG_SD_INSTALL) { 14977 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14978 + " at code path: " + ps.codePathString); 14979 } 14980 14981 // We do have a valid package installed on sdcard 14982 processCids.put(args, ps.codePathString); 14983 final int uid = ps.appId; 14984 if (uid != -1) { 14985 uidArr = ArrayUtils.appendInt(uidArr, uid); 14986 } 14987 } else { 14988 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14989 + ps.codePathString); 14990 } 14991 } 14992 } 14993 14994 Arrays.sort(uidArr); 14995 } 14996 14997 // Process packages with valid entries. 14998 if (isMounted) { 14999 if (DEBUG_SD_INSTALL) 15000 Log.i(TAG, "Loading packages"); 15001 loadMediaPackages(processCids, uidArr); 15002 startCleaningPackages(); 15003 mInstallerService.onSecureContainersAvailable(); 15004 } else { 15005 if (DEBUG_SD_INSTALL) 15006 Log.i(TAG, "Unloading packages"); 15007 unloadMediaPackages(processCids, uidArr, reportStatus); 15008 } 15009 } 15010 15011 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15012 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15013 final int size = infos.size(); 15014 final String[] packageNames = new String[size]; 15015 final int[] packageUids = new int[size]; 15016 for (int i = 0; i < size; i++) { 15017 final ApplicationInfo info = infos.get(i); 15018 packageNames[i] = info.packageName; 15019 packageUids[i] = info.uid; 15020 } 15021 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15022 finishedReceiver); 15023 } 15024 15025 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15026 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15027 sendResourcesChangedBroadcast(mediaStatus, replacing, 15028 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15029 } 15030 15031 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15032 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15033 int size = pkgList.length; 15034 if (size > 0) { 15035 // Send broadcasts here 15036 Bundle extras = new Bundle(); 15037 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15038 if (uidArr != null) { 15039 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15040 } 15041 if (replacing) { 15042 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15043 } 15044 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15045 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15046 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15047 } 15048 } 15049 15050 /* 15051 * Look at potentially valid container ids from processCids If package 15052 * information doesn't match the one on record or package scanning fails, 15053 * the cid is added to list of removeCids. We currently don't delete stale 15054 * containers. 15055 */ 15056 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15057 ArrayList<String> pkgList = new ArrayList<String>(); 15058 Set<AsecInstallArgs> keys = processCids.keySet(); 15059 15060 for (AsecInstallArgs args : keys) { 15061 String codePath = processCids.get(args); 15062 if (DEBUG_SD_INSTALL) 15063 Log.i(TAG, "Loading container : " + args.cid); 15064 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15065 try { 15066 // Make sure there are no container errors first. 15067 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15068 Slog.e(TAG, "Failed to mount cid : " + args.cid 15069 + " when installing from sdcard"); 15070 continue; 15071 } 15072 // Check code path here. 15073 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15074 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15075 + " does not match one in settings " + codePath); 15076 continue; 15077 } 15078 // Parse package 15079 int parseFlags = mDefParseFlags; 15080 if (args.isExternalAsec()) { 15081 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15082 } 15083 if (args.isFwdLocked()) { 15084 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15085 } 15086 15087 synchronized (mInstallLock) { 15088 PackageParser.Package pkg = null; 15089 try { 15090 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15091 } catch (PackageManagerException e) { 15092 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15093 } 15094 // Scan the package 15095 if (pkg != null) { 15096 /* 15097 * TODO why is the lock being held? doPostInstall is 15098 * called in other places without the lock. This needs 15099 * to be straightened out. 15100 */ 15101 // writer 15102 synchronized (mPackages) { 15103 retCode = PackageManager.INSTALL_SUCCEEDED; 15104 pkgList.add(pkg.packageName); 15105 // Post process args 15106 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15107 pkg.applicationInfo.uid); 15108 } 15109 } else { 15110 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15111 } 15112 } 15113 15114 } finally { 15115 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15116 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15117 } 15118 } 15119 } 15120 // writer 15121 synchronized (mPackages) { 15122 // If the platform SDK has changed since the last time we booted, 15123 // we need to re-grant app permission to catch any new ones that 15124 // appear. This is really a hack, and means that apps can in some 15125 // cases get permissions that the user didn't initially explicitly 15126 // allow... it would be nice to have some better way to handle 15127 // this situation. 15128 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15129 if (regrantPermissions) 15130 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15131 + mSdkVersion + "; regranting permissions for external storage"); 15132 mSettings.mExternalSdkPlatform = mSdkVersion; 15133 15134 // Make sure group IDs have been assigned, and any permission 15135 // changes in other apps are accounted for 15136 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15137 | (regrantPermissions 15138 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15139 : 0)); 15140 15141 mSettings.updateExternalDatabaseVersion(); 15142 15143 // can downgrade to reader 15144 // Persist settings 15145 mSettings.writeLPr(); 15146 } 15147 // Send a broadcast to let everyone know we are done processing 15148 if (pkgList.size() > 0) { 15149 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15150 } 15151 } 15152 15153 /* 15154 * Utility method to unload a list of specified containers 15155 */ 15156 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15157 // Just unmount all valid containers. 15158 for (AsecInstallArgs arg : cidArgs) { 15159 synchronized (mInstallLock) { 15160 arg.doPostDeleteLI(false); 15161 } 15162 } 15163 } 15164 15165 /* 15166 * Unload packages mounted on external media. This involves deleting package 15167 * data from internal structures, sending broadcasts about diabled packages, 15168 * gc'ing to free up references, unmounting all secure containers 15169 * corresponding to packages on external media, and posting a 15170 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15171 * that we always have to post this message if status has been requested no 15172 * matter what. 15173 */ 15174 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15175 final boolean reportStatus) { 15176 if (DEBUG_SD_INSTALL) 15177 Log.i(TAG, "unloading media packages"); 15178 ArrayList<String> pkgList = new ArrayList<String>(); 15179 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15180 final Set<AsecInstallArgs> keys = processCids.keySet(); 15181 for (AsecInstallArgs args : keys) { 15182 String pkgName = args.getPackageName(); 15183 if (DEBUG_SD_INSTALL) 15184 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15185 // Delete package internally 15186 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15187 synchronized (mInstallLock) { 15188 boolean res = deletePackageLI(pkgName, null, false, null, null, 15189 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15190 if (res) { 15191 pkgList.add(pkgName); 15192 } else { 15193 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15194 failedList.add(args); 15195 } 15196 } 15197 } 15198 15199 // reader 15200 synchronized (mPackages) { 15201 // We didn't update the settings after removing each package; 15202 // write them now for all packages. 15203 mSettings.writeLPr(); 15204 } 15205 15206 // We have to absolutely send UPDATED_MEDIA_STATUS only 15207 // after confirming that all the receivers processed the ordered 15208 // broadcast when packages get disabled, force a gc to clean things up. 15209 // and unload all the containers. 15210 if (pkgList.size() > 0) { 15211 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15212 new IIntentReceiver.Stub() { 15213 public void performReceive(Intent intent, int resultCode, String data, 15214 Bundle extras, boolean ordered, boolean sticky, 15215 int sendingUser) throws RemoteException { 15216 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15217 reportStatus ? 1 : 0, 1, keys); 15218 mHandler.sendMessage(msg); 15219 } 15220 }); 15221 } else { 15222 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15223 keys); 15224 mHandler.sendMessage(msg); 15225 } 15226 } 15227 15228 private void loadPrivatePackages(VolumeInfo vol) { 15229 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15230 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15231 synchronized (mInstallLock) { 15232 synchronized (mPackages) { 15233 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15234 for (PackageSetting ps : packages) { 15235 final PackageParser.Package pkg; 15236 try { 15237 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15238 loaded.add(pkg.applicationInfo); 15239 } catch (PackageManagerException e) { 15240 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15241 } 15242 } 15243 15244 // TODO: regrant any permissions that changed based since original install 15245 15246 mSettings.writeLPr(); 15247 } 15248 } 15249 15250 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15251 sendResourcesChangedBroadcast(true, false, loaded, null); 15252 } 15253 15254 private void unloadPrivatePackages(VolumeInfo vol) { 15255 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15256 synchronized (mInstallLock) { 15257 synchronized (mPackages) { 15258 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15259 for (PackageSetting ps : packages) { 15260 if (ps.pkg == null) continue; 15261 15262 final ApplicationInfo info = ps.pkg.applicationInfo; 15263 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15264 if (deletePackageLI(ps.name, null, false, null, null, 15265 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15266 unloaded.add(info); 15267 } else { 15268 Slog.w(TAG, "Failed to unload " + ps.codePath); 15269 } 15270 } 15271 15272 mSettings.writeLPr(); 15273 } 15274 } 15275 15276 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15277 sendResourcesChangedBroadcast(false, false, unloaded, null); 15278 } 15279 15280 /** 15281 * Examine all users present on given mounted volume, and destroy data 15282 * belonging to users that are no longer valid, or whose user ID has been 15283 * recycled. 15284 */ 15285 private void reconcileUsers(String volumeUuid) { 15286 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15287 if (ArrayUtils.isEmpty(files)) { 15288 Slog.d(TAG, "No users found on " + volumeUuid); 15289 return; 15290 } 15291 15292 for (File file : files) { 15293 if (!file.isDirectory()) continue; 15294 15295 final int userId; 15296 final UserInfo info; 15297 try { 15298 userId = Integer.parseInt(file.getName()); 15299 info = sUserManager.getUserInfo(userId); 15300 } catch (NumberFormatException e) { 15301 Slog.w(TAG, "Invalid user directory " + file); 15302 continue; 15303 } 15304 15305 boolean destroyUser = false; 15306 if (info == null) { 15307 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15308 + " because no matching user was found"); 15309 destroyUser = true; 15310 } else { 15311 try { 15312 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15313 } catch (IOException e) { 15314 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15315 + " because we failed to enforce serial number: " + e); 15316 destroyUser = true; 15317 } 15318 } 15319 15320 if (destroyUser) { 15321 synchronized (mInstallLock) { 15322 mInstaller.removeUserDataDirs(volumeUuid, userId); 15323 } 15324 } 15325 } 15326 15327 final UserManager um = mContext.getSystemService(UserManager.class); 15328 for (UserInfo user : um.getUsers()) { 15329 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15330 if (userDir.exists()) continue; 15331 15332 try { 15333 UserManagerService.prepareUserDirectory(userDir); 15334 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15335 } catch (IOException e) { 15336 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15337 } 15338 } 15339 } 15340 15341 /** 15342 * Examine all apps present on given mounted volume, and destroy apps that 15343 * aren't expected, either due to uninstallation or reinstallation on 15344 * another volume. 15345 */ 15346 private void reconcileApps(String volumeUuid) { 15347 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15348 if (ArrayUtils.isEmpty(files)) { 15349 Slog.d(TAG, "No apps found on " + volumeUuid); 15350 return; 15351 } 15352 15353 for (File file : files) { 15354 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15355 && !PackageInstallerService.isStageName(file.getName()); 15356 if (!isPackage) { 15357 // Ignore entries which are not packages 15358 continue; 15359 } 15360 15361 boolean destroyApp = false; 15362 String packageName = null; 15363 try { 15364 final PackageLite pkg = PackageParser.parsePackageLite(file, 15365 PackageParser.PARSE_MUST_BE_APK); 15366 packageName = pkg.packageName; 15367 15368 synchronized (mPackages) { 15369 final PackageSetting ps = mSettings.mPackages.get(packageName); 15370 if (ps == null) { 15371 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15372 + volumeUuid + " because we found no install record"); 15373 destroyApp = true; 15374 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15375 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15376 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15377 destroyApp = true; 15378 } 15379 } 15380 15381 } catch (PackageParserException e) { 15382 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15383 destroyApp = true; 15384 } 15385 15386 if (destroyApp) { 15387 synchronized (mInstallLock) { 15388 if (packageName != null) { 15389 removeDataDirsLI(volumeUuid, packageName); 15390 } 15391 if (file.isDirectory()) { 15392 mInstaller.rmPackageDir(file.getAbsolutePath()); 15393 } else { 15394 file.delete(); 15395 } 15396 } 15397 } 15398 } 15399 } 15400 15401 private void unfreezePackage(String packageName) { 15402 synchronized (mPackages) { 15403 final PackageSetting ps = mSettings.mPackages.get(packageName); 15404 if (ps != null) { 15405 ps.frozen = false; 15406 } 15407 } 15408 } 15409 15410 @Override 15411 public int movePackage(final String packageName, final String volumeUuid) { 15412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15413 15414 final int moveId = mNextMoveId.getAndIncrement(); 15415 try { 15416 movePackageInternal(packageName, volumeUuid, moveId); 15417 } catch (PackageManagerException e) { 15418 Slog.w(TAG, "Failed to move " + packageName, e); 15419 mMoveCallbacks.notifyStatusChanged(moveId, 15420 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15421 } 15422 return moveId; 15423 } 15424 15425 private void movePackageInternal(final String packageName, final String volumeUuid, 15426 final int moveId) throws PackageManagerException { 15427 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15428 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15429 final PackageManager pm = mContext.getPackageManager(); 15430 15431 final boolean currentAsec; 15432 final String currentVolumeUuid; 15433 final File codeFile; 15434 final String installerPackageName; 15435 final String packageAbiOverride; 15436 final int appId; 15437 final String seinfo; 15438 final String label; 15439 15440 // reader 15441 synchronized (mPackages) { 15442 final PackageParser.Package pkg = mPackages.get(packageName); 15443 final PackageSetting ps = mSettings.mPackages.get(packageName); 15444 if (pkg == null || ps == null) { 15445 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15446 } 15447 15448 if (pkg.applicationInfo.isSystemApp()) { 15449 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15450 "Cannot move system application"); 15451 } 15452 15453 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15454 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15455 "Package already moved to " + volumeUuid); 15456 } 15457 15458 final File probe = new File(pkg.codePath); 15459 final File probeOat = new File(probe, "oat"); 15460 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15461 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15462 "Move only supported for modern cluster style installs"); 15463 } 15464 15465 if (ps.frozen) { 15466 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15467 "Failed to move already frozen package"); 15468 } 15469 ps.frozen = true; 15470 15471 currentAsec = pkg.applicationInfo.isForwardLocked() 15472 || pkg.applicationInfo.isExternalAsec(); 15473 currentVolumeUuid = ps.volumeUuid; 15474 codeFile = new File(pkg.codePath); 15475 installerPackageName = ps.installerPackageName; 15476 packageAbiOverride = ps.cpuAbiOverrideString; 15477 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15478 seinfo = pkg.applicationInfo.seinfo; 15479 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15480 } 15481 15482 // Now that we're guarded by frozen state, kill app during move 15483 killApplication(packageName, appId, "move pkg"); 15484 15485 final Bundle extras = new Bundle(); 15486 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15487 extras.putString(Intent.EXTRA_TITLE, label); 15488 mMoveCallbacks.notifyCreated(moveId, extras); 15489 15490 int installFlags; 15491 final boolean moveCompleteApp; 15492 final File measurePath; 15493 15494 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15495 installFlags = INSTALL_INTERNAL; 15496 moveCompleteApp = !currentAsec; 15497 measurePath = Environment.getDataAppDirectory(volumeUuid); 15498 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15499 installFlags = INSTALL_EXTERNAL; 15500 moveCompleteApp = false; 15501 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15502 } else { 15503 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15504 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15505 || !volume.isMountedWritable()) { 15506 unfreezePackage(packageName); 15507 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15508 "Move location not mounted private volume"); 15509 } 15510 15511 Preconditions.checkState(!currentAsec); 15512 15513 installFlags = INSTALL_INTERNAL; 15514 moveCompleteApp = true; 15515 measurePath = Environment.getDataAppDirectory(volumeUuid); 15516 } 15517 15518 final PackageStats stats = new PackageStats(null, -1); 15519 synchronized (mInstaller) { 15520 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15521 unfreezePackage(packageName); 15522 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15523 "Failed to measure package size"); 15524 } 15525 } 15526 15527 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15528 + stats.dataSize); 15529 15530 final long startFreeBytes = measurePath.getFreeSpace(); 15531 final long sizeBytes; 15532 if (moveCompleteApp) { 15533 sizeBytes = stats.codeSize + stats.dataSize; 15534 } else { 15535 sizeBytes = stats.codeSize; 15536 } 15537 15538 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15539 unfreezePackage(packageName); 15540 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15541 "Not enough free space to move"); 15542 } 15543 15544 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15545 15546 final CountDownLatch installedLatch = new CountDownLatch(1); 15547 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15548 @Override 15549 public void onUserActionRequired(Intent intent) throws RemoteException { 15550 throw new IllegalStateException(); 15551 } 15552 15553 @Override 15554 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15555 Bundle extras) throws RemoteException { 15556 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15557 + PackageManager.installStatusToString(returnCode, msg)); 15558 15559 installedLatch.countDown(); 15560 15561 // Regardless of success or failure of the move operation, 15562 // always unfreeze the package 15563 unfreezePackage(packageName); 15564 15565 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15566 switch (status) { 15567 case PackageInstaller.STATUS_SUCCESS: 15568 mMoveCallbacks.notifyStatusChanged(moveId, 15569 PackageManager.MOVE_SUCCEEDED); 15570 break; 15571 case PackageInstaller.STATUS_FAILURE_STORAGE: 15572 mMoveCallbacks.notifyStatusChanged(moveId, 15573 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15574 break; 15575 default: 15576 mMoveCallbacks.notifyStatusChanged(moveId, 15577 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15578 break; 15579 } 15580 } 15581 }; 15582 15583 final MoveInfo move; 15584 if (moveCompleteApp) { 15585 // Kick off a thread to report progress estimates 15586 new Thread() { 15587 @Override 15588 public void run() { 15589 while (true) { 15590 try { 15591 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15592 break; 15593 } 15594 } catch (InterruptedException ignored) { 15595 } 15596 15597 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15598 final int progress = 10 + (int) MathUtils.constrain( 15599 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15600 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15601 } 15602 } 15603 }.start(); 15604 15605 final String dataAppName = codeFile.getName(); 15606 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15607 dataAppName, appId, seinfo); 15608 } else { 15609 move = null; 15610 } 15611 15612 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15613 15614 final Message msg = mHandler.obtainMessage(INIT_COPY); 15615 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15616 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15617 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15618 mHandler.sendMessage(msg); 15619 } 15620 15621 @Override 15622 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15623 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15624 15625 final int realMoveId = mNextMoveId.getAndIncrement(); 15626 final Bundle extras = new Bundle(); 15627 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15628 mMoveCallbacks.notifyCreated(realMoveId, extras); 15629 15630 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15631 @Override 15632 public void onCreated(int moveId, Bundle extras) { 15633 // Ignored 15634 } 15635 15636 @Override 15637 public void onStatusChanged(int moveId, int status, long estMillis) { 15638 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15639 } 15640 }; 15641 15642 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15643 storage.setPrimaryStorageUuid(volumeUuid, callback); 15644 return realMoveId; 15645 } 15646 15647 @Override 15648 public int getMoveStatus(int moveId) { 15649 mContext.enforceCallingOrSelfPermission( 15650 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15651 return mMoveCallbacks.mLastStatus.get(moveId); 15652 } 15653 15654 @Override 15655 public void registerMoveCallback(IPackageMoveObserver callback) { 15656 mContext.enforceCallingOrSelfPermission( 15657 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15658 mMoveCallbacks.register(callback); 15659 } 15660 15661 @Override 15662 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15663 mContext.enforceCallingOrSelfPermission( 15664 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15665 mMoveCallbacks.unregister(callback); 15666 } 15667 15668 @Override 15669 public boolean setInstallLocation(int loc) { 15670 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15671 null); 15672 if (getInstallLocation() == loc) { 15673 return true; 15674 } 15675 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15676 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15677 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15678 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15679 return true; 15680 } 15681 return false; 15682 } 15683 15684 @Override 15685 public int getInstallLocation() { 15686 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15687 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15688 PackageHelper.APP_INSTALL_AUTO); 15689 } 15690 15691 /** Called by UserManagerService */ 15692 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15693 mDirtyUsers.remove(userHandle); 15694 mSettings.removeUserLPw(userHandle); 15695 mPendingBroadcasts.remove(userHandle); 15696 if (mInstaller != null) { 15697 // Technically, we shouldn't be doing this with the package lock 15698 // held. However, this is very rare, and there is already so much 15699 // other disk I/O going on, that we'll let it slide for now. 15700 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15701 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15702 final String volumeUuid = vol.getFsUuid(); 15703 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15704 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15705 } 15706 } 15707 mUserNeedsBadging.delete(userHandle); 15708 removeUnusedPackagesLILPw(userManager, userHandle); 15709 } 15710 15711 /** 15712 * We're removing userHandle and would like to remove any downloaded packages 15713 * that are no longer in use by any other user. 15714 * @param userHandle the user being removed 15715 */ 15716 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15717 final boolean DEBUG_CLEAN_APKS = false; 15718 int [] users = userManager.getUserIdsLPr(); 15719 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15720 while (psit.hasNext()) { 15721 PackageSetting ps = psit.next(); 15722 if (ps.pkg == null) { 15723 continue; 15724 } 15725 final String packageName = ps.pkg.packageName; 15726 // Skip over if system app 15727 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15728 continue; 15729 } 15730 if (DEBUG_CLEAN_APKS) { 15731 Slog.i(TAG, "Checking package " + packageName); 15732 } 15733 boolean keep = false; 15734 for (int i = 0; i < users.length; i++) { 15735 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15736 keep = true; 15737 if (DEBUG_CLEAN_APKS) { 15738 Slog.i(TAG, " Keeping package " + packageName + " for user " 15739 + users[i]); 15740 } 15741 break; 15742 } 15743 } 15744 if (!keep) { 15745 if (DEBUG_CLEAN_APKS) { 15746 Slog.i(TAG, " Removing package " + packageName); 15747 } 15748 mHandler.post(new Runnable() { 15749 public void run() { 15750 deletePackageX(packageName, userHandle, 0); 15751 } //end run 15752 }); 15753 } 15754 } 15755 } 15756 15757 /** Called by UserManagerService */ 15758 void createNewUserLILPw(int userHandle) { 15759 if (mInstaller != null) { 15760 mInstaller.createUserConfig(userHandle); 15761 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15762 applyFactoryDefaultBrowserLPw(userHandle); 15763 } 15764 } 15765 15766 void newUserCreatedLILPw(final int userHandle) { 15767 // We cannot grant the default permissions with a lock held as 15768 // we query providers from other components for default handlers 15769 // such as enabled IMEs, etc. 15770 mHandler.post(new Runnable() { 15771 @Override 15772 public void run() { 15773 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15774 } 15775 }); 15776 } 15777 15778 @Override 15779 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15780 mContext.enforceCallingOrSelfPermission( 15781 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15782 "Only package verification agents can read the verifier device identity"); 15783 15784 synchronized (mPackages) { 15785 return mSettings.getVerifierDeviceIdentityLPw(); 15786 } 15787 } 15788 15789 @Override 15790 public void setPermissionEnforced(String permission, boolean enforced) { 15791 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15792 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15793 synchronized (mPackages) { 15794 if (mSettings.mReadExternalStorageEnforced == null 15795 || mSettings.mReadExternalStorageEnforced != enforced) { 15796 mSettings.mReadExternalStorageEnforced = enforced; 15797 mSettings.writeLPr(); 15798 } 15799 } 15800 // kill any non-foreground processes so we restart them and 15801 // grant/revoke the GID. 15802 final IActivityManager am = ActivityManagerNative.getDefault(); 15803 if (am != null) { 15804 final long token = Binder.clearCallingIdentity(); 15805 try { 15806 am.killProcessesBelowForeground("setPermissionEnforcement"); 15807 } catch (RemoteException e) { 15808 } finally { 15809 Binder.restoreCallingIdentity(token); 15810 } 15811 } 15812 } else { 15813 throw new IllegalArgumentException("No selective enforcement for " + permission); 15814 } 15815 } 15816 15817 @Override 15818 @Deprecated 15819 public boolean isPermissionEnforced(String permission) { 15820 return true; 15821 } 15822 15823 @Override 15824 public boolean isStorageLow() { 15825 final long token = Binder.clearCallingIdentity(); 15826 try { 15827 final DeviceStorageMonitorInternal 15828 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15829 if (dsm != null) { 15830 return dsm.isMemoryLow(); 15831 } else { 15832 return false; 15833 } 15834 } finally { 15835 Binder.restoreCallingIdentity(token); 15836 } 15837 } 15838 15839 @Override 15840 public IPackageInstaller getPackageInstaller() { 15841 return mInstallerService; 15842 } 15843 15844 private boolean userNeedsBadging(int userId) { 15845 int index = mUserNeedsBadging.indexOfKey(userId); 15846 if (index < 0) { 15847 final UserInfo userInfo; 15848 final long token = Binder.clearCallingIdentity(); 15849 try { 15850 userInfo = sUserManager.getUserInfo(userId); 15851 } finally { 15852 Binder.restoreCallingIdentity(token); 15853 } 15854 final boolean b; 15855 if (userInfo != null && userInfo.isManagedProfile()) { 15856 b = true; 15857 } else { 15858 b = false; 15859 } 15860 mUserNeedsBadging.put(userId, b); 15861 return b; 15862 } 15863 return mUserNeedsBadging.valueAt(index); 15864 } 15865 15866 @Override 15867 public KeySet getKeySetByAlias(String packageName, String alias) { 15868 if (packageName == null || alias == null) { 15869 return null; 15870 } 15871 synchronized(mPackages) { 15872 final PackageParser.Package pkg = mPackages.get(packageName); 15873 if (pkg == null) { 15874 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15875 throw new IllegalArgumentException("Unknown package: " + packageName); 15876 } 15877 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15878 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15879 } 15880 } 15881 15882 @Override 15883 public KeySet getSigningKeySet(String packageName) { 15884 if (packageName == null) { 15885 return null; 15886 } 15887 synchronized(mPackages) { 15888 final PackageParser.Package pkg = mPackages.get(packageName); 15889 if (pkg == null) { 15890 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15891 throw new IllegalArgumentException("Unknown package: " + packageName); 15892 } 15893 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15894 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15895 throw new SecurityException("May not access signing KeySet of other apps."); 15896 } 15897 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15898 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15899 } 15900 } 15901 15902 @Override 15903 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15904 if (packageName == null || ks == null) { 15905 return false; 15906 } 15907 synchronized(mPackages) { 15908 final PackageParser.Package pkg = mPackages.get(packageName); 15909 if (pkg == null) { 15910 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15911 throw new IllegalArgumentException("Unknown package: " + packageName); 15912 } 15913 IBinder ksh = ks.getToken(); 15914 if (ksh instanceof KeySetHandle) { 15915 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15916 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15917 } 15918 return false; 15919 } 15920 } 15921 15922 @Override 15923 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15924 if (packageName == null || ks == null) { 15925 return false; 15926 } 15927 synchronized(mPackages) { 15928 final PackageParser.Package pkg = mPackages.get(packageName); 15929 if (pkg == null) { 15930 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15931 throw new IllegalArgumentException("Unknown package: " + packageName); 15932 } 15933 IBinder ksh = ks.getToken(); 15934 if (ksh instanceof KeySetHandle) { 15935 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15936 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15937 } 15938 return false; 15939 } 15940 } 15941 15942 public void getUsageStatsIfNoPackageUsageInfo() { 15943 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15944 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15945 if (usm == null) { 15946 throw new IllegalStateException("UsageStatsManager must be initialized"); 15947 } 15948 long now = System.currentTimeMillis(); 15949 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15950 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15951 String packageName = entry.getKey(); 15952 PackageParser.Package pkg = mPackages.get(packageName); 15953 if (pkg == null) { 15954 continue; 15955 } 15956 UsageStats usage = entry.getValue(); 15957 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15958 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15959 } 15960 } 15961 } 15962 15963 /** 15964 * Check and throw if the given before/after packages would be considered a 15965 * downgrade. 15966 */ 15967 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15968 throws PackageManagerException { 15969 if (after.versionCode < before.mVersionCode) { 15970 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15971 "Update version code " + after.versionCode + " is older than current " 15972 + before.mVersionCode); 15973 } else if (after.versionCode == before.mVersionCode) { 15974 if (after.baseRevisionCode < before.baseRevisionCode) { 15975 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15976 "Update base revision code " + after.baseRevisionCode 15977 + " is older than current " + before.baseRevisionCode); 15978 } 15979 15980 if (!ArrayUtils.isEmpty(after.splitNames)) { 15981 for (int i = 0; i < after.splitNames.length; i++) { 15982 final String splitName = after.splitNames[i]; 15983 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15984 if (j != -1) { 15985 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15986 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15987 "Update split " + splitName + " revision code " 15988 + after.splitRevisionCodes[i] + " is older than current " 15989 + before.splitRevisionCodes[j]); 15990 } 15991 } 15992 } 15993 } 15994 } 15995 } 15996 15997 private static class MoveCallbacks extends Handler { 15998 private static final int MSG_CREATED = 1; 15999 private static final int MSG_STATUS_CHANGED = 2; 16000 16001 private final RemoteCallbackList<IPackageMoveObserver> 16002 mCallbacks = new RemoteCallbackList<>(); 16003 16004 private final SparseIntArray mLastStatus = new SparseIntArray(); 16005 16006 public MoveCallbacks(Looper looper) { 16007 super(looper); 16008 } 16009 16010 public void register(IPackageMoveObserver callback) { 16011 mCallbacks.register(callback); 16012 } 16013 16014 public void unregister(IPackageMoveObserver callback) { 16015 mCallbacks.unregister(callback); 16016 } 16017 16018 @Override 16019 public void handleMessage(Message msg) { 16020 final SomeArgs args = (SomeArgs) msg.obj; 16021 final int n = mCallbacks.beginBroadcast(); 16022 for (int i = 0; i < n; i++) { 16023 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16024 try { 16025 invokeCallback(callback, msg.what, args); 16026 } catch (RemoteException ignored) { 16027 } 16028 } 16029 mCallbacks.finishBroadcast(); 16030 args.recycle(); 16031 } 16032 16033 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16034 throws RemoteException { 16035 switch (what) { 16036 case MSG_CREATED: { 16037 callback.onCreated(args.argi1, (Bundle) args.arg2); 16038 break; 16039 } 16040 case MSG_STATUS_CHANGED: { 16041 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16042 break; 16043 } 16044 } 16045 } 16046 16047 private void notifyCreated(int moveId, Bundle extras) { 16048 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16049 16050 final SomeArgs args = SomeArgs.obtain(); 16051 args.argi1 = moveId; 16052 args.arg2 = extras; 16053 obtainMessage(MSG_CREATED, args).sendToTarget(); 16054 } 16055 16056 private void notifyStatusChanged(int moveId, int status) { 16057 notifyStatusChanged(moveId, status, -1); 16058 } 16059 16060 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16061 Slog.v(TAG, "Move " + moveId + " status " + status); 16062 16063 final SomeArgs args = SomeArgs.obtain(); 16064 args.argi1 = moveId; 16065 args.argi2 = status; 16066 args.arg3 = estMillis; 16067 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16068 16069 synchronized (mLastStatus) { 16070 mLastStatus.put(moveId, status); 16071 } 16072 } 16073 } 16074 16075 private final class OnPermissionChangeListeners extends Handler { 16076 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16077 16078 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16079 new RemoteCallbackList<>(); 16080 16081 public OnPermissionChangeListeners(Looper looper) { 16082 super(looper); 16083 } 16084 16085 @Override 16086 public void handleMessage(Message msg) { 16087 switch (msg.what) { 16088 case MSG_ON_PERMISSIONS_CHANGED: { 16089 final int uid = msg.arg1; 16090 handleOnPermissionsChanged(uid); 16091 } break; 16092 } 16093 } 16094 16095 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16096 mPermissionListeners.register(listener); 16097 16098 } 16099 16100 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16101 mPermissionListeners.unregister(listener); 16102 } 16103 16104 public void onPermissionsChanged(int uid) { 16105 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16106 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16107 } 16108 } 16109 16110 private void handleOnPermissionsChanged(int uid) { 16111 final int count = mPermissionListeners.beginBroadcast(); 16112 try { 16113 for (int i = 0; i < count; i++) { 16114 IOnPermissionsChangeListener callback = mPermissionListeners 16115 .getBroadcastItem(i); 16116 try { 16117 callback.onPermissionsChanged(uid); 16118 } catch (RemoteException e) { 16119 Log.e(TAG, "Permission listener is dead", e); 16120 } 16121 } 16122 } finally { 16123 mPermissionListeners.finishBroadcast(); 16124 } 16125 } 16126 } 16127 16128 private class PackageManagerInternalImpl extends PackageManagerInternal { 16129 @Override 16130 public void setLocationPackagesProvider(PackagesProvider provider) { 16131 synchronized (mPackages) { 16132 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16133 } 16134 } 16135 16136 @Override 16137 public void setImePackagesProvider(PackagesProvider provider) { 16138 synchronized (mPackages) { 16139 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16140 } 16141 } 16142 16143 @Override 16144 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16145 synchronized (mPackages) { 16146 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16147 } 16148 } 16149 16150 @Override 16151 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16152 synchronized (mPackages) { 16153 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16154 } 16155 } 16156 16157 @Override 16158 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16159 synchronized (mPackages) { 16160 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16161 } 16162 } 16163 16164 @Override 16165 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16166 synchronized (mPackages) { 16167 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16168 } 16169 } 16170 16171 @Override 16172 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16173 synchronized (mPackages) { 16174 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16175 packageName, userId); 16176 } 16177 } 16178 16179 @Override 16180 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16181 synchronized (mPackages) { 16182 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16183 packageName, userId); 16184 } 16185 } 16186 } 16187 16188 @Override 16189 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16190 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16191 synchronized (mPackages) { 16192 final long identity = Binder.clearCallingIdentity(); 16193 try { 16194 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16195 packageNames, userId); 16196 } finally { 16197 Binder.restoreCallingIdentity(identity); 16198 } 16199 } 16200 } 16201 16202 private static void enforceSystemOrPhoneCaller(String tag) { 16203 int callingUid = Binder.getCallingUid(); 16204 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16205 throw new SecurityException( 16206 "Cannot call " + tag + " from UID " + callingUid); 16207 } 16208 } 16209} 16210