PackageManagerService.java revision b42e3e044085e9e25c3936c60fc5869284fe6357
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 22import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 60import static android.content.pm.PackageManager.MATCH_ALL; 61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 65import static android.content.pm.PackageManager.PERMISSION_GRANTED; 66import static android.content.pm.PackageParser.isApkFile; 67import static android.os.Process.PACKAGE_INFO_GID; 68import static android.os.Process.SYSTEM_UID; 69import static android.system.OsConstants.O_CREAT; 70import static android.system.OsConstants.O_RDWR; 71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 75import static com.android.internal.util.ArrayUtils.appendInt; 76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 84 85import android.Manifest; 86import android.app.ActivityManager; 87import android.app.ActivityManagerNative; 88import android.app.AppGlobals; 89import android.app.IActivityManager; 90import android.app.admin.IDevicePolicyManager; 91import android.app.backup.IBackupManager; 92import android.app.usage.UsageStats; 93import android.app.usage.UsageStatsManager; 94import android.content.BroadcastReceiver; 95import android.content.ComponentName; 96import android.content.Context; 97import android.content.IIntentReceiver; 98import android.content.Intent; 99import android.content.IntentFilter; 100import android.content.IntentSender; 101import android.content.IntentSender.SendIntentException; 102import android.content.ServiceConnection; 103import android.content.pm.ActivityInfo; 104import android.content.pm.ApplicationInfo; 105import android.content.pm.FeatureInfo; 106import android.content.pm.IOnPermissionsChangeListener; 107import android.content.pm.IPackageDataObserver; 108import android.content.pm.IPackageDeleteObserver; 109import android.content.pm.IPackageDeleteObserver2; 110import android.content.pm.IPackageInstallObserver2; 111import android.content.pm.IPackageInstaller; 112import android.content.pm.IPackageManager; 113import android.content.pm.IPackageMoveObserver; 114import android.content.pm.IPackageStatsObserver; 115import android.content.pm.InstrumentationInfo; 116import android.content.pm.IntentFilterVerificationInfo; 117import android.content.pm.KeySet; 118import android.content.pm.ManifestDigest; 119import android.content.pm.PackageCleanItem; 120import android.content.pm.PackageInfo; 121import android.content.pm.PackageInfoLite; 122import android.content.pm.PackageInstaller; 123import android.content.pm.PackageManager; 124import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 125import android.content.pm.PackageManagerInternal; 126import android.content.pm.PackageParser; 127import android.content.pm.PackageParser.ActivityIntentInfo; 128import android.content.pm.PackageParser.PackageLite; 129import android.content.pm.PackageParser.PackageParserException; 130import android.content.pm.PackageStats; 131import android.content.pm.PackageUserState; 132import android.content.pm.ParceledListSlice; 133import android.content.pm.PermissionGroupInfo; 134import android.content.pm.PermissionInfo; 135import android.content.pm.ProviderInfo; 136import android.content.pm.ResolveInfo; 137import android.content.pm.ServiceInfo; 138import android.content.pm.Signature; 139import android.content.pm.UserInfo; 140import android.content.pm.VerificationParams; 141import android.content.pm.VerifierDeviceIdentity; 142import android.content.pm.VerifierInfo; 143import android.content.res.Resources; 144import android.hardware.display.DisplayManager; 145import android.net.Uri; 146import android.os.Binder; 147import android.os.Build; 148import android.os.Bundle; 149import android.os.Debug; 150import android.os.Environment; 151import android.os.Environment.UserEnvironment; 152import android.os.FileUtils; 153import android.os.Handler; 154import android.os.IBinder; 155import android.os.Looper; 156import android.os.Message; 157import android.os.Parcel; 158import android.os.ParcelFileDescriptor; 159import android.os.Process; 160import android.os.RemoteCallbackList; 161import android.os.RemoteException; 162import android.os.SELinux; 163import android.os.ServiceManager; 164import android.os.SystemClock; 165import android.os.SystemProperties; 166import android.os.UserHandle; 167import android.os.UserManager; 168import android.os.storage.IMountService; 169import android.os.storage.StorageEventListener; 170import android.os.storage.StorageManager; 171import android.os.storage.VolumeInfo; 172import android.os.storage.VolumeRecord; 173import android.security.KeyStore; 174import android.security.SystemKeyStore; 175import android.system.ErrnoException; 176import android.system.Os; 177import android.system.StructStat; 178import android.text.TextUtils; 179import android.text.format.DateUtils; 180import android.util.ArrayMap; 181import android.util.ArraySet; 182import android.util.AtomicFile; 183import android.util.DisplayMetrics; 184import android.util.EventLog; 185import android.util.ExceptionUtils; 186import android.util.Log; 187import android.util.LogPrinter; 188import android.util.MathUtils; 189import android.util.PrintStreamPrinter; 190import android.util.Slog; 191import android.util.SparseArray; 192import android.util.SparseBooleanArray; 193import android.util.SparseIntArray; 194import android.util.Xml; 195import android.view.Display; 196 197import dalvik.system.DexFile; 198import dalvik.system.VMRuntime; 199 200import libcore.io.IoUtils; 201import libcore.util.EmptyArray; 202 203import com.android.internal.R; 204import com.android.internal.annotations.GuardedBy; 205import com.android.internal.app.IMediaContainerService; 206import com.android.internal.app.ResolverActivity; 207import com.android.internal.content.NativeLibraryHelper; 208import com.android.internal.content.PackageHelper; 209import com.android.internal.os.IParcelFileDescriptorFactory; 210import com.android.internal.os.SomeArgs; 211import com.android.internal.os.Zygote; 212import com.android.internal.util.ArrayUtils; 213import com.android.internal.util.FastPrintWriter; 214import com.android.internal.util.FastXmlSerializer; 215import com.android.internal.util.IndentingPrintWriter; 216import com.android.internal.util.Preconditions; 217import com.android.server.EventLogTags; 218import com.android.server.FgThread; 219import com.android.server.IntentResolver; 220import com.android.server.LocalServices; 221import com.android.server.ServiceThread; 222import com.android.server.SystemConfig; 223import com.android.server.Watchdog; 224import com.android.server.pm.PermissionsState.PermissionState; 225import com.android.server.pm.Settings.DatabaseVersion; 226import com.android.server.storage.DeviceStorageMonitorInternal; 227 228import org.xmlpull.v1.XmlPullParser; 229import org.xmlpull.v1.XmlPullParserException; 230import org.xmlpull.v1.XmlSerializer; 231 232import java.io.BufferedInputStream; 233import java.io.BufferedOutputStream; 234import java.io.BufferedReader; 235import java.io.ByteArrayInputStream; 236import java.io.ByteArrayOutputStream; 237import java.io.File; 238import java.io.FileDescriptor; 239import java.io.FileNotFoundException; 240import java.io.FileOutputStream; 241import java.io.FileReader; 242import java.io.FilenameFilter; 243import java.io.IOException; 244import java.io.InputStream; 245import java.io.PrintWriter; 246import java.nio.charset.StandardCharsets; 247import java.security.NoSuchAlgorithmException; 248import java.security.PublicKey; 249import java.security.cert.CertificateEncodingException; 250import java.security.cert.CertificateException; 251import java.text.SimpleDateFormat; 252import java.util.ArrayList; 253import java.util.Arrays; 254import java.util.Collection; 255import java.util.Collections; 256import java.util.Comparator; 257import java.util.Date; 258import java.util.Iterator; 259import java.util.List; 260import java.util.Map; 261import java.util.Objects; 262import java.util.Set; 263import java.util.concurrent.CountDownLatch; 264import java.util.concurrent.TimeUnit; 265import java.util.concurrent.atomic.AtomicBoolean; 266import java.util.concurrent.atomic.AtomicInteger; 267import java.util.concurrent.atomic.AtomicLong; 268 269/** 270 * Keep track of all those .apks everywhere. 271 * 272 * This is very central to the platform's security; please run the unit 273 * tests whenever making modifications here: 274 * 275runtest -c android.content.pm.PackageManagerTests frameworks-core 276 * 277 * {@hide} 278 */ 279public class PackageManagerService extends IPackageManager.Stub { 280 static final String TAG = "PackageManager"; 281 static final boolean DEBUG_SETTINGS = false; 282 static final boolean DEBUG_PREFERRED = false; 283 static final boolean DEBUG_UPGRADE = false; 284 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 285 private static final boolean DEBUG_BACKUP = true; 286 private static final boolean DEBUG_INSTALL = false; 287 private static final boolean DEBUG_REMOVE = false; 288 private static final boolean DEBUG_BROADCASTS = false; 289 private static final boolean DEBUG_SHOW_INFO = false; 290 private static final boolean DEBUG_PACKAGE_INFO = false; 291 private static final boolean DEBUG_INTENT_MATCHING = false; 292 private static final boolean DEBUG_PACKAGE_SCANNING = false; 293 private static final boolean DEBUG_VERIFY = false; 294 private static final boolean DEBUG_DEXOPT = false; 295 private static final boolean DEBUG_ABI_SELECTION = false; 296 297 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 298 299 private static final int RADIO_UID = Process.PHONE_UID; 300 private static final int LOG_UID = Process.LOG_UID; 301 private static final int NFC_UID = Process.NFC_UID; 302 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 303 private static final int SHELL_UID = Process.SHELL_UID; 304 305 // Cap the size of permission trees that 3rd party apps can define 306 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 307 308 // Suffix used during package installation when copying/moving 309 // package apks to install directory. 310 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 311 312 static final int SCAN_NO_DEX = 1<<1; 313 static final int SCAN_FORCE_DEX = 1<<2; 314 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 315 static final int SCAN_NEW_INSTALL = 1<<4; 316 static final int SCAN_NO_PATHS = 1<<5; 317 static final int SCAN_UPDATE_TIME = 1<<6; 318 static final int SCAN_DEFER_DEX = 1<<7; 319 static final int SCAN_BOOTING = 1<<8; 320 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 321 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 322 static final int SCAN_REQUIRE_KNOWN = 1<<12; 323 static final int SCAN_MOVE = 1<<13; 324 static final int SCAN_INITIAL = 1<<14; 325 326 static final int REMOVE_CHATTY = 1<<16; 327 328 private static final int[] EMPTY_INT_ARRAY = new int[0]; 329 330 /** 331 * Timeout (in milliseconds) after which the watchdog should declare that 332 * our handler thread is wedged. The usual default for such things is one 333 * minute but we sometimes do very lengthy I/O operations on this thread, 334 * such as installing multi-gigabyte applications, so ours needs to be longer. 335 */ 336 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 337 338 /** 339 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 340 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 341 * settings entry if available, otherwise we use the hardcoded default. If it's been 342 * more than this long since the last fstrim, we force one during the boot sequence. 343 * 344 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 345 * one gets run at the next available charging+idle time. This final mandatory 346 * no-fstrim check kicks in only of the other scheduling criteria is never met. 347 */ 348 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 349 350 /** 351 * Whether verification is enabled by default. 352 */ 353 private static final boolean DEFAULT_VERIFY_ENABLE = true; 354 355 /** 356 * The default maximum time to wait for the verification agent to return in 357 * milliseconds. 358 */ 359 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 360 361 /** 362 * The default response for package verification timeout. 363 * 364 * This can be either PackageManager.VERIFICATION_ALLOW or 365 * PackageManager.VERIFICATION_REJECT. 366 */ 367 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 368 369 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 370 371 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 372 DEFAULT_CONTAINER_PACKAGE, 373 "com.android.defcontainer.DefaultContainerService"); 374 375 private static final String KILL_APP_REASON_GIDS_CHANGED = 376 "permission grant or revoke changed gids"; 377 378 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 379 "permissions revoked"; 380 381 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 382 383 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 384 385 /** Permission grant: not grant the permission. */ 386 private static final int GRANT_DENIED = 1; 387 388 /** Permission grant: grant the permission as an install permission. */ 389 private static final int GRANT_INSTALL = 2; 390 391 /** Permission grant: grant the permission as an install permission for a legacy app. */ 392 private static final int GRANT_INSTALL_LEGACY = 3; 393 394 /** Permission grant: grant the permission as a runtime one. */ 395 private static final int GRANT_RUNTIME = 4; 396 397 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 398 private static final int GRANT_UPGRADE = 5; 399 400 /** Canonical intent used to identify what counts as a "web browser" app */ 401 private static final Intent sBrowserIntent; 402 static { 403 sBrowserIntent = new Intent(); 404 sBrowserIntent.setAction(Intent.ACTION_VIEW); 405 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 406 sBrowserIntent.setData(Uri.parse("http:")); 407 } 408 409 final ServiceThread mHandlerThread; 410 411 final PackageHandler mHandler; 412 413 /** 414 * Messages for {@link #mHandler} that need to wait for system ready before 415 * being dispatched. 416 */ 417 private ArrayList<Message> mPostSystemReadyMessages; 418 419 final int mSdkVersion = Build.VERSION.SDK_INT; 420 421 final Context mContext; 422 final boolean mFactoryTest; 423 final boolean mOnlyCore; 424 final boolean mLazyDexOpt; 425 final long mDexOptLRUThresholdInMills; 426 final DisplayMetrics mMetrics; 427 final int mDefParseFlags; 428 final String[] mSeparateProcesses; 429 final boolean mIsUpgrade; 430 431 // This is where all application persistent data goes. 432 final File mAppDataDir; 433 434 // This is where all application persistent data goes for secondary users. 435 final File mUserAppDataDir; 436 437 /** The location for ASEC container files on internal storage. */ 438 final String mAsecInternalPath; 439 440 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 441 // LOCK HELD. Can be called with mInstallLock held. 442 @GuardedBy("mInstallLock") 443 final Installer mInstaller; 444 445 /** Directory where installed third-party apps stored */ 446 final File mAppInstallDir; 447 448 /** 449 * Directory to which applications installed internally have their 450 * 32 bit native libraries copied. 451 */ 452 private File mAppLib32InstallDir; 453 454 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 455 // apps. 456 final File mDrmAppPrivateInstallDir; 457 458 // ---------------------------------------------------------------- 459 460 // Lock for state used when installing and doing other long running 461 // operations. Methods that must be called with this lock held have 462 // the suffix "LI". 463 final Object mInstallLock = new Object(); 464 465 // ---------------------------------------------------------------- 466 467 // Keys are String (package name), values are Package. This also serves 468 // as the lock for the global state. Methods that must be called with 469 // this lock held have the prefix "LP". 470 @GuardedBy("mPackages") 471 final ArrayMap<String, PackageParser.Package> mPackages = 472 new ArrayMap<String, PackageParser.Package>(); 473 474 // Tracks available target package names -> overlay package paths. 475 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 476 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 477 478 final Settings mSettings; 479 boolean mRestoredSettings; 480 481 // System configuration read by SystemConfig. 482 final int[] mGlobalGids; 483 final SparseArray<ArraySet<String>> mSystemPermissions; 484 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 485 486 // If mac_permissions.xml was found for seinfo labeling. 487 boolean mFoundPolicyFile; 488 489 // If a recursive restorecon of /data/data/<pkg> is needed. 490 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 491 492 public static final class SharedLibraryEntry { 493 public final String path; 494 public final String apk; 495 496 SharedLibraryEntry(String _path, String _apk) { 497 path = _path; 498 apk = _apk; 499 } 500 } 501 502 // Currently known shared libraries. 503 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 504 new ArrayMap<String, SharedLibraryEntry>(); 505 506 // All available activities, for your resolving pleasure. 507 final ActivityIntentResolver mActivities = 508 new ActivityIntentResolver(); 509 510 // All available receivers, for your resolving pleasure. 511 final ActivityIntentResolver mReceivers = 512 new ActivityIntentResolver(); 513 514 // All available services, for your resolving pleasure. 515 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 516 517 // All available providers, for your resolving pleasure. 518 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 519 520 // Mapping from provider base names (first directory in content URI codePath) 521 // to the provider information. 522 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 523 new ArrayMap<String, PackageParser.Provider>(); 524 525 // Mapping from instrumentation class names to info about them. 526 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 527 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 528 529 // Mapping from permission names to info about them. 530 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 531 new ArrayMap<String, PackageParser.PermissionGroup>(); 532 533 // Packages whose data we have transfered into another package, thus 534 // should no longer exist. 535 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 536 537 // Broadcast actions that are only available to the system. 538 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 539 540 /** List of packages waiting for verification. */ 541 final SparseArray<PackageVerificationState> mPendingVerification 542 = new SparseArray<PackageVerificationState>(); 543 544 /** Set of packages associated with each app op permission. */ 545 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 546 547 final PackageInstallerService mInstallerService; 548 549 private final PackageDexOptimizer mPackageDexOptimizer; 550 551 private AtomicInteger mNextMoveId = new AtomicInteger(); 552 private final MoveCallbacks mMoveCallbacks; 553 554 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 555 556 // Cache of users who need badging. 557 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 558 559 /** Token for keys in mPendingVerification. */ 560 private int mPendingVerificationToken = 0; 561 562 volatile boolean mSystemReady; 563 volatile boolean mSafeMode; 564 volatile boolean mHasSystemUidErrors; 565 566 ApplicationInfo mAndroidApplication; 567 final ActivityInfo mResolveActivity = new ActivityInfo(); 568 final ResolveInfo mResolveInfo = new ResolveInfo(); 569 ComponentName mResolveComponentName; 570 PackageParser.Package mPlatformPackage; 571 ComponentName mCustomResolverComponentName; 572 573 boolean mResolverReplaced = false; 574 575 private final ComponentName mIntentFilterVerifierComponent; 576 private int mIntentFilterVerificationToken = 0; 577 578 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 579 = new SparseArray<IntentFilterVerificationState>(); 580 581 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 582 new DefaultPermissionGrantPolicy(this); 583 584 private static class IFVerificationParams { 585 PackageParser.Package pkg; 586 boolean replacing; 587 int userId; 588 int verifierUid; 589 590 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 591 int _userId, int _verifierUid) { 592 pkg = _pkg; 593 replacing = _replacing; 594 userId = _userId; 595 replacing = _replacing; 596 verifierUid = _verifierUid; 597 } 598 } 599 600 private interface IntentFilterVerifier<T extends IntentFilter> { 601 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 602 T filter, String packageName); 603 void startVerifications(int userId); 604 void receiveVerificationResponse(int verificationId); 605 } 606 607 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 608 private Context mContext; 609 private ComponentName mIntentFilterVerifierComponent; 610 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 611 612 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 613 mContext = context; 614 mIntentFilterVerifierComponent = verifierComponent; 615 } 616 617 private String getDefaultScheme() { 618 return IntentFilter.SCHEME_HTTPS; 619 } 620 621 @Override 622 public void startVerifications(int userId) { 623 // Launch verifications requests 624 int count = mCurrentIntentFilterVerifications.size(); 625 for (int n=0; n<count; n++) { 626 int verificationId = mCurrentIntentFilterVerifications.get(n); 627 final IntentFilterVerificationState ivs = 628 mIntentFilterVerificationStates.get(verificationId); 629 630 String packageName = ivs.getPackageName(); 631 632 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 633 final int filterCount = filters.size(); 634 ArraySet<String> domainsSet = new ArraySet<>(); 635 for (int m=0; m<filterCount; m++) { 636 PackageParser.ActivityIntentInfo filter = filters.get(m); 637 domainsSet.addAll(filter.getHostsList()); 638 } 639 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 640 synchronized (mPackages) { 641 if (mSettings.createIntentFilterVerificationIfNeededLPw( 642 packageName, domainsList) != null) { 643 scheduleWriteSettingsLocked(); 644 } 645 } 646 sendVerificationRequest(userId, verificationId, ivs); 647 } 648 mCurrentIntentFilterVerifications.clear(); 649 } 650 651 private void sendVerificationRequest(int userId, int verificationId, 652 IntentFilterVerificationState ivs) { 653 654 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 655 verificationIntent.putExtra( 656 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 657 verificationId); 658 verificationIntent.putExtra( 659 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 660 getDefaultScheme()); 661 verificationIntent.putExtra( 662 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 663 ivs.getHostsString()); 664 verificationIntent.putExtra( 665 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 666 ivs.getPackageName()); 667 verificationIntent.setComponent(mIntentFilterVerifierComponent); 668 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 669 670 UserHandle user = new UserHandle(userId); 671 mContext.sendBroadcastAsUser(verificationIntent, user); 672 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 673 "Sending IntentFilter verification broadcast"); 674 } 675 676 public void receiveVerificationResponse(int verificationId) { 677 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 678 679 final boolean verified = ivs.isVerified(); 680 681 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 682 final int count = filters.size(); 683 if (DEBUG_DOMAIN_VERIFICATION) { 684 Slog.i(TAG, "Received verification response " + verificationId 685 + " for " + count + " filters, verified=" + verified); 686 } 687 for (int n=0; n<count; n++) { 688 PackageParser.ActivityIntentInfo filter = filters.get(n); 689 filter.setVerified(verified); 690 691 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 692 + " verified with result:" + verified + " and hosts:" 693 + ivs.getHostsString()); 694 } 695 696 mIntentFilterVerificationStates.remove(verificationId); 697 698 final String packageName = ivs.getPackageName(); 699 IntentFilterVerificationInfo ivi = null; 700 701 synchronized (mPackages) { 702 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 703 } 704 if (ivi == null) { 705 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 706 + verificationId + " packageName:" + packageName); 707 return; 708 } 709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 710 "Updating IntentFilterVerificationInfo for package " + packageName 711 +" verificationId:" + verificationId); 712 713 synchronized (mPackages) { 714 if (verified) { 715 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 716 } else { 717 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 718 } 719 scheduleWriteSettingsLocked(); 720 721 final int userId = ivs.getUserId(); 722 if (userId != UserHandle.USER_ALL) { 723 final int userStatus = 724 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 725 726 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 727 boolean needUpdate = false; 728 729 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 730 // already been set by the User thru the Disambiguation dialog 731 switch (userStatus) { 732 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 733 if (verified) { 734 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 735 } else { 736 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 737 } 738 needUpdate = true; 739 break; 740 741 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 742 if (verified) { 743 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 744 needUpdate = true; 745 } 746 break; 747 748 default: 749 // Nothing to do 750 } 751 752 if (needUpdate) { 753 mSettings.updateIntentFilterVerificationStatusLPw( 754 packageName, updatedStatus, userId); 755 scheduleWritePackageRestrictionsLocked(userId); 756 } 757 } 758 } 759 } 760 761 @Override 762 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 763 ActivityIntentInfo filter, String packageName) { 764 if (!hasValidDomains(filter)) { 765 return false; 766 } 767 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 768 if (ivs == null) { 769 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 770 packageName); 771 } 772 if (DEBUG_DOMAIN_VERIFICATION) { 773 Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter); 774 } 775 ivs.addFilter(filter); 776 return true; 777 } 778 779 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 780 int userId, int verificationId, String packageName) { 781 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 782 verifierUid, userId, packageName); 783 ivs.setPendingState(); 784 synchronized (mPackages) { 785 mIntentFilterVerificationStates.append(verificationId, ivs); 786 mCurrentIntentFilterVerifications.add(verificationId); 787 } 788 return ivs; 789 } 790 } 791 792 private static boolean hasValidDomains(ActivityIntentInfo filter) { 793 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 794 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 795 if (!hasHTTPorHTTPS) { 796 return false; 797 } 798 return true; 799 } 800 801 private IntentFilterVerifier mIntentFilterVerifier; 802 803 // Set of pending broadcasts for aggregating enable/disable of components. 804 static class PendingPackageBroadcasts { 805 // for each user id, a map of <package name -> components within that package> 806 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 807 808 public PendingPackageBroadcasts() { 809 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 810 } 811 812 public ArrayList<String> get(int userId, String packageName) { 813 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 814 return packages.get(packageName); 815 } 816 817 public void put(int userId, String packageName, ArrayList<String> components) { 818 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 819 packages.put(packageName, components); 820 } 821 822 public void remove(int userId, String packageName) { 823 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 824 if (packages != null) { 825 packages.remove(packageName); 826 } 827 } 828 829 public void remove(int userId) { 830 mUidMap.remove(userId); 831 } 832 833 public int userIdCount() { 834 return mUidMap.size(); 835 } 836 837 public int userIdAt(int n) { 838 return mUidMap.keyAt(n); 839 } 840 841 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 842 return mUidMap.get(userId); 843 } 844 845 public int size() { 846 // total number of pending broadcast entries across all userIds 847 int num = 0; 848 for (int i = 0; i< mUidMap.size(); i++) { 849 num += mUidMap.valueAt(i).size(); 850 } 851 return num; 852 } 853 854 public void clear() { 855 mUidMap.clear(); 856 } 857 858 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 859 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 860 if (map == null) { 861 map = new ArrayMap<String, ArrayList<String>>(); 862 mUidMap.put(userId, map); 863 } 864 return map; 865 } 866 } 867 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 868 869 // Service Connection to remote media container service to copy 870 // package uri's from external media onto secure containers 871 // or internal storage. 872 private IMediaContainerService mContainerService = null; 873 874 static final int SEND_PENDING_BROADCAST = 1; 875 static final int MCS_BOUND = 3; 876 static final int END_COPY = 4; 877 static final int INIT_COPY = 5; 878 static final int MCS_UNBIND = 6; 879 static final int START_CLEANING_PACKAGE = 7; 880 static final int FIND_INSTALL_LOC = 8; 881 static final int POST_INSTALL = 9; 882 static final int MCS_RECONNECT = 10; 883 static final int MCS_GIVE_UP = 11; 884 static final int UPDATED_MEDIA_STATUS = 12; 885 static final int WRITE_SETTINGS = 13; 886 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 887 static final int PACKAGE_VERIFIED = 15; 888 static final int CHECK_PENDING_VERIFICATION = 16; 889 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 890 static final int INTENT_FILTER_VERIFIED = 18; 891 892 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 893 894 // Delay time in millisecs 895 static final int BROADCAST_DELAY = 10 * 1000; 896 897 static UserManagerService sUserManager; 898 899 // Stores a list of users whose package restrictions file needs to be updated 900 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 901 902 final private DefaultContainerConnection mDefContainerConn = 903 new DefaultContainerConnection(); 904 class DefaultContainerConnection implements ServiceConnection { 905 public void onServiceConnected(ComponentName name, IBinder service) { 906 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 907 IMediaContainerService imcs = 908 IMediaContainerService.Stub.asInterface(service); 909 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 910 } 911 912 public void onServiceDisconnected(ComponentName name) { 913 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 914 } 915 } 916 917 // Recordkeeping of restore-after-install operations that are currently in flight 918 // between the Package Manager and the Backup Manager 919 class PostInstallData { 920 public InstallArgs args; 921 public PackageInstalledInfo res; 922 923 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 924 args = _a; 925 res = _r; 926 } 927 } 928 929 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 930 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 931 932 // XML tags for backup/restore of various bits of state 933 private static final String TAG_PREFERRED_BACKUP = "pa"; 934 private static final String TAG_DEFAULT_APPS = "da"; 935 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 936 937 final String mRequiredVerifierPackage; 938 final String mRequiredInstallerPackage; 939 940 private final PackageUsage mPackageUsage = new PackageUsage(); 941 942 private class PackageUsage { 943 private static final int WRITE_INTERVAL 944 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 945 946 private final Object mFileLock = new Object(); 947 private final AtomicLong mLastWritten = new AtomicLong(0); 948 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 949 950 private boolean mIsHistoricalPackageUsageAvailable = true; 951 952 boolean isHistoricalPackageUsageAvailable() { 953 return mIsHistoricalPackageUsageAvailable; 954 } 955 956 void write(boolean force) { 957 if (force) { 958 writeInternal(); 959 return; 960 } 961 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 962 && !DEBUG_DEXOPT) { 963 return; 964 } 965 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 966 new Thread("PackageUsage_DiskWriter") { 967 @Override 968 public void run() { 969 try { 970 writeInternal(); 971 } finally { 972 mBackgroundWriteRunning.set(false); 973 } 974 } 975 }.start(); 976 } 977 } 978 979 private void writeInternal() { 980 synchronized (mPackages) { 981 synchronized (mFileLock) { 982 AtomicFile file = getFile(); 983 FileOutputStream f = null; 984 try { 985 f = file.startWrite(); 986 BufferedOutputStream out = new BufferedOutputStream(f); 987 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 988 StringBuilder sb = new StringBuilder(); 989 for (PackageParser.Package pkg : mPackages.values()) { 990 if (pkg.mLastPackageUsageTimeInMills == 0) { 991 continue; 992 } 993 sb.setLength(0); 994 sb.append(pkg.packageName); 995 sb.append(' '); 996 sb.append((long)pkg.mLastPackageUsageTimeInMills); 997 sb.append('\n'); 998 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 999 } 1000 out.flush(); 1001 file.finishWrite(f); 1002 } catch (IOException e) { 1003 if (f != null) { 1004 file.failWrite(f); 1005 } 1006 Log.e(TAG, "Failed to write package usage times", e); 1007 } 1008 } 1009 } 1010 mLastWritten.set(SystemClock.elapsedRealtime()); 1011 } 1012 1013 void readLP() { 1014 synchronized (mFileLock) { 1015 AtomicFile file = getFile(); 1016 BufferedInputStream in = null; 1017 try { 1018 in = new BufferedInputStream(file.openRead()); 1019 StringBuffer sb = new StringBuffer(); 1020 while (true) { 1021 String packageName = readToken(in, sb, ' '); 1022 if (packageName == null) { 1023 break; 1024 } 1025 String timeInMillisString = readToken(in, sb, '\n'); 1026 if (timeInMillisString == null) { 1027 throw new IOException("Failed to find last usage time for package " 1028 + packageName); 1029 } 1030 PackageParser.Package pkg = mPackages.get(packageName); 1031 if (pkg == null) { 1032 continue; 1033 } 1034 long timeInMillis; 1035 try { 1036 timeInMillis = Long.parseLong(timeInMillisString.toString()); 1037 } catch (NumberFormatException e) { 1038 throw new IOException("Failed to parse " + timeInMillisString 1039 + " as a long.", e); 1040 } 1041 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1042 } 1043 } catch (FileNotFoundException expected) { 1044 mIsHistoricalPackageUsageAvailable = false; 1045 } catch (IOException e) { 1046 Log.w(TAG, "Failed to read package usage times", e); 1047 } finally { 1048 IoUtils.closeQuietly(in); 1049 } 1050 } 1051 mLastWritten.set(SystemClock.elapsedRealtime()); 1052 } 1053 1054 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1055 throws IOException { 1056 sb.setLength(0); 1057 while (true) { 1058 int ch = in.read(); 1059 if (ch == -1) { 1060 if (sb.length() == 0) { 1061 return null; 1062 } 1063 throw new IOException("Unexpected EOF"); 1064 } 1065 if (ch == endOfToken) { 1066 return sb.toString(); 1067 } 1068 sb.append((char)ch); 1069 } 1070 } 1071 1072 private AtomicFile getFile() { 1073 File dataDir = Environment.getDataDirectory(); 1074 File systemDir = new File(dataDir, "system"); 1075 File fname = new File(systemDir, "package-usage.list"); 1076 return new AtomicFile(fname); 1077 } 1078 } 1079 1080 class PackageHandler extends Handler { 1081 private boolean mBound = false; 1082 final ArrayList<HandlerParams> mPendingInstalls = 1083 new ArrayList<HandlerParams>(); 1084 1085 private boolean connectToService() { 1086 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1087 " DefaultContainerService"); 1088 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1089 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1090 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1091 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1092 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1093 mBound = true; 1094 return true; 1095 } 1096 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1097 return false; 1098 } 1099 1100 private void disconnectService() { 1101 mContainerService = null; 1102 mBound = false; 1103 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1104 mContext.unbindService(mDefContainerConn); 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 } 1107 1108 PackageHandler(Looper looper) { 1109 super(looper); 1110 } 1111 1112 public void handleMessage(Message msg) { 1113 try { 1114 doHandleMessage(msg); 1115 } finally { 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 } 1118 } 1119 1120 void doHandleMessage(Message msg) { 1121 switch (msg.what) { 1122 case INIT_COPY: { 1123 HandlerParams params = (HandlerParams) msg.obj; 1124 int idx = mPendingInstalls.size(); 1125 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1126 // If a bind was already initiated we dont really 1127 // need to do anything. The pending install 1128 // will be processed later on. 1129 if (!mBound) { 1130 // If this is the only one pending we might 1131 // have to bind to the service again. 1132 if (!connectToService()) { 1133 Slog.e(TAG, "Failed to bind to media container service"); 1134 params.serviceError(); 1135 return; 1136 } else { 1137 // Once we bind to the service, the first 1138 // pending request will be processed. 1139 mPendingInstalls.add(idx, params); 1140 } 1141 } else { 1142 mPendingInstalls.add(idx, params); 1143 // Already bound to the service. Just make 1144 // sure we trigger off processing the first request. 1145 if (idx == 0) { 1146 mHandler.sendEmptyMessage(MCS_BOUND); 1147 } 1148 } 1149 break; 1150 } 1151 case MCS_BOUND: { 1152 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1153 if (msg.obj != null) { 1154 mContainerService = (IMediaContainerService) msg.obj; 1155 } 1156 if (mContainerService == null) { 1157 if (!mBound) { 1158 // Something seriously wrong since we are not bound and we are not 1159 // waiting for connection. Bail out. 1160 Slog.e(TAG, "Cannot bind to media container service"); 1161 for (HandlerParams params : mPendingInstalls) { 1162 // Indicate service bind error 1163 params.serviceError(); 1164 } 1165 mPendingInstalls.clear(); 1166 } else { 1167 Slog.w(TAG, "Waiting to connect to media container service"); 1168 } 1169 } else if (mPendingInstalls.size() > 0) { 1170 HandlerParams params = mPendingInstalls.get(0); 1171 if (params != null) { 1172 if (params.startCopy()) { 1173 // We are done... look for more work or to 1174 // go idle. 1175 if (DEBUG_SD_INSTALL) Log.i(TAG, 1176 "Checking for more work or unbind..."); 1177 // Delete pending install 1178 if (mPendingInstalls.size() > 0) { 1179 mPendingInstalls.remove(0); 1180 } 1181 if (mPendingInstalls.size() == 0) { 1182 if (mBound) { 1183 if (DEBUG_SD_INSTALL) Log.i(TAG, 1184 "Posting delayed MCS_UNBIND"); 1185 removeMessages(MCS_UNBIND); 1186 Message ubmsg = obtainMessage(MCS_UNBIND); 1187 // Unbind after a little delay, to avoid 1188 // continual thrashing. 1189 sendMessageDelayed(ubmsg, 10000); 1190 } 1191 } else { 1192 // There are more pending requests in queue. 1193 // Just post MCS_BOUND message to trigger processing 1194 // of next pending install. 1195 if (DEBUG_SD_INSTALL) Log.i(TAG, 1196 "Posting MCS_BOUND for next work"); 1197 mHandler.sendEmptyMessage(MCS_BOUND); 1198 } 1199 } 1200 } 1201 } else { 1202 // Should never happen ideally. 1203 Slog.w(TAG, "Empty queue"); 1204 } 1205 break; 1206 } 1207 case MCS_RECONNECT: { 1208 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1209 if (mPendingInstalls.size() > 0) { 1210 if (mBound) { 1211 disconnectService(); 1212 } 1213 if (!connectToService()) { 1214 Slog.e(TAG, "Failed to bind to media container service"); 1215 for (HandlerParams params : mPendingInstalls) { 1216 // Indicate service bind error 1217 params.serviceError(); 1218 } 1219 mPendingInstalls.clear(); 1220 } 1221 } 1222 break; 1223 } 1224 case MCS_UNBIND: { 1225 // If there is no actual work left, then time to unbind. 1226 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1227 1228 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1229 if (mBound) { 1230 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1231 1232 disconnectService(); 1233 } 1234 } else if (mPendingInstalls.size() > 0) { 1235 // There are more pending requests in queue. 1236 // Just post MCS_BOUND message to trigger processing 1237 // of next pending install. 1238 mHandler.sendEmptyMessage(MCS_BOUND); 1239 } 1240 1241 break; 1242 } 1243 case MCS_GIVE_UP: { 1244 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1245 mPendingInstalls.remove(0); 1246 break; 1247 } 1248 case SEND_PENDING_BROADCAST: { 1249 String packages[]; 1250 ArrayList<String> components[]; 1251 int size = 0; 1252 int uids[]; 1253 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1254 synchronized (mPackages) { 1255 if (mPendingBroadcasts == null) { 1256 return; 1257 } 1258 size = mPendingBroadcasts.size(); 1259 if (size <= 0) { 1260 // Nothing to be done. Just return 1261 return; 1262 } 1263 packages = new String[size]; 1264 components = new ArrayList[size]; 1265 uids = new int[size]; 1266 int i = 0; // filling out the above arrays 1267 1268 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1269 int packageUserId = mPendingBroadcasts.userIdAt(n); 1270 Iterator<Map.Entry<String, ArrayList<String>>> it 1271 = mPendingBroadcasts.packagesForUserId(packageUserId) 1272 .entrySet().iterator(); 1273 while (it.hasNext() && i < size) { 1274 Map.Entry<String, ArrayList<String>> ent = it.next(); 1275 packages[i] = ent.getKey(); 1276 components[i] = ent.getValue(); 1277 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1278 uids[i] = (ps != null) 1279 ? UserHandle.getUid(packageUserId, ps.appId) 1280 : -1; 1281 i++; 1282 } 1283 } 1284 size = i; 1285 mPendingBroadcasts.clear(); 1286 } 1287 // Send broadcasts 1288 for (int i = 0; i < size; i++) { 1289 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1290 } 1291 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1292 break; 1293 } 1294 case START_CLEANING_PACKAGE: { 1295 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1296 final String packageName = (String)msg.obj; 1297 final int userId = msg.arg1; 1298 final boolean andCode = msg.arg2 != 0; 1299 synchronized (mPackages) { 1300 if (userId == UserHandle.USER_ALL) { 1301 int[] users = sUserManager.getUserIds(); 1302 for (int user : users) { 1303 mSettings.addPackageToCleanLPw( 1304 new PackageCleanItem(user, packageName, andCode)); 1305 } 1306 } else { 1307 mSettings.addPackageToCleanLPw( 1308 new PackageCleanItem(userId, packageName, andCode)); 1309 } 1310 } 1311 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1312 startCleaningPackages(); 1313 } break; 1314 case POST_INSTALL: { 1315 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1316 PostInstallData data = mRunningInstalls.get(msg.arg1); 1317 mRunningInstalls.delete(msg.arg1); 1318 boolean deleteOld = false; 1319 1320 if (data != null) { 1321 InstallArgs args = data.args; 1322 PackageInstalledInfo res = data.res; 1323 1324 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1325 final String packageName = res.pkg.applicationInfo.packageName; 1326 res.removedInfo.sendBroadcast(false, true, false); 1327 Bundle extras = new Bundle(1); 1328 extras.putInt(Intent.EXTRA_UID, res.uid); 1329 1330 // Now that we successfully installed the package, grant runtime 1331 // permissions if requested before broadcasting the install. 1332 if ((args.installFlags 1333 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1334 grantRequestedRuntimePermissions(res.pkg, 1335 args.user.getIdentifier()); 1336 } 1337 1338 // Determine the set of users who are adding this 1339 // package for the first time vs. those who are seeing 1340 // an update. 1341 int[] firstUsers; 1342 int[] updateUsers = new int[0]; 1343 if (res.origUsers == null || res.origUsers.length == 0) { 1344 firstUsers = res.newUsers; 1345 } else { 1346 firstUsers = new int[0]; 1347 for (int i=0; i<res.newUsers.length; i++) { 1348 int user = res.newUsers[i]; 1349 boolean isNew = true; 1350 for (int j=0; j<res.origUsers.length; j++) { 1351 if (res.origUsers[j] == user) { 1352 isNew = false; 1353 break; 1354 } 1355 } 1356 if (isNew) { 1357 int[] newFirst = new int[firstUsers.length+1]; 1358 System.arraycopy(firstUsers, 0, newFirst, 0, 1359 firstUsers.length); 1360 newFirst[firstUsers.length] = user; 1361 firstUsers = newFirst; 1362 } else { 1363 int[] newUpdate = new int[updateUsers.length+1]; 1364 System.arraycopy(updateUsers, 0, newUpdate, 0, 1365 updateUsers.length); 1366 newUpdate[updateUsers.length] = user; 1367 updateUsers = newUpdate; 1368 } 1369 } 1370 } 1371 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1372 packageName, extras, null, null, firstUsers); 1373 final boolean update = res.removedInfo.removedPackage != null; 1374 if (update) { 1375 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1376 } 1377 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1378 packageName, extras, null, null, updateUsers); 1379 if (update) { 1380 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1381 packageName, extras, null, null, updateUsers); 1382 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1383 null, null, packageName, null, updateUsers); 1384 1385 // treat asec-hosted packages like removable media on upgrade 1386 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1387 if (DEBUG_INSTALL) { 1388 Slog.i(TAG, "upgrading pkg " + res.pkg 1389 + " is ASEC-hosted -> AVAILABLE"); 1390 } 1391 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1392 ArrayList<String> pkgList = new ArrayList<String>(1); 1393 pkgList.add(packageName); 1394 sendResourcesChangedBroadcast(true, true, 1395 pkgList,uidArray, null); 1396 } 1397 } 1398 if (res.removedInfo.args != null) { 1399 // Remove the replaced package's older resources safely now 1400 deleteOld = true; 1401 } 1402 1403 // If this app is a browser and it's newly-installed for some 1404 // users, clear any default-browser state in those users 1405 if (firstUsers.length > 0) { 1406 // the app's nature doesn't depend on the user, so we can just 1407 // check its browser nature in any user and generalize. 1408 if (packageIsBrowser(packageName, firstUsers[0])) { 1409 synchronized (mPackages) { 1410 for (int userId : firstUsers) { 1411 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1412 } 1413 } 1414 } 1415 } 1416 // Log current value of "unknown sources" setting 1417 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1418 getUnknownSourcesSettings()); 1419 } 1420 // Force a gc to clear up things 1421 Runtime.getRuntime().gc(); 1422 // We delete after a gc for applications on sdcard. 1423 if (deleteOld) { 1424 synchronized (mInstallLock) { 1425 res.removedInfo.args.doPostDeleteLI(true); 1426 } 1427 } 1428 if (args.observer != null) { 1429 try { 1430 Bundle extras = extrasForInstallResult(res); 1431 args.observer.onPackageInstalled(res.name, res.returnCode, 1432 res.returnMsg, extras); 1433 } catch (RemoteException e) { 1434 Slog.i(TAG, "Observer no longer exists."); 1435 } 1436 } 1437 } else { 1438 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1439 } 1440 } break; 1441 case UPDATED_MEDIA_STATUS: { 1442 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1443 boolean reportStatus = msg.arg1 == 1; 1444 boolean doGc = msg.arg2 == 1; 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1446 if (doGc) { 1447 // Force a gc to clear up stale containers. 1448 Runtime.getRuntime().gc(); 1449 } 1450 if (msg.obj != null) { 1451 @SuppressWarnings("unchecked") 1452 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1454 // Unload containers 1455 unloadAllContainers(args); 1456 } 1457 if (reportStatus) { 1458 try { 1459 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1460 PackageHelper.getMountService().finishMediaUpdate(); 1461 } catch (RemoteException e) { 1462 Log.e(TAG, "MountService not running?"); 1463 } 1464 } 1465 } break; 1466 case WRITE_SETTINGS: { 1467 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1468 synchronized (mPackages) { 1469 removeMessages(WRITE_SETTINGS); 1470 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1471 mSettings.writeLPr(); 1472 mDirtyUsers.clear(); 1473 } 1474 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1475 } break; 1476 case WRITE_PACKAGE_RESTRICTIONS: { 1477 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1478 synchronized (mPackages) { 1479 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1480 for (int userId : mDirtyUsers) { 1481 mSettings.writePackageRestrictionsLPr(userId); 1482 } 1483 mDirtyUsers.clear(); 1484 } 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1486 } break; 1487 case CHECK_PENDING_VERIFICATION: { 1488 final int verificationId = msg.arg1; 1489 final PackageVerificationState state = mPendingVerification.get(verificationId); 1490 1491 if ((state != null) && !state.timeoutExtended()) { 1492 final InstallArgs args = state.getInstallArgs(); 1493 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1494 1495 Slog.i(TAG, "Verification timed out for " + originUri); 1496 mPendingVerification.remove(verificationId); 1497 1498 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1499 1500 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1501 Slog.i(TAG, "Continuing with installation of " + originUri); 1502 state.setVerifierResponse(Binder.getCallingUid(), 1503 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1504 broadcastPackageVerified(verificationId, originUri, 1505 PackageManager.VERIFICATION_ALLOW, 1506 state.getInstallArgs().getUser()); 1507 try { 1508 ret = args.copyApk(mContainerService, true); 1509 } catch (RemoteException e) { 1510 Slog.e(TAG, "Could not contact the ContainerService"); 1511 } 1512 } else { 1513 broadcastPackageVerified(verificationId, originUri, 1514 PackageManager.VERIFICATION_REJECT, 1515 state.getInstallArgs().getUser()); 1516 } 1517 1518 processPendingInstall(args, ret); 1519 mHandler.sendEmptyMessage(MCS_UNBIND); 1520 } 1521 break; 1522 } 1523 case PACKAGE_VERIFIED: { 1524 final int verificationId = msg.arg1; 1525 1526 final PackageVerificationState state = mPendingVerification.get(verificationId); 1527 if (state == null) { 1528 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1529 break; 1530 } 1531 1532 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1533 1534 state.setVerifierResponse(response.callerUid, response.code); 1535 1536 if (state.isVerificationComplete()) { 1537 mPendingVerification.remove(verificationId); 1538 1539 final InstallArgs args = state.getInstallArgs(); 1540 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1541 1542 int ret; 1543 if (state.isInstallAllowed()) { 1544 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1545 broadcastPackageVerified(verificationId, originUri, 1546 response.code, state.getInstallArgs().getUser()); 1547 try { 1548 ret = args.copyApk(mContainerService, true); 1549 } catch (RemoteException e) { 1550 Slog.e(TAG, "Could not contact the ContainerService"); 1551 } 1552 } else { 1553 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1554 } 1555 1556 processPendingInstall(args, ret); 1557 1558 mHandler.sendEmptyMessage(MCS_UNBIND); 1559 } 1560 1561 break; 1562 } 1563 case START_INTENT_FILTER_VERIFICATIONS: { 1564 IFVerificationParams params = (IFVerificationParams) msg.obj; 1565 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1566 params.replacing, params.pkg); 1567 break; 1568 } 1569 case INTENT_FILTER_VERIFIED: { 1570 final int verificationId = msg.arg1; 1571 1572 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1573 verificationId); 1574 if (state == null) { 1575 Slog.w(TAG, "Invalid IntentFilter verification token " 1576 + verificationId + " received"); 1577 break; 1578 } 1579 1580 final int userId = state.getUserId(); 1581 1582 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1583 "Processing IntentFilter verification with token:" 1584 + verificationId + " and userId:" + userId); 1585 1586 final IntentFilterVerificationResponse response = 1587 (IntentFilterVerificationResponse) msg.obj; 1588 1589 state.setVerifierResponse(response.callerUid, response.code); 1590 1591 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1592 "IntentFilter verification with token:" + verificationId 1593 + " and userId:" + userId 1594 + " is settings verifier response with response code:" 1595 + response.code); 1596 1597 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1598 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1599 + response.getFailedDomainsString()); 1600 } 1601 1602 if (state.isVerificationComplete()) { 1603 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1604 } else { 1605 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1606 "IntentFilter verification with token:" + verificationId 1607 + " was not said to be complete"); 1608 } 1609 1610 break; 1611 } 1612 } 1613 } 1614 } 1615 1616 private StorageEventListener mStorageListener = new StorageEventListener() { 1617 @Override 1618 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1619 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1620 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1621 final String volumeUuid = vol.getFsUuid(); 1622 1623 // Clean up any users or apps that were removed or recreated 1624 // while this volume was missing 1625 reconcileUsers(volumeUuid); 1626 reconcileApps(volumeUuid); 1627 1628 // Clean up any install sessions that expired or were 1629 // cancelled while this volume was missing 1630 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1631 1632 loadPrivatePackages(vol); 1633 1634 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1635 unloadPrivatePackages(vol); 1636 } 1637 } 1638 1639 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1640 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1641 updateExternalMediaStatus(true, false); 1642 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1643 updateExternalMediaStatus(false, false); 1644 } 1645 } 1646 } 1647 1648 @Override 1649 public void onVolumeForgotten(String fsUuid) { 1650 // Remove any apps installed on the forgotten volume 1651 synchronized (mPackages) { 1652 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1653 for (PackageSetting ps : packages) { 1654 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1655 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1656 UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS); 1657 } 1658 1659 mSettings.writeLPr(); 1660 } 1661 } 1662 }; 1663 1664 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1665 if (userId >= UserHandle.USER_OWNER) { 1666 grantRequestedRuntimePermissionsForUser(pkg, userId); 1667 } else if (userId == UserHandle.USER_ALL) { 1668 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1669 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1670 } 1671 } 1672 1673 // We could have touched GID membership, so flush out packages.list 1674 synchronized (mPackages) { 1675 mSettings.writePackageListLPr(); 1676 } 1677 } 1678 1679 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1680 SettingBase sb = (SettingBase) pkg.mExtras; 1681 if (sb == null) { 1682 return; 1683 } 1684 1685 PermissionsState permissionsState = sb.getPermissionsState(); 1686 1687 for (String permission : pkg.requestedPermissions) { 1688 BasePermission bp = mSettings.mPermissions.get(permission); 1689 if (bp != null && bp.isRuntime()) { 1690 permissionsState.grantRuntimePermission(bp, userId); 1691 } 1692 } 1693 } 1694 1695 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1696 Bundle extras = null; 1697 switch (res.returnCode) { 1698 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1699 extras = new Bundle(); 1700 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1701 res.origPermission); 1702 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1703 res.origPackage); 1704 break; 1705 } 1706 case PackageManager.INSTALL_SUCCEEDED: { 1707 extras = new Bundle(); 1708 extras.putBoolean(Intent.EXTRA_REPLACING, 1709 res.removedInfo != null && res.removedInfo.removedPackage != null); 1710 break; 1711 } 1712 } 1713 return extras; 1714 } 1715 1716 void scheduleWriteSettingsLocked() { 1717 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1718 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1719 } 1720 } 1721 1722 void scheduleWritePackageRestrictionsLocked(int userId) { 1723 if (!sUserManager.exists(userId)) return; 1724 mDirtyUsers.add(userId); 1725 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1726 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1727 } 1728 } 1729 1730 public static PackageManagerService main(Context context, Installer installer, 1731 boolean factoryTest, boolean onlyCore) { 1732 PackageManagerService m = new PackageManagerService(context, installer, 1733 factoryTest, onlyCore); 1734 ServiceManager.addService("package", m); 1735 return m; 1736 } 1737 1738 static String[] splitString(String str, char sep) { 1739 int count = 1; 1740 int i = 0; 1741 while ((i=str.indexOf(sep, i)) >= 0) { 1742 count++; 1743 i++; 1744 } 1745 1746 String[] res = new String[count]; 1747 i=0; 1748 count = 0; 1749 int lastI=0; 1750 while ((i=str.indexOf(sep, i)) >= 0) { 1751 res[count] = str.substring(lastI, i); 1752 count++; 1753 i++; 1754 lastI = i; 1755 } 1756 res[count] = str.substring(lastI, str.length()); 1757 return res; 1758 } 1759 1760 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1761 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1762 Context.DISPLAY_SERVICE); 1763 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1764 } 1765 1766 public PackageManagerService(Context context, Installer installer, 1767 boolean factoryTest, boolean onlyCore) { 1768 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1769 SystemClock.uptimeMillis()); 1770 1771 if (mSdkVersion <= 0) { 1772 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1773 } 1774 1775 mContext = context; 1776 mFactoryTest = factoryTest; 1777 mOnlyCore = onlyCore; 1778 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1779 mMetrics = new DisplayMetrics(); 1780 mSettings = new Settings(mPackages); 1781 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1782 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1783 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1784 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1785 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1786 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1787 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1788 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1789 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1790 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1791 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1792 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1793 1794 // TODO: add a property to control this? 1795 long dexOptLRUThresholdInMinutes; 1796 if (mLazyDexOpt) { 1797 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1798 } else { 1799 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1800 } 1801 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1802 1803 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1804 if (separateProcesses != null && separateProcesses.length() > 0) { 1805 if ("*".equals(separateProcesses)) { 1806 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1807 mSeparateProcesses = null; 1808 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1809 } else { 1810 mDefParseFlags = 0; 1811 mSeparateProcesses = separateProcesses.split(","); 1812 Slog.w(TAG, "Running with debug.separate_processes: " 1813 + separateProcesses); 1814 } 1815 } else { 1816 mDefParseFlags = 0; 1817 mSeparateProcesses = null; 1818 } 1819 1820 mInstaller = installer; 1821 mPackageDexOptimizer = new PackageDexOptimizer(this); 1822 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1823 1824 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1825 FgThread.get().getLooper()); 1826 1827 getDefaultDisplayMetrics(context, mMetrics); 1828 1829 SystemConfig systemConfig = SystemConfig.getInstance(); 1830 mGlobalGids = systemConfig.getGlobalGids(); 1831 mSystemPermissions = systemConfig.getSystemPermissions(); 1832 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1833 1834 synchronized (mInstallLock) { 1835 // writer 1836 synchronized (mPackages) { 1837 mHandlerThread = new ServiceThread(TAG, 1838 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1839 mHandlerThread.start(); 1840 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1841 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1842 1843 File dataDir = Environment.getDataDirectory(); 1844 mAppDataDir = new File(dataDir, "data"); 1845 mAppInstallDir = new File(dataDir, "app"); 1846 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1847 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1848 mUserAppDataDir = new File(dataDir, "user"); 1849 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1850 1851 sUserManager = new UserManagerService(context, this, 1852 mInstallLock, mPackages); 1853 1854 // Propagate permission configuration in to package manager. 1855 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1856 = systemConfig.getPermissions(); 1857 for (int i=0; i<permConfig.size(); i++) { 1858 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1859 BasePermission bp = mSettings.mPermissions.get(perm.name); 1860 if (bp == null) { 1861 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1862 mSettings.mPermissions.put(perm.name, bp); 1863 } 1864 if (perm.gids != null) { 1865 bp.setGids(perm.gids, perm.perUser); 1866 } 1867 } 1868 1869 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1870 for (int i=0; i<libConfig.size(); i++) { 1871 mSharedLibraries.put(libConfig.keyAt(i), 1872 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1873 } 1874 1875 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1876 1877 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1878 mSdkVersion, mOnlyCore); 1879 1880 String customResolverActivity = Resources.getSystem().getString( 1881 R.string.config_customResolverActivity); 1882 if (TextUtils.isEmpty(customResolverActivity)) { 1883 customResolverActivity = null; 1884 } else { 1885 mCustomResolverComponentName = ComponentName.unflattenFromString( 1886 customResolverActivity); 1887 } 1888 1889 long startTime = SystemClock.uptimeMillis(); 1890 1891 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1892 startTime); 1893 1894 // Set flag to monitor and not change apk file paths when 1895 // scanning install directories. 1896 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1897 1898 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1899 1900 /** 1901 * Add everything in the in the boot class path to the 1902 * list of process files because dexopt will have been run 1903 * if necessary during zygote startup. 1904 */ 1905 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1906 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1907 1908 if (bootClassPath != null) { 1909 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1910 for (String element : bootClassPathElements) { 1911 alreadyDexOpted.add(element); 1912 } 1913 } else { 1914 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1915 } 1916 1917 if (systemServerClassPath != null) { 1918 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1919 for (String element : systemServerClassPathElements) { 1920 alreadyDexOpted.add(element); 1921 } 1922 } else { 1923 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1924 } 1925 1926 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1927 final String[] dexCodeInstructionSets = 1928 getDexCodeInstructionSets( 1929 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1930 1931 /** 1932 * Ensure all external libraries have had dexopt run on them. 1933 */ 1934 if (mSharedLibraries.size() > 0) { 1935 // NOTE: For now, we're compiling these system "shared libraries" 1936 // (and framework jars) into all available architectures. It's possible 1937 // to compile them only when we come across an app that uses them (there's 1938 // already logic for that in scanPackageLI) but that adds some complexity. 1939 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1940 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1941 final String lib = libEntry.path; 1942 if (lib == null) { 1943 continue; 1944 } 1945 1946 try { 1947 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1948 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1949 alreadyDexOpted.add(lib); 1950 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1951 } 1952 } catch (FileNotFoundException e) { 1953 Slog.w(TAG, "Library not found: " + lib); 1954 } catch (IOException e) { 1955 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1956 + e.getMessage()); 1957 } 1958 } 1959 } 1960 } 1961 1962 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1963 1964 // Gross hack for now: we know this file doesn't contain any 1965 // code, so don't dexopt it to avoid the resulting log spew. 1966 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1967 1968 // Gross hack for now: we know this file is only part of 1969 // the boot class path for art, so don't dexopt it to 1970 // avoid the resulting log spew. 1971 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1972 1973 /** 1974 * There are a number of commands implemented in Java, which 1975 * we currently need to do the dexopt on so that they can be 1976 * run from a non-root shell. 1977 */ 1978 String[] frameworkFiles = frameworkDir.list(); 1979 if (frameworkFiles != null) { 1980 // TODO: We could compile these only for the most preferred ABI. We should 1981 // first double check that the dex files for these commands are not referenced 1982 // by other system apps. 1983 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1984 for (int i=0; i<frameworkFiles.length; i++) { 1985 File libPath = new File(frameworkDir, frameworkFiles[i]); 1986 String path = libPath.getPath(); 1987 // Skip the file if we already did it. 1988 if (alreadyDexOpted.contains(path)) { 1989 continue; 1990 } 1991 // Skip the file if it is not a type we want to dexopt. 1992 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1993 continue; 1994 } 1995 try { 1996 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1997 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1998 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1999 } 2000 } catch (FileNotFoundException e) { 2001 Slog.w(TAG, "Jar not found: " + path); 2002 } catch (IOException e) { 2003 Slog.w(TAG, "Exception reading jar: " + path, e); 2004 } 2005 } 2006 } 2007 } 2008 2009 // Collect vendor overlay packages. 2010 // (Do this before scanning any apps.) 2011 // For security and version matching reason, only consider 2012 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2013 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2014 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2015 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2016 2017 // Find base frameworks (resource packages without code). 2018 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2019 | PackageParser.PARSE_IS_SYSTEM_DIR 2020 | PackageParser.PARSE_IS_PRIVILEGED, 2021 scanFlags | SCAN_NO_DEX, 0); 2022 2023 // Collected privileged system packages. 2024 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2025 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2026 | PackageParser.PARSE_IS_SYSTEM_DIR 2027 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2028 2029 // Collect ordinary system packages. 2030 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2031 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2032 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2033 2034 // Collect all vendor packages. 2035 File vendorAppDir = new File("/vendor/app"); 2036 try { 2037 vendorAppDir = vendorAppDir.getCanonicalFile(); 2038 } catch (IOException e) { 2039 // failed to look up canonical path, continue with original one 2040 } 2041 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2042 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2043 2044 // Collect all OEM packages. 2045 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2046 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2047 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2048 2049 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2050 mInstaller.moveFiles(); 2051 2052 // Prune any system packages that no longer exist. 2053 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2054 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 2055 if (!mOnlyCore) { 2056 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2057 while (psit.hasNext()) { 2058 PackageSetting ps = psit.next(); 2059 2060 /* 2061 * If this is not a system app, it can't be a 2062 * disable system app. 2063 */ 2064 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2065 continue; 2066 } 2067 2068 /* 2069 * If the package is scanned, it's not erased. 2070 */ 2071 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2072 if (scannedPkg != null) { 2073 /* 2074 * If the system app is both scanned and in the 2075 * disabled packages list, then it must have been 2076 * added via OTA. Remove it from the currently 2077 * scanned package so the previously user-installed 2078 * application can be scanned. 2079 */ 2080 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2081 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2082 + ps.name + "; removing system app. Last known codePath=" 2083 + ps.codePathString + ", installStatus=" + ps.installStatus 2084 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2085 + scannedPkg.mVersionCode); 2086 removePackageLI(ps, true); 2087 expectingBetter.put(ps.name, ps.codePath); 2088 } 2089 2090 continue; 2091 } 2092 2093 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2094 psit.remove(); 2095 logCriticalInfo(Log.WARN, "System package " + ps.name 2096 + " no longer exists; wiping its data"); 2097 removeDataDirsLI(null, ps.name); 2098 } else { 2099 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2100 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2101 possiblyDeletedUpdatedSystemApps.add(ps.name); 2102 } 2103 } 2104 } 2105 } 2106 2107 //look for any incomplete package installations 2108 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2109 //clean up list 2110 for(int i = 0; i < deletePkgsList.size(); i++) { 2111 //clean up here 2112 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2113 } 2114 //delete tmp files 2115 deleteTempPackageFiles(); 2116 2117 // Remove any shared userIDs that have no associated packages 2118 mSettings.pruneSharedUsersLPw(); 2119 2120 if (!mOnlyCore) { 2121 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2122 SystemClock.uptimeMillis()); 2123 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2124 2125 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2126 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2127 2128 /** 2129 * Remove disable package settings for any updated system 2130 * apps that were removed via an OTA. If they're not a 2131 * previously-updated app, remove them completely. 2132 * Otherwise, just revoke their system-level permissions. 2133 */ 2134 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2135 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2136 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2137 2138 String msg; 2139 if (deletedPkg == null) { 2140 msg = "Updated system package " + deletedAppName 2141 + " no longer exists; wiping its data"; 2142 removeDataDirsLI(null, deletedAppName); 2143 } else { 2144 msg = "Updated system app + " + deletedAppName 2145 + " no longer present; removing system privileges for " 2146 + deletedAppName; 2147 2148 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2149 2150 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2151 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2152 } 2153 logCriticalInfo(Log.WARN, msg); 2154 } 2155 2156 /** 2157 * Make sure all system apps that we expected to appear on 2158 * the userdata partition actually showed up. If they never 2159 * appeared, crawl back and revive the system version. 2160 */ 2161 for (int i = 0; i < expectingBetter.size(); i++) { 2162 final String packageName = expectingBetter.keyAt(i); 2163 if (!mPackages.containsKey(packageName)) { 2164 final File scanFile = expectingBetter.valueAt(i); 2165 2166 logCriticalInfo(Log.WARN, "Expected better " + packageName 2167 + " but never showed up; reverting to system"); 2168 2169 final int reparseFlags; 2170 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2171 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2172 | PackageParser.PARSE_IS_SYSTEM_DIR 2173 | PackageParser.PARSE_IS_PRIVILEGED; 2174 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2175 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2176 | PackageParser.PARSE_IS_SYSTEM_DIR; 2177 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2178 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2179 | PackageParser.PARSE_IS_SYSTEM_DIR; 2180 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2181 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2182 | PackageParser.PARSE_IS_SYSTEM_DIR; 2183 } else { 2184 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2185 continue; 2186 } 2187 2188 mSettings.enableSystemPackageLPw(packageName); 2189 2190 try { 2191 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2192 } catch (PackageManagerException e) { 2193 Slog.e(TAG, "Failed to parse original system package: " 2194 + e.getMessage()); 2195 } 2196 } 2197 } 2198 } 2199 2200 // Now that we know all of the shared libraries, update all clients to have 2201 // the correct library paths. 2202 updateAllSharedLibrariesLPw(); 2203 2204 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2205 // NOTE: We ignore potential failures here during a system scan (like 2206 // the rest of the commands above) because there's precious little we 2207 // can do about it. A settings error is reported, though. 2208 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2209 false /* force dexopt */, false /* defer dexopt */); 2210 } 2211 2212 // Now that we know all the packages we are keeping, 2213 // read and update their last usage times. 2214 mPackageUsage.readLP(); 2215 2216 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2217 SystemClock.uptimeMillis()); 2218 Slog.i(TAG, "Time to scan packages: " 2219 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2220 + " seconds"); 2221 2222 // If the platform SDK has changed since the last time we booted, 2223 // we need to re-grant app permission to catch any new ones that 2224 // appear. This is really a hack, and means that apps can in some 2225 // cases get permissions that the user didn't initially explicitly 2226 // allow... it would be nice to have some better way to handle 2227 // this situation. 2228 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2229 != mSdkVersion; 2230 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2231 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2232 + "; regranting permissions for internal storage"); 2233 mSettings.mInternalSdkPlatform = mSdkVersion; 2234 2235 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2236 | (regrantPermissions 2237 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2238 : 0)); 2239 2240 // If this is the first boot, and it is a normal boot, then 2241 // we need to initialize the default preferred apps. 2242 if (!mRestoredSettings && !onlyCore) { 2243 mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER); 2244 applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER); 2245 primeDomainVerificationsLPw(UserHandle.USER_OWNER); 2246 } 2247 2248 // If this is first boot after an OTA, and a normal boot, then 2249 // we need to clear code cache directories. 2250 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2251 if (mIsUpgrade && !onlyCore) { 2252 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2253 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2254 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2255 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2256 } 2257 mSettings.mFingerprint = Build.FINGERPRINT; 2258 } 2259 2260 checkDefaultBrowser(); 2261 2262 // All the changes are done during package scanning. 2263 mSettings.updateInternalDatabaseVersion(); 2264 2265 // can downgrade to reader 2266 mSettings.writeLPr(); 2267 2268 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2269 SystemClock.uptimeMillis()); 2270 2271 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2272 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2273 2274 mInstallerService = new PackageInstallerService(context, this); 2275 2276 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2277 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2278 mIntentFilterVerifierComponent); 2279 2280 } // synchronized (mPackages) 2281 } // synchronized (mInstallLock) 2282 2283 // Now after opening every single application zip, make sure they 2284 // are all flushed. Not really needed, but keeps things nice and 2285 // tidy. 2286 Runtime.getRuntime().gc(); 2287 2288 // Expose private service for system components to use. 2289 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2290 } 2291 2292 @Override 2293 public boolean isFirstBoot() { 2294 return !mRestoredSettings; 2295 } 2296 2297 @Override 2298 public boolean isOnlyCoreApps() { 2299 return mOnlyCore; 2300 } 2301 2302 @Override 2303 public boolean isUpgrade() { 2304 return mIsUpgrade; 2305 } 2306 2307 private String getRequiredVerifierLPr() { 2308 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2309 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2310 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2311 2312 String requiredVerifier = null; 2313 2314 final int N = receivers.size(); 2315 for (int i = 0; i < N; i++) { 2316 final ResolveInfo info = receivers.get(i); 2317 2318 if (info.activityInfo == null) { 2319 continue; 2320 } 2321 2322 final String packageName = info.activityInfo.packageName; 2323 2324 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2325 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2326 continue; 2327 } 2328 2329 if (requiredVerifier != null) { 2330 throw new RuntimeException("There can be only one required verifier"); 2331 } 2332 2333 requiredVerifier = packageName; 2334 } 2335 2336 return requiredVerifier; 2337 } 2338 2339 private String getRequiredInstallerLPr() { 2340 Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2341 installerIntent.addCategory(Intent.CATEGORY_DEFAULT); 2342 installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2343 2344 final List<ResolveInfo> installers = queryIntentActivities(installerIntent, 2345 PACKAGE_MIME_TYPE, 0, 0); 2346 2347 String requiredInstaller = null; 2348 2349 final int N = installers.size(); 2350 for (int i = 0; i < N; i++) { 2351 final ResolveInfo info = installers.get(i); 2352 final String packageName = info.activityInfo.packageName; 2353 2354 if (!info.activityInfo.applicationInfo.isSystemApp()) { 2355 continue; 2356 } 2357 2358 if (requiredInstaller != null) { 2359 throw new RuntimeException("There must be one required installer"); 2360 } 2361 2362 requiredInstaller = packageName; 2363 } 2364 2365 if (requiredInstaller == null) { 2366 throw new RuntimeException("There must be one required installer"); 2367 } 2368 2369 return requiredInstaller; 2370 } 2371 2372 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2373 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2374 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2375 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2376 2377 ComponentName verifierComponentName = null; 2378 2379 int priority = -1000; 2380 final int N = receivers.size(); 2381 for (int i = 0; i < N; i++) { 2382 final ResolveInfo info = receivers.get(i); 2383 2384 if (info.activityInfo == null) { 2385 continue; 2386 } 2387 2388 final String packageName = info.activityInfo.packageName; 2389 2390 final PackageSetting ps = mSettings.mPackages.get(packageName); 2391 if (ps == null) { 2392 continue; 2393 } 2394 2395 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2396 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2397 continue; 2398 } 2399 2400 // Select the IntentFilterVerifier with the highest priority 2401 if (priority < info.priority) { 2402 priority = info.priority; 2403 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2404 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2405 + verifierComponentName + " with priority: " + info.priority); 2406 } 2407 } 2408 2409 return verifierComponentName; 2410 } 2411 2412 private void primeDomainVerificationsLPw(int userId) { 2413 if (DEBUG_DOMAIN_VERIFICATION) { 2414 Slog.d(TAG, "Priming domain verifications in user " + userId); 2415 } 2416 2417 SystemConfig systemConfig = SystemConfig.getInstance(); 2418 ArraySet<String> packages = systemConfig.getLinkedApps(); 2419 ArraySet<String> domains = new ArraySet<String>(); 2420 2421 for (String packageName : packages) { 2422 PackageParser.Package pkg = mPackages.get(packageName); 2423 if (pkg != null) { 2424 if (!pkg.isSystemApp()) { 2425 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2426 continue; 2427 } 2428 2429 domains.clear(); 2430 for (PackageParser.Activity a : pkg.activities) { 2431 for (ActivityIntentInfo filter : a.intents) { 2432 if (hasValidDomains(filter)) { 2433 domains.addAll(filter.getHostsList()); 2434 } 2435 } 2436 } 2437 2438 if (domains.size() > 0) { 2439 if (DEBUG_DOMAIN_VERIFICATION) { 2440 Slog.v(TAG, " + " + packageName); 2441 } 2442 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2443 // state w.r.t. the formal app-linkage "no verification attempted" state; 2444 // and then 'always' in the per-user state actually used for intent resolution. 2445 final IntentFilterVerificationInfo ivi; 2446 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2447 new ArrayList<String>(domains)); 2448 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2449 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2450 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2451 } else { 2452 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2453 + "' does not handle web links"); 2454 } 2455 } else { 2456 Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>"); 2457 } 2458 } 2459 2460 scheduleWritePackageRestrictionsLocked(userId); 2461 scheduleWriteSettingsLocked(); 2462 } 2463 2464 private void applyFactoryDefaultBrowserLPw(int userId) { 2465 // The default browser app's package name is stored in a string resource, 2466 // with a product-specific overlay used for vendor customization. 2467 String browserPkg = mContext.getResources().getString( 2468 com.android.internal.R.string.default_browser); 2469 if (!TextUtils.isEmpty(browserPkg)) { 2470 // non-empty string => required to be a known package 2471 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2472 if (ps == null) { 2473 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2474 browserPkg = null; 2475 } else { 2476 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2477 } 2478 } 2479 2480 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2481 // default. If there's more than one, just leave everything alone. 2482 if (browserPkg == null) { 2483 calculateDefaultBrowserLPw(userId); 2484 } 2485 } 2486 2487 private void calculateDefaultBrowserLPw(int userId) { 2488 List<String> allBrowsers = resolveAllBrowserApps(userId); 2489 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2490 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2491 } 2492 2493 private List<String> resolveAllBrowserApps(int userId) { 2494 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2495 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2496 PackageManager.MATCH_ALL, userId); 2497 2498 final int count = list.size(); 2499 List<String> result = new ArrayList<String>(count); 2500 for (int i=0; i<count; i++) { 2501 ResolveInfo info = list.get(i); 2502 if (info.activityInfo == null 2503 || !info.handleAllWebDataURI 2504 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2505 || result.contains(info.activityInfo.packageName)) { 2506 continue; 2507 } 2508 result.add(info.activityInfo.packageName); 2509 } 2510 2511 return result; 2512 } 2513 2514 private boolean packageIsBrowser(String packageName, int userId) { 2515 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2516 PackageManager.MATCH_ALL, userId); 2517 final int N = list.size(); 2518 for (int i = 0; i < N; i++) { 2519 ResolveInfo info = list.get(i); 2520 if (packageName.equals(info.activityInfo.packageName)) { 2521 return true; 2522 } 2523 } 2524 return false; 2525 } 2526 2527 private void checkDefaultBrowser() { 2528 final int myUserId = UserHandle.myUserId(); 2529 final String packageName = getDefaultBrowserPackageName(myUserId); 2530 if (packageName != null) { 2531 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2532 if (info == null) { 2533 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2534 synchronized (mPackages) { 2535 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2536 } 2537 } 2538 } 2539 } 2540 2541 @Override 2542 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2543 throws RemoteException { 2544 try { 2545 return super.onTransact(code, data, reply, flags); 2546 } catch (RuntimeException e) { 2547 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2548 Slog.wtf(TAG, "Package Manager Crash", e); 2549 } 2550 throw e; 2551 } 2552 } 2553 2554 void cleanupInstallFailedPackage(PackageSetting ps) { 2555 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2556 2557 removeDataDirsLI(ps.volumeUuid, ps.name); 2558 if (ps.codePath != null) { 2559 if (ps.codePath.isDirectory()) { 2560 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2561 } else { 2562 ps.codePath.delete(); 2563 } 2564 } 2565 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2566 if (ps.resourcePath.isDirectory()) { 2567 FileUtils.deleteContents(ps.resourcePath); 2568 } 2569 ps.resourcePath.delete(); 2570 } 2571 mSettings.removePackageLPw(ps.name); 2572 } 2573 2574 static int[] appendInts(int[] cur, int[] add) { 2575 if (add == null) return cur; 2576 if (cur == null) return add; 2577 final int N = add.length; 2578 for (int i=0; i<N; i++) { 2579 cur = appendInt(cur, add[i]); 2580 } 2581 return cur; 2582 } 2583 2584 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2585 if (!sUserManager.exists(userId)) return null; 2586 final PackageSetting ps = (PackageSetting) p.mExtras; 2587 if (ps == null) { 2588 return null; 2589 } 2590 2591 final PermissionsState permissionsState = ps.getPermissionsState(); 2592 2593 final int[] gids = permissionsState.computeGids(userId); 2594 final Set<String> permissions = permissionsState.getPermissions(userId); 2595 final PackageUserState state = ps.readUserState(userId); 2596 2597 return PackageParser.generatePackageInfo(p, gids, flags, 2598 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2599 } 2600 2601 @Override 2602 public boolean isPackageFrozen(String packageName) { 2603 synchronized (mPackages) { 2604 final PackageSetting ps = mSettings.mPackages.get(packageName); 2605 if (ps != null) { 2606 return ps.frozen; 2607 } 2608 } 2609 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2610 return true; 2611 } 2612 2613 @Override 2614 public boolean isPackageAvailable(String packageName, int userId) { 2615 if (!sUserManager.exists(userId)) return false; 2616 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2617 synchronized (mPackages) { 2618 PackageParser.Package p = mPackages.get(packageName); 2619 if (p != null) { 2620 final PackageSetting ps = (PackageSetting) p.mExtras; 2621 if (ps != null) { 2622 final PackageUserState state = ps.readUserState(userId); 2623 if (state != null) { 2624 return PackageParser.isAvailable(state); 2625 } 2626 } 2627 } 2628 } 2629 return false; 2630 } 2631 2632 @Override 2633 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2634 if (!sUserManager.exists(userId)) return null; 2635 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2636 // reader 2637 synchronized (mPackages) { 2638 PackageParser.Package p = mPackages.get(packageName); 2639 if (DEBUG_PACKAGE_INFO) 2640 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2641 if (p != null) { 2642 return generatePackageInfo(p, flags, userId); 2643 } 2644 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2645 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2646 } 2647 } 2648 return null; 2649 } 2650 2651 @Override 2652 public String[] currentToCanonicalPackageNames(String[] names) { 2653 String[] out = new String[names.length]; 2654 // reader 2655 synchronized (mPackages) { 2656 for (int i=names.length-1; i>=0; i--) { 2657 PackageSetting ps = mSettings.mPackages.get(names[i]); 2658 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2659 } 2660 } 2661 return out; 2662 } 2663 2664 @Override 2665 public String[] canonicalToCurrentPackageNames(String[] names) { 2666 String[] out = new String[names.length]; 2667 // reader 2668 synchronized (mPackages) { 2669 for (int i=names.length-1; i>=0; i--) { 2670 String cur = mSettings.mRenamedPackages.get(names[i]); 2671 out[i] = cur != null ? cur : names[i]; 2672 } 2673 } 2674 return out; 2675 } 2676 2677 @Override 2678 public int getPackageUid(String packageName, int userId) { 2679 if (!sUserManager.exists(userId)) return -1; 2680 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2681 2682 // reader 2683 synchronized (mPackages) { 2684 PackageParser.Package p = mPackages.get(packageName); 2685 if(p != null) { 2686 return UserHandle.getUid(userId, p.applicationInfo.uid); 2687 } 2688 PackageSetting ps = mSettings.mPackages.get(packageName); 2689 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2690 return -1; 2691 } 2692 p = ps.pkg; 2693 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2694 } 2695 } 2696 2697 @Override 2698 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2699 if (!sUserManager.exists(userId)) { 2700 return null; 2701 } 2702 2703 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2704 "getPackageGids"); 2705 2706 // reader 2707 synchronized (mPackages) { 2708 PackageParser.Package p = mPackages.get(packageName); 2709 if (DEBUG_PACKAGE_INFO) { 2710 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2711 } 2712 if (p != null) { 2713 PackageSetting ps = (PackageSetting) p.mExtras; 2714 return ps.getPermissionsState().computeGids(userId); 2715 } 2716 } 2717 2718 return null; 2719 } 2720 2721 @Override 2722 public int getMountExternalMode(int uid) { 2723 if (Process.isIsolated(uid)) { 2724 return Zygote.MOUNT_EXTERNAL_NONE; 2725 } else { 2726 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 2727 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2728 } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2729 return Zygote.MOUNT_EXTERNAL_WRITE; 2730 } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) { 2731 return Zygote.MOUNT_EXTERNAL_READ; 2732 } else { 2733 return Zygote.MOUNT_EXTERNAL_DEFAULT; 2734 } 2735 } 2736 } 2737 2738 static PermissionInfo generatePermissionInfo( 2739 BasePermission bp, int flags) { 2740 if (bp.perm != null) { 2741 return PackageParser.generatePermissionInfo(bp.perm, flags); 2742 } 2743 PermissionInfo pi = new PermissionInfo(); 2744 pi.name = bp.name; 2745 pi.packageName = bp.sourcePackage; 2746 pi.nonLocalizedLabel = bp.name; 2747 pi.protectionLevel = bp.protectionLevel; 2748 return pi; 2749 } 2750 2751 @Override 2752 public PermissionInfo getPermissionInfo(String name, int flags) { 2753 // reader 2754 synchronized (mPackages) { 2755 final BasePermission p = mSettings.mPermissions.get(name); 2756 if (p != null) { 2757 return generatePermissionInfo(p, flags); 2758 } 2759 return null; 2760 } 2761 } 2762 2763 @Override 2764 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2765 // reader 2766 synchronized (mPackages) { 2767 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2768 for (BasePermission p : mSettings.mPermissions.values()) { 2769 if (group == null) { 2770 if (p.perm == null || p.perm.info.group == null) { 2771 out.add(generatePermissionInfo(p, flags)); 2772 } 2773 } else { 2774 if (p.perm != null && group.equals(p.perm.info.group)) { 2775 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2776 } 2777 } 2778 } 2779 2780 if (out.size() > 0) { 2781 return out; 2782 } 2783 return mPermissionGroups.containsKey(group) ? out : null; 2784 } 2785 } 2786 2787 @Override 2788 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2789 // reader 2790 synchronized (mPackages) { 2791 return PackageParser.generatePermissionGroupInfo( 2792 mPermissionGroups.get(name), flags); 2793 } 2794 } 2795 2796 @Override 2797 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2798 // reader 2799 synchronized (mPackages) { 2800 final int N = mPermissionGroups.size(); 2801 ArrayList<PermissionGroupInfo> out 2802 = new ArrayList<PermissionGroupInfo>(N); 2803 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2804 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2805 } 2806 return out; 2807 } 2808 } 2809 2810 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2811 int userId) { 2812 if (!sUserManager.exists(userId)) return null; 2813 PackageSetting ps = mSettings.mPackages.get(packageName); 2814 if (ps != null) { 2815 if (ps.pkg == null) { 2816 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2817 flags, userId); 2818 if (pInfo != null) { 2819 return pInfo.applicationInfo; 2820 } 2821 return null; 2822 } 2823 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2824 ps.readUserState(userId), userId); 2825 } 2826 return null; 2827 } 2828 2829 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2830 int userId) { 2831 if (!sUserManager.exists(userId)) return null; 2832 PackageSetting ps = mSettings.mPackages.get(packageName); 2833 if (ps != null) { 2834 PackageParser.Package pkg = ps.pkg; 2835 if (pkg == null) { 2836 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2837 return null; 2838 } 2839 // Only data remains, so we aren't worried about code paths 2840 pkg = new PackageParser.Package(packageName); 2841 pkg.applicationInfo.packageName = packageName; 2842 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2843 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2844 pkg.applicationInfo.dataDir = Environment 2845 .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName) 2846 .getAbsolutePath(); 2847 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2848 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2849 } 2850 return generatePackageInfo(pkg, flags, userId); 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2857 if (!sUserManager.exists(userId)) return null; 2858 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2859 // writer 2860 synchronized (mPackages) { 2861 PackageParser.Package p = mPackages.get(packageName); 2862 if (DEBUG_PACKAGE_INFO) Log.v( 2863 TAG, "getApplicationInfo " + packageName 2864 + ": " + p); 2865 if (p != null) { 2866 PackageSetting ps = mSettings.mPackages.get(packageName); 2867 if (ps == null) return null; 2868 // Note: isEnabledLP() does not apply here - always return info 2869 return PackageParser.generateApplicationInfo( 2870 p, flags, ps.readUserState(userId), userId); 2871 } 2872 if ("android".equals(packageName)||"system".equals(packageName)) { 2873 return mAndroidApplication; 2874 } 2875 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2876 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2877 } 2878 } 2879 return null; 2880 } 2881 2882 @Override 2883 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2884 final IPackageDataObserver observer) { 2885 mContext.enforceCallingOrSelfPermission( 2886 android.Manifest.permission.CLEAR_APP_CACHE, null); 2887 // Queue up an async operation since clearing cache may take a little while. 2888 mHandler.post(new Runnable() { 2889 public void run() { 2890 mHandler.removeCallbacks(this); 2891 int retCode = -1; 2892 synchronized (mInstallLock) { 2893 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2894 if (retCode < 0) { 2895 Slog.w(TAG, "Couldn't clear application caches"); 2896 } 2897 } 2898 if (observer != null) { 2899 try { 2900 observer.onRemoveCompleted(null, (retCode >= 0)); 2901 } catch (RemoteException e) { 2902 Slog.w(TAG, "RemoveException when invoking call back"); 2903 } 2904 } 2905 } 2906 }); 2907 } 2908 2909 @Override 2910 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2911 final IntentSender pi) { 2912 mContext.enforceCallingOrSelfPermission( 2913 android.Manifest.permission.CLEAR_APP_CACHE, null); 2914 // Queue up an async operation since clearing cache may take a little while. 2915 mHandler.post(new Runnable() { 2916 public void run() { 2917 mHandler.removeCallbacks(this); 2918 int retCode = -1; 2919 synchronized (mInstallLock) { 2920 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2921 if (retCode < 0) { 2922 Slog.w(TAG, "Couldn't clear application caches"); 2923 } 2924 } 2925 if(pi != null) { 2926 try { 2927 // Callback via pending intent 2928 int code = (retCode >= 0) ? 1 : 0; 2929 pi.sendIntent(null, code, null, 2930 null, null); 2931 } catch (SendIntentException e1) { 2932 Slog.i(TAG, "Failed to send pending intent"); 2933 } 2934 } 2935 } 2936 }); 2937 } 2938 2939 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2940 synchronized (mInstallLock) { 2941 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2942 throw new IOException("Failed to free enough space"); 2943 } 2944 } 2945 } 2946 2947 @Override 2948 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2949 if (!sUserManager.exists(userId)) return null; 2950 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2951 synchronized (mPackages) { 2952 PackageParser.Activity a = mActivities.mActivities.get(component); 2953 2954 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2955 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2956 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2957 if (ps == null) return null; 2958 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2959 userId); 2960 } 2961 if (mResolveComponentName.equals(component)) { 2962 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2963 new PackageUserState(), userId); 2964 } 2965 } 2966 return null; 2967 } 2968 2969 @Override 2970 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2971 String resolvedType) { 2972 synchronized (mPackages) { 2973 PackageParser.Activity a = mActivities.mActivities.get(component); 2974 if (a == null) { 2975 return false; 2976 } 2977 for (int i=0; i<a.intents.size(); i++) { 2978 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2979 intent.getData(), intent.getCategories(), TAG) >= 0) { 2980 return true; 2981 } 2982 } 2983 return false; 2984 } 2985 } 2986 2987 @Override 2988 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2989 if (!sUserManager.exists(userId)) return null; 2990 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2991 synchronized (mPackages) { 2992 PackageParser.Activity a = mReceivers.mActivities.get(component); 2993 if (DEBUG_PACKAGE_INFO) Log.v( 2994 TAG, "getReceiverInfo " + component + ": " + a); 2995 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2996 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2997 if (ps == null) return null; 2998 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2999 userId); 3000 } 3001 } 3002 return null; 3003 } 3004 3005 @Override 3006 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3007 if (!sUserManager.exists(userId)) return null; 3008 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3009 synchronized (mPackages) { 3010 PackageParser.Service s = mServices.mServices.get(component); 3011 if (DEBUG_PACKAGE_INFO) Log.v( 3012 TAG, "getServiceInfo " + component + ": " + s); 3013 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 3014 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3015 if (ps == null) return null; 3016 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3017 userId); 3018 } 3019 } 3020 return null; 3021 } 3022 3023 @Override 3024 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3025 if (!sUserManager.exists(userId)) return null; 3026 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3027 synchronized (mPackages) { 3028 PackageParser.Provider p = mProviders.mProviders.get(component); 3029 if (DEBUG_PACKAGE_INFO) Log.v( 3030 TAG, "getProviderInfo " + component + ": " + p); 3031 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 3032 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3033 if (ps == null) return null; 3034 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3035 userId); 3036 } 3037 } 3038 return null; 3039 } 3040 3041 @Override 3042 public String[] getSystemSharedLibraryNames() { 3043 Set<String> libSet; 3044 synchronized (mPackages) { 3045 libSet = mSharedLibraries.keySet(); 3046 int size = libSet.size(); 3047 if (size > 0) { 3048 String[] libs = new String[size]; 3049 libSet.toArray(libs); 3050 return libs; 3051 } 3052 } 3053 return null; 3054 } 3055 3056 /** 3057 * @hide 3058 */ 3059 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3060 synchronized (mPackages) { 3061 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3062 if (lib != null && lib.apk != null) { 3063 return mPackages.get(lib.apk); 3064 } 3065 } 3066 return null; 3067 } 3068 3069 @Override 3070 public FeatureInfo[] getSystemAvailableFeatures() { 3071 Collection<FeatureInfo> featSet; 3072 synchronized (mPackages) { 3073 featSet = mAvailableFeatures.values(); 3074 int size = featSet.size(); 3075 if (size > 0) { 3076 FeatureInfo[] features = new FeatureInfo[size+1]; 3077 featSet.toArray(features); 3078 FeatureInfo fi = new FeatureInfo(); 3079 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3080 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3081 features[size] = fi; 3082 return features; 3083 } 3084 } 3085 return null; 3086 } 3087 3088 @Override 3089 public boolean hasSystemFeature(String name) { 3090 synchronized (mPackages) { 3091 return mAvailableFeatures.containsKey(name); 3092 } 3093 } 3094 3095 private void checkValidCaller(int uid, int userId) { 3096 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 3097 return; 3098 3099 throw new SecurityException("Caller uid=" + uid 3100 + " is not privileged to communicate with user=" + userId); 3101 } 3102 3103 @Override 3104 public int checkPermission(String permName, String pkgName, int userId) { 3105 if (!sUserManager.exists(userId)) { 3106 return PackageManager.PERMISSION_DENIED; 3107 } 3108 3109 synchronized (mPackages) { 3110 final PackageParser.Package p = mPackages.get(pkgName); 3111 if (p != null && p.mExtras != null) { 3112 final PackageSetting ps = (PackageSetting) p.mExtras; 3113 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3114 return PackageManager.PERMISSION_GRANTED; 3115 } 3116 } 3117 } 3118 3119 return PackageManager.PERMISSION_DENIED; 3120 } 3121 3122 @Override 3123 public int checkUidPermission(String permName, int uid) { 3124 final int userId = UserHandle.getUserId(uid); 3125 3126 if (!sUserManager.exists(userId)) { 3127 return PackageManager.PERMISSION_DENIED; 3128 } 3129 3130 synchronized (mPackages) { 3131 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3132 if (obj != null) { 3133 final SettingBase ps = (SettingBase) obj; 3134 if (ps.getPermissionsState().hasPermission(permName, userId)) { 3135 return PackageManager.PERMISSION_GRANTED; 3136 } 3137 } else { 3138 ArraySet<String> perms = mSystemPermissions.get(uid); 3139 if (perms != null && perms.contains(permName)) { 3140 return PackageManager.PERMISSION_GRANTED; 3141 } 3142 } 3143 } 3144 3145 return PackageManager.PERMISSION_DENIED; 3146 } 3147 3148 /** 3149 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3150 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3151 * @param checkShell TODO(yamasani): 3152 * @param message the message to log on security exception 3153 */ 3154 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3155 boolean checkShell, String message) { 3156 if (userId < 0) { 3157 throw new IllegalArgumentException("Invalid userId " + userId); 3158 } 3159 if (checkShell) { 3160 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3161 } 3162 if (userId == UserHandle.getUserId(callingUid)) return; 3163 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3164 if (requireFullPermission) { 3165 mContext.enforceCallingOrSelfPermission( 3166 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3167 } else { 3168 try { 3169 mContext.enforceCallingOrSelfPermission( 3170 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3171 } catch (SecurityException se) { 3172 mContext.enforceCallingOrSelfPermission( 3173 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3174 } 3175 } 3176 } 3177 } 3178 3179 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3180 if (callingUid == Process.SHELL_UID) { 3181 if (userHandle >= 0 3182 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3183 throw new SecurityException("Shell does not have permission to access user " 3184 + userHandle); 3185 } else if (userHandle < 0) { 3186 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3187 + Debug.getCallers(3)); 3188 } 3189 } 3190 } 3191 3192 private BasePermission findPermissionTreeLP(String permName) { 3193 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3194 if (permName.startsWith(bp.name) && 3195 permName.length() > bp.name.length() && 3196 permName.charAt(bp.name.length()) == '.') { 3197 return bp; 3198 } 3199 } 3200 return null; 3201 } 3202 3203 private BasePermission checkPermissionTreeLP(String permName) { 3204 if (permName != null) { 3205 BasePermission bp = findPermissionTreeLP(permName); 3206 if (bp != null) { 3207 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3208 return bp; 3209 } 3210 throw new SecurityException("Calling uid " 3211 + Binder.getCallingUid() 3212 + " is not allowed to add to permission tree " 3213 + bp.name + " owned by uid " + bp.uid); 3214 } 3215 } 3216 throw new SecurityException("No permission tree found for " + permName); 3217 } 3218 3219 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3220 if (s1 == null) { 3221 return s2 == null; 3222 } 3223 if (s2 == null) { 3224 return false; 3225 } 3226 if (s1.getClass() != s2.getClass()) { 3227 return false; 3228 } 3229 return s1.equals(s2); 3230 } 3231 3232 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3233 if (pi1.icon != pi2.icon) return false; 3234 if (pi1.logo != pi2.logo) return false; 3235 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3236 if (!compareStrings(pi1.name, pi2.name)) return false; 3237 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3238 // We'll take care of setting this one. 3239 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3240 // These are not currently stored in settings. 3241 //if (!compareStrings(pi1.group, pi2.group)) return false; 3242 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3243 //if (pi1.labelRes != pi2.labelRes) return false; 3244 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3245 return true; 3246 } 3247 3248 int permissionInfoFootprint(PermissionInfo info) { 3249 int size = info.name.length(); 3250 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3251 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3252 return size; 3253 } 3254 3255 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3256 int size = 0; 3257 for (BasePermission perm : mSettings.mPermissions.values()) { 3258 if (perm.uid == tree.uid) { 3259 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3260 } 3261 } 3262 return size; 3263 } 3264 3265 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3266 // We calculate the max size of permissions defined by this uid and throw 3267 // if that plus the size of 'info' would exceed our stated maximum. 3268 if (tree.uid != Process.SYSTEM_UID) { 3269 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3270 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3271 throw new SecurityException("Permission tree size cap exceeded"); 3272 } 3273 } 3274 } 3275 3276 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3277 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3278 throw new SecurityException("Label must be specified in permission"); 3279 } 3280 BasePermission tree = checkPermissionTreeLP(info.name); 3281 BasePermission bp = mSettings.mPermissions.get(info.name); 3282 boolean added = bp == null; 3283 boolean changed = true; 3284 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3285 if (added) { 3286 enforcePermissionCapLocked(info, tree); 3287 bp = new BasePermission(info.name, tree.sourcePackage, 3288 BasePermission.TYPE_DYNAMIC); 3289 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3290 throw new SecurityException( 3291 "Not allowed to modify non-dynamic permission " 3292 + info.name); 3293 } else { 3294 if (bp.protectionLevel == fixedLevel 3295 && bp.perm.owner.equals(tree.perm.owner) 3296 && bp.uid == tree.uid 3297 && comparePermissionInfos(bp.perm.info, info)) { 3298 changed = false; 3299 } 3300 } 3301 bp.protectionLevel = fixedLevel; 3302 info = new PermissionInfo(info); 3303 info.protectionLevel = fixedLevel; 3304 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3305 bp.perm.info.packageName = tree.perm.info.packageName; 3306 bp.uid = tree.uid; 3307 if (added) { 3308 mSettings.mPermissions.put(info.name, bp); 3309 } 3310 if (changed) { 3311 if (!async) { 3312 mSettings.writeLPr(); 3313 } else { 3314 scheduleWriteSettingsLocked(); 3315 } 3316 } 3317 return added; 3318 } 3319 3320 @Override 3321 public boolean addPermission(PermissionInfo info) { 3322 synchronized (mPackages) { 3323 return addPermissionLocked(info, false); 3324 } 3325 } 3326 3327 @Override 3328 public boolean addPermissionAsync(PermissionInfo info) { 3329 synchronized (mPackages) { 3330 return addPermissionLocked(info, true); 3331 } 3332 } 3333 3334 @Override 3335 public void removePermission(String name) { 3336 synchronized (mPackages) { 3337 checkPermissionTreeLP(name); 3338 BasePermission bp = mSettings.mPermissions.get(name); 3339 if (bp != null) { 3340 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3341 throw new SecurityException( 3342 "Not allowed to modify non-dynamic permission " 3343 + name); 3344 } 3345 mSettings.mPermissions.remove(name); 3346 mSettings.writeLPr(); 3347 } 3348 } 3349 } 3350 3351 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3352 BasePermission bp) { 3353 int index = pkg.requestedPermissions.indexOf(bp.name); 3354 if (index == -1) { 3355 throw new SecurityException("Package " + pkg.packageName 3356 + " has not requested permission " + bp.name); 3357 } 3358 if (!bp.isRuntime()) { 3359 throw new SecurityException("Permission " + bp.name 3360 + " is not a changeable permission type"); 3361 } 3362 } 3363 3364 @Override 3365 public void grantRuntimePermission(String packageName, String name, final int userId) { 3366 if (!sUserManager.exists(userId)) { 3367 Log.e(TAG, "No such user:" + userId); 3368 return; 3369 } 3370 3371 mContext.enforceCallingOrSelfPermission( 3372 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3373 "grantRuntimePermission"); 3374 3375 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3376 "grantRuntimePermission"); 3377 3378 final int uid; 3379 final SettingBase sb; 3380 3381 synchronized (mPackages) { 3382 final PackageParser.Package pkg = mPackages.get(packageName); 3383 if (pkg == null) { 3384 throw new IllegalArgumentException("Unknown package: " + packageName); 3385 } 3386 3387 final BasePermission bp = mSettings.mPermissions.get(name); 3388 if (bp == null) { 3389 throw new IllegalArgumentException("Unknown permission: " + name); 3390 } 3391 3392 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3393 3394 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3395 sb = (SettingBase) pkg.mExtras; 3396 if (sb == null) { 3397 throw new IllegalArgumentException("Unknown package: " + packageName); 3398 } 3399 3400 final PermissionsState permissionsState = sb.getPermissionsState(); 3401 3402 final int flags = permissionsState.getPermissionFlags(name, userId); 3403 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3404 throw new SecurityException("Cannot grant system fixed permission: " 3405 + name + " for package: " + packageName); 3406 } 3407 3408 final int result = permissionsState.grantRuntimePermission(bp, userId); 3409 switch (result) { 3410 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3411 return; 3412 } 3413 3414 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3415 mHandler.post(new Runnable() { 3416 @Override 3417 public void run() { 3418 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3419 } 3420 }); 3421 } break; 3422 } 3423 3424 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3425 3426 // Not critical if that is lost - app has to request again. 3427 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3428 } 3429 3430 if (READ_EXTERNAL_STORAGE.equals(name) 3431 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3432 final long token = Binder.clearCallingIdentity(); 3433 try { 3434 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3435 storage.remountUid(uid); 3436 } finally { 3437 Binder.restoreCallingIdentity(token); 3438 } 3439 } 3440 } 3441 3442 @Override 3443 public void revokeRuntimePermission(String packageName, String name, int userId) { 3444 if (!sUserManager.exists(userId)) { 3445 Log.e(TAG, "No such user:" + userId); 3446 return; 3447 } 3448 3449 mContext.enforceCallingOrSelfPermission( 3450 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3451 "revokeRuntimePermission"); 3452 3453 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3454 "revokeRuntimePermission"); 3455 3456 final SettingBase sb; 3457 3458 synchronized (mPackages) { 3459 final PackageParser.Package pkg = mPackages.get(packageName); 3460 if (pkg == null) { 3461 throw new IllegalArgumentException("Unknown package: " + packageName); 3462 } 3463 3464 final BasePermission bp = mSettings.mPermissions.get(name); 3465 if (bp == null) { 3466 throw new IllegalArgumentException("Unknown permission: " + name); 3467 } 3468 3469 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3470 3471 sb = (SettingBase) pkg.mExtras; 3472 if (sb == null) { 3473 throw new IllegalArgumentException("Unknown package: " + packageName); 3474 } 3475 3476 final PermissionsState permissionsState = sb.getPermissionsState(); 3477 3478 final int flags = permissionsState.getPermissionFlags(name, userId); 3479 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3480 throw new SecurityException("Cannot revoke system fixed permission: " 3481 + name + " for package: " + packageName); 3482 } 3483 3484 if (permissionsState.revokeRuntimePermission(bp, userId) == 3485 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3486 return; 3487 } 3488 3489 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3490 3491 // Critical, after this call app should never have the permission. 3492 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3493 } 3494 3495 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3496 } 3497 3498 @Override 3499 public void resetRuntimePermissions() { 3500 mContext.enforceCallingOrSelfPermission( 3501 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3502 "revokeRuntimePermission"); 3503 3504 int callingUid = Binder.getCallingUid(); 3505 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3506 mContext.enforceCallingOrSelfPermission( 3507 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3508 "resetRuntimePermissions"); 3509 } 3510 3511 final int[] userIds; 3512 3513 synchronized (mPackages) { 3514 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3515 final int userCount = UserManagerService.getInstance().getUserIds().length; 3516 userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount); 3517 } 3518 3519 for (int userId : userIds) { 3520 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 3521 } 3522 } 3523 3524 @Override 3525 public int getPermissionFlags(String name, String packageName, int userId) { 3526 if (!sUserManager.exists(userId)) { 3527 return 0; 3528 } 3529 3530 mContext.enforceCallingOrSelfPermission( 3531 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3532 "getPermissionFlags"); 3533 3534 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3535 "getPermissionFlags"); 3536 3537 synchronized (mPackages) { 3538 final PackageParser.Package pkg = mPackages.get(packageName); 3539 if (pkg == null) { 3540 throw new IllegalArgumentException("Unknown package: " + packageName); 3541 } 3542 3543 final BasePermission bp = mSettings.mPermissions.get(name); 3544 if (bp == null) { 3545 throw new IllegalArgumentException("Unknown permission: " + name); 3546 } 3547 3548 SettingBase sb = (SettingBase) pkg.mExtras; 3549 if (sb == null) { 3550 throw new IllegalArgumentException("Unknown package: " + packageName); 3551 } 3552 3553 PermissionsState permissionsState = sb.getPermissionsState(); 3554 return permissionsState.getPermissionFlags(name, userId); 3555 } 3556 } 3557 3558 @Override 3559 public void updatePermissionFlags(String name, String packageName, int flagMask, 3560 int flagValues, int userId) { 3561 if (!sUserManager.exists(userId)) { 3562 return; 3563 } 3564 3565 mContext.enforceCallingOrSelfPermission( 3566 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3567 "updatePermissionFlags"); 3568 3569 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3570 "updatePermissionFlags"); 3571 3572 // Only the system can change system fixed flags. 3573 if (getCallingUid() != Process.SYSTEM_UID) { 3574 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3575 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3576 } 3577 3578 synchronized (mPackages) { 3579 final PackageParser.Package pkg = mPackages.get(packageName); 3580 if (pkg == null) { 3581 throw new IllegalArgumentException("Unknown package: " + packageName); 3582 } 3583 3584 final BasePermission bp = mSettings.mPermissions.get(name); 3585 if (bp == null) { 3586 throw new IllegalArgumentException("Unknown permission: " + name); 3587 } 3588 3589 SettingBase sb = (SettingBase) pkg.mExtras; 3590 if (sb == null) { 3591 throw new IllegalArgumentException("Unknown package: " + packageName); 3592 } 3593 3594 PermissionsState permissionsState = sb.getPermissionsState(); 3595 3596 // Only the package manager can change flags for system component permissions. 3597 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3598 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3599 return; 3600 } 3601 3602 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3603 3604 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3605 // Install and runtime permissions are stored in different places, 3606 // so figure out what permission changed and persist the change. 3607 if (permissionsState.getInstallPermissionState(name) != null) { 3608 scheduleWriteSettingsLocked(); 3609 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3610 || hadState) { 3611 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3612 } 3613 } 3614 } 3615 } 3616 3617 /** 3618 * Update the permission flags for all packages and runtime permissions of a user in order 3619 * to allow device or profile owner to remove POLICY_FIXED. 3620 */ 3621 @Override 3622 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3623 if (!sUserManager.exists(userId)) { 3624 return; 3625 } 3626 3627 mContext.enforceCallingOrSelfPermission( 3628 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3629 "updatePermissionFlagsForAllApps"); 3630 3631 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3632 "updatePermissionFlagsForAllApps"); 3633 3634 // Only the system can change system fixed flags. 3635 if (getCallingUid() != Process.SYSTEM_UID) { 3636 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3637 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3638 } 3639 3640 synchronized (mPackages) { 3641 boolean changed = false; 3642 final int packageCount = mPackages.size(); 3643 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3644 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3645 SettingBase sb = (SettingBase) pkg.mExtras; 3646 if (sb == null) { 3647 continue; 3648 } 3649 PermissionsState permissionsState = sb.getPermissionsState(); 3650 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 3651 userId, flagMask, flagValues); 3652 } 3653 if (changed) { 3654 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3655 } 3656 } 3657 } 3658 3659 @Override 3660 public boolean shouldShowRequestPermissionRationale(String permissionName, 3661 String packageName, int userId) { 3662 if (UserHandle.getCallingUserId() != userId) { 3663 mContext.enforceCallingPermission( 3664 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3665 "canShowRequestPermissionRationale for user " + userId); 3666 } 3667 3668 final int uid = getPackageUid(packageName, userId); 3669 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3670 return false; 3671 } 3672 3673 if (checkPermission(permissionName, packageName, userId) 3674 == PackageManager.PERMISSION_GRANTED) { 3675 return false; 3676 } 3677 3678 final int flags; 3679 3680 final long identity = Binder.clearCallingIdentity(); 3681 try { 3682 flags = getPermissionFlags(permissionName, 3683 packageName, userId); 3684 } finally { 3685 Binder.restoreCallingIdentity(identity); 3686 } 3687 3688 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3689 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3690 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3691 3692 if ((flags & fixedFlags) != 0) { 3693 return false; 3694 } 3695 3696 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3697 } 3698 3699 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3700 BasePermission bp = mSettings.mPermissions.get(permission); 3701 if (bp == null) { 3702 throw new SecurityException("Missing " + permission + " permission"); 3703 } 3704 3705 SettingBase sb = (SettingBase) pkg.mExtras; 3706 PermissionsState permissionsState = sb.getPermissionsState(); 3707 3708 if (permissionsState.grantInstallPermission(bp) != 3709 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3710 scheduleWriteSettingsLocked(); 3711 } 3712 } 3713 3714 @Override 3715 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3716 mContext.enforceCallingOrSelfPermission( 3717 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3718 "addOnPermissionsChangeListener"); 3719 3720 synchronized (mPackages) { 3721 mOnPermissionChangeListeners.addListenerLocked(listener); 3722 } 3723 } 3724 3725 @Override 3726 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3727 synchronized (mPackages) { 3728 mOnPermissionChangeListeners.removeListenerLocked(listener); 3729 } 3730 } 3731 3732 @Override 3733 public boolean isProtectedBroadcast(String actionName) { 3734 synchronized (mPackages) { 3735 return mProtectedBroadcasts.contains(actionName); 3736 } 3737 } 3738 3739 @Override 3740 public int checkSignatures(String pkg1, String pkg2) { 3741 synchronized (mPackages) { 3742 final PackageParser.Package p1 = mPackages.get(pkg1); 3743 final PackageParser.Package p2 = mPackages.get(pkg2); 3744 if (p1 == null || p1.mExtras == null 3745 || p2 == null || p2.mExtras == null) { 3746 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3747 } 3748 return compareSignatures(p1.mSignatures, p2.mSignatures); 3749 } 3750 } 3751 3752 @Override 3753 public int checkUidSignatures(int uid1, int uid2) { 3754 // Map to base uids. 3755 uid1 = UserHandle.getAppId(uid1); 3756 uid2 = UserHandle.getAppId(uid2); 3757 // reader 3758 synchronized (mPackages) { 3759 Signature[] s1; 3760 Signature[] s2; 3761 Object obj = mSettings.getUserIdLPr(uid1); 3762 if (obj != null) { 3763 if (obj instanceof SharedUserSetting) { 3764 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3765 } else if (obj instanceof PackageSetting) { 3766 s1 = ((PackageSetting)obj).signatures.mSignatures; 3767 } else { 3768 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3769 } 3770 } else { 3771 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3772 } 3773 obj = mSettings.getUserIdLPr(uid2); 3774 if (obj != null) { 3775 if (obj instanceof SharedUserSetting) { 3776 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3777 } else if (obj instanceof PackageSetting) { 3778 s2 = ((PackageSetting)obj).signatures.mSignatures; 3779 } else { 3780 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3781 } 3782 } else { 3783 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3784 } 3785 return compareSignatures(s1, s2); 3786 } 3787 } 3788 3789 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3790 final long identity = Binder.clearCallingIdentity(); 3791 try { 3792 if (sb instanceof SharedUserSetting) { 3793 SharedUserSetting sus = (SharedUserSetting) sb; 3794 final int packageCount = sus.packages.size(); 3795 for (int i = 0; i < packageCount; i++) { 3796 PackageSetting susPs = sus.packages.valueAt(i); 3797 if (userId == UserHandle.USER_ALL) { 3798 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3799 } else { 3800 final int uid = UserHandle.getUid(userId, susPs.appId); 3801 killUid(uid, reason); 3802 } 3803 } 3804 } else if (sb instanceof PackageSetting) { 3805 PackageSetting ps = (PackageSetting) sb; 3806 if (userId == UserHandle.USER_ALL) { 3807 killApplication(ps.pkg.packageName, ps.appId, reason); 3808 } else { 3809 final int uid = UserHandle.getUid(userId, ps.appId); 3810 killUid(uid, reason); 3811 } 3812 } 3813 } finally { 3814 Binder.restoreCallingIdentity(identity); 3815 } 3816 } 3817 3818 private static void killUid(int uid, String reason) { 3819 IActivityManager am = ActivityManagerNative.getDefault(); 3820 if (am != null) { 3821 try { 3822 am.killUid(uid, reason); 3823 } catch (RemoteException e) { 3824 /* ignore - same process */ 3825 } 3826 } 3827 } 3828 3829 /** 3830 * Compares two sets of signatures. Returns: 3831 * <br /> 3832 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3833 * <br /> 3834 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3835 * <br /> 3836 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3837 * <br /> 3838 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3839 * <br /> 3840 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3841 */ 3842 static int compareSignatures(Signature[] s1, Signature[] s2) { 3843 if (s1 == null) { 3844 return s2 == null 3845 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3846 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3847 } 3848 3849 if (s2 == null) { 3850 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3851 } 3852 3853 if (s1.length != s2.length) { 3854 return PackageManager.SIGNATURE_NO_MATCH; 3855 } 3856 3857 // Since both signature sets are of size 1, we can compare without HashSets. 3858 if (s1.length == 1) { 3859 return s1[0].equals(s2[0]) ? 3860 PackageManager.SIGNATURE_MATCH : 3861 PackageManager.SIGNATURE_NO_MATCH; 3862 } 3863 3864 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3865 for (Signature sig : s1) { 3866 set1.add(sig); 3867 } 3868 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3869 for (Signature sig : s2) { 3870 set2.add(sig); 3871 } 3872 // Make sure s2 contains all signatures in s1. 3873 if (set1.equals(set2)) { 3874 return PackageManager.SIGNATURE_MATCH; 3875 } 3876 return PackageManager.SIGNATURE_NO_MATCH; 3877 } 3878 3879 /** 3880 * If the database version for this type of package (internal storage or 3881 * external storage) is less than the version where package signatures 3882 * were updated, return true. 3883 */ 3884 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3885 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3886 DatabaseVersion.SIGNATURE_END_ENTITY)) 3887 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3888 DatabaseVersion.SIGNATURE_END_ENTITY)); 3889 } 3890 3891 /** 3892 * Used for backward compatibility to make sure any packages with 3893 * certificate chains get upgraded to the new style. {@code existingSigs} 3894 * will be in the old format (since they were stored on disk from before the 3895 * system upgrade) and {@code scannedSigs} will be in the newer format. 3896 */ 3897 private int compareSignaturesCompat(PackageSignatures existingSigs, 3898 PackageParser.Package scannedPkg) { 3899 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3900 return PackageManager.SIGNATURE_NO_MATCH; 3901 } 3902 3903 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3904 for (Signature sig : existingSigs.mSignatures) { 3905 existingSet.add(sig); 3906 } 3907 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3908 for (Signature sig : scannedPkg.mSignatures) { 3909 try { 3910 Signature[] chainSignatures = sig.getChainSignatures(); 3911 for (Signature chainSig : chainSignatures) { 3912 scannedCompatSet.add(chainSig); 3913 } 3914 } catch (CertificateEncodingException e) { 3915 scannedCompatSet.add(sig); 3916 } 3917 } 3918 /* 3919 * Make sure the expanded scanned set contains all signatures in the 3920 * existing one. 3921 */ 3922 if (scannedCompatSet.equals(existingSet)) { 3923 // Migrate the old signatures to the new scheme. 3924 existingSigs.assignSignatures(scannedPkg.mSignatures); 3925 // The new KeySets will be re-added later in the scanning process. 3926 synchronized (mPackages) { 3927 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3928 } 3929 return PackageManager.SIGNATURE_MATCH; 3930 } 3931 return PackageManager.SIGNATURE_NO_MATCH; 3932 } 3933 3934 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3935 if (isExternal(scannedPkg)) { 3936 return mSettings.isExternalDatabaseVersionOlderThan( 3937 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3938 } else { 3939 return mSettings.isInternalDatabaseVersionOlderThan( 3940 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3941 } 3942 } 3943 3944 private int compareSignaturesRecover(PackageSignatures existingSigs, 3945 PackageParser.Package scannedPkg) { 3946 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3947 return PackageManager.SIGNATURE_NO_MATCH; 3948 } 3949 3950 String msg = null; 3951 try { 3952 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3953 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3954 + scannedPkg.packageName); 3955 return PackageManager.SIGNATURE_MATCH; 3956 } 3957 } catch (CertificateException e) { 3958 msg = e.getMessage(); 3959 } 3960 3961 logCriticalInfo(Log.INFO, 3962 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3963 return PackageManager.SIGNATURE_NO_MATCH; 3964 } 3965 3966 @Override 3967 public String[] getPackagesForUid(int uid) { 3968 uid = UserHandle.getAppId(uid); 3969 // reader 3970 synchronized (mPackages) { 3971 Object obj = mSettings.getUserIdLPr(uid); 3972 if (obj instanceof SharedUserSetting) { 3973 final SharedUserSetting sus = (SharedUserSetting) obj; 3974 final int N = sus.packages.size(); 3975 final String[] res = new String[N]; 3976 final Iterator<PackageSetting> it = sus.packages.iterator(); 3977 int i = 0; 3978 while (it.hasNext()) { 3979 res[i++] = it.next().name; 3980 } 3981 return res; 3982 } else if (obj instanceof PackageSetting) { 3983 final PackageSetting ps = (PackageSetting) obj; 3984 return new String[] { ps.name }; 3985 } 3986 } 3987 return null; 3988 } 3989 3990 @Override 3991 public String getNameForUid(int uid) { 3992 // reader 3993 synchronized (mPackages) { 3994 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3995 if (obj instanceof SharedUserSetting) { 3996 final SharedUserSetting sus = (SharedUserSetting) obj; 3997 return sus.name + ":" + sus.userId; 3998 } else if (obj instanceof PackageSetting) { 3999 final PackageSetting ps = (PackageSetting) obj; 4000 return ps.name; 4001 } 4002 } 4003 return null; 4004 } 4005 4006 @Override 4007 public int getUidForSharedUser(String sharedUserName) { 4008 if(sharedUserName == null) { 4009 return -1; 4010 } 4011 // reader 4012 synchronized (mPackages) { 4013 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4014 if (suid == null) { 4015 return -1; 4016 } 4017 return suid.userId; 4018 } 4019 } 4020 4021 @Override 4022 public int getFlagsForUid(int uid) { 4023 synchronized (mPackages) { 4024 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4025 if (obj instanceof SharedUserSetting) { 4026 final SharedUserSetting sus = (SharedUserSetting) obj; 4027 return sus.pkgFlags; 4028 } else if (obj instanceof PackageSetting) { 4029 final PackageSetting ps = (PackageSetting) obj; 4030 return ps.pkgFlags; 4031 } 4032 } 4033 return 0; 4034 } 4035 4036 @Override 4037 public int getPrivateFlagsForUid(int uid) { 4038 synchronized (mPackages) { 4039 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4040 if (obj instanceof SharedUserSetting) { 4041 final SharedUserSetting sus = (SharedUserSetting) obj; 4042 return sus.pkgPrivateFlags; 4043 } else if (obj instanceof PackageSetting) { 4044 final PackageSetting ps = (PackageSetting) obj; 4045 return ps.pkgPrivateFlags; 4046 } 4047 } 4048 return 0; 4049 } 4050 4051 @Override 4052 public boolean isUidPrivileged(int uid) { 4053 uid = UserHandle.getAppId(uid); 4054 // reader 4055 synchronized (mPackages) { 4056 Object obj = mSettings.getUserIdLPr(uid); 4057 if (obj instanceof SharedUserSetting) { 4058 final SharedUserSetting sus = (SharedUserSetting) obj; 4059 final Iterator<PackageSetting> it = sus.packages.iterator(); 4060 while (it.hasNext()) { 4061 if (it.next().isPrivileged()) { 4062 return true; 4063 } 4064 } 4065 } else if (obj instanceof PackageSetting) { 4066 final PackageSetting ps = (PackageSetting) obj; 4067 return ps.isPrivileged(); 4068 } 4069 } 4070 return false; 4071 } 4072 4073 @Override 4074 public String[] getAppOpPermissionPackages(String permissionName) { 4075 synchronized (mPackages) { 4076 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4077 if (pkgs == null) { 4078 return null; 4079 } 4080 return pkgs.toArray(new String[pkgs.size()]); 4081 } 4082 } 4083 4084 @Override 4085 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4086 int flags, int userId) { 4087 if (!sUserManager.exists(userId)) return null; 4088 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4089 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4090 return chooseBestActivity(intent, resolvedType, flags, query, userId); 4091 } 4092 4093 @Override 4094 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4095 IntentFilter filter, int match, ComponentName activity) { 4096 final int userId = UserHandle.getCallingUserId(); 4097 if (DEBUG_PREFERRED) { 4098 Log.v(TAG, "setLastChosenActivity intent=" + intent 4099 + " resolvedType=" + resolvedType 4100 + " flags=" + flags 4101 + " filter=" + filter 4102 + " match=" + match 4103 + " activity=" + activity); 4104 filter.dump(new PrintStreamPrinter(System.out), " "); 4105 } 4106 intent.setComponent(null); 4107 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4108 // Find any earlier preferred or last chosen entries and nuke them 4109 findPreferredActivity(intent, resolvedType, 4110 flags, query, 0, false, true, false, userId); 4111 // Add the new activity as the last chosen for this filter 4112 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4113 "Setting last chosen"); 4114 } 4115 4116 @Override 4117 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4118 final int userId = UserHandle.getCallingUserId(); 4119 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4120 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4121 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4122 false, false, false, userId); 4123 } 4124 4125 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4126 int flags, List<ResolveInfo> query, int userId) { 4127 if (query != null) { 4128 final int N = query.size(); 4129 if (N == 1) { 4130 return query.get(0); 4131 } else if (N > 1) { 4132 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4133 // If there is more than one activity with the same priority, 4134 // then let the user decide between them. 4135 ResolveInfo r0 = query.get(0); 4136 ResolveInfo r1 = query.get(1); 4137 if (DEBUG_INTENT_MATCHING || debug) { 4138 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4139 + r1.activityInfo.name + "=" + r1.priority); 4140 } 4141 // If the first activity has a higher priority, or a different 4142 // default, then it is always desireable to pick it. 4143 if (r0.priority != r1.priority 4144 || r0.preferredOrder != r1.preferredOrder 4145 || r0.isDefault != r1.isDefault) { 4146 return query.get(0); 4147 } 4148 // If we have saved a preference for a preferred activity for 4149 // this Intent, use that. 4150 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4151 flags, query, r0.priority, true, false, debug, userId); 4152 if (ri != null) { 4153 return ri; 4154 } 4155 if (userId != 0) { 4156 ri = new ResolveInfo(mResolveInfo); 4157 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4158 ri.activityInfo.applicationInfo = new ApplicationInfo( 4159 ri.activityInfo.applicationInfo); 4160 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4161 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4162 return ri; 4163 } 4164 return mResolveInfo; 4165 } 4166 } 4167 return null; 4168 } 4169 4170 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4171 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4172 final int N = query.size(); 4173 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4174 .get(userId); 4175 // Get the list of persistent preferred activities that handle the intent 4176 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4177 List<PersistentPreferredActivity> pprefs = ppir != null 4178 ? ppir.queryIntent(intent, resolvedType, 4179 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4180 : null; 4181 if (pprefs != null && pprefs.size() > 0) { 4182 final int M = pprefs.size(); 4183 for (int i=0; i<M; i++) { 4184 final PersistentPreferredActivity ppa = pprefs.get(i); 4185 if (DEBUG_PREFERRED || debug) { 4186 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4187 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4188 + "\n component=" + ppa.mComponent); 4189 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4190 } 4191 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4192 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4193 if (DEBUG_PREFERRED || debug) { 4194 Slog.v(TAG, "Found persistent preferred activity:"); 4195 if (ai != null) { 4196 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4197 } else { 4198 Slog.v(TAG, " null"); 4199 } 4200 } 4201 if (ai == null) { 4202 // This previously registered persistent preferred activity 4203 // component is no longer known. Ignore it and do NOT remove it. 4204 continue; 4205 } 4206 for (int j=0; j<N; j++) { 4207 final ResolveInfo ri = query.get(j); 4208 if (!ri.activityInfo.applicationInfo.packageName 4209 .equals(ai.applicationInfo.packageName)) { 4210 continue; 4211 } 4212 if (!ri.activityInfo.name.equals(ai.name)) { 4213 continue; 4214 } 4215 // Found a persistent preference that can handle the intent. 4216 if (DEBUG_PREFERRED || debug) { 4217 Slog.v(TAG, "Returning persistent preferred activity: " + 4218 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4219 } 4220 return ri; 4221 } 4222 } 4223 } 4224 return null; 4225 } 4226 4227 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4228 List<ResolveInfo> query, int priority, boolean always, 4229 boolean removeMatches, boolean debug, int userId) { 4230 if (!sUserManager.exists(userId)) return null; 4231 // writer 4232 synchronized (mPackages) { 4233 if (intent.getSelector() != null) { 4234 intent = intent.getSelector(); 4235 } 4236 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4237 4238 // Try to find a matching persistent preferred activity. 4239 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4240 debug, userId); 4241 4242 // If a persistent preferred activity matched, use it. 4243 if (pri != null) { 4244 return pri; 4245 } 4246 4247 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4248 // Get the list of preferred activities that handle the intent 4249 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4250 List<PreferredActivity> prefs = pir != null 4251 ? pir.queryIntent(intent, resolvedType, 4252 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4253 : null; 4254 if (prefs != null && prefs.size() > 0) { 4255 boolean changed = false; 4256 try { 4257 // First figure out how good the original match set is. 4258 // We will only allow preferred activities that came 4259 // from the same match quality. 4260 int match = 0; 4261 4262 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4263 4264 final int N = query.size(); 4265 for (int j=0; j<N; j++) { 4266 final ResolveInfo ri = query.get(j); 4267 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4268 + ": 0x" + Integer.toHexString(match)); 4269 if (ri.match > match) { 4270 match = ri.match; 4271 } 4272 } 4273 4274 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4275 + Integer.toHexString(match)); 4276 4277 match &= IntentFilter.MATCH_CATEGORY_MASK; 4278 final int M = prefs.size(); 4279 for (int i=0; i<M; i++) { 4280 final PreferredActivity pa = prefs.get(i); 4281 if (DEBUG_PREFERRED || debug) { 4282 Slog.v(TAG, "Checking PreferredActivity ds=" 4283 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4284 + "\n component=" + pa.mPref.mComponent); 4285 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4286 } 4287 if (pa.mPref.mMatch != match) { 4288 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4289 + Integer.toHexString(pa.mPref.mMatch)); 4290 continue; 4291 } 4292 // If it's not an "always" type preferred activity and that's what we're 4293 // looking for, skip it. 4294 if (always && !pa.mPref.mAlways) { 4295 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4296 continue; 4297 } 4298 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4299 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4300 if (DEBUG_PREFERRED || debug) { 4301 Slog.v(TAG, "Found preferred activity:"); 4302 if (ai != null) { 4303 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4304 } else { 4305 Slog.v(TAG, " null"); 4306 } 4307 } 4308 if (ai == null) { 4309 // This previously registered preferred activity 4310 // component is no longer known. Most likely an update 4311 // to the app was installed and in the new version this 4312 // component no longer exists. Clean it up by removing 4313 // it from the preferred activities list, and skip it. 4314 Slog.w(TAG, "Removing dangling preferred activity: " 4315 + pa.mPref.mComponent); 4316 pir.removeFilter(pa); 4317 changed = true; 4318 continue; 4319 } 4320 for (int j=0; j<N; j++) { 4321 final ResolveInfo ri = query.get(j); 4322 if (!ri.activityInfo.applicationInfo.packageName 4323 .equals(ai.applicationInfo.packageName)) { 4324 continue; 4325 } 4326 if (!ri.activityInfo.name.equals(ai.name)) { 4327 continue; 4328 } 4329 4330 if (removeMatches) { 4331 pir.removeFilter(pa); 4332 changed = true; 4333 if (DEBUG_PREFERRED) { 4334 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4335 } 4336 break; 4337 } 4338 4339 // Okay we found a previously set preferred or last chosen app. 4340 // If the result set is different from when this 4341 // was created, we need to clear it and re-ask the 4342 // user their preference, if we're looking for an "always" type entry. 4343 if (always && !pa.mPref.sameSet(query)) { 4344 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4345 + intent + " type " + resolvedType); 4346 if (DEBUG_PREFERRED) { 4347 Slog.v(TAG, "Removing preferred activity since set changed " 4348 + pa.mPref.mComponent); 4349 } 4350 pir.removeFilter(pa); 4351 // Re-add the filter as a "last chosen" entry (!always) 4352 PreferredActivity lastChosen = new PreferredActivity( 4353 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4354 pir.addFilter(lastChosen); 4355 changed = true; 4356 return null; 4357 } 4358 4359 // Yay! Either the set matched or we're looking for the last chosen 4360 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4361 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4362 return ri; 4363 } 4364 } 4365 } finally { 4366 if (changed) { 4367 if (DEBUG_PREFERRED) { 4368 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4369 } 4370 scheduleWritePackageRestrictionsLocked(userId); 4371 } 4372 } 4373 } 4374 } 4375 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4376 return null; 4377 } 4378 4379 /* 4380 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4381 */ 4382 @Override 4383 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4384 int targetUserId) { 4385 mContext.enforceCallingOrSelfPermission( 4386 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4387 List<CrossProfileIntentFilter> matches = 4388 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4389 if (matches != null) { 4390 int size = matches.size(); 4391 for (int i = 0; i < size; i++) { 4392 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4393 } 4394 } 4395 if (hasWebURI(intent)) { 4396 // cross-profile app linking works only towards the parent. 4397 final UserInfo parent = getProfileParent(sourceUserId); 4398 synchronized(mPackages) { 4399 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4400 parent.id) != null; 4401 } 4402 } 4403 return false; 4404 } 4405 4406 private UserInfo getProfileParent(int userId) { 4407 final long identity = Binder.clearCallingIdentity(); 4408 try { 4409 return sUserManager.getProfileParent(userId); 4410 } finally { 4411 Binder.restoreCallingIdentity(identity); 4412 } 4413 } 4414 4415 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4416 String resolvedType, int userId) { 4417 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4418 if (resolver != null) { 4419 return resolver.queryIntent(intent, resolvedType, false, userId); 4420 } 4421 return null; 4422 } 4423 4424 @Override 4425 public List<ResolveInfo> queryIntentActivities(Intent intent, 4426 String resolvedType, int flags, int userId) { 4427 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4428 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4429 ComponentName comp = intent.getComponent(); 4430 if (comp == null) { 4431 if (intent.getSelector() != null) { 4432 intent = intent.getSelector(); 4433 comp = intent.getComponent(); 4434 } 4435 } 4436 4437 if (comp != null) { 4438 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4439 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4440 if (ai != null) { 4441 final ResolveInfo ri = new ResolveInfo(); 4442 ri.activityInfo = ai; 4443 list.add(ri); 4444 } 4445 return list; 4446 } 4447 4448 // reader 4449 synchronized (mPackages) { 4450 final String pkgName = intent.getPackage(); 4451 if (pkgName == null) { 4452 List<CrossProfileIntentFilter> matchingFilters = 4453 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4454 // Check for results that need to skip the current profile. 4455 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4456 resolvedType, flags, userId); 4457 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4458 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4459 result.add(xpResolveInfo); 4460 return filterIfNotPrimaryUser(result, userId); 4461 } 4462 4463 // Check for results in the current profile. 4464 List<ResolveInfo> result = mActivities.queryIntent( 4465 intent, resolvedType, flags, userId); 4466 4467 // Check for cross profile results. 4468 xpResolveInfo = queryCrossProfileIntents( 4469 matchingFilters, intent, resolvedType, flags, userId); 4470 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4471 result.add(xpResolveInfo); 4472 Collections.sort(result, mResolvePrioritySorter); 4473 } 4474 result = filterIfNotPrimaryUser(result, userId); 4475 if (hasWebURI(intent)) { 4476 CrossProfileDomainInfo xpDomainInfo = null; 4477 final UserInfo parent = getProfileParent(userId); 4478 if (parent != null) { 4479 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4480 flags, userId, parent.id); 4481 } 4482 if (xpDomainInfo != null) { 4483 if (xpResolveInfo != null) { 4484 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4485 // in the result. 4486 result.remove(xpResolveInfo); 4487 } 4488 if (result.size() == 0) { 4489 result.add(xpDomainInfo.resolveInfo); 4490 return result; 4491 } 4492 } else if (result.size() <= 1) { 4493 return result; 4494 } 4495 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4496 xpDomainInfo); 4497 Collections.sort(result, mResolvePrioritySorter); 4498 } 4499 return result; 4500 } 4501 final PackageParser.Package pkg = mPackages.get(pkgName); 4502 if (pkg != null) { 4503 return filterIfNotPrimaryUser( 4504 mActivities.queryIntentForPackage( 4505 intent, resolvedType, flags, pkg.activities, userId), 4506 userId); 4507 } 4508 return new ArrayList<ResolveInfo>(); 4509 } 4510 } 4511 4512 private static class CrossProfileDomainInfo { 4513 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4514 ResolveInfo resolveInfo; 4515 /* Best domain verification status of the activities found in the other profile */ 4516 int bestDomainVerificationStatus; 4517 } 4518 4519 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4520 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4521 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4522 sourceUserId)) { 4523 return null; 4524 } 4525 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4526 resolvedType, flags, parentUserId); 4527 4528 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4529 return null; 4530 } 4531 CrossProfileDomainInfo result = null; 4532 int size = resultTargetUser.size(); 4533 for (int i = 0; i < size; i++) { 4534 ResolveInfo riTargetUser = resultTargetUser.get(i); 4535 // Intent filter verification is only for filters that specify a host. So don't return 4536 // those that handle all web uris. 4537 if (riTargetUser.handleAllWebDataURI) { 4538 continue; 4539 } 4540 String packageName = riTargetUser.activityInfo.packageName; 4541 PackageSetting ps = mSettings.mPackages.get(packageName); 4542 if (ps == null) { 4543 continue; 4544 } 4545 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4546 if (result == null) { 4547 result = new CrossProfileDomainInfo(); 4548 result.resolveInfo = 4549 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4550 result.bestDomainVerificationStatus = status; 4551 } else { 4552 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4553 result.bestDomainVerificationStatus); 4554 } 4555 } 4556 return result; 4557 } 4558 4559 /** 4560 * Verification statuses are ordered from the worse to the best, except for 4561 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4562 */ 4563 private int bestDomainVerificationStatus(int status1, int status2) { 4564 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4565 return status2; 4566 } 4567 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4568 return status1; 4569 } 4570 return (int) MathUtils.max(status1, status2); 4571 } 4572 4573 private boolean isUserEnabled(int userId) { 4574 long callingId = Binder.clearCallingIdentity(); 4575 try { 4576 UserInfo userInfo = sUserManager.getUserInfo(userId); 4577 return userInfo != null && userInfo.isEnabled(); 4578 } finally { 4579 Binder.restoreCallingIdentity(callingId); 4580 } 4581 } 4582 4583 /** 4584 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4585 * 4586 * @return filtered list 4587 */ 4588 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4589 if (userId == UserHandle.USER_OWNER) { 4590 return resolveInfos; 4591 } 4592 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4593 ResolveInfo info = resolveInfos.get(i); 4594 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4595 resolveInfos.remove(i); 4596 } 4597 } 4598 return resolveInfos; 4599 } 4600 4601 private static boolean hasWebURI(Intent intent) { 4602 if (intent.getData() == null) { 4603 return false; 4604 } 4605 final String scheme = intent.getScheme(); 4606 if (TextUtils.isEmpty(scheme)) { 4607 return false; 4608 } 4609 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4610 } 4611 4612 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4613 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4614 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4615 Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " + 4616 candidates.size()); 4617 } 4618 4619 final int userId = UserHandle.getCallingUserId(); 4620 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4621 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4622 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4623 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4624 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4625 4626 synchronized (mPackages) { 4627 final int count = candidates.size(); 4628 // First, try to use linked apps. Partition the candidates into four lists: 4629 // one for the final results, one for the "do not use ever", one for "undefined status" 4630 // and finally one for "browser app type". 4631 for (int n=0; n<count; n++) { 4632 ResolveInfo info = candidates.get(n); 4633 String packageName = info.activityInfo.packageName; 4634 PackageSetting ps = mSettings.mPackages.get(packageName); 4635 if (ps != null) { 4636 // Add to the special match all list (Browser use case) 4637 if (info.handleAllWebDataURI) { 4638 matchAllList.add(info); 4639 continue; 4640 } 4641 // Try to get the status from User settings first 4642 int status = getDomainVerificationStatusLPr(ps, userId); 4643 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4644 if (DEBUG_DOMAIN_VERIFICATION) { 4645 Slog.i(TAG, " + always: " + info.activityInfo.packageName); 4646 } 4647 alwaysList.add(info); 4648 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4649 if (DEBUG_DOMAIN_VERIFICATION) { 4650 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 4651 } 4652 neverList.add(info); 4653 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4654 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4655 if (DEBUG_DOMAIN_VERIFICATION) { 4656 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 4657 } 4658 undefinedList.add(info); 4659 } 4660 } 4661 } 4662 // First try to add the "always" resolution for the current user if there is any 4663 if (alwaysList.size() > 0) { 4664 result.addAll(alwaysList); 4665 // if there is an "always" for the parent user, add it. 4666 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4667 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4668 result.add(xpDomainInfo.resolveInfo); 4669 } else { 4670 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4671 result.addAll(undefinedList); 4672 if (xpDomainInfo != null && ( 4673 xpDomainInfo.bestDomainVerificationStatus 4674 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4675 || xpDomainInfo.bestDomainVerificationStatus 4676 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4677 result.add(xpDomainInfo.resolveInfo); 4678 } 4679 // Also add Browsers (all of them or only the default one) 4680 if ((flags & MATCH_ALL) != 0) { 4681 result.addAll(matchAllList); 4682 } else { 4683 // Try to add the Default Browser if we can 4684 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4685 UserHandle.myUserId()); 4686 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4687 boolean defaultBrowserFound = false; 4688 final int browserCount = matchAllList.size(); 4689 for (int n=0; n<browserCount; n++) { 4690 ResolveInfo browser = matchAllList.get(n); 4691 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4692 result.add(browser); 4693 defaultBrowserFound = true; 4694 break; 4695 } 4696 } 4697 if (!defaultBrowserFound) { 4698 result.addAll(matchAllList); 4699 } 4700 } else { 4701 result.addAll(matchAllList); 4702 } 4703 } 4704 4705 // If there is nothing selected, add all candidates and remove the ones that the user 4706 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4707 if (result.size() == 0) { 4708 result.addAll(candidates); 4709 result.removeAll(neverList); 4710 } 4711 } 4712 } 4713 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 4714 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 4715 result.size()); 4716 for (ResolveInfo info : result) { 4717 Slog.v(TAG, " + " + info.activityInfo); 4718 } 4719 } 4720 return result; 4721 } 4722 4723 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4724 int status = ps.getDomainVerificationStatusForUser(userId); 4725 // if none available, get the master status 4726 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4727 if (ps.getIntentFilterVerificationInfo() != null) { 4728 status = ps.getIntentFilterVerificationInfo().getStatus(); 4729 } 4730 } 4731 return status; 4732 } 4733 4734 private ResolveInfo querySkipCurrentProfileIntents( 4735 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4736 int flags, int sourceUserId) { 4737 if (matchingFilters != null) { 4738 int size = matchingFilters.size(); 4739 for (int i = 0; i < size; i ++) { 4740 CrossProfileIntentFilter filter = matchingFilters.get(i); 4741 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4742 // Checking if there are activities in the target user that can handle the 4743 // intent. 4744 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4745 flags, sourceUserId); 4746 if (resolveInfo != null) { 4747 return resolveInfo; 4748 } 4749 } 4750 } 4751 } 4752 return null; 4753 } 4754 4755 // Return matching ResolveInfo if any for skip current profile intent filters. 4756 private ResolveInfo queryCrossProfileIntents( 4757 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4758 int flags, int sourceUserId) { 4759 if (matchingFilters != null) { 4760 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4761 // match the same intent. For performance reasons, it is better not to 4762 // run queryIntent twice for the same userId 4763 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4764 int size = matchingFilters.size(); 4765 for (int i = 0; i < size; i++) { 4766 CrossProfileIntentFilter filter = matchingFilters.get(i); 4767 int targetUserId = filter.getTargetUserId(); 4768 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4769 && !alreadyTriedUserIds.get(targetUserId)) { 4770 // Checking if there are activities in the target user that can handle the 4771 // intent. 4772 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4773 flags, sourceUserId); 4774 if (resolveInfo != null) return resolveInfo; 4775 alreadyTriedUserIds.put(targetUserId, true); 4776 } 4777 } 4778 } 4779 return null; 4780 } 4781 4782 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4783 String resolvedType, int flags, int sourceUserId) { 4784 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4785 resolvedType, flags, filter.getTargetUserId()); 4786 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4787 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4788 } 4789 return null; 4790 } 4791 4792 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4793 int sourceUserId, int targetUserId) { 4794 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4795 String className; 4796 if (targetUserId == UserHandle.USER_OWNER) { 4797 className = FORWARD_INTENT_TO_USER_OWNER; 4798 } else { 4799 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4800 } 4801 ComponentName forwardingActivityComponentName = new ComponentName( 4802 mAndroidApplication.packageName, className); 4803 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4804 sourceUserId); 4805 if (targetUserId == UserHandle.USER_OWNER) { 4806 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4807 forwardingResolveInfo.noResourceId = true; 4808 } 4809 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4810 forwardingResolveInfo.priority = 0; 4811 forwardingResolveInfo.preferredOrder = 0; 4812 forwardingResolveInfo.match = 0; 4813 forwardingResolveInfo.isDefault = true; 4814 forwardingResolveInfo.filter = filter; 4815 forwardingResolveInfo.targetUserId = targetUserId; 4816 return forwardingResolveInfo; 4817 } 4818 4819 @Override 4820 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4821 Intent[] specifics, String[] specificTypes, Intent intent, 4822 String resolvedType, int flags, int userId) { 4823 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4824 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4825 false, "query intent activity options"); 4826 final String resultsAction = intent.getAction(); 4827 4828 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4829 | PackageManager.GET_RESOLVED_FILTER, userId); 4830 4831 if (DEBUG_INTENT_MATCHING) { 4832 Log.v(TAG, "Query " + intent + ": " + results); 4833 } 4834 4835 int specificsPos = 0; 4836 int N; 4837 4838 // todo: note that the algorithm used here is O(N^2). This 4839 // isn't a problem in our current environment, but if we start running 4840 // into situations where we have more than 5 or 10 matches then this 4841 // should probably be changed to something smarter... 4842 4843 // First we go through and resolve each of the specific items 4844 // that were supplied, taking care of removing any corresponding 4845 // duplicate items in the generic resolve list. 4846 if (specifics != null) { 4847 for (int i=0; i<specifics.length; i++) { 4848 final Intent sintent = specifics[i]; 4849 if (sintent == null) { 4850 continue; 4851 } 4852 4853 if (DEBUG_INTENT_MATCHING) { 4854 Log.v(TAG, "Specific #" + i + ": " + sintent); 4855 } 4856 4857 String action = sintent.getAction(); 4858 if (resultsAction != null && resultsAction.equals(action)) { 4859 // If this action was explicitly requested, then don't 4860 // remove things that have it. 4861 action = null; 4862 } 4863 4864 ResolveInfo ri = null; 4865 ActivityInfo ai = null; 4866 4867 ComponentName comp = sintent.getComponent(); 4868 if (comp == null) { 4869 ri = resolveIntent( 4870 sintent, 4871 specificTypes != null ? specificTypes[i] : null, 4872 flags, userId); 4873 if (ri == null) { 4874 continue; 4875 } 4876 if (ri == mResolveInfo) { 4877 // ACK! Must do something better with this. 4878 } 4879 ai = ri.activityInfo; 4880 comp = new ComponentName(ai.applicationInfo.packageName, 4881 ai.name); 4882 } else { 4883 ai = getActivityInfo(comp, flags, userId); 4884 if (ai == null) { 4885 continue; 4886 } 4887 } 4888 4889 // Look for any generic query activities that are duplicates 4890 // of this specific one, and remove them from the results. 4891 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4892 N = results.size(); 4893 int j; 4894 for (j=specificsPos; j<N; j++) { 4895 ResolveInfo sri = results.get(j); 4896 if ((sri.activityInfo.name.equals(comp.getClassName()) 4897 && sri.activityInfo.applicationInfo.packageName.equals( 4898 comp.getPackageName())) 4899 || (action != null && sri.filter.matchAction(action))) { 4900 results.remove(j); 4901 if (DEBUG_INTENT_MATCHING) Log.v( 4902 TAG, "Removing duplicate item from " + j 4903 + " due to specific " + specificsPos); 4904 if (ri == null) { 4905 ri = sri; 4906 } 4907 j--; 4908 N--; 4909 } 4910 } 4911 4912 // Add this specific item to its proper place. 4913 if (ri == null) { 4914 ri = new ResolveInfo(); 4915 ri.activityInfo = ai; 4916 } 4917 results.add(specificsPos, ri); 4918 ri.specificIndex = i; 4919 specificsPos++; 4920 } 4921 } 4922 4923 // Now we go through the remaining generic results and remove any 4924 // duplicate actions that are found here. 4925 N = results.size(); 4926 for (int i=specificsPos; i<N-1; i++) { 4927 final ResolveInfo rii = results.get(i); 4928 if (rii.filter == null) { 4929 continue; 4930 } 4931 4932 // Iterate over all of the actions of this result's intent 4933 // filter... typically this should be just one. 4934 final Iterator<String> it = rii.filter.actionsIterator(); 4935 if (it == null) { 4936 continue; 4937 } 4938 while (it.hasNext()) { 4939 final String action = it.next(); 4940 if (resultsAction != null && resultsAction.equals(action)) { 4941 // If this action was explicitly requested, then don't 4942 // remove things that have it. 4943 continue; 4944 } 4945 for (int j=i+1; j<N; j++) { 4946 final ResolveInfo rij = results.get(j); 4947 if (rij.filter != null && rij.filter.hasAction(action)) { 4948 results.remove(j); 4949 if (DEBUG_INTENT_MATCHING) Log.v( 4950 TAG, "Removing duplicate item from " + j 4951 + " due to action " + action + " at " + i); 4952 j--; 4953 N--; 4954 } 4955 } 4956 } 4957 4958 // If the caller didn't request filter information, drop it now 4959 // so we don't have to marshall/unmarshall it. 4960 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4961 rii.filter = null; 4962 } 4963 } 4964 4965 // Filter out the caller activity if so requested. 4966 if (caller != null) { 4967 N = results.size(); 4968 for (int i=0; i<N; i++) { 4969 ActivityInfo ainfo = results.get(i).activityInfo; 4970 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4971 && caller.getClassName().equals(ainfo.name)) { 4972 results.remove(i); 4973 break; 4974 } 4975 } 4976 } 4977 4978 // If the caller didn't request filter information, 4979 // drop them now so we don't have to 4980 // marshall/unmarshall it. 4981 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4982 N = results.size(); 4983 for (int i=0; i<N; i++) { 4984 results.get(i).filter = null; 4985 } 4986 } 4987 4988 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4989 return results; 4990 } 4991 4992 @Override 4993 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4994 int userId) { 4995 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4996 ComponentName comp = intent.getComponent(); 4997 if (comp == null) { 4998 if (intent.getSelector() != null) { 4999 intent = intent.getSelector(); 5000 comp = intent.getComponent(); 5001 } 5002 } 5003 if (comp != null) { 5004 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5005 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5006 if (ai != null) { 5007 ResolveInfo ri = new ResolveInfo(); 5008 ri.activityInfo = ai; 5009 list.add(ri); 5010 } 5011 return list; 5012 } 5013 5014 // reader 5015 synchronized (mPackages) { 5016 String pkgName = intent.getPackage(); 5017 if (pkgName == null) { 5018 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5019 } 5020 final PackageParser.Package pkg = mPackages.get(pkgName); 5021 if (pkg != null) { 5022 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5023 userId); 5024 } 5025 return null; 5026 } 5027 } 5028 5029 @Override 5030 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5031 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5032 if (!sUserManager.exists(userId)) return null; 5033 if (query != null) { 5034 if (query.size() >= 1) { 5035 // If there is more than one service with the same priority, 5036 // just arbitrarily pick the first one. 5037 return query.get(0); 5038 } 5039 } 5040 return null; 5041 } 5042 5043 @Override 5044 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5045 int userId) { 5046 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5047 ComponentName comp = intent.getComponent(); 5048 if (comp == null) { 5049 if (intent.getSelector() != null) { 5050 intent = intent.getSelector(); 5051 comp = intent.getComponent(); 5052 } 5053 } 5054 if (comp != null) { 5055 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5056 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5057 if (si != null) { 5058 final ResolveInfo ri = new ResolveInfo(); 5059 ri.serviceInfo = si; 5060 list.add(ri); 5061 } 5062 return list; 5063 } 5064 5065 // reader 5066 synchronized (mPackages) { 5067 String pkgName = intent.getPackage(); 5068 if (pkgName == null) { 5069 return mServices.queryIntent(intent, resolvedType, flags, userId); 5070 } 5071 final PackageParser.Package pkg = mPackages.get(pkgName); 5072 if (pkg != null) { 5073 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5074 userId); 5075 } 5076 return null; 5077 } 5078 } 5079 5080 @Override 5081 public List<ResolveInfo> queryIntentContentProviders( 5082 Intent intent, String resolvedType, int flags, int userId) { 5083 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5084 ComponentName comp = intent.getComponent(); 5085 if (comp == null) { 5086 if (intent.getSelector() != null) { 5087 intent = intent.getSelector(); 5088 comp = intent.getComponent(); 5089 } 5090 } 5091 if (comp != null) { 5092 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5093 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5094 if (pi != null) { 5095 final ResolveInfo ri = new ResolveInfo(); 5096 ri.providerInfo = pi; 5097 list.add(ri); 5098 } 5099 return list; 5100 } 5101 5102 // reader 5103 synchronized (mPackages) { 5104 String pkgName = intent.getPackage(); 5105 if (pkgName == null) { 5106 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5107 } 5108 final PackageParser.Package pkg = mPackages.get(pkgName); 5109 if (pkg != null) { 5110 return mProviders.queryIntentForPackage( 5111 intent, resolvedType, flags, pkg.providers, userId); 5112 } 5113 return null; 5114 } 5115 } 5116 5117 @Override 5118 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5119 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5120 5121 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5122 5123 // writer 5124 synchronized (mPackages) { 5125 ArrayList<PackageInfo> list; 5126 if (listUninstalled) { 5127 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5128 for (PackageSetting ps : mSettings.mPackages.values()) { 5129 PackageInfo pi; 5130 if (ps.pkg != null) { 5131 pi = generatePackageInfo(ps.pkg, flags, userId); 5132 } else { 5133 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5134 } 5135 if (pi != null) { 5136 list.add(pi); 5137 } 5138 } 5139 } else { 5140 list = new ArrayList<PackageInfo>(mPackages.size()); 5141 for (PackageParser.Package p : mPackages.values()) { 5142 PackageInfo pi = generatePackageInfo(p, flags, userId); 5143 if (pi != null) { 5144 list.add(pi); 5145 } 5146 } 5147 } 5148 5149 return new ParceledListSlice<PackageInfo>(list); 5150 } 5151 } 5152 5153 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5154 String[] permissions, boolean[] tmp, int flags, int userId) { 5155 int numMatch = 0; 5156 final PermissionsState permissionsState = ps.getPermissionsState(); 5157 for (int i=0; i<permissions.length; i++) { 5158 final String permission = permissions[i]; 5159 if (permissionsState.hasPermission(permission, userId)) { 5160 tmp[i] = true; 5161 numMatch++; 5162 } else { 5163 tmp[i] = false; 5164 } 5165 } 5166 if (numMatch == 0) { 5167 return; 5168 } 5169 PackageInfo pi; 5170 if (ps.pkg != null) { 5171 pi = generatePackageInfo(ps.pkg, flags, userId); 5172 } else { 5173 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5174 } 5175 // The above might return null in cases of uninstalled apps or install-state 5176 // skew across users/profiles. 5177 if (pi != null) { 5178 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5179 if (numMatch == permissions.length) { 5180 pi.requestedPermissions = permissions; 5181 } else { 5182 pi.requestedPermissions = new String[numMatch]; 5183 numMatch = 0; 5184 for (int i=0; i<permissions.length; i++) { 5185 if (tmp[i]) { 5186 pi.requestedPermissions[numMatch] = permissions[i]; 5187 numMatch++; 5188 } 5189 } 5190 } 5191 } 5192 list.add(pi); 5193 } 5194 } 5195 5196 @Override 5197 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5198 String[] permissions, int flags, int userId) { 5199 if (!sUserManager.exists(userId)) return null; 5200 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5201 5202 // writer 5203 synchronized (mPackages) { 5204 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5205 boolean[] tmpBools = new boolean[permissions.length]; 5206 if (listUninstalled) { 5207 for (PackageSetting ps : mSettings.mPackages.values()) { 5208 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5209 } 5210 } else { 5211 for (PackageParser.Package pkg : mPackages.values()) { 5212 PackageSetting ps = (PackageSetting)pkg.mExtras; 5213 if (ps != null) { 5214 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5215 userId); 5216 } 5217 } 5218 } 5219 5220 return new ParceledListSlice<PackageInfo>(list); 5221 } 5222 } 5223 5224 @Override 5225 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5226 if (!sUserManager.exists(userId)) return null; 5227 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 5228 5229 // writer 5230 synchronized (mPackages) { 5231 ArrayList<ApplicationInfo> list; 5232 if (listUninstalled) { 5233 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5234 for (PackageSetting ps : mSettings.mPackages.values()) { 5235 ApplicationInfo ai; 5236 if (ps.pkg != null) { 5237 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5238 ps.readUserState(userId), userId); 5239 } else { 5240 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5241 } 5242 if (ai != null) { 5243 list.add(ai); 5244 } 5245 } 5246 } else { 5247 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5248 for (PackageParser.Package p : mPackages.values()) { 5249 if (p.mExtras != null) { 5250 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5251 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5252 if (ai != null) { 5253 list.add(ai); 5254 } 5255 } 5256 } 5257 } 5258 5259 return new ParceledListSlice<ApplicationInfo>(list); 5260 } 5261 } 5262 5263 public List<ApplicationInfo> getPersistentApplications(int flags) { 5264 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5265 5266 // reader 5267 synchronized (mPackages) { 5268 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5269 final int userId = UserHandle.getCallingUserId(); 5270 while (i.hasNext()) { 5271 final PackageParser.Package p = i.next(); 5272 if (p.applicationInfo != null 5273 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5274 && (!mSafeMode || isSystemApp(p))) { 5275 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5276 if (ps != null) { 5277 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5278 ps.readUserState(userId), userId); 5279 if (ai != null) { 5280 finalList.add(ai); 5281 } 5282 } 5283 } 5284 } 5285 } 5286 5287 return finalList; 5288 } 5289 5290 @Override 5291 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5292 if (!sUserManager.exists(userId)) return null; 5293 // reader 5294 synchronized (mPackages) { 5295 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5296 PackageSetting ps = provider != null 5297 ? mSettings.mPackages.get(provider.owner.packageName) 5298 : null; 5299 return ps != null 5300 && mSettings.isEnabledLPr(provider.info, flags, userId) 5301 && (!mSafeMode || (provider.info.applicationInfo.flags 5302 &ApplicationInfo.FLAG_SYSTEM) != 0) 5303 ? PackageParser.generateProviderInfo(provider, flags, 5304 ps.readUserState(userId), userId) 5305 : null; 5306 } 5307 } 5308 5309 /** 5310 * @deprecated 5311 */ 5312 @Deprecated 5313 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5314 // reader 5315 synchronized (mPackages) { 5316 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5317 .entrySet().iterator(); 5318 final int userId = UserHandle.getCallingUserId(); 5319 while (i.hasNext()) { 5320 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5321 PackageParser.Provider p = entry.getValue(); 5322 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5323 5324 if (ps != null && p.syncable 5325 && (!mSafeMode || (p.info.applicationInfo.flags 5326 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5327 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5328 ps.readUserState(userId), userId); 5329 if (info != null) { 5330 outNames.add(entry.getKey()); 5331 outInfo.add(info); 5332 } 5333 } 5334 } 5335 } 5336 } 5337 5338 @Override 5339 public List<ProviderInfo> queryContentProviders(String processName, 5340 int uid, int flags) { 5341 ArrayList<ProviderInfo> finalList = null; 5342 // reader 5343 synchronized (mPackages) { 5344 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5345 final int userId = processName != null ? 5346 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5347 while (i.hasNext()) { 5348 final PackageParser.Provider p = i.next(); 5349 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5350 if (ps != null && p.info.authority != null 5351 && (processName == null 5352 || (p.info.processName.equals(processName) 5353 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5354 && mSettings.isEnabledLPr(p.info, flags, userId) 5355 && (!mSafeMode 5356 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5357 if (finalList == null) { 5358 finalList = new ArrayList<ProviderInfo>(3); 5359 } 5360 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5361 ps.readUserState(userId), userId); 5362 if (info != null) { 5363 finalList.add(info); 5364 } 5365 } 5366 } 5367 } 5368 5369 if (finalList != null) { 5370 Collections.sort(finalList, mProviderInitOrderSorter); 5371 } 5372 5373 return finalList; 5374 } 5375 5376 @Override 5377 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5378 int flags) { 5379 // reader 5380 synchronized (mPackages) { 5381 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5382 return PackageParser.generateInstrumentationInfo(i, flags); 5383 } 5384 } 5385 5386 @Override 5387 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5388 int flags) { 5389 ArrayList<InstrumentationInfo> finalList = 5390 new ArrayList<InstrumentationInfo>(); 5391 5392 // reader 5393 synchronized (mPackages) { 5394 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5395 while (i.hasNext()) { 5396 final PackageParser.Instrumentation p = i.next(); 5397 if (targetPackage == null 5398 || targetPackage.equals(p.info.targetPackage)) { 5399 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5400 flags); 5401 if (ii != null) { 5402 finalList.add(ii); 5403 } 5404 } 5405 } 5406 } 5407 5408 return finalList; 5409 } 5410 5411 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5412 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5413 if (overlays == null) { 5414 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5415 return; 5416 } 5417 for (PackageParser.Package opkg : overlays.values()) { 5418 // Not much to do if idmap fails: we already logged the error 5419 // and we certainly don't want to abort installation of pkg simply 5420 // because an overlay didn't fit properly. For these reasons, 5421 // ignore the return value of createIdmapForPackagePairLI. 5422 createIdmapForPackagePairLI(pkg, opkg); 5423 } 5424 } 5425 5426 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5427 PackageParser.Package opkg) { 5428 if (!opkg.mTrustedOverlay) { 5429 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5430 opkg.baseCodePath + ": overlay not trusted"); 5431 return false; 5432 } 5433 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5434 if (overlaySet == null) { 5435 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5436 opkg.baseCodePath + " but target package has no known overlays"); 5437 return false; 5438 } 5439 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5440 // TODO: generate idmap for split APKs 5441 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5442 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5443 + opkg.baseCodePath); 5444 return false; 5445 } 5446 PackageParser.Package[] overlayArray = 5447 overlaySet.values().toArray(new PackageParser.Package[0]); 5448 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5449 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5450 return p1.mOverlayPriority - p2.mOverlayPriority; 5451 } 5452 }; 5453 Arrays.sort(overlayArray, cmp); 5454 5455 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5456 int i = 0; 5457 for (PackageParser.Package p : overlayArray) { 5458 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5459 } 5460 return true; 5461 } 5462 5463 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5464 final File[] files = dir.listFiles(); 5465 if (ArrayUtils.isEmpty(files)) { 5466 Log.d(TAG, "No files in app dir " + dir); 5467 return; 5468 } 5469 5470 if (DEBUG_PACKAGE_SCANNING) { 5471 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5472 + " flags=0x" + Integer.toHexString(parseFlags)); 5473 } 5474 5475 for (File file : files) { 5476 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5477 && !PackageInstallerService.isStageName(file.getName()); 5478 if (!isPackage) { 5479 // Ignore entries which are not packages 5480 continue; 5481 } 5482 try { 5483 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5484 scanFlags, currentTime, null); 5485 } catch (PackageManagerException e) { 5486 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5487 5488 // Delete invalid userdata apps 5489 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5490 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5491 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5492 if (file.isDirectory()) { 5493 mInstaller.rmPackageDir(file.getAbsolutePath()); 5494 } else { 5495 file.delete(); 5496 } 5497 } 5498 } 5499 } 5500 } 5501 5502 private static File getSettingsProblemFile() { 5503 File dataDir = Environment.getDataDirectory(); 5504 File systemDir = new File(dataDir, "system"); 5505 File fname = new File(systemDir, "uiderrors.txt"); 5506 return fname; 5507 } 5508 5509 static void reportSettingsProblem(int priority, String msg) { 5510 logCriticalInfo(priority, msg); 5511 } 5512 5513 static void logCriticalInfo(int priority, String msg) { 5514 Slog.println(priority, TAG, msg); 5515 EventLogTags.writePmCriticalInfo(msg); 5516 try { 5517 File fname = getSettingsProblemFile(); 5518 FileOutputStream out = new FileOutputStream(fname, true); 5519 PrintWriter pw = new FastPrintWriter(out); 5520 SimpleDateFormat formatter = new SimpleDateFormat(); 5521 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5522 pw.println(dateString + ": " + msg); 5523 pw.close(); 5524 FileUtils.setPermissions( 5525 fname.toString(), 5526 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5527 -1, -1); 5528 } catch (java.io.IOException e) { 5529 } 5530 } 5531 5532 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5533 PackageParser.Package pkg, File srcFile, int parseFlags) 5534 throws PackageManagerException { 5535 if (ps != null 5536 && ps.codePath.equals(srcFile) 5537 && ps.timeStamp == srcFile.lastModified() 5538 && !isCompatSignatureUpdateNeeded(pkg) 5539 && !isRecoverSignatureUpdateNeeded(pkg)) { 5540 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5541 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5542 ArraySet<PublicKey> signingKs; 5543 synchronized (mPackages) { 5544 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5545 } 5546 if (ps.signatures.mSignatures != null 5547 && ps.signatures.mSignatures.length != 0 5548 && signingKs != null) { 5549 // Optimization: reuse the existing cached certificates 5550 // if the package appears to be unchanged. 5551 pkg.mSignatures = ps.signatures.mSignatures; 5552 pkg.mSigningKeys = signingKs; 5553 return; 5554 } 5555 5556 Slog.w(TAG, "PackageSetting for " + ps.name 5557 + " is missing signatures. Collecting certs again to recover them."); 5558 } else { 5559 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5560 } 5561 5562 try { 5563 pp.collectCertificates(pkg, parseFlags); 5564 pp.collectManifestDigest(pkg); 5565 } catch (PackageParserException e) { 5566 throw PackageManagerException.from(e); 5567 } 5568 } 5569 5570 /* 5571 * Scan a package and return the newly parsed package. 5572 * Returns null in case of errors and the error code is stored in mLastScanError 5573 */ 5574 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5575 long currentTime, UserHandle user) throws PackageManagerException { 5576 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5577 parseFlags |= mDefParseFlags; 5578 PackageParser pp = new PackageParser(); 5579 pp.setSeparateProcesses(mSeparateProcesses); 5580 pp.setOnlyCoreApps(mOnlyCore); 5581 pp.setDisplayMetrics(mMetrics); 5582 5583 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5584 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5585 } 5586 5587 final PackageParser.Package pkg; 5588 try { 5589 pkg = pp.parsePackage(scanFile, parseFlags); 5590 } catch (PackageParserException e) { 5591 throw PackageManagerException.from(e); 5592 } 5593 5594 PackageSetting ps = null; 5595 PackageSetting updatedPkg; 5596 // reader 5597 synchronized (mPackages) { 5598 // Look to see if we already know about this package. 5599 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5600 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5601 // This package has been renamed to its original name. Let's 5602 // use that. 5603 ps = mSettings.peekPackageLPr(oldName); 5604 } 5605 // If there was no original package, see one for the real package name. 5606 if (ps == null) { 5607 ps = mSettings.peekPackageLPr(pkg.packageName); 5608 } 5609 // Check to see if this package could be hiding/updating a system 5610 // package. Must look for it either under the original or real 5611 // package name depending on our state. 5612 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5613 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5614 } 5615 boolean updatedPkgBetter = false; 5616 // First check if this is a system package that may involve an update 5617 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5618 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5619 // it needs to drop FLAG_PRIVILEGED. 5620 if (locationIsPrivileged(scanFile)) { 5621 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5622 } else { 5623 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5624 } 5625 5626 if (ps != null && !ps.codePath.equals(scanFile)) { 5627 // The path has changed from what was last scanned... check the 5628 // version of the new path against what we have stored to determine 5629 // what to do. 5630 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5631 if (pkg.mVersionCode <= ps.versionCode) { 5632 // The system package has been updated and the code path does not match 5633 // Ignore entry. Skip it. 5634 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5635 + " ignored: updated version " + ps.versionCode 5636 + " better than this " + pkg.mVersionCode); 5637 if (!updatedPkg.codePath.equals(scanFile)) { 5638 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5639 + ps.name + " changing from " + updatedPkg.codePathString 5640 + " to " + scanFile); 5641 updatedPkg.codePath = scanFile; 5642 updatedPkg.codePathString = scanFile.toString(); 5643 updatedPkg.resourcePath = scanFile; 5644 updatedPkg.resourcePathString = scanFile.toString(); 5645 } 5646 updatedPkg.pkg = pkg; 5647 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5648 } else { 5649 // The current app on the system partition is better than 5650 // what we have updated to on the data partition; switch 5651 // back to the system partition version. 5652 // At this point, its safely assumed that package installation for 5653 // apps in system partition will go through. If not there won't be a working 5654 // version of the app 5655 // writer 5656 synchronized (mPackages) { 5657 // Just remove the loaded entries from package lists. 5658 mPackages.remove(ps.name); 5659 } 5660 5661 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5662 + " reverting from " + ps.codePathString 5663 + ": new version " + pkg.mVersionCode 5664 + " better than installed " + ps.versionCode); 5665 5666 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5667 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5668 synchronized (mInstallLock) { 5669 args.cleanUpResourcesLI(); 5670 } 5671 synchronized (mPackages) { 5672 mSettings.enableSystemPackageLPw(ps.name); 5673 } 5674 updatedPkgBetter = true; 5675 } 5676 } 5677 } 5678 5679 if (updatedPkg != null) { 5680 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5681 // initially 5682 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5683 5684 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5685 // flag set initially 5686 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5687 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5688 } 5689 } 5690 5691 // Verify certificates against what was last scanned 5692 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5693 5694 /* 5695 * A new system app appeared, but we already had a non-system one of the 5696 * same name installed earlier. 5697 */ 5698 boolean shouldHideSystemApp = false; 5699 if (updatedPkg == null && ps != null 5700 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5701 /* 5702 * Check to make sure the signatures match first. If they don't, 5703 * wipe the installed application and its data. 5704 */ 5705 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5706 != PackageManager.SIGNATURE_MATCH) { 5707 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5708 + " signatures don't match existing userdata copy; removing"); 5709 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5710 ps = null; 5711 } else { 5712 /* 5713 * If the newly-added system app is an older version than the 5714 * already installed version, hide it. It will be scanned later 5715 * and re-added like an update. 5716 */ 5717 if (pkg.mVersionCode <= ps.versionCode) { 5718 shouldHideSystemApp = true; 5719 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5720 + " but new version " + pkg.mVersionCode + " better than installed " 5721 + ps.versionCode + "; hiding system"); 5722 } else { 5723 /* 5724 * The newly found system app is a newer version that the 5725 * one previously installed. Simply remove the 5726 * already-installed application and replace it with our own 5727 * while keeping the application data. 5728 */ 5729 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5730 + " reverting from " + ps.codePathString + ": new version " 5731 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5732 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5733 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5734 synchronized (mInstallLock) { 5735 args.cleanUpResourcesLI(); 5736 } 5737 } 5738 } 5739 } 5740 5741 // The apk is forward locked (not public) if its code and resources 5742 // are kept in different files. (except for app in either system or 5743 // vendor path). 5744 // TODO grab this value from PackageSettings 5745 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5746 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5747 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5748 } 5749 } 5750 5751 // TODO: extend to support forward-locked splits 5752 String resourcePath = null; 5753 String baseResourcePath = null; 5754 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5755 if (ps != null && ps.resourcePathString != null) { 5756 resourcePath = ps.resourcePathString; 5757 baseResourcePath = ps.resourcePathString; 5758 } else { 5759 // Should not happen at all. Just log an error. 5760 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5761 } 5762 } else { 5763 resourcePath = pkg.codePath; 5764 baseResourcePath = pkg.baseCodePath; 5765 } 5766 5767 // Set application objects path explicitly. 5768 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5769 pkg.applicationInfo.setCodePath(pkg.codePath); 5770 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5771 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5772 pkg.applicationInfo.setResourcePath(resourcePath); 5773 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5774 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5775 5776 // Note that we invoke the following method only if we are about to unpack an application 5777 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5778 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5779 5780 /* 5781 * If the system app should be overridden by a previously installed 5782 * data, hide the system app now and let the /data/app scan pick it up 5783 * again. 5784 */ 5785 if (shouldHideSystemApp) { 5786 synchronized (mPackages) { 5787 /* 5788 * We have to grant systems permissions before we hide, because 5789 * grantPermissions will assume the package update is trying to 5790 * expand its permissions. 5791 */ 5792 grantPermissionsLPw(pkg, true, pkg.packageName); 5793 mSettings.disableSystemPackageLPw(pkg.packageName); 5794 } 5795 } 5796 5797 return scannedPkg; 5798 } 5799 5800 private static String fixProcessName(String defProcessName, 5801 String processName, int uid) { 5802 if (processName == null) { 5803 return defProcessName; 5804 } 5805 return processName; 5806 } 5807 5808 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5809 throws PackageManagerException { 5810 if (pkgSetting.signatures.mSignatures != null) { 5811 // Already existing package. Make sure signatures match 5812 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5813 == PackageManager.SIGNATURE_MATCH; 5814 if (!match) { 5815 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5816 == PackageManager.SIGNATURE_MATCH; 5817 } 5818 if (!match) { 5819 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5820 == PackageManager.SIGNATURE_MATCH; 5821 } 5822 if (!match) { 5823 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5824 + pkg.packageName + " signatures do not match the " 5825 + "previously installed version; ignoring!"); 5826 } 5827 } 5828 5829 // Check for shared user signatures 5830 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5831 // Already existing package. Make sure signatures match 5832 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5833 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5834 if (!match) { 5835 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5836 == PackageManager.SIGNATURE_MATCH; 5837 } 5838 if (!match) { 5839 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5840 == PackageManager.SIGNATURE_MATCH; 5841 } 5842 if (!match) { 5843 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5844 "Package " + pkg.packageName 5845 + " has no signatures that match those in shared user " 5846 + pkgSetting.sharedUser.name + "; ignoring!"); 5847 } 5848 } 5849 } 5850 5851 /** 5852 * Enforces that only the system UID or root's UID can call a method exposed 5853 * via Binder. 5854 * 5855 * @param message used as message if SecurityException is thrown 5856 * @throws SecurityException if the caller is not system or root 5857 */ 5858 private static final void enforceSystemOrRoot(String message) { 5859 final int uid = Binder.getCallingUid(); 5860 if (uid != Process.SYSTEM_UID && uid != 0) { 5861 throw new SecurityException(message); 5862 } 5863 } 5864 5865 @Override 5866 public void performBootDexOpt() { 5867 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5868 5869 // Before everything else, see whether we need to fstrim. 5870 try { 5871 IMountService ms = PackageHelper.getMountService(); 5872 if (ms != null) { 5873 final boolean isUpgrade = isUpgrade(); 5874 boolean doTrim = isUpgrade; 5875 if (doTrim) { 5876 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5877 } else { 5878 final long interval = android.provider.Settings.Global.getLong( 5879 mContext.getContentResolver(), 5880 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5881 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5882 if (interval > 0) { 5883 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5884 if (timeSinceLast > interval) { 5885 doTrim = true; 5886 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5887 + "; running immediately"); 5888 } 5889 } 5890 } 5891 if (doTrim) { 5892 if (!isFirstBoot()) { 5893 try { 5894 ActivityManagerNative.getDefault().showBootMessage( 5895 mContext.getResources().getString( 5896 R.string.android_upgrading_fstrim), true); 5897 } catch (RemoteException e) { 5898 } 5899 } 5900 ms.runMaintenance(); 5901 } 5902 } else { 5903 Slog.e(TAG, "Mount service unavailable!"); 5904 } 5905 } catch (RemoteException e) { 5906 // Can't happen; MountService is local 5907 } 5908 5909 final ArraySet<PackageParser.Package> pkgs; 5910 synchronized (mPackages) { 5911 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5912 } 5913 5914 if (pkgs != null) { 5915 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5916 // in case the device runs out of space. 5917 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5918 // Give priority to core apps. 5919 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5920 PackageParser.Package pkg = it.next(); 5921 if (pkg.coreApp) { 5922 if (DEBUG_DEXOPT) { 5923 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5924 } 5925 sortedPkgs.add(pkg); 5926 it.remove(); 5927 } 5928 } 5929 // Give priority to system apps that listen for pre boot complete. 5930 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5931 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5932 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5933 PackageParser.Package pkg = it.next(); 5934 if (pkgNames.contains(pkg.packageName)) { 5935 if (DEBUG_DEXOPT) { 5936 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5937 } 5938 sortedPkgs.add(pkg); 5939 it.remove(); 5940 } 5941 } 5942 // Give priority to system apps. 5943 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5944 PackageParser.Package pkg = it.next(); 5945 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5946 if (DEBUG_DEXOPT) { 5947 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5948 } 5949 sortedPkgs.add(pkg); 5950 it.remove(); 5951 } 5952 } 5953 // Give priority to updated system apps. 5954 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5955 PackageParser.Package pkg = it.next(); 5956 if (pkg.isUpdatedSystemApp()) { 5957 if (DEBUG_DEXOPT) { 5958 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5959 } 5960 sortedPkgs.add(pkg); 5961 it.remove(); 5962 } 5963 } 5964 // Give priority to apps that listen for boot complete. 5965 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5966 pkgNames = getPackageNamesForIntent(intent); 5967 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5968 PackageParser.Package pkg = it.next(); 5969 if (pkgNames.contains(pkg.packageName)) { 5970 if (DEBUG_DEXOPT) { 5971 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5972 } 5973 sortedPkgs.add(pkg); 5974 it.remove(); 5975 } 5976 } 5977 // Filter out packages that aren't recently used. 5978 filterRecentlyUsedApps(pkgs); 5979 // Add all remaining apps. 5980 for (PackageParser.Package pkg : pkgs) { 5981 if (DEBUG_DEXOPT) { 5982 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5983 } 5984 sortedPkgs.add(pkg); 5985 } 5986 5987 // If we want to be lazy, filter everything that wasn't recently used. 5988 if (mLazyDexOpt) { 5989 filterRecentlyUsedApps(sortedPkgs); 5990 } 5991 5992 int i = 0; 5993 int total = sortedPkgs.size(); 5994 File dataDir = Environment.getDataDirectory(); 5995 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5996 if (lowThreshold == 0) { 5997 throw new IllegalStateException("Invalid low memory threshold"); 5998 } 5999 for (PackageParser.Package pkg : sortedPkgs) { 6000 long usableSpace = dataDir.getUsableSpace(); 6001 if (usableSpace < lowThreshold) { 6002 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 6003 break; 6004 } 6005 performBootDexOpt(pkg, ++i, total); 6006 } 6007 } 6008 } 6009 6010 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 6011 // Filter out packages that aren't recently used. 6012 // 6013 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 6014 // should do a full dexopt. 6015 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 6016 int total = pkgs.size(); 6017 int skipped = 0; 6018 long now = System.currentTimeMillis(); 6019 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 6020 PackageParser.Package pkg = i.next(); 6021 long then = pkg.mLastPackageUsageTimeInMills; 6022 if (then + mDexOptLRUThresholdInMills < now) { 6023 if (DEBUG_DEXOPT) { 6024 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 6025 ((then == 0) ? "never" : new Date(then))); 6026 } 6027 i.remove(); 6028 skipped++; 6029 } 6030 } 6031 if (DEBUG_DEXOPT) { 6032 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 6033 } 6034 } 6035 } 6036 6037 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 6038 List<ResolveInfo> ris = null; 6039 try { 6040 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6041 intent, null, 0, UserHandle.USER_OWNER); 6042 } catch (RemoteException e) { 6043 } 6044 ArraySet<String> pkgNames = new ArraySet<String>(); 6045 if (ris != null) { 6046 for (ResolveInfo ri : ris) { 6047 pkgNames.add(ri.activityInfo.packageName); 6048 } 6049 } 6050 return pkgNames; 6051 } 6052 6053 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 6054 if (DEBUG_DEXOPT) { 6055 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 6056 } 6057 if (!isFirstBoot()) { 6058 try { 6059 ActivityManagerNative.getDefault().showBootMessage( 6060 mContext.getResources().getString(R.string.android_upgrading_apk, 6061 curr, total), true); 6062 } catch (RemoteException e) { 6063 } 6064 } 6065 PackageParser.Package p = pkg; 6066 synchronized (mInstallLock) { 6067 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 6068 false /* force dex */, false /* defer */, true /* include dependencies */); 6069 } 6070 } 6071 6072 @Override 6073 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6074 return performDexOpt(packageName, instructionSet, false); 6075 } 6076 6077 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 6078 boolean dexopt = mLazyDexOpt || backgroundDexopt; 6079 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 6080 if (!dexopt && !updateUsage) { 6081 // We aren't going to dexopt or update usage, so bail early. 6082 return false; 6083 } 6084 PackageParser.Package p; 6085 final String targetInstructionSet; 6086 synchronized (mPackages) { 6087 p = mPackages.get(packageName); 6088 if (p == null) { 6089 return false; 6090 } 6091 if (updateUsage) { 6092 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6093 } 6094 mPackageUsage.write(false); 6095 if (!dexopt) { 6096 // We aren't going to dexopt, so bail early. 6097 return false; 6098 } 6099 6100 targetInstructionSet = instructionSet != null ? instructionSet : 6101 getPrimaryInstructionSet(p.applicationInfo); 6102 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6103 return false; 6104 } 6105 } 6106 6107 synchronized (mInstallLock) { 6108 final String[] instructionSets = new String[] { targetInstructionSet }; 6109 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6110 false /* forceDex */, false /* defer */, true /* inclDependencies */); 6111 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6112 } 6113 } 6114 6115 public ArraySet<String> getPackagesThatNeedDexOpt() { 6116 ArraySet<String> pkgs = null; 6117 synchronized (mPackages) { 6118 for (PackageParser.Package p : mPackages.values()) { 6119 if (DEBUG_DEXOPT) { 6120 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6121 } 6122 if (!p.mDexOptPerformed.isEmpty()) { 6123 continue; 6124 } 6125 if (pkgs == null) { 6126 pkgs = new ArraySet<String>(); 6127 } 6128 pkgs.add(p.packageName); 6129 } 6130 } 6131 return pkgs; 6132 } 6133 6134 public void shutdown() { 6135 mPackageUsage.write(true); 6136 } 6137 6138 @Override 6139 public void forceDexOpt(String packageName) { 6140 enforceSystemOrRoot("forceDexOpt"); 6141 6142 PackageParser.Package pkg; 6143 synchronized (mPackages) { 6144 pkg = mPackages.get(packageName); 6145 if (pkg == null) { 6146 throw new IllegalArgumentException("Missing package: " + packageName); 6147 } 6148 } 6149 6150 synchronized (mInstallLock) { 6151 final String[] instructionSets = new String[] { 6152 getPrimaryInstructionSet(pkg.applicationInfo) }; 6153 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6154 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 6155 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6156 throw new IllegalStateException("Failed to dexopt: " + res); 6157 } 6158 } 6159 } 6160 6161 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6162 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6163 Slog.w(TAG, "Unable to update from " + oldPkg.name 6164 + " to " + newPkg.packageName 6165 + ": old package not in system partition"); 6166 return false; 6167 } else if (mPackages.get(oldPkg.name) != null) { 6168 Slog.w(TAG, "Unable to update from " + oldPkg.name 6169 + " to " + newPkg.packageName 6170 + ": old package still exists"); 6171 return false; 6172 } 6173 return true; 6174 } 6175 6176 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 6177 int[] users = sUserManager.getUserIds(); 6178 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6179 if (res < 0) { 6180 return res; 6181 } 6182 for (int user : users) { 6183 if (user != 0) { 6184 res = mInstaller.createUserData(volumeUuid, packageName, 6185 UserHandle.getUid(user, uid), user, seinfo); 6186 if (res < 0) { 6187 return res; 6188 } 6189 } 6190 } 6191 return res; 6192 } 6193 6194 private int removeDataDirsLI(String volumeUuid, String packageName) { 6195 int[] users = sUserManager.getUserIds(); 6196 int res = 0; 6197 for (int user : users) { 6198 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6199 if (resInner < 0) { 6200 res = resInner; 6201 } 6202 } 6203 6204 return res; 6205 } 6206 6207 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6208 int[] users = sUserManager.getUserIds(); 6209 int res = 0; 6210 for (int user : users) { 6211 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6212 if (resInner < 0) { 6213 res = resInner; 6214 } 6215 } 6216 return res; 6217 } 6218 6219 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6220 PackageParser.Package changingLib) { 6221 if (file.path != null) { 6222 usesLibraryFiles.add(file.path); 6223 return; 6224 } 6225 PackageParser.Package p = mPackages.get(file.apk); 6226 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6227 // If we are doing this while in the middle of updating a library apk, 6228 // then we need to make sure to use that new apk for determining the 6229 // dependencies here. (We haven't yet finished committing the new apk 6230 // to the package manager state.) 6231 if (p == null || p.packageName.equals(changingLib.packageName)) { 6232 p = changingLib; 6233 } 6234 } 6235 if (p != null) { 6236 usesLibraryFiles.addAll(p.getAllCodePaths()); 6237 } 6238 } 6239 6240 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6241 PackageParser.Package changingLib) throws PackageManagerException { 6242 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6243 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6244 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6245 for (int i=0; i<N; i++) { 6246 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6247 if (file == null) { 6248 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6249 "Package " + pkg.packageName + " requires unavailable shared library " 6250 + pkg.usesLibraries.get(i) + "; failing!"); 6251 } 6252 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6253 } 6254 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6255 for (int i=0; i<N; i++) { 6256 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6257 if (file == null) { 6258 Slog.w(TAG, "Package " + pkg.packageName 6259 + " desires unavailable shared library " 6260 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6261 } else { 6262 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6263 } 6264 } 6265 N = usesLibraryFiles.size(); 6266 if (N > 0) { 6267 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6268 } else { 6269 pkg.usesLibraryFiles = null; 6270 } 6271 } 6272 } 6273 6274 private static boolean hasString(List<String> list, List<String> which) { 6275 if (list == null) { 6276 return false; 6277 } 6278 for (int i=list.size()-1; i>=0; i--) { 6279 for (int j=which.size()-1; j>=0; j--) { 6280 if (which.get(j).equals(list.get(i))) { 6281 return true; 6282 } 6283 } 6284 } 6285 return false; 6286 } 6287 6288 private void updateAllSharedLibrariesLPw() { 6289 for (PackageParser.Package pkg : mPackages.values()) { 6290 try { 6291 updateSharedLibrariesLPw(pkg, null); 6292 } catch (PackageManagerException e) { 6293 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6294 } 6295 } 6296 } 6297 6298 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6299 PackageParser.Package changingPkg) { 6300 ArrayList<PackageParser.Package> res = null; 6301 for (PackageParser.Package pkg : mPackages.values()) { 6302 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6303 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6304 if (res == null) { 6305 res = new ArrayList<PackageParser.Package>(); 6306 } 6307 res.add(pkg); 6308 try { 6309 updateSharedLibrariesLPw(pkg, changingPkg); 6310 } catch (PackageManagerException e) { 6311 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6312 } 6313 } 6314 } 6315 return res; 6316 } 6317 6318 /** 6319 * Derive the value of the {@code cpuAbiOverride} based on the provided 6320 * value and an optional stored value from the package settings. 6321 */ 6322 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6323 String cpuAbiOverride = null; 6324 6325 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6326 cpuAbiOverride = null; 6327 } else if (abiOverride != null) { 6328 cpuAbiOverride = abiOverride; 6329 } else if (settings != null) { 6330 cpuAbiOverride = settings.cpuAbiOverrideString; 6331 } 6332 6333 return cpuAbiOverride; 6334 } 6335 6336 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6337 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6338 boolean success = false; 6339 try { 6340 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6341 currentTime, user); 6342 success = true; 6343 return res; 6344 } finally { 6345 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6346 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6347 } 6348 } 6349 } 6350 6351 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6352 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6353 final File scanFile = new File(pkg.codePath); 6354 if (pkg.applicationInfo.getCodePath() == null || 6355 pkg.applicationInfo.getResourcePath() == null) { 6356 // Bail out. The resource and code paths haven't been set. 6357 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6358 "Code and resource paths haven't been set correctly"); 6359 } 6360 6361 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6362 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6363 } else { 6364 // Only allow system apps to be flagged as core apps. 6365 pkg.coreApp = false; 6366 } 6367 6368 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6369 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6370 } 6371 6372 if (mCustomResolverComponentName != null && 6373 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6374 setUpCustomResolverActivity(pkg); 6375 } 6376 6377 if (pkg.packageName.equals("android")) { 6378 synchronized (mPackages) { 6379 if (mAndroidApplication != null) { 6380 Slog.w(TAG, "*************************************************"); 6381 Slog.w(TAG, "Core android package being redefined. Skipping."); 6382 Slog.w(TAG, " file=" + scanFile); 6383 Slog.w(TAG, "*************************************************"); 6384 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6385 "Core android package being redefined. Skipping."); 6386 } 6387 6388 // Set up information for our fall-back user intent resolution activity. 6389 mPlatformPackage = pkg; 6390 pkg.mVersionCode = mSdkVersion; 6391 mAndroidApplication = pkg.applicationInfo; 6392 6393 if (!mResolverReplaced) { 6394 mResolveActivity.applicationInfo = mAndroidApplication; 6395 mResolveActivity.name = ResolverActivity.class.getName(); 6396 mResolveActivity.packageName = mAndroidApplication.packageName; 6397 mResolveActivity.processName = "system:ui"; 6398 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6399 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6400 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6401 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6402 mResolveActivity.exported = true; 6403 mResolveActivity.enabled = true; 6404 mResolveInfo.activityInfo = mResolveActivity; 6405 mResolveInfo.priority = 0; 6406 mResolveInfo.preferredOrder = 0; 6407 mResolveInfo.match = 0; 6408 mResolveComponentName = new ComponentName( 6409 mAndroidApplication.packageName, mResolveActivity.name); 6410 } 6411 } 6412 } 6413 6414 if (DEBUG_PACKAGE_SCANNING) { 6415 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6416 Log.d(TAG, "Scanning package " + pkg.packageName); 6417 } 6418 6419 if (mPackages.containsKey(pkg.packageName) 6420 || mSharedLibraries.containsKey(pkg.packageName)) { 6421 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6422 "Application package " + pkg.packageName 6423 + " already installed. Skipping duplicate."); 6424 } 6425 6426 // If we're only installing presumed-existing packages, require that the 6427 // scanned APK is both already known and at the path previously established 6428 // for it. Previously unknown packages we pick up normally, but if we have an 6429 // a priori expectation about this package's install presence, enforce it. 6430 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6431 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6432 if (known != null) { 6433 if (DEBUG_PACKAGE_SCANNING) { 6434 Log.d(TAG, "Examining " + pkg.codePath 6435 + " and requiring known paths " + known.codePathString 6436 + " & " + known.resourcePathString); 6437 } 6438 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6439 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6440 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6441 "Application package " + pkg.packageName 6442 + " found at " + pkg.applicationInfo.getCodePath() 6443 + " but expected at " + known.codePathString + "; ignoring."); 6444 } 6445 } 6446 } 6447 6448 // Initialize package source and resource directories 6449 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6450 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6451 6452 SharedUserSetting suid = null; 6453 PackageSetting pkgSetting = null; 6454 6455 if (!isSystemApp(pkg)) { 6456 // Only system apps can use these features. 6457 pkg.mOriginalPackages = null; 6458 pkg.mRealPackage = null; 6459 pkg.mAdoptPermissions = null; 6460 } 6461 6462 // writer 6463 synchronized (mPackages) { 6464 if (pkg.mSharedUserId != null) { 6465 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6466 if (suid == null) { 6467 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6468 "Creating application package " + pkg.packageName 6469 + " for shared user failed"); 6470 } 6471 if (DEBUG_PACKAGE_SCANNING) { 6472 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6473 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6474 + "): packages=" + suid.packages); 6475 } 6476 } 6477 6478 // Check if we are renaming from an original package name. 6479 PackageSetting origPackage = null; 6480 String realName = null; 6481 if (pkg.mOriginalPackages != null) { 6482 // This package may need to be renamed to a previously 6483 // installed name. Let's check on that... 6484 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6485 if (pkg.mOriginalPackages.contains(renamed)) { 6486 // This package had originally been installed as the 6487 // original name, and we have already taken care of 6488 // transitioning to the new one. Just update the new 6489 // one to continue using the old name. 6490 realName = pkg.mRealPackage; 6491 if (!pkg.packageName.equals(renamed)) { 6492 // Callers into this function may have already taken 6493 // care of renaming the package; only do it here if 6494 // it is not already done. 6495 pkg.setPackageName(renamed); 6496 } 6497 6498 } else { 6499 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6500 if ((origPackage = mSettings.peekPackageLPr( 6501 pkg.mOriginalPackages.get(i))) != null) { 6502 // We do have the package already installed under its 6503 // original name... should we use it? 6504 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6505 // New package is not compatible with original. 6506 origPackage = null; 6507 continue; 6508 } else if (origPackage.sharedUser != null) { 6509 // Make sure uid is compatible between packages. 6510 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6511 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6512 + " to " + pkg.packageName + ": old uid " 6513 + origPackage.sharedUser.name 6514 + " differs from " + pkg.mSharedUserId); 6515 origPackage = null; 6516 continue; 6517 } 6518 } else { 6519 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6520 + pkg.packageName + " to old name " + origPackage.name); 6521 } 6522 break; 6523 } 6524 } 6525 } 6526 } 6527 6528 if (mTransferedPackages.contains(pkg.packageName)) { 6529 Slog.w(TAG, "Package " + pkg.packageName 6530 + " was transferred to another, but its .apk remains"); 6531 } 6532 6533 // Just create the setting, don't add it yet. For already existing packages 6534 // the PkgSetting exists already and doesn't have to be created. 6535 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6536 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6537 pkg.applicationInfo.primaryCpuAbi, 6538 pkg.applicationInfo.secondaryCpuAbi, 6539 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6540 user, false); 6541 if (pkgSetting == null) { 6542 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6543 "Creating application package " + pkg.packageName + " failed"); 6544 } 6545 6546 if (pkgSetting.origPackage != null) { 6547 // If we are first transitioning from an original package, 6548 // fix up the new package's name now. We need to do this after 6549 // looking up the package under its new name, so getPackageLP 6550 // can take care of fiddling things correctly. 6551 pkg.setPackageName(origPackage.name); 6552 6553 // File a report about this. 6554 String msg = "New package " + pkgSetting.realName 6555 + " renamed to replace old package " + pkgSetting.name; 6556 reportSettingsProblem(Log.WARN, msg); 6557 6558 // Make a note of it. 6559 mTransferedPackages.add(origPackage.name); 6560 6561 // No longer need to retain this. 6562 pkgSetting.origPackage = null; 6563 } 6564 6565 if (realName != null) { 6566 // Make a note of it. 6567 mTransferedPackages.add(pkg.packageName); 6568 } 6569 6570 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6571 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6572 } 6573 6574 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6575 // Check all shared libraries and map to their actual file path. 6576 // We only do this here for apps not on a system dir, because those 6577 // are the only ones that can fail an install due to this. We 6578 // will take care of the system apps by updating all of their 6579 // library paths after the scan is done. 6580 updateSharedLibrariesLPw(pkg, null); 6581 } 6582 6583 if (mFoundPolicyFile) { 6584 SELinuxMMAC.assignSeinfoValue(pkg); 6585 } 6586 6587 pkg.applicationInfo.uid = pkgSetting.appId; 6588 pkg.mExtras = pkgSetting; 6589 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6590 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6591 // We just determined the app is signed correctly, so bring 6592 // over the latest parsed certs. 6593 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6594 } else { 6595 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6596 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6597 "Package " + pkg.packageName + " upgrade keys do not match the " 6598 + "previously installed version"); 6599 } else { 6600 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6601 String msg = "System package " + pkg.packageName 6602 + " signature changed; retaining data."; 6603 reportSettingsProblem(Log.WARN, msg); 6604 } 6605 } 6606 } else { 6607 try { 6608 verifySignaturesLP(pkgSetting, pkg); 6609 // We just determined the app is signed correctly, so bring 6610 // over the latest parsed certs. 6611 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6612 } catch (PackageManagerException e) { 6613 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6614 throw e; 6615 } 6616 // The signature has changed, but this package is in the system 6617 // image... let's recover! 6618 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6619 // However... if this package is part of a shared user, but it 6620 // doesn't match the signature of the shared user, let's fail. 6621 // What this means is that you can't change the signatures 6622 // associated with an overall shared user, which doesn't seem all 6623 // that unreasonable. 6624 if (pkgSetting.sharedUser != null) { 6625 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6626 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6627 throw new PackageManagerException( 6628 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6629 "Signature mismatch for shared user : " 6630 + pkgSetting.sharedUser); 6631 } 6632 } 6633 // File a report about this. 6634 String msg = "System package " + pkg.packageName 6635 + " signature changed; retaining data."; 6636 reportSettingsProblem(Log.WARN, msg); 6637 } 6638 } 6639 // Verify that this new package doesn't have any content providers 6640 // that conflict with existing packages. Only do this if the 6641 // package isn't already installed, since we don't want to break 6642 // things that are installed. 6643 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6644 final int N = pkg.providers.size(); 6645 int i; 6646 for (i=0; i<N; i++) { 6647 PackageParser.Provider p = pkg.providers.get(i); 6648 if (p.info.authority != null) { 6649 String names[] = p.info.authority.split(";"); 6650 for (int j = 0; j < names.length; j++) { 6651 if (mProvidersByAuthority.containsKey(names[j])) { 6652 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6653 final String otherPackageName = 6654 ((other != null && other.getComponentName() != null) ? 6655 other.getComponentName().getPackageName() : "?"); 6656 throw new PackageManagerException( 6657 INSTALL_FAILED_CONFLICTING_PROVIDER, 6658 "Can't install because provider name " + names[j] 6659 + " (in package " + pkg.applicationInfo.packageName 6660 + ") is already used by " + otherPackageName); 6661 } 6662 } 6663 } 6664 } 6665 } 6666 6667 if (pkg.mAdoptPermissions != null) { 6668 // This package wants to adopt ownership of permissions from 6669 // another package. 6670 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6671 final String origName = pkg.mAdoptPermissions.get(i); 6672 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6673 if (orig != null) { 6674 if (verifyPackageUpdateLPr(orig, pkg)) { 6675 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6676 + pkg.packageName); 6677 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6678 } 6679 } 6680 } 6681 } 6682 } 6683 6684 final String pkgName = pkg.packageName; 6685 6686 final long scanFileTime = scanFile.lastModified(); 6687 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6688 pkg.applicationInfo.processName = fixProcessName( 6689 pkg.applicationInfo.packageName, 6690 pkg.applicationInfo.processName, 6691 pkg.applicationInfo.uid); 6692 6693 File dataPath; 6694 if (mPlatformPackage == pkg) { 6695 // The system package is special. 6696 dataPath = new File(Environment.getDataDirectory(), "system"); 6697 6698 pkg.applicationInfo.dataDir = dataPath.getPath(); 6699 6700 } else { 6701 // This is a normal package, need to make its data directory. 6702 dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid, 6703 UserHandle.USER_OWNER, pkg.packageName); 6704 6705 boolean uidError = false; 6706 if (dataPath.exists()) { 6707 int currentUid = 0; 6708 try { 6709 StructStat stat = Os.stat(dataPath.getPath()); 6710 currentUid = stat.st_uid; 6711 } catch (ErrnoException e) { 6712 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6713 } 6714 6715 // If we have mismatched owners for the data path, we have a problem. 6716 if (currentUid != pkg.applicationInfo.uid) { 6717 boolean recovered = false; 6718 if (currentUid == 0) { 6719 // The directory somehow became owned by root. Wow. 6720 // This is probably because the system was stopped while 6721 // installd was in the middle of messing with its libs 6722 // directory. Ask installd to fix that. 6723 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6724 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6725 if (ret >= 0) { 6726 recovered = true; 6727 String msg = "Package " + pkg.packageName 6728 + " unexpectedly changed to uid 0; recovered to " + 6729 + pkg.applicationInfo.uid; 6730 reportSettingsProblem(Log.WARN, msg); 6731 } 6732 } 6733 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6734 || (scanFlags&SCAN_BOOTING) != 0)) { 6735 // If this is a system app, we can at least delete its 6736 // current data so the application will still work. 6737 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6738 if (ret >= 0) { 6739 // TODO: Kill the processes first 6740 // Old data gone! 6741 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6742 ? "System package " : "Third party package "; 6743 String msg = prefix + pkg.packageName 6744 + " has changed from uid: " 6745 + currentUid + " to " 6746 + pkg.applicationInfo.uid + "; old data erased"; 6747 reportSettingsProblem(Log.WARN, msg); 6748 recovered = true; 6749 6750 // And now re-install the app. 6751 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6752 pkg.applicationInfo.seinfo); 6753 if (ret == -1) { 6754 // Ack should not happen! 6755 msg = prefix + pkg.packageName 6756 + " could not have data directory re-created after delete."; 6757 reportSettingsProblem(Log.WARN, msg); 6758 throw new PackageManagerException( 6759 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6760 } 6761 } 6762 if (!recovered) { 6763 mHasSystemUidErrors = true; 6764 } 6765 } else if (!recovered) { 6766 // If we allow this install to proceed, we will be broken. 6767 // Abort, abort! 6768 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6769 "scanPackageLI"); 6770 } 6771 if (!recovered) { 6772 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6773 + pkg.applicationInfo.uid + "/fs_" 6774 + currentUid; 6775 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6776 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6777 String msg = "Package " + pkg.packageName 6778 + " has mismatched uid: " 6779 + currentUid + " on disk, " 6780 + pkg.applicationInfo.uid + " in settings"; 6781 // writer 6782 synchronized (mPackages) { 6783 mSettings.mReadMessages.append(msg); 6784 mSettings.mReadMessages.append('\n'); 6785 uidError = true; 6786 if (!pkgSetting.uidError) { 6787 reportSettingsProblem(Log.ERROR, msg); 6788 } 6789 } 6790 } 6791 } 6792 pkg.applicationInfo.dataDir = dataPath.getPath(); 6793 if (mShouldRestoreconData) { 6794 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6795 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6796 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6797 } 6798 } else { 6799 if (DEBUG_PACKAGE_SCANNING) { 6800 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6801 Log.v(TAG, "Want this data dir: " + dataPath); 6802 } 6803 //invoke installer to do the actual installation 6804 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6805 pkg.applicationInfo.seinfo); 6806 if (ret < 0) { 6807 // Error from installer 6808 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6809 "Unable to create data dirs [errorCode=" + ret + "]"); 6810 } 6811 6812 if (dataPath.exists()) { 6813 pkg.applicationInfo.dataDir = dataPath.getPath(); 6814 } else { 6815 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6816 pkg.applicationInfo.dataDir = null; 6817 } 6818 } 6819 6820 pkgSetting.uidError = uidError; 6821 } 6822 6823 final String path = scanFile.getPath(); 6824 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6825 6826 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6827 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6828 6829 // Some system apps still use directory structure for native libraries 6830 // in which case we might end up not detecting abi solely based on apk 6831 // structure. Try to detect abi based on directory structure. 6832 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6833 pkg.applicationInfo.primaryCpuAbi == null) { 6834 setBundledAppAbisAndRoots(pkg, pkgSetting); 6835 setNativeLibraryPaths(pkg); 6836 } 6837 6838 } else { 6839 if ((scanFlags & SCAN_MOVE) != 0) { 6840 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6841 // but we already have this packages package info in the PackageSetting. We just 6842 // use that and derive the native library path based on the new codepath. 6843 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6844 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6845 } 6846 6847 // Set native library paths again. For moves, the path will be updated based on the 6848 // ABIs we've determined above. For non-moves, the path will be updated based on the 6849 // ABIs we determined during compilation, but the path will depend on the final 6850 // package path (after the rename away from the stage path). 6851 setNativeLibraryPaths(pkg); 6852 } 6853 6854 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6855 final int[] userIds = sUserManager.getUserIds(); 6856 synchronized (mInstallLock) { 6857 // Make sure all user data directories are ready to roll; we're okay 6858 // if they already exist 6859 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 6860 for (int userId : userIds) { 6861 if (userId != 0) { 6862 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 6863 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 6864 pkg.applicationInfo.seinfo); 6865 } 6866 } 6867 } 6868 6869 // Create a native library symlink only if we have native libraries 6870 // and if the native libraries are 32 bit libraries. We do not provide 6871 // this symlink for 64 bit libraries. 6872 if (pkg.applicationInfo.primaryCpuAbi != null && 6873 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6874 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6875 for (int userId : userIds) { 6876 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6877 nativeLibPath, userId) < 0) { 6878 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6879 "Failed linking native library dir (user=" + userId + ")"); 6880 } 6881 } 6882 } 6883 } 6884 6885 // This is a special case for the "system" package, where the ABI is 6886 // dictated by the zygote configuration (and init.rc). We should keep track 6887 // of this ABI so that we can deal with "normal" applications that run under 6888 // the same UID correctly. 6889 if (mPlatformPackage == pkg) { 6890 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6891 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6892 } 6893 6894 // If there's a mismatch between the abi-override in the package setting 6895 // and the abiOverride specified for the install. Warn about this because we 6896 // would've already compiled the app without taking the package setting into 6897 // account. 6898 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6899 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6900 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6901 " for package: " + pkg.packageName); 6902 } 6903 } 6904 6905 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6906 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6907 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6908 6909 // Copy the derived override back to the parsed package, so that we can 6910 // update the package settings accordingly. 6911 pkg.cpuAbiOverride = cpuAbiOverride; 6912 6913 if (DEBUG_ABI_SELECTION) { 6914 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6915 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6916 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6917 } 6918 6919 // Push the derived path down into PackageSettings so we know what to 6920 // clean up at uninstall time. 6921 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6922 6923 if (DEBUG_ABI_SELECTION) { 6924 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6925 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6926 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6927 } 6928 6929 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6930 // We don't do this here during boot because we can do it all 6931 // at once after scanning all existing packages. 6932 // 6933 // We also do this *before* we perform dexopt on this package, so that 6934 // we can avoid redundant dexopts, and also to make sure we've got the 6935 // code and package path correct. 6936 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6937 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6938 } 6939 6940 if ((scanFlags & SCAN_NO_DEX) == 0) { 6941 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6942 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6943 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6944 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6945 } 6946 } 6947 if (mFactoryTest && pkg.requestedPermissions.contains( 6948 android.Manifest.permission.FACTORY_TEST)) { 6949 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6950 } 6951 6952 ArrayList<PackageParser.Package> clientLibPkgs = null; 6953 6954 // writer 6955 synchronized (mPackages) { 6956 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6957 // Only system apps can add new shared libraries. 6958 if (pkg.libraryNames != null) { 6959 for (int i=0; i<pkg.libraryNames.size(); i++) { 6960 String name = pkg.libraryNames.get(i); 6961 boolean allowed = false; 6962 if (pkg.isUpdatedSystemApp()) { 6963 // New library entries can only be added through the 6964 // system image. This is important to get rid of a lot 6965 // of nasty edge cases: for example if we allowed a non- 6966 // system update of the app to add a library, then uninstalling 6967 // the update would make the library go away, and assumptions 6968 // we made such as through app install filtering would now 6969 // have allowed apps on the device which aren't compatible 6970 // with it. Better to just have the restriction here, be 6971 // conservative, and create many fewer cases that can negatively 6972 // impact the user experience. 6973 final PackageSetting sysPs = mSettings 6974 .getDisabledSystemPkgLPr(pkg.packageName); 6975 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6976 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6977 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6978 allowed = true; 6979 allowed = true; 6980 break; 6981 } 6982 } 6983 } 6984 } else { 6985 allowed = true; 6986 } 6987 if (allowed) { 6988 if (!mSharedLibraries.containsKey(name)) { 6989 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6990 } else if (!name.equals(pkg.packageName)) { 6991 Slog.w(TAG, "Package " + pkg.packageName + " library " 6992 + name + " already exists; skipping"); 6993 } 6994 } else { 6995 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6996 + name + " that is not declared on system image; skipping"); 6997 } 6998 } 6999 if ((scanFlags&SCAN_BOOTING) == 0) { 7000 // If we are not booting, we need to update any applications 7001 // that are clients of our shared library. If we are booting, 7002 // this will all be done once the scan is complete. 7003 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7004 } 7005 } 7006 } 7007 } 7008 7009 // We also need to dexopt any apps that are dependent on this library. Note that 7010 // if these fail, we should abort the install since installing the library will 7011 // result in some apps being broken. 7012 if (clientLibPkgs != null) { 7013 if ((scanFlags & SCAN_NO_DEX) == 0) { 7014 for (int i = 0; i < clientLibPkgs.size(); i++) { 7015 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7016 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 7017 null /* instruction sets */, forceDex, 7018 (scanFlags & SCAN_DEFER_DEX) != 0, false); 7019 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7020 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 7021 "scanPackageLI failed to dexopt clientLibPkgs"); 7022 } 7023 } 7024 } 7025 } 7026 7027 // Also need to kill any apps that are dependent on the library. 7028 if (clientLibPkgs != null) { 7029 for (int i=0; i<clientLibPkgs.size(); i++) { 7030 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7031 killApplication(clientPkg.applicationInfo.packageName, 7032 clientPkg.applicationInfo.uid, "update lib"); 7033 } 7034 } 7035 7036 // Make sure we're not adding any bogus keyset info 7037 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7038 ksms.assertScannedPackageValid(pkg); 7039 7040 // writer 7041 synchronized (mPackages) { 7042 // We don't expect installation to fail beyond this point 7043 7044 // Add the new setting to mSettings 7045 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7046 // Add the new setting to mPackages 7047 mPackages.put(pkg.applicationInfo.packageName, pkg); 7048 // Make sure we don't accidentally delete its data. 7049 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7050 while (iter.hasNext()) { 7051 PackageCleanItem item = iter.next(); 7052 if (pkgName.equals(item.packageName)) { 7053 iter.remove(); 7054 } 7055 } 7056 7057 // Take care of first install / last update times. 7058 if (currentTime != 0) { 7059 if (pkgSetting.firstInstallTime == 0) { 7060 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7061 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7062 pkgSetting.lastUpdateTime = currentTime; 7063 } 7064 } else if (pkgSetting.firstInstallTime == 0) { 7065 // We need *something*. Take time time stamp of the file. 7066 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7067 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7068 if (scanFileTime != pkgSetting.timeStamp) { 7069 // A package on the system image has changed; consider this 7070 // to be an update. 7071 pkgSetting.lastUpdateTime = scanFileTime; 7072 } 7073 } 7074 7075 // Add the package's KeySets to the global KeySetManagerService 7076 ksms.addScannedPackageLPw(pkg); 7077 7078 int N = pkg.providers.size(); 7079 StringBuilder r = null; 7080 int i; 7081 for (i=0; i<N; i++) { 7082 PackageParser.Provider p = pkg.providers.get(i); 7083 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7084 p.info.processName, pkg.applicationInfo.uid); 7085 mProviders.addProvider(p); 7086 p.syncable = p.info.isSyncable; 7087 if (p.info.authority != null) { 7088 String names[] = p.info.authority.split(";"); 7089 p.info.authority = null; 7090 for (int j = 0; j < names.length; j++) { 7091 if (j == 1 && p.syncable) { 7092 // We only want the first authority for a provider to possibly be 7093 // syncable, so if we already added this provider using a different 7094 // authority clear the syncable flag. We copy the provider before 7095 // changing it because the mProviders object contains a reference 7096 // to a provider that we don't want to change. 7097 // Only do this for the second authority since the resulting provider 7098 // object can be the same for all future authorities for this provider. 7099 p = new PackageParser.Provider(p); 7100 p.syncable = false; 7101 } 7102 if (!mProvidersByAuthority.containsKey(names[j])) { 7103 mProvidersByAuthority.put(names[j], p); 7104 if (p.info.authority == null) { 7105 p.info.authority = names[j]; 7106 } else { 7107 p.info.authority = p.info.authority + ";" + names[j]; 7108 } 7109 if (DEBUG_PACKAGE_SCANNING) { 7110 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7111 Log.d(TAG, "Registered content provider: " + names[j] 7112 + ", className = " + p.info.name + ", isSyncable = " 7113 + p.info.isSyncable); 7114 } 7115 } else { 7116 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7117 Slog.w(TAG, "Skipping provider name " + names[j] + 7118 " (in package " + pkg.applicationInfo.packageName + 7119 "): name already used by " 7120 + ((other != null && other.getComponentName() != null) 7121 ? other.getComponentName().getPackageName() : "?")); 7122 } 7123 } 7124 } 7125 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7126 if (r == null) { 7127 r = new StringBuilder(256); 7128 } else { 7129 r.append(' '); 7130 } 7131 r.append(p.info.name); 7132 } 7133 } 7134 if (r != null) { 7135 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7136 } 7137 7138 N = pkg.services.size(); 7139 r = null; 7140 for (i=0; i<N; i++) { 7141 PackageParser.Service s = pkg.services.get(i); 7142 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7143 s.info.processName, pkg.applicationInfo.uid); 7144 mServices.addService(s); 7145 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7146 if (r == null) { 7147 r = new StringBuilder(256); 7148 } else { 7149 r.append(' '); 7150 } 7151 r.append(s.info.name); 7152 } 7153 } 7154 if (r != null) { 7155 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7156 } 7157 7158 N = pkg.receivers.size(); 7159 r = null; 7160 for (i=0; i<N; i++) { 7161 PackageParser.Activity a = pkg.receivers.get(i); 7162 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7163 a.info.processName, pkg.applicationInfo.uid); 7164 mReceivers.addActivity(a, "receiver"); 7165 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7166 if (r == null) { 7167 r = new StringBuilder(256); 7168 } else { 7169 r.append(' '); 7170 } 7171 r.append(a.info.name); 7172 } 7173 } 7174 if (r != null) { 7175 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7176 } 7177 7178 N = pkg.activities.size(); 7179 r = null; 7180 for (i=0; i<N; i++) { 7181 PackageParser.Activity a = pkg.activities.get(i); 7182 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7183 a.info.processName, pkg.applicationInfo.uid); 7184 mActivities.addActivity(a, "activity"); 7185 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7186 if (r == null) { 7187 r = new StringBuilder(256); 7188 } else { 7189 r.append(' '); 7190 } 7191 r.append(a.info.name); 7192 } 7193 } 7194 if (r != null) { 7195 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7196 } 7197 7198 N = pkg.permissionGroups.size(); 7199 r = null; 7200 for (i=0; i<N; i++) { 7201 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7202 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7203 if (cur == null) { 7204 mPermissionGroups.put(pg.info.name, pg); 7205 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7206 if (r == null) { 7207 r = new StringBuilder(256); 7208 } else { 7209 r.append(' '); 7210 } 7211 r.append(pg.info.name); 7212 } 7213 } else { 7214 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7215 + pg.info.packageName + " ignored: original from " 7216 + cur.info.packageName); 7217 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7218 if (r == null) { 7219 r = new StringBuilder(256); 7220 } else { 7221 r.append(' '); 7222 } 7223 r.append("DUP:"); 7224 r.append(pg.info.name); 7225 } 7226 } 7227 } 7228 if (r != null) { 7229 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7230 } 7231 7232 N = pkg.permissions.size(); 7233 r = null; 7234 for (i=0; i<N; i++) { 7235 PackageParser.Permission p = pkg.permissions.get(i); 7236 7237 // Now that permission groups have a special meaning, we ignore permission 7238 // groups for legacy apps to prevent unexpected behavior. In particular, 7239 // permissions for one app being granted to someone just becuase they happen 7240 // to be in a group defined by another app (before this had no implications). 7241 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7242 p.group = mPermissionGroups.get(p.info.group); 7243 // Warn for a permission in an unknown group. 7244 if (p.info.group != null && p.group == null) { 7245 Slog.w(TAG, "Permission " + p.info.name + " from package " 7246 + p.info.packageName + " in an unknown group " + p.info.group); 7247 } 7248 } 7249 7250 ArrayMap<String, BasePermission> permissionMap = 7251 p.tree ? mSettings.mPermissionTrees 7252 : mSettings.mPermissions; 7253 BasePermission bp = permissionMap.get(p.info.name); 7254 7255 // Allow system apps to redefine non-system permissions 7256 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7257 final boolean currentOwnerIsSystem = (bp.perm != null 7258 && isSystemApp(bp.perm.owner)); 7259 if (isSystemApp(p.owner)) { 7260 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7261 // It's a built-in permission and no owner, take ownership now 7262 bp.packageSetting = pkgSetting; 7263 bp.perm = p; 7264 bp.uid = pkg.applicationInfo.uid; 7265 bp.sourcePackage = p.info.packageName; 7266 } else if (!currentOwnerIsSystem) { 7267 String msg = "New decl " + p.owner + " of permission " 7268 + p.info.name + " is system; overriding " + bp.sourcePackage; 7269 reportSettingsProblem(Log.WARN, msg); 7270 bp = null; 7271 } 7272 } 7273 } 7274 7275 if (bp == null) { 7276 bp = new BasePermission(p.info.name, p.info.packageName, 7277 BasePermission.TYPE_NORMAL); 7278 permissionMap.put(p.info.name, bp); 7279 } 7280 7281 if (bp.perm == null) { 7282 if (bp.sourcePackage == null 7283 || bp.sourcePackage.equals(p.info.packageName)) { 7284 BasePermission tree = findPermissionTreeLP(p.info.name); 7285 if (tree == null 7286 || tree.sourcePackage.equals(p.info.packageName)) { 7287 bp.packageSetting = pkgSetting; 7288 bp.perm = p; 7289 bp.uid = pkg.applicationInfo.uid; 7290 bp.sourcePackage = p.info.packageName; 7291 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7292 if (r == null) { 7293 r = new StringBuilder(256); 7294 } else { 7295 r.append(' '); 7296 } 7297 r.append(p.info.name); 7298 } 7299 } else { 7300 Slog.w(TAG, "Permission " + p.info.name + " from package " 7301 + p.info.packageName + " ignored: base tree " 7302 + tree.name + " is from package " 7303 + tree.sourcePackage); 7304 } 7305 } else { 7306 Slog.w(TAG, "Permission " + p.info.name + " from package " 7307 + p.info.packageName + " ignored: original from " 7308 + bp.sourcePackage); 7309 } 7310 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7311 if (r == null) { 7312 r = new StringBuilder(256); 7313 } else { 7314 r.append(' '); 7315 } 7316 r.append("DUP:"); 7317 r.append(p.info.name); 7318 } 7319 if (bp.perm == p) { 7320 bp.protectionLevel = p.info.protectionLevel; 7321 } 7322 } 7323 7324 if (r != null) { 7325 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7326 } 7327 7328 N = pkg.instrumentation.size(); 7329 r = null; 7330 for (i=0; i<N; i++) { 7331 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7332 a.info.packageName = pkg.applicationInfo.packageName; 7333 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7334 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7335 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7336 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7337 a.info.dataDir = pkg.applicationInfo.dataDir; 7338 7339 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7340 // need other information about the application, like the ABI and what not ? 7341 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7342 mInstrumentation.put(a.getComponentName(), a); 7343 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7344 if (r == null) { 7345 r = new StringBuilder(256); 7346 } else { 7347 r.append(' '); 7348 } 7349 r.append(a.info.name); 7350 } 7351 } 7352 if (r != null) { 7353 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7354 } 7355 7356 if (pkg.protectedBroadcasts != null) { 7357 N = pkg.protectedBroadcasts.size(); 7358 for (i=0; i<N; i++) { 7359 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7360 } 7361 } 7362 7363 pkgSetting.setTimeStamp(scanFileTime); 7364 7365 // Create idmap files for pairs of (packages, overlay packages). 7366 // Note: "android", ie framework-res.apk, is handled by native layers. 7367 if (pkg.mOverlayTarget != null) { 7368 // This is an overlay package. 7369 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7370 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7371 mOverlays.put(pkg.mOverlayTarget, 7372 new ArrayMap<String, PackageParser.Package>()); 7373 } 7374 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7375 map.put(pkg.packageName, pkg); 7376 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7377 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7378 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7379 "scanPackageLI failed to createIdmap"); 7380 } 7381 } 7382 } else if (mOverlays.containsKey(pkg.packageName) && 7383 !pkg.packageName.equals("android")) { 7384 // This is a regular package, with one or more known overlay packages. 7385 createIdmapsForPackageLI(pkg); 7386 } 7387 } 7388 7389 return pkg; 7390 } 7391 7392 /** 7393 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7394 * is derived purely on the basis of the contents of {@code scanFile} and 7395 * {@code cpuAbiOverride}. 7396 * 7397 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7398 */ 7399 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7400 String cpuAbiOverride, boolean extractLibs) 7401 throws PackageManagerException { 7402 // TODO: We can probably be smarter about this stuff. For installed apps, 7403 // we can calculate this information at install time once and for all. For 7404 // system apps, we can probably assume that this information doesn't change 7405 // after the first boot scan. As things stand, we do lots of unnecessary work. 7406 7407 // Give ourselves some initial paths; we'll come back for another 7408 // pass once we've determined ABI below. 7409 setNativeLibraryPaths(pkg); 7410 7411 // We would never need to extract libs for forward-locked and external packages, 7412 // since the container service will do it for us. We shouldn't attempt to 7413 // extract libs from system app when it was not updated. 7414 if (pkg.isForwardLocked() || isExternal(pkg) || 7415 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7416 extractLibs = false; 7417 } 7418 7419 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7420 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7421 7422 NativeLibraryHelper.Handle handle = null; 7423 try { 7424 handle = NativeLibraryHelper.Handle.create(pkg); 7425 // TODO(multiArch): This can be null for apps that didn't go through the 7426 // usual installation process. We can calculate it again, like we 7427 // do during install time. 7428 // 7429 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7430 // unnecessary. 7431 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7432 7433 // Null out the abis so that they can be recalculated. 7434 pkg.applicationInfo.primaryCpuAbi = null; 7435 pkg.applicationInfo.secondaryCpuAbi = null; 7436 if (isMultiArch(pkg.applicationInfo)) { 7437 // Warn if we've set an abiOverride for multi-lib packages.. 7438 // By definition, we need to copy both 32 and 64 bit libraries for 7439 // such packages. 7440 if (pkg.cpuAbiOverride != null 7441 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7442 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7443 } 7444 7445 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7446 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7447 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7448 if (extractLibs) { 7449 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7450 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7451 useIsaSpecificSubdirs); 7452 } else { 7453 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7454 } 7455 } 7456 7457 maybeThrowExceptionForMultiArchCopy( 7458 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7459 7460 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7461 if (extractLibs) { 7462 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7463 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7464 useIsaSpecificSubdirs); 7465 } else { 7466 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7467 } 7468 } 7469 7470 maybeThrowExceptionForMultiArchCopy( 7471 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7472 7473 if (abi64 >= 0) { 7474 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7475 } 7476 7477 if (abi32 >= 0) { 7478 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7479 if (abi64 >= 0) { 7480 pkg.applicationInfo.secondaryCpuAbi = abi; 7481 } else { 7482 pkg.applicationInfo.primaryCpuAbi = abi; 7483 } 7484 } 7485 } else { 7486 String[] abiList = (cpuAbiOverride != null) ? 7487 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7488 7489 // Enable gross and lame hacks for apps that are built with old 7490 // SDK tools. We must scan their APKs for renderscript bitcode and 7491 // not launch them if it's present. Don't bother checking on devices 7492 // that don't have 64 bit support. 7493 boolean needsRenderScriptOverride = false; 7494 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7495 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7496 abiList = Build.SUPPORTED_32_BIT_ABIS; 7497 needsRenderScriptOverride = true; 7498 } 7499 7500 final int copyRet; 7501 if (extractLibs) { 7502 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7503 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7504 } else { 7505 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7506 } 7507 7508 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7509 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7510 "Error unpackaging native libs for app, errorCode=" + copyRet); 7511 } 7512 7513 if (copyRet >= 0) { 7514 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7515 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7516 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7517 } else if (needsRenderScriptOverride) { 7518 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7519 } 7520 } 7521 } catch (IOException ioe) { 7522 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7523 } finally { 7524 IoUtils.closeQuietly(handle); 7525 } 7526 7527 // Now that we've calculated the ABIs and determined if it's an internal app, 7528 // we will go ahead and populate the nativeLibraryPath. 7529 setNativeLibraryPaths(pkg); 7530 } 7531 7532 /** 7533 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7534 * i.e, so that all packages can be run inside a single process if required. 7535 * 7536 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7537 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7538 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7539 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7540 * updating a package that belongs to a shared user. 7541 * 7542 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7543 * adds unnecessary complexity. 7544 */ 7545 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7546 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7547 String requiredInstructionSet = null; 7548 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7549 requiredInstructionSet = VMRuntime.getInstructionSet( 7550 scannedPackage.applicationInfo.primaryCpuAbi); 7551 } 7552 7553 PackageSetting requirer = null; 7554 for (PackageSetting ps : packagesForUser) { 7555 // If packagesForUser contains scannedPackage, we skip it. This will happen 7556 // when scannedPackage is an update of an existing package. Without this check, 7557 // we will never be able to change the ABI of any package belonging to a shared 7558 // user, even if it's compatible with other packages. 7559 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7560 if (ps.primaryCpuAbiString == null) { 7561 continue; 7562 } 7563 7564 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7565 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7566 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7567 // this but there's not much we can do. 7568 String errorMessage = "Instruction set mismatch, " 7569 + ((requirer == null) ? "[caller]" : requirer) 7570 + " requires " + requiredInstructionSet + " whereas " + ps 7571 + " requires " + instructionSet; 7572 Slog.w(TAG, errorMessage); 7573 } 7574 7575 if (requiredInstructionSet == null) { 7576 requiredInstructionSet = instructionSet; 7577 requirer = ps; 7578 } 7579 } 7580 } 7581 7582 if (requiredInstructionSet != null) { 7583 String adjustedAbi; 7584 if (requirer != null) { 7585 // requirer != null implies that either scannedPackage was null or that scannedPackage 7586 // did not require an ABI, in which case we have to adjust scannedPackage to match 7587 // the ABI of the set (which is the same as requirer's ABI) 7588 adjustedAbi = requirer.primaryCpuAbiString; 7589 if (scannedPackage != null) { 7590 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7591 } 7592 } else { 7593 // requirer == null implies that we're updating all ABIs in the set to 7594 // match scannedPackage. 7595 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7596 } 7597 7598 for (PackageSetting ps : packagesForUser) { 7599 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7600 if (ps.primaryCpuAbiString != null) { 7601 continue; 7602 } 7603 7604 ps.primaryCpuAbiString = adjustedAbi; 7605 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7606 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7607 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7608 7609 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7610 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7611 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7612 ps.primaryCpuAbiString = null; 7613 ps.pkg.applicationInfo.primaryCpuAbi = null; 7614 return; 7615 } else { 7616 mInstaller.rmdex(ps.codePathString, 7617 getDexCodeInstructionSet(getPreferredInstructionSet())); 7618 } 7619 } 7620 } 7621 } 7622 } 7623 } 7624 7625 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7626 synchronized (mPackages) { 7627 mResolverReplaced = true; 7628 // Set up information for custom user intent resolution activity. 7629 mResolveActivity.applicationInfo = pkg.applicationInfo; 7630 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7631 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7632 mResolveActivity.processName = pkg.applicationInfo.packageName; 7633 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7634 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7635 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7636 mResolveActivity.theme = 0; 7637 mResolveActivity.exported = true; 7638 mResolveActivity.enabled = true; 7639 mResolveInfo.activityInfo = mResolveActivity; 7640 mResolveInfo.priority = 0; 7641 mResolveInfo.preferredOrder = 0; 7642 mResolveInfo.match = 0; 7643 mResolveComponentName = mCustomResolverComponentName; 7644 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7645 mResolveComponentName); 7646 } 7647 } 7648 7649 private static String calculateBundledApkRoot(final String codePathString) { 7650 final File codePath = new File(codePathString); 7651 final File codeRoot; 7652 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7653 codeRoot = Environment.getRootDirectory(); 7654 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7655 codeRoot = Environment.getOemDirectory(); 7656 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7657 codeRoot = Environment.getVendorDirectory(); 7658 } else { 7659 // Unrecognized code path; take its top real segment as the apk root: 7660 // e.g. /something/app/blah.apk => /something 7661 try { 7662 File f = codePath.getCanonicalFile(); 7663 File parent = f.getParentFile(); // non-null because codePath is a file 7664 File tmp; 7665 while ((tmp = parent.getParentFile()) != null) { 7666 f = parent; 7667 parent = tmp; 7668 } 7669 codeRoot = f; 7670 Slog.w(TAG, "Unrecognized code path " 7671 + codePath + " - using " + codeRoot); 7672 } catch (IOException e) { 7673 // Can't canonicalize the code path -- shenanigans? 7674 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7675 return Environment.getRootDirectory().getPath(); 7676 } 7677 } 7678 return codeRoot.getPath(); 7679 } 7680 7681 /** 7682 * Derive and set the location of native libraries for the given package, 7683 * which varies depending on where and how the package was installed. 7684 */ 7685 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7686 final ApplicationInfo info = pkg.applicationInfo; 7687 final String codePath = pkg.codePath; 7688 final File codeFile = new File(codePath); 7689 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7690 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7691 7692 info.nativeLibraryRootDir = null; 7693 info.nativeLibraryRootRequiresIsa = false; 7694 info.nativeLibraryDir = null; 7695 info.secondaryNativeLibraryDir = null; 7696 7697 if (isApkFile(codeFile)) { 7698 // Monolithic install 7699 if (bundledApp) { 7700 // If "/system/lib64/apkname" exists, assume that is the per-package 7701 // native library directory to use; otherwise use "/system/lib/apkname". 7702 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7703 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7704 getPrimaryInstructionSet(info)); 7705 7706 // This is a bundled system app so choose the path based on the ABI. 7707 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7708 // is just the default path. 7709 final String apkName = deriveCodePathName(codePath); 7710 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7711 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7712 apkName).getAbsolutePath(); 7713 7714 if (info.secondaryCpuAbi != null) { 7715 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7716 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7717 secondaryLibDir, apkName).getAbsolutePath(); 7718 } 7719 } else if (asecApp) { 7720 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7721 .getAbsolutePath(); 7722 } else { 7723 final String apkName = deriveCodePathName(codePath); 7724 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7725 .getAbsolutePath(); 7726 } 7727 7728 info.nativeLibraryRootRequiresIsa = false; 7729 info.nativeLibraryDir = info.nativeLibraryRootDir; 7730 } else { 7731 // Cluster install 7732 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7733 info.nativeLibraryRootRequiresIsa = true; 7734 7735 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7736 getPrimaryInstructionSet(info)).getAbsolutePath(); 7737 7738 if (info.secondaryCpuAbi != null) { 7739 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7740 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7741 } 7742 } 7743 } 7744 7745 /** 7746 * Calculate the abis and roots for a bundled app. These can uniquely 7747 * be determined from the contents of the system partition, i.e whether 7748 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7749 * of this information, and instead assume that the system was built 7750 * sensibly. 7751 */ 7752 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7753 PackageSetting pkgSetting) { 7754 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7755 7756 // If "/system/lib64/apkname" exists, assume that is the per-package 7757 // native library directory to use; otherwise use "/system/lib/apkname". 7758 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7759 setBundledAppAbi(pkg, apkRoot, apkName); 7760 // pkgSetting might be null during rescan following uninstall of updates 7761 // to a bundled app, so accommodate that possibility. The settings in 7762 // that case will be established later from the parsed package. 7763 // 7764 // If the settings aren't null, sync them up with what we've just derived. 7765 // note that apkRoot isn't stored in the package settings. 7766 if (pkgSetting != null) { 7767 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7768 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7769 } 7770 } 7771 7772 /** 7773 * Deduces the ABI of a bundled app and sets the relevant fields on the 7774 * parsed pkg object. 7775 * 7776 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7777 * under which system libraries are installed. 7778 * @param apkName the name of the installed package. 7779 */ 7780 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7781 final File codeFile = new File(pkg.codePath); 7782 7783 final boolean has64BitLibs; 7784 final boolean has32BitLibs; 7785 if (isApkFile(codeFile)) { 7786 // Monolithic install 7787 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7788 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7789 } else { 7790 // Cluster install 7791 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7792 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7793 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7794 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7795 has64BitLibs = (new File(rootDir, isa)).exists(); 7796 } else { 7797 has64BitLibs = false; 7798 } 7799 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7800 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7801 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7802 has32BitLibs = (new File(rootDir, isa)).exists(); 7803 } else { 7804 has32BitLibs = false; 7805 } 7806 } 7807 7808 if (has64BitLibs && !has32BitLibs) { 7809 // The package has 64 bit libs, but not 32 bit libs. Its primary 7810 // ABI should be 64 bit. We can safely assume here that the bundled 7811 // native libraries correspond to the most preferred ABI in the list. 7812 7813 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7814 pkg.applicationInfo.secondaryCpuAbi = null; 7815 } else if (has32BitLibs && !has64BitLibs) { 7816 // The package has 32 bit libs but not 64 bit libs. Its primary 7817 // ABI should be 32 bit. 7818 7819 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7820 pkg.applicationInfo.secondaryCpuAbi = null; 7821 } else if (has32BitLibs && has64BitLibs) { 7822 // The application has both 64 and 32 bit bundled libraries. We check 7823 // here that the app declares multiArch support, and warn if it doesn't. 7824 // 7825 // We will be lenient here and record both ABIs. The primary will be the 7826 // ABI that's higher on the list, i.e, a device that's configured to prefer 7827 // 64 bit apps will see a 64 bit primary ABI, 7828 7829 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7830 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7831 } 7832 7833 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7834 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7835 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7836 } else { 7837 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7838 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7839 } 7840 } else { 7841 pkg.applicationInfo.primaryCpuAbi = null; 7842 pkg.applicationInfo.secondaryCpuAbi = null; 7843 } 7844 } 7845 7846 private void killApplication(String pkgName, int appId, String reason) { 7847 // Request the ActivityManager to kill the process(only for existing packages) 7848 // so that we do not end up in a confused state while the user is still using the older 7849 // version of the application while the new one gets installed. 7850 IActivityManager am = ActivityManagerNative.getDefault(); 7851 if (am != null) { 7852 try { 7853 am.killApplicationWithAppId(pkgName, appId, reason); 7854 } catch (RemoteException e) { 7855 } 7856 } 7857 } 7858 7859 void removePackageLI(PackageSetting ps, boolean chatty) { 7860 if (DEBUG_INSTALL) { 7861 if (chatty) 7862 Log.d(TAG, "Removing package " + ps.name); 7863 } 7864 7865 // writer 7866 synchronized (mPackages) { 7867 mPackages.remove(ps.name); 7868 final PackageParser.Package pkg = ps.pkg; 7869 if (pkg != null) { 7870 cleanPackageDataStructuresLILPw(pkg, chatty); 7871 } 7872 } 7873 } 7874 7875 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7876 if (DEBUG_INSTALL) { 7877 if (chatty) 7878 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7879 } 7880 7881 // writer 7882 synchronized (mPackages) { 7883 mPackages.remove(pkg.applicationInfo.packageName); 7884 cleanPackageDataStructuresLILPw(pkg, chatty); 7885 } 7886 } 7887 7888 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7889 int N = pkg.providers.size(); 7890 StringBuilder r = null; 7891 int i; 7892 for (i=0; i<N; i++) { 7893 PackageParser.Provider p = pkg.providers.get(i); 7894 mProviders.removeProvider(p); 7895 if (p.info.authority == null) { 7896 7897 /* There was another ContentProvider with this authority when 7898 * this app was installed so this authority is null, 7899 * Ignore it as we don't have to unregister the provider. 7900 */ 7901 continue; 7902 } 7903 String names[] = p.info.authority.split(";"); 7904 for (int j = 0; j < names.length; j++) { 7905 if (mProvidersByAuthority.get(names[j]) == p) { 7906 mProvidersByAuthority.remove(names[j]); 7907 if (DEBUG_REMOVE) { 7908 if (chatty) 7909 Log.d(TAG, "Unregistered content provider: " + names[j] 7910 + ", className = " + p.info.name + ", isSyncable = " 7911 + p.info.isSyncable); 7912 } 7913 } 7914 } 7915 if (DEBUG_REMOVE && chatty) { 7916 if (r == null) { 7917 r = new StringBuilder(256); 7918 } else { 7919 r.append(' '); 7920 } 7921 r.append(p.info.name); 7922 } 7923 } 7924 if (r != null) { 7925 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7926 } 7927 7928 N = pkg.services.size(); 7929 r = null; 7930 for (i=0; i<N; i++) { 7931 PackageParser.Service s = pkg.services.get(i); 7932 mServices.removeService(s); 7933 if (chatty) { 7934 if (r == null) { 7935 r = new StringBuilder(256); 7936 } else { 7937 r.append(' '); 7938 } 7939 r.append(s.info.name); 7940 } 7941 } 7942 if (r != null) { 7943 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7944 } 7945 7946 N = pkg.receivers.size(); 7947 r = null; 7948 for (i=0; i<N; i++) { 7949 PackageParser.Activity a = pkg.receivers.get(i); 7950 mReceivers.removeActivity(a, "receiver"); 7951 if (DEBUG_REMOVE && chatty) { 7952 if (r == null) { 7953 r = new StringBuilder(256); 7954 } else { 7955 r.append(' '); 7956 } 7957 r.append(a.info.name); 7958 } 7959 } 7960 if (r != null) { 7961 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7962 } 7963 7964 N = pkg.activities.size(); 7965 r = null; 7966 for (i=0; i<N; i++) { 7967 PackageParser.Activity a = pkg.activities.get(i); 7968 mActivities.removeActivity(a, "activity"); 7969 if (DEBUG_REMOVE && chatty) { 7970 if (r == null) { 7971 r = new StringBuilder(256); 7972 } else { 7973 r.append(' '); 7974 } 7975 r.append(a.info.name); 7976 } 7977 } 7978 if (r != null) { 7979 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7980 } 7981 7982 N = pkg.permissions.size(); 7983 r = null; 7984 for (i=0; i<N; i++) { 7985 PackageParser.Permission p = pkg.permissions.get(i); 7986 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7987 if (bp == null) { 7988 bp = mSettings.mPermissionTrees.get(p.info.name); 7989 } 7990 if (bp != null && bp.perm == p) { 7991 bp.perm = null; 7992 if (DEBUG_REMOVE && chatty) { 7993 if (r == null) { 7994 r = new StringBuilder(256); 7995 } else { 7996 r.append(' '); 7997 } 7998 r.append(p.info.name); 7999 } 8000 } 8001 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8002 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 8003 if (appOpPerms != null) { 8004 appOpPerms.remove(pkg.packageName); 8005 } 8006 } 8007 } 8008 if (r != null) { 8009 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8010 } 8011 8012 N = pkg.requestedPermissions.size(); 8013 r = null; 8014 for (i=0; i<N; i++) { 8015 String perm = pkg.requestedPermissions.get(i); 8016 BasePermission bp = mSettings.mPermissions.get(perm); 8017 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8018 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 8019 if (appOpPerms != null) { 8020 appOpPerms.remove(pkg.packageName); 8021 if (appOpPerms.isEmpty()) { 8022 mAppOpPermissionPackages.remove(perm); 8023 } 8024 } 8025 } 8026 } 8027 if (r != null) { 8028 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8029 } 8030 8031 N = pkg.instrumentation.size(); 8032 r = null; 8033 for (i=0; i<N; i++) { 8034 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8035 mInstrumentation.remove(a.getComponentName()); 8036 if (DEBUG_REMOVE && chatty) { 8037 if (r == null) { 8038 r = new StringBuilder(256); 8039 } else { 8040 r.append(' '); 8041 } 8042 r.append(a.info.name); 8043 } 8044 } 8045 if (r != null) { 8046 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8047 } 8048 8049 r = null; 8050 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8051 // Only system apps can hold shared libraries. 8052 if (pkg.libraryNames != null) { 8053 for (i=0; i<pkg.libraryNames.size(); i++) { 8054 String name = pkg.libraryNames.get(i); 8055 SharedLibraryEntry cur = mSharedLibraries.get(name); 8056 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8057 mSharedLibraries.remove(name); 8058 if (DEBUG_REMOVE && chatty) { 8059 if (r == null) { 8060 r = new StringBuilder(256); 8061 } else { 8062 r.append(' '); 8063 } 8064 r.append(name); 8065 } 8066 } 8067 } 8068 } 8069 } 8070 if (r != null) { 8071 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8072 } 8073 } 8074 8075 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8076 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8077 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8078 return true; 8079 } 8080 } 8081 return false; 8082 } 8083 8084 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8085 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8086 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8087 8088 private void updatePermissionsLPw(String changingPkg, 8089 PackageParser.Package pkgInfo, int flags) { 8090 // Make sure there are no dangling permission trees. 8091 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8092 while (it.hasNext()) { 8093 final BasePermission bp = it.next(); 8094 if (bp.packageSetting == null) { 8095 // We may not yet have parsed the package, so just see if 8096 // we still know about its settings. 8097 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8098 } 8099 if (bp.packageSetting == null) { 8100 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8101 + " from package " + bp.sourcePackage); 8102 it.remove(); 8103 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8104 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8105 Slog.i(TAG, "Removing old permission tree: " + bp.name 8106 + " from package " + bp.sourcePackage); 8107 flags |= UPDATE_PERMISSIONS_ALL; 8108 it.remove(); 8109 } 8110 } 8111 } 8112 8113 // Make sure all dynamic permissions have been assigned to a package, 8114 // and make sure there are no dangling permissions. 8115 it = mSettings.mPermissions.values().iterator(); 8116 while (it.hasNext()) { 8117 final BasePermission bp = it.next(); 8118 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8119 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8120 + bp.name + " pkg=" + bp.sourcePackage 8121 + " info=" + bp.pendingInfo); 8122 if (bp.packageSetting == null && bp.pendingInfo != null) { 8123 final BasePermission tree = findPermissionTreeLP(bp.name); 8124 if (tree != null && tree.perm != null) { 8125 bp.packageSetting = tree.packageSetting; 8126 bp.perm = new PackageParser.Permission(tree.perm.owner, 8127 new PermissionInfo(bp.pendingInfo)); 8128 bp.perm.info.packageName = tree.perm.info.packageName; 8129 bp.perm.info.name = bp.name; 8130 bp.uid = tree.uid; 8131 } 8132 } 8133 } 8134 if (bp.packageSetting == null) { 8135 // We may not yet have parsed the package, so just see if 8136 // we still know about its settings. 8137 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8138 } 8139 if (bp.packageSetting == null) { 8140 Slog.w(TAG, "Removing dangling permission: " + bp.name 8141 + " from package " + bp.sourcePackage); 8142 it.remove(); 8143 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8144 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8145 Slog.i(TAG, "Removing old permission: " + bp.name 8146 + " from package " + bp.sourcePackage); 8147 flags |= UPDATE_PERMISSIONS_ALL; 8148 it.remove(); 8149 } 8150 } 8151 } 8152 8153 // Now update the permissions for all packages, in particular 8154 // replace the granted permissions of the system packages. 8155 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8156 for (PackageParser.Package pkg : mPackages.values()) { 8157 if (pkg != pkgInfo) { 8158 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 8159 changingPkg); 8160 } 8161 } 8162 } 8163 8164 if (pkgInfo != null) { 8165 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 8166 } 8167 } 8168 8169 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8170 String packageOfInterest) { 8171 // IMPORTANT: There are two types of permissions: install and runtime. 8172 // Install time permissions are granted when the app is installed to 8173 // all device users and users added in the future. Runtime permissions 8174 // are granted at runtime explicitly to specific users. Normal and signature 8175 // protected permissions are install time permissions. Dangerous permissions 8176 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8177 // otherwise they are runtime permissions. This function does not manage 8178 // runtime permissions except for the case an app targeting Lollipop MR1 8179 // being upgraded to target a newer SDK, in which case dangerous permissions 8180 // are transformed from install time to runtime ones. 8181 8182 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8183 if (ps == null) { 8184 return; 8185 } 8186 8187 PermissionsState permissionsState = ps.getPermissionsState(); 8188 PermissionsState origPermissions = permissionsState; 8189 8190 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8191 8192 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8193 8194 boolean changedInstallPermission = false; 8195 8196 if (replace) { 8197 ps.installPermissionsFixed = false; 8198 if (!ps.isSharedUser()) { 8199 origPermissions = new PermissionsState(permissionsState); 8200 permissionsState.reset(); 8201 } 8202 } 8203 8204 permissionsState.setGlobalGids(mGlobalGids); 8205 8206 final int N = pkg.requestedPermissions.size(); 8207 for (int i=0; i<N; i++) { 8208 final String name = pkg.requestedPermissions.get(i); 8209 final BasePermission bp = mSettings.mPermissions.get(name); 8210 8211 if (DEBUG_INSTALL) { 8212 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8213 } 8214 8215 if (bp == null || bp.packageSetting == null) { 8216 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8217 Slog.w(TAG, "Unknown permission " + name 8218 + " in package " + pkg.packageName); 8219 } 8220 continue; 8221 } 8222 8223 final String perm = bp.name; 8224 boolean allowedSig = false; 8225 int grant = GRANT_DENIED; 8226 8227 // Keep track of app op permissions. 8228 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8229 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8230 if (pkgs == null) { 8231 pkgs = new ArraySet<>(); 8232 mAppOpPermissionPackages.put(bp.name, pkgs); 8233 } 8234 pkgs.add(pkg.packageName); 8235 } 8236 8237 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8238 switch (level) { 8239 case PermissionInfo.PROTECTION_NORMAL: { 8240 // For all apps normal permissions are install time ones. 8241 grant = GRANT_INSTALL; 8242 } break; 8243 8244 case PermissionInfo.PROTECTION_DANGEROUS: { 8245 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 8246 // For legacy apps dangerous permissions are install time ones. 8247 grant = GRANT_INSTALL_LEGACY; 8248 } else if (origPermissions.hasInstallPermission(bp.name)) { 8249 // For legacy apps that became modern, install becomes runtime. 8250 grant = GRANT_UPGRADE; 8251 } else { 8252 // For modern apps keep runtime permissions unchanged. 8253 grant = GRANT_RUNTIME; 8254 } 8255 } break; 8256 8257 case PermissionInfo.PROTECTION_SIGNATURE: { 8258 // For all apps signature permissions are install time ones. 8259 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8260 if (allowedSig) { 8261 grant = GRANT_INSTALL; 8262 } 8263 } break; 8264 } 8265 8266 if (DEBUG_INSTALL) { 8267 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8268 } 8269 8270 if (grant != GRANT_DENIED) { 8271 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8272 // If this is an existing, non-system package, then 8273 // we can't add any new permissions to it. 8274 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8275 // Except... if this is a permission that was added 8276 // to the platform (note: need to only do this when 8277 // updating the platform). 8278 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8279 grant = GRANT_DENIED; 8280 } 8281 } 8282 } 8283 8284 switch (grant) { 8285 case GRANT_INSTALL: { 8286 // Revoke this as runtime permission to handle the case of 8287 // a runtime permission being downgraded to an install one. 8288 for (int userId : UserManagerService.getInstance().getUserIds()) { 8289 if (origPermissions.getRuntimePermissionState( 8290 bp.name, userId) != null) { 8291 // Revoke the runtime permission and clear the flags. 8292 origPermissions.revokeRuntimePermission(bp, userId); 8293 origPermissions.updatePermissionFlags(bp, userId, 8294 PackageManager.MASK_PERMISSION_FLAGS, 0); 8295 // If we revoked a permission permission, we have to write. 8296 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8297 changedRuntimePermissionUserIds, userId); 8298 } 8299 } 8300 // Grant an install permission. 8301 if (permissionsState.grantInstallPermission(bp) != 8302 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8303 changedInstallPermission = true; 8304 } 8305 } break; 8306 8307 case GRANT_INSTALL_LEGACY: { 8308 // Grant an install permission. 8309 if (permissionsState.grantInstallPermission(bp) != 8310 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8311 changedInstallPermission = true; 8312 } 8313 } break; 8314 8315 case GRANT_RUNTIME: { 8316 // Grant previously granted runtime permissions. 8317 for (int userId : UserManagerService.getInstance().getUserIds()) { 8318 PermissionState permissionState = origPermissions 8319 .getRuntimePermissionState(bp.name, userId); 8320 final int flags = permissionState != null 8321 ? permissionState.getFlags() : 0; 8322 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8323 if (permissionsState.grantRuntimePermission(bp, userId) == 8324 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8325 // If we cannot put the permission as it was, we have to write. 8326 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8327 changedRuntimePermissionUserIds, userId); 8328 } 8329 } 8330 // Propagate the permission flags. 8331 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8332 } 8333 } break; 8334 8335 case GRANT_UPGRADE: { 8336 // Grant runtime permissions for a previously held install permission. 8337 PermissionState permissionState = origPermissions 8338 .getInstallPermissionState(bp.name); 8339 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8340 8341 if (origPermissions.revokeInstallPermission(bp) 8342 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8343 // We will be transferring the permission flags, so clear them. 8344 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8345 PackageManager.MASK_PERMISSION_FLAGS, 0); 8346 changedInstallPermission = true; 8347 } 8348 8349 // If the permission is not to be promoted to runtime we ignore it and 8350 // also its other flags as they are not applicable to install permissions. 8351 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8352 for (int userId : currentUserIds) { 8353 if (permissionsState.grantRuntimePermission(bp, userId) != 8354 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8355 // Transfer the permission flags. 8356 permissionsState.updatePermissionFlags(bp, userId, 8357 flags, flags); 8358 // If we granted the permission, we have to write. 8359 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8360 changedRuntimePermissionUserIds, userId); 8361 } 8362 } 8363 } 8364 } break; 8365 8366 default: { 8367 if (packageOfInterest == null 8368 || packageOfInterest.equals(pkg.packageName)) { 8369 Slog.w(TAG, "Not granting permission " + perm 8370 + " to package " + pkg.packageName 8371 + " because it was previously installed without"); 8372 } 8373 } break; 8374 } 8375 } else { 8376 if (permissionsState.revokeInstallPermission(bp) != 8377 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8378 // Also drop the permission flags. 8379 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8380 PackageManager.MASK_PERMISSION_FLAGS, 0); 8381 changedInstallPermission = true; 8382 Slog.i(TAG, "Un-granting permission " + perm 8383 + " from package " + pkg.packageName 8384 + " (protectionLevel=" + bp.protectionLevel 8385 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8386 + ")"); 8387 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8388 // Don't print warning for app op permissions, since it is fine for them 8389 // not to be granted, there is a UI for the user to decide. 8390 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8391 Slog.w(TAG, "Not granting permission " + perm 8392 + " to package " + pkg.packageName 8393 + " (protectionLevel=" + bp.protectionLevel 8394 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8395 + ")"); 8396 } 8397 } 8398 } 8399 } 8400 8401 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8402 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8403 // This is the first that we have heard about this package, so the 8404 // permissions we have now selected are fixed until explicitly 8405 // changed. 8406 ps.installPermissionsFixed = true; 8407 } 8408 8409 // Persist the runtime permissions state for users with changes. 8410 for (int userId : changedRuntimePermissionUserIds) { 8411 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8412 } 8413 } 8414 8415 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8416 boolean allowed = false; 8417 final int NP = PackageParser.NEW_PERMISSIONS.length; 8418 for (int ip=0; ip<NP; ip++) { 8419 final PackageParser.NewPermissionInfo npi 8420 = PackageParser.NEW_PERMISSIONS[ip]; 8421 if (npi.name.equals(perm) 8422 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8423 allowed = true; 8424 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8425 + pkg.packageName); 8426 break; 8427 } 8428 } 8429 return allowed; 8430 } 8431 8432 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8433 BasePermission bp, PermissionsState origPermissions) { 8434 boolean allowed; 8435 allowed = (compareSignatures( 8436 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8437 == PackageManager.SIGNATURE_MATCH) 8438 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8439 == PackageManager.SIGNATURE_MATCH); 8440 if (!allowed && (bp.protectionLevel 8441 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 8442 if (isSystemApp(pkg)) { 8443 // For updated system applications, a system permission 8444 // is granted only if it had been defined by the original application. 8445 if (pkg.isUpdatedSystemApp()) { 8446 final PackageSetting sysPs = mSettings 8447 .getDisabledSystemPkgLPr(pkg.packageName); 8448 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8449 // If the original was granted this permission, we take 8450 // that grant decision as read and propagate it to the 8451 // update. 8452 if (sysPs.isPrivileged()) { 8453 allowed = true; 8454 } 8455 } else { 8456 // The system apk may have been updated with an older 8457 // version of the one on the data partition, but which 8458 // granted a new system permission that it didn't have 8459 // before. In this case we do want to allow the app to 8460 // now get the new permission if the ancestral apk is 8461 // privileged to get it. 8462 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8463 for (int j=0; 8464 j<sysPs.pkg.requestedPermissions.size(); j++) { 8465 if (perm.equals( 8466 sysPs.pkg.requestedPermissions.get(j))) { 8467 allowed = true; 8468 break; 8469 } 8470 } 8471 } 8472 } 8473 } else { 8474 allowed = isPrivilegedApp(pkg); 8475 } 8476 } 8477 } 8478 if (!allowed) { 8479 if (!allowed && (bp.protectionLevel 8480 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 8481 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) { 8482 // If this was a previously normal/dangerous permission that got moved 8483 // to a system permission as part of the runtime permission redesign, then 8484 // we still want to blindly grant it to old apps. 8485 allowed = true; 8486 } 8487 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 8488 && pkg.packageName.equals(mRequiredInstallerPackage)) { 8489 // If this permission is to be granted to the system installer and 8490 // this app is an installer, then it gets the permission. 8491 allowed = true; 8492 } 8493 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 8494 && pkg.packageName.equals(mRequiredVerifierPackage)) { 8495 // If this permission is to be granted to the system verifier and 8496 // this app is a verifier, then it gets the permission. 8497 allowed = true; 8498 } 8499 if (!allowed && (bp.protectionLevel 8500 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 8501 && isSystemApp(pkg)) { 8502 // Any pre-installed system app is allowed to get this permission. 8503 allowed = true; 8504 } 8505 if (!allowed && (bp.protectionLevel 8506 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8507 // For development permissions, a development permission 8508 // is granted only if it was already granted. 8509 allowed = origPermissions.hasInstallPermission(perm); 8510 } 8511 } 8512 return allowed; 8513 } 8514 8515 final class ActivityIntentResolver 8516 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8517 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8518 boolean defaultOnly, int userId) { 8519 if (!sUserManager.exists(userId)) return null; 8520 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8521 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8522 } 8523 8524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8525 int userId) { 8526 if (!sUserManager.exists(userId)) return null; 8527 mFlags = flags; 8528 return super.queryIntent(intent, resolvedType, 8529 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8530 } 8531 8532 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8533 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8534 if (!sUserManager.exists(userId)) return null; 8535 if (packageActivities == null) { 8536 return null; 8537 } 8538 mFlags = flags; 8539 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8540 final int N = packageActivities.size(); 8541 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8542 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8543 8544 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8545 for (int i = 0; i < N; ++i) { 8546 intentFilters = packageActivities.get(i).intents; 8547 if (intentFilters != null && intentFilters.size() > 0) { 8548 PackageParser.ActivityIntentInfo[] array = 8549 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8550 intentFilters.toArray(array); 8551 listCut.add(array); 8552 } 8553 } 8554 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8555 } 8556 8557 public final void addActivity(PackageParser.Activity a, String type) { 8558 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8559 mActivities.put(a.getComponentName(), a); 8560 if (DEBUG_SHOW_INFO) 8561 Log.v( 8562 TAG, " " + type + " " + 8563 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8564 if (DEBUG_SHOW_INFO) 8565 Log.v(TAG, " Class=" + a.info.name); 8566 final int NI = a.intents.size(); 8567 for (int j=0; j<NI; j++) { 8568 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8569 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8570 intent.setPriority(0); 8571 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8572 + a.className + " with priority > 0, forcing to 0"); 8573 } 8574 if (DEBUG_SHOW_INFO) { 8575 Log.v(TAG, " IntentFilter:"); 8576 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8577 } 8578 if (!intent.debugCheck()) { 8579 Log.w(TAG, "==> For Activity " + a.info.name); 8580 } 8581 addFilter(intent); 8582 } 8583 } 8584 8585 public final void removeActivity(PackageParser.Activity a, String type) { 8586 mActivities.remove(a.getComponentName()); 8587 if (DEBUG_SHOW_INFO) { 8588 Log.v(TAG, " " + type + " " 8589 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8590 : a.info.name) + ":"); 8591 Log.v(TAG, " Class=" + a.info.name); 8592 } 8593 final int NI = a.intents.size(); 8594 for (int j=0; j<NI; j++) { 8595 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8596 if (DEBUG_SHOW_INFO) { 8597 Log.v(TAG, " IntentFilter:"); 8598 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8599 } 8600 removeFilter(intent); 8601 } 8602 } 8603 8604 @Override 8605 protected boolean allowFilterResult( 8606 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8607 ActivityInfo filterAi = filter.activity.info; 8608 for (int i=dest.size()-1; i>=0; i--) { 8609 ActivityInfo destAi = dest.get(i).activityInfo; 8610 if (destAi.name == filterAi.name 8611 && destAi.packageName == filterAi.packageName) { 8612 return false; 8613 } 8614 } 8615 return true; 8616 } 8617 8618 @Override 8619 protected ActivityIntentInfo[] newArray(int size) { 8620 return new ActivityIntentInfo[size]; 8621 } 8622 8623 @Override 8624 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8625 if (!sUserManager.exists(userId)) return true; 8626 PackageParser.Package p = filter.activity.owner; 8627 if (p != null) { 8628 PackageSetting ps = (PackageSetting)p.mExtras; 8629 if (ps != null) { 8630 // System apps are never considered stopped for purposes of 8631 // filtering, because there may be no way for the user to 8632 // actually re-launch them. 8633 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8634 && ps.getStopped(userId); 8635 } 8636 } 8637 return false; 8638 } 8639 8640 @Override 8641 protected boolean isPackageForFilter(String packageName, 8642 PackageParser.ActivityIntentInfo info) { 8643 return packageName.equals(info.activity.owner.packageName); 8644 } 8645 8646 @Override 8647 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8648 int match, int userId) { 8649 if (!sUserManager.exists(userId)) return null; 8650 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8651 return null; 8652 } 8653 final PackageParser.Activity activity = info.activity; 8654 if (mSafeMode && (activity.info.applicationInfo.flags 8655 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8656 return null; 8657 } 8658 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8659 if (ps == null) { 8660 return null; 8661 } 8662 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8663 ps.readUserState(userId), userId); 8664 if (ai == null) { 8665 return null; 8666 } 8667 final ResolveInfo res = new ResolveInfo(); 8668 res.activityInfo = ai; 8669 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8670 res.filter = info; 8671 } 8672 if (info != null) { 8673 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8674 } 8675 res.priority = info.getPriority(); 8676 res.preferredOrder = activity.owner.mPreferredOrder; 8677 //System.out.println("Result: " + res.activityInfo.className + 8678 // " = " + res.priority); 8679 res.match = match; 8680 res.isDefault = info.hasDefault; 8681 res.labelRes = info.labelRes; 8682 res.nonLocalizedLabel = info.nonLocalizedLabel; 8683 if (userNeedsBadging(userId)) { 8684 res.noResourceId = true; 8685 } else { 8686 res.icon = info.icon; 8687 } 8688 res.iconResourceId = info.icon; 8689 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8690 return res; 8691 } 8692 8693 @Override 8694 protected void sortResults(List<ResolveInfo> results) { 8695 Collections.sort(results, mResolvePrioritySorter); 8696 } 8697 8698 @Override 8699 protected void dumpFilter(PrintWriter out, String prefix, 8700 PackageParser.ActivityIntentInfo filter) { 8701 out.print(prefix); out.print( 8702 Integer.toHexString(System.identityHashCode(filter.activity))); 8703 out.print(' '); 8704 filter.activity.printComponentShortName(out); 8705 out.print(" filter "); 8706 out.println(Integer.toHexString(System.identityHashCode(filter))); 8707 } 8708 8709 @Override 8710 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8711 return filter.activity; 8712 } 8713 8714 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8715 PackageParser.Activity activity = (PackageParser.Activity)label; 8716 out.print(prefix); out.print( 8717 Integer.toHexString(System.identityHashCode(activity))); 8718 out.print(' '); 8719 activity.printComponentShortName(out); 8720 if (count > 1) { 8721 out.print(" ("); out.print(count); out.print(" filters)"); 8722 } 8723 out.println(); 8724 } 8725 8726// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8727// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8728// final List<ResolveInfo> retList = Lists.newArrayList(); 8729// while (i.hasNext()) { 8730// final ResolveInfo resolveInfo = i.next(); 8731// if (isEnabledLP(resolveInfo.activityInfo)) { 8732// retList.add(resolveInfo); 8733// } 8734// } 8735// return retList; 8736// } 8737 8738 // Keys are String (activity class name), values are Activity. 8739 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8740 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8741 private int mFlags; 8742 } 8743 8744 private final class ServiceIntentResolver 8745 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8746 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8747 boolean defaultOnly, int userId) { 8748 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8749 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8750 } 8751 8752 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8753 int userId) { 8754 if (!sUserManager.exists(userId)) return null; 8755 mFlags = flags; 8756 return super.queryIntent(intent, resolvedType, 8757 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8758 } 8759 8760 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8761 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8762 if (!sUserManager.exists(userId)) return null; 8763 if (packageServices == null) { 8764 return null; 8765 } 8766 mFlags = flags; 8767 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8768 final int N = packageServices.size(); 8769 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8770 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8771 8772 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8773 for (int i = 0; i < N; ++i) { 8774 intentFilters = packageServices.get(i).intents; 8775 if (intentFilters != null && intentFilters.size() > 0) { 8776 PackageParser.ServiceIntentInfo[] array = 8777 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8778 intentFilters.toArray(array); 8779 listCut.add(array); 8780 } 8781 } 8782 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8783 } 8784 8785 public final void addService(PackageParser.Service s) { 8786 mServices.put(s.getComponentName(), s); 8787 if (DEBUG_SHOW_INFO) { 8788 Log.v(TAG, " " 8789 + (s.info.nonLocalizedLabel != null 8790 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8791 Log.v(TAG, " Class=" + s.info.name); 8792 } 8793 final int NI = s.intents.size(); 8794 int j; 8795 for (j=0; j<NI; j++) { 8796 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8797 if (DEBUG_SHOW_INFO) { 8798 Log.v(TAG, " IntentFilter:"); 8799 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8800 } 8801 if (!intent.debugCheck()) { 8802 Log.w(TAG, "==> For Service " + s.info.name); 8803 } 8804 addFilter(intent); 8805 } 8806 } 8807 8808 public final void removeService(PackageParser.Service s) { 8809 mServices.remove(s.getComponentName()); 8810 if (DEBUG_SHOW_INFO) { 8811 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8812 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8813 Log.v(TAG, " Class=" + s.info.name); 8814 } 8815 final int NI = s.intents.size(); 8816 int j; 8817 for (j=0; j<NI; j++) { 8818 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8819 if (DEBUG_SHOW_INFO) { 8820 Log.v(TAG, " IntentFilter:"); 8821 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8822 } 8823 removeFilter(intent); 8824 } 8825 } 8826 8827 @Override 8828 protected boolean allowFilterResult( 8829 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8830 ServiceInfo filterSi = filter.service.info; 8831 for (int i=dest.size()-1; i>=0; i--) { 8832 ServiceInfo destAi = dest.get(i).serviceInfo; 8833 if (destAi.name == filterSi.name 8834 && destAi.packageName == filterSi.packageName) { 8835 return false; 8836 } 8837 } 8838 return true; 8839 } 8840 8841 @Override 8842 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8843 return new PackageParser.ServiceIntentInfo[size]; 8844 } 8845 8846 @Override 8847 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8848 if (!sUserManager.exists(userId)) return true; 8849 PackageParser.Package p = filter.service.owner; 8850 if (p != null) { 8851 PackageSetting ps = (PackageSetting)p.mExtras; 8852 if (ps != null) { 8853 // System apps are never considered stopped for purposes of 8854 // filtering, because there may be no way for the user to 8855 // actually re-launch them. 8856 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8857 && ps.getStopped(userId); 8858 } 8859 } 8860 return false; 8861 } 8862 8863 @Override 8864 protected boolean isPackageForFilter(String packageName, 8865 PackageParser.ServiceIntentInfo info) { 8866 return packageName.equals(info.service.owner.packageName); 8867 } 8868 8869 @Override 8870 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8871 int match, int userId) { 8872 if (!sUserManager.exists(userId)) return null; 8873 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8874 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8875 return null; 8876 } 8877 final PackageParser.Service service = info.service; 8878 if (mSafeMode && (service.info.applicationInfo.flags 8879 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8880 return null; 8881 } 8882 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8883 if (ps == null) { 8884 return null; 8885 } 8886 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8887 ps.readUserState(userId), userId); 8888 if (si == null) { 8889 return null; 8890 } 8891 final ResolveInfo res = new ResolveInfo(); 8892 res.serviceInfo = si; 8893 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8894 res.filter = filter; 8895 } 8896 res.priority = info.getPriority(); 8897 res.preferredOrder = service.owner.mPreferredOrder; 8898 res.match = match; 8899 res.isDefault = info.hasDefault; 8900 res.labelRes = info.labelRes; 8901 res.nonLocalizedLabel = info.nonLocalizedLabel; 8902 res.icon = info.icon; 8903 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8904 return res; 8905 } 8906 8907 @Override 8908 protected void sortResults(List<ResolveInfo> results) { 8909 Collections.sort(results, mResolvePrioritySorter); 8910 } 8911 8912 @Override 8913 protected void dumpFilter(PrintWriter out, String prefix, 8914 PackageParser.ServiceIntentInfo filter) { 8915 out.print(prefix); out.print( 8916 Integer.toHexString(System.identityHashCode(filter.service))); 8917 out.print(' '); 8918 filter.service.printComponentShortName(out); 8919 out.print(" filter "); 8920 out.println(Integer.toHexString(System.identityHashCode(filter))); 8921 } 8922 8923 @Override 8924 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8925 return filter.service; 8926 } 8927 8928 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8929 PackageParser.Service service = (PackageParser.Service)label; 8930 out.print(prefix); out.print( 8931 Integer.toHexString(System.identityHashCode(service))); 8932 out.print(' '); 8933 service.printComponentShortName(out); 8934 if (count > 1) { 8935 out.print(" ("); out.print(count); out.print(" filters)"); 8936 } 8937 out.println(); 8938 } 8939 8940// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8941// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8942// final List<ResolveInfo> retList = Lists.newArrayList(); 8943// while (i.hasNext()) { 8944// final ResolveInfo resolveInfo = (ResolveInfo) i; 8945// if (isEnabledLP(resolveInfo.serviceInfo)) { 8946// retList.add(resolveInfo); 8947// } 8948// } 8949// return retList; 8950// } 8951 8952 // Keys are String (activity class name), values are Activity. 8953 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8954 = new ArrayMap<ComponentName, PackageParser.Service>(); 8955 private int mFlags; 8956 }; 8957 8958 private final class ProviderIntentResolver 8959 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8960 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8961 boolean defaultOnly, int userId) { 8962 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8963 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8964 } 8965 8966 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8967 int userId) { 8968 if (!sUserManager.exists(userId)) 8969 return null; 8970 mFlags = flags; 8971 return super.queryIntent(intent, resolvedType, 8972 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8973 } 8974 8975 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8976 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8977 if (!sUserManager.exists(userId)) 8978 return null; 8979 if (packageProviders == null) { 8980 return null; 8981 } 8982 mFlags = flags; 8983 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8984 final int N = packageProviders.size(); 8985 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8986 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8987 8988 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8989 for (int i = 0; i < N; ++i) { 8990 intentFilters = packageProviders.get(i).intents; 8991 if (intentFilters != null && intentFilters.size() > 0) { 8992 PackageParser.ProviderIntentInfo[] array = 8993 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8994 intentFilters.toArray(array); 8995 listCut.add(array); 8996 } 8997 } 8998 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8999 } 9000 9001 public final void addProvider(PackageParser.Provider p) { 9002 if (mProviders.containsKey(p.getComponentName())) { 9003 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9004 return; 9005 } 9006 9007 mProviders.put(p.getComponentName(), p); 9008 if (DEBUG_SHOW_INFO) { 9009 Log.v(TAG, " " 9010 + (p.info.nonLocalizedLabel != null 9011 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9012 Log.v(TAG, " Class=" + p.info.name); 9013 } 9014 final int NI = p.intents.size(); 9015 int j; 9016 for (j = 0; j < NI; j++) { 9017 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9018 if (DEBUG_SHOW_INFO) { 9019 Log.v(TAG, " IntentFilter:"); 9020 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9021 } 9022 if (!intent.debugCheck()) { 9023 Log.w(TAG, "==> For Provider " + p.info.name); 9024 } 9025 addFilter(intent); 9026 } 9027 } 9028 9029 public final void removeProvider(PackageParser.Provider p) { 9030 mProviders.remove(p.getComponentName()); 9031 if (DEBUG_SHOW_INFO) { 9032 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9033 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9034 Log.v(TAG, " Class=" + p.info.name); 9035 } 9036 final int NI = p.intents.size(); 9037 int j; 9038 for (j = 0; j < NI; j++) { 9039 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9040 if (DEBUG_SHOW_INFO) { 9041 Log.v(TAG, " IntentFilter:"); 9042 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9043 } 9044 removeFilter(intent); 9045 } 9046 } 9047 9048 @Override 9049 protected boolean allowFilterResult( 9050 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9051 ProviderInfo filterPi = filter.provider.info; 9052 for (int i = dest.size() - 1; i >= 0; i--) { 9053 ProviderInfo destPi = dest.get(i).providerInfo; 9054 if (destPi.name == filterPi.name 9055 && destPi.packageName == filterPi.packageName) { 9056 return false; 9057 } 9058 } 9059 return true; 9060 } 9061 9062 @Override 9063 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9064 return new PackageParser.ProviderIntentInfo[size]; 9065 } 9066 9067 @Override 9068 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9069 if (!sUserManager.exists(userId)) 9070 return true; 9071 PackageParser.Package p = filter.provider.owner; 9072 if (p != null) { 9073 PackageSetting ps = (PackageSetting) p.mExtras; 9074 if (ps != null) { 9075 // System apps are never considered stopped for purposes of 9076 // filtering, because there may be no way for the user to 9077 // actually re-launch them. 9078 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9079 && ps.getStopped(userId); 9080 } 9081 } 9082 return false; 9083 } 9084 9085 @Override 9086 protected boolean isPackageForFilter(String packageName, 9087 PackageParser.ProviderIntentInfo info) { 9088 return packageName.equals(info.provider.owner.packageName); 9089 } 9090 9091 @Override 9092 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9093 int match, int userId) { 9094 if (!sUserManager.exists(userId)) 9095 return null; 9096 final PackageParser.ProviderIntentInfo info = filter; 9097 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 9098 return null; 9099 } 9100 final PackageParser.Provider provider = info.provider; 9101 if (mSafeMode && (provider.info.applicationInfo.flags 9102 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9103 return null; 9104 } 9105 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9106 if (ps == null) { 9107 return null; 9108 } 9109 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9110 ps.readUserState(userId), userId); 9111 if (pi == null) { 9112 return null; 9113 } 9114 final ResolveInfo res = new ResolveInfo(); 9115 res.providerInfo = pi; 9116 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9117 res.filter = filter; 9118 } 9119 res.priority = info.getPriority(); 9120 res.preferredOrder = provider.owner.mPreferredOrder; 9121 res.match = match; 9122 res.isDefault = info.hasDefault; 9123 res.labelRes = info.labelRes; 9124 res.nonLocalizedLabel = info.nonLocalizedLabel; 9125 res.icon = info.icon; 9126 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9127 return res; 9128 } 9129 9130 @Override 9131 protected void sortResults(List<ResolveInfo> results) { 9132 Collections.sort(results, mResolvePrioritySorter); 9133 } 9134 9135 @Override 9136 protected void dumpFilter(PrintWriter out, String prefix, 9137 PackageParser.ProviderIntentInfo filter) { 9138 out.print(prefix); 9139 out.print( 9140 Integer.toHexString(System.identityHashCode(filter.provider))); 9141 out.print(' '); 9142 filter.provider.printComponentShortName(out); 9143 out.print(" filter "); 9144 out.println(Integer.toHexString(System.identityHashCode(filter))); 9145 } 9146 9147 @Override 9148 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9149 return filter.provider; 9150 } 9151 9152 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9153 PackageParser.Provider provider = (PackageParser.Provider)label; 9154 out.print(prefix); out.print( 9155 Integer.toHexString(System.identityHashCode(provider))); 9156 out.print(' '); 9157 provider.printComponentShortName(out); 9158 if (count > 1) { 9159 out.print(" ("); out.print(count); out.print(" filters)"); 9160 } 9161 out.println(); 9162 } 9163 9164 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9165 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9166 private int mFlags; 9167 }; 9168 9169 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9170 new Comparator<ResolveInfo>() { 9171 public int compare(ResolveInfo r1, ResolveInfo r2) { 9172 int v1 = r1.priority; 9173 int v2 = r2.priority; 9174 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9175 if (v1 != v2) { 9176 return (v1 > v2) ? -1 : 1; 9177 } 9178 v1 = r1.preferredOrder; 9179 v2 = r2.preferredOrder; 9180 if (v1 != v2) { 9181 return (v1 > v2) ? -1 : 1; 9182 } 9183 if (r1.isDefault != r2.isDefault) { 9184 return r1.isDefault ? -1 : 1; 9185 } 9186 v1 = r1.match; 9187 v2 = r2.match; 9188 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9189 if (v1 != v2) { 9190 return (v1 > v2) ? -1 : 1; 9191 } 9192 if (r1.system != r2.system) { 9193 return r1.system ? -1 : 1; 9194 } 9195 return 0; 9196 } 9197 }; 9198 9199 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9200 new Comparator<ProviderInfo>() { 9201 public int compare(ProviderInfo p1, ProviderInfo p2) { 9202 final int v1 = p1.initOrder; 9203 final int v2 = p2.initOrder; 9204 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9205 } 9206 }; 9207 9208 final void sendPackageBroadcast(final String action, final String pkg, 9209 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 9210 final int[] userIds) { 9211 mHandler.post(new Runnable() { 9212 @Override 9213 public void run() { 9214 try { 9215 final IActivityManager am = ActivityManagerNative.getDefault(); 9216 if (am == null) return; 9217 final int[] resolvedUserIds; 9218 if (userIds == null) { 9219 resolvedUserIds = am.getRunningUserIds(); 9220 } else { 9221 resolvedUserIds = userIds; 9222 } 9223 for (int id : resolvedUserIds) { 9224 final Intent intent = new Intent(action, 9225 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9226 if (extras != null) { 9227 intent.putExtras(extras); 9228 } 9229 if (targetPkg != null) { 9230 intent.setPackage(targetPkg); 9231 } 9232 // Modify the UID when posting to other users 9233 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9234 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9235 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9236 intent.putExtra(Intent.EXTRA_UID, uid); 9237 } 9238 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9239 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 9240 if (DEBUG_BROADCASTS) { 9241 RuntimeException here = new RuntimeException("here"); 9242 here.fillInStackTrace(); 9243 Slog.d(TAG, "Sending to user " + id + ": " 9244 + intent.toShortString(false, true, false, false) 9245 + " " + intent.getExtras(), here); 9246 } 9247 am.broadcastIntent(null, intent, null, finishedReceiver, 9248 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9249 null, finishedReceiver != null, false, id); 9250 } 9251 } catch (RemoteException ex) { 9252 } 9253 } 9254 }); 9255 } 9256 9257 /** 9258 * Check if the external storage media is available. This is true if there 9259 * is a mounted external storage medium or if the external storage is 9260 * emulated. 9261 */ 9262 private boolean isExternalMediaAvailable() { 9263 return mMediaMounted || Environment.isExternalStorageEmulated(); 9264 } 9265 9266 @Override 9267 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9268 // writer 9269 synchronized (mPackages) { 9270 if (!isExternalMediaAvailable()) { 9271 // If the external storage is no longer mounted at this point, 9272 // the caller may not have been able to delete all of this 9273 // packages files and can not delete any more. Bail. 9274 return null; 9275 } 9276 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9277 if (lastPackage != null) { 9278 pkgs.remove(lastPackage); 9279 } 9280 if (pkgs.size() > 0) { 9281 return pkgs.get(0); 9282 } 9283 } 9284 return null; 9285 } 9286 9287 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9288 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9289 userId, andCode ? 1 : 0, packageName); 9290 if (mSystemReady) { 9291 msg.sendToTarget(); 9292 } else { 9293 if (mPostSystemReadyMessages == null) { 9294 mPostSystemReadyMessages = new ArrayList<>(); 9295 } 9296 mPostSystemReadyMessages.add(msg); 9297 } 9298 } 9299 9300 void startCleaningPackages() { 9301 // reader 9302 synchronized (mPackages) { 9303 if (!isExternalMediaAvailable()) { 9304 return; 9305 } 9306 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9307 return; 9308 } 9309 } 9310 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9311 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9312 IActivityManager am = ActivityManagerNative.getDefault(); 9313 if (am != null) { 9314 try { 9315 am.startService(null, intent, null, mContext.getOpPackageName(), 9316 UserHandle.USER_OWNER); 9317 } catch (RemoteException e) { 9318 } 9319 } 9320 } 9321 9322 @Override 9323 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9324 int installFlags, String installerPackageName, VerificationParams verificationParams, 9325 String packageAbiOverride) { 9326 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9327 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9328 } 9329 9330 @Override 9331 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9332 int installFlags, String installerPackageName, VerificationParams verificationParams, 9333 String packageAbiOverride, int userId) { 9334 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9335 9336 final int callingUid = Binder.getCallingUid(); 9337 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9338 9339 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9340 try { 9341 if (observer != null) { 9342 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9343 } 9344 } catch (RemoteException re) { 9345 } 9346 return; 9347 } 9348 9349 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9350 installFlags |= PackageManager.INSTALL_FROM_ADB; 9351 9352 } else { 9353 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9354 // about installerPackageName. 9355 9356 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9357 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9358 } 9359 9360 UserHandle user; 9361 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9362 user = UserHandle.ALL; 9363 } else { 9364 user = new UserHandle(userId); 9365 } 9366 9367 // Only system components can circumvent runtime permissions when installing. 9368 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9369 && mContext.checkCallingOrSelfPermission(Manifest.permission 9370 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9371 throw new SecurityException("You need the " 9372 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9373 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9374 } 9375 9376 verificationParams.setInstallerUid(callingUid); 9377 9378 final File originFile = new File(originPath); 9379 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9380 9381 final Message msg = mHandler.obtainMessage(INIT_COPY); 9382 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9383 null, verificationParams, user, packageAbiOverride); 9384 mHandler.sendMessage(msg); 9385 } 9386 9387 void installStage(String packageName, File stagedDir, String stagedCid, 9388 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9389 String installerPackageName, int installerUid, UserHandle user) { 9390 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9391 params.referrerUri, installerUid, null); 9392 verifParams.setInstallerUid(installerUid); 9393 9394 final OriginInfo origin; 9395 if (stagedDir != null) { 9396 origin = OriginInfo.fromStagedFile(stagedDir); 9397 } else { 9398 origin = OriginInfo.fromStagedContainer(stagedCid); 9399 } 9400 9401 final Message msg = mHandler.obtainMessage(INIT_COPY); 9402 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9403 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9404 mHandler.sendMessage(msg); 9405 } 9406 9407 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9408 Bundle extras = new Bundle(1); 9409 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9410 9411 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9412 packageName, extras, null, null, new int[] {userId}); 9413 try { 9414 IActivityManager am = ActivityManagerNative.getDefault(); 9415 final boolean isSystem = 9416 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9417 if (isSystem && am.isUserRunning(userId, false)) { 9418 // The just-installed/enabled app is bundled on the system, so presumed 9419 // to be able to run automatically without needing an explicit launch. 9420 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9421 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9422 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9423 .setPackage(packageName); 9424 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9425 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9426 } 9427 } catch (RemoteException e) { 9428 // shouldn't happen 9429 Slog.w(TAG, "Unable to bootstrap installed package", e); 9430 } 9431 } 9432 9433 @Override 9434 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9435 int userId) { 9436 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9437 PackageSetting pkgSetting; 9438 final int uid = Binder.getCallingUid(); 9439 enforceCrossUserPermission(uid, userId, true, true, 9440 "setApplicationHiddenSetting for user " + userId); 9441 9442 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9443 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9444 return false; 9445 } 9446 9447 long callingId = Binder.clearCallingIdentity(); 9448 try { 9449 boolean sendAdded = false; 9450 boolean sendRemoved = false; 9451 // writer 9452 synchronized (mPackages) { 9453 pkgSetting = mSettings.mPackages.get(packageName); 9454 if (pkgSetting == null) { 9455 return false; 9456 } 9457 if (pkgSetting.getHidden(userId) != hidden) { 9458 pkgSetting.setHidden(hidden, userId); 9459 mSettings.writePackageRestrictionsLPr(userId); 9460 if (hidden) { 9461 sendRemoved = true; 9462 } else { 9463 sendAdded = true; 9464 } 9465 } 9466 } 9467 if (sendAdded) { 9468 sendPackageAddedForUser(packageName, pkgSetting, userId); 9469 return true; 9470 } 9471 if (sendRemoved) { 9472 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9473 "hiding pkg"); 9474 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9475 } 9476 } finally { 9477 Binder.restoreCallingIdentity(callingId); 9478 } 9479 return false; 9480 } 9481 9482 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9483 int userId) { 9484 final PackageRemovedInfo info = new PackageRemovedInfo(); 9485 info.removedPackage = packageName; 9486 info.removedUsers = new int[] {userId}; 9487 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9488 info.sendBroadcast(false, false, false); 9489 } 9490 9491 /** 9492 * Returns true if application is not found or there was an error. Otherwise it returns 9493 * the hidden state of the package for the given user. 9494 */ 9495 @Override 9496 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9497 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9498 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9499 false, "getApplicationHidden for user " + userId); 9500 PackageSetting pkgSetting; 9501 long callingId = Binder.clearCallingIdentity(); 9502 try { 9503 // writer 9504 synchronized (mPackages) { 9505 pkgSetting = mSettings.mPackages.get(packageName); 9506 if (pkgSetting == null) { 9507 return true; 9508 } 9509 return pkgSetting.getHidden(userId); 9510 } 9511 } finally { 9512 Binder.restoreCallingIdentity(callingId); 9513 } 9514 } 9515 9516 /** 9517 * @hide 9518 */ 9519 @Override 9520 public int installExistingPackageAsUser(String packageName, int userId) { 9521 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9522 null); 9523 PackageSetting pkgSetting; 9524 final int uid = Binder.getCallingUid(); 9525 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9526 + userId); 9527 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9528 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9529 } 9530 9531 long callingId = Binder.clearCallingIdentity(); 9532 try { 9533 boolean sendAdded = false; 9534 9535 // writer 9536 synchronized (mPackages) { 9537 pkgSetting = mSettings.mPackages.get(packageName); 9538 if (pkgSetting == null) { 9539 return PackageManager.INSTALL_FAILED_INVALID_URI; 9540 } 9541 if (!pkgSetting.getInstalled(userId)) { 9542 pkgSetting.setInstalled(true, userId); 9543 pkgSetting.setHidden(false, userId); 9544 mSettings.writePackageRestrictionsLPr(userId); 9545 sendAdded = true; 9546 } 9547 } 9548 9549 if (sendAdded) { 9550 sendPackageAddedForUser(packageName, pkgSetting, userId); 9551 } 9552 } finally { 9553 Binder.restoreCallingIdentity(callingId); 9554 } 9555 9556 return PackageManager.INSTALL_SUCCEEDED; 9557 } 9558 9559 boolean isUserRestricted(int userId, String restrictionKey) { 9560 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9561 if (restrictions.getBoolean(restrictionKey, false)) { 9562 Log.w(TAG, "User is restricted: " + restrictionKey); 9563 return true; 9564 } 9565 return false; 9566 } 9567 9568 @Override 9569 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9570 mContext.enforceCallingOrSelfPermission( 9571 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9572 "Only package verification agents can verify applications"); 9573 9574 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9575 final PackageVerificationResponse response = new PackageVerificationResponse( 9576 verificationCode, Binder.getCallingUid()); 9577 msg.arg1 = id; 9578 msg.obj = response; 9579 mHandler.sendMessage(msg); 9580 } 9581 9582 @Override 9583 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9584 long millisecondsToDelay) { 9585 mContext.enforceCallingOrSelfPermission( 9586 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9587 "Only package verification agents can extend verification timeouts"); 9588 9589 final PackageVerificationState state = mPendingVerification.get(id); 9590 final PackageVerificationResponse response = new PackageVerificationResponse( 9591 verificationCodeAtTimeout, Binder.getCallingUid()); 9592 9593 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9594 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9595 } 9596 if (millisecondsToDelay < 0) { 9597 millisecondsToDelay = 0; 9598 } 9599 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9600 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9601 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9602 } 9603 9604 if ((state != null) && !state.timeoutExtended()) { 9605 state.extendTimeout(); 9606 9607 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9608 msg.arg1 = id; 9609 msg.obj = response; 9610 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9611 } 9612 } 9613 9614 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9615 int verificationCode, UserHandle user) { 9616 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9617 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9618 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9619 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9620 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9621 9622 mContext.sendBroadcastAsUser(intent, user, 9623 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9624 } 9625 9626 private ComponentName matchComponentForVerifier(String packageName, 9627 List<ResolveInfo> receivers) { 9628 ActivityInfo targetReceiver = null; 9629 9630 final int NR = receivers.size(); 9631 for (int i = 0; i < NR; i++) { 9632 final ResolveInfo info = receivers.get(i); 9633 if (info.activityInfo == null) { 9634 continue; 9635 } 9636 9637 if (packageName.equals(info.activityInfo.packageName)) { 9638 targetReceiver = info.activityInfo; 9639 break; 9640 } 9641 } 9642 9643 if (targetReceiver == null) { 9644 return null; 9645 } 9646 9647 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9648 } 9649 9650 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9651 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9652 if (pkgInfo.verifiers.length == 0) { 9653 return null; 9654 } 9655 9656 final int N = pkgInfo.verifiers.length; 9657 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9658 for (int i = 0; i < N; i++) { 9659 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9660 9661 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9662 receivers); 9663 if (comp == null) { 9664 continue; 9665 } 9666 9667 final int verifierUid = getUidForVerifier(verifierInfo); 9668 if (verifierUid == -1) { 9669 continue; 9670 } 9671 9672 if (DEBUG_VERIFY) { 9673 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9674 + " with the correct signature"); 9675 } 9676 sufficientVerifiers.add(comp); 9677 verificationState.addSufficientVerifier(verifierUid); 9678 } 9679 9680 return sufficientVerifiers; 9681 } 9682 9683 private int getUidForVerifier(VerifierInfo verifierInfo) { 9684 synchronized (mPackages) { 9685 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9686 if (pkg == null) { 9687 return -1; 9688 } else if (pkg.mSignatures.length != 1) { 9689 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9690 + " has more than one signature; ignoring"); 9691 return -1; 9692 } 9693 9694 /* 9695 * If the public key of the package's signature does not match 9696 * our expected public key, then this is a different package and 9697 * we should skip. 9698 */ 9699 9700 final byte[] expectedPublicKey; 9701 try { 9702 final Signature verifierSig = pkg.mSignatures[0]; 9703 final PublicKey publicKey = verifierSig.getPublicKey(); 9704 expectedPublicKey = publicKey.getEncoded(); 9705 } catch (CertificateException e) { 9706 return -1; 9707 } 9708 9709 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9710 9711 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9712 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9713 + " does not have the expected public key; ignoring"); 9714 return -1; 9715 } 9716 9717 return pkg.applicationInfo.uid; 9718 } 9719 } 9720 9721 @Override 9722 public void finishPackageInstall(int token) { 9723 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9724 9725 if (DEBUG_INSTALL) { 9726 Slog.v(TAG, "BM finishing package install for " + token); 9727 } 9728 9729 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9730 mHandler.sendMessage(msg); 9731 } 9732 9733 /** 9734 * Get the verification agent timeout. 9735 * 9736 * @return verification timeout in milliseconds 9737 */ 9738 private long getVerificationTimeout() { 9739 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9740 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9741 DEFAULT_VERIFICATION_TIMEOUT); 9742 } 9743 9744 /** 9745 * Get the default verification agent response code. 9746 * 9747 * @return default verification response code 9748 */ 9749 private int getDefaultVerificationResponse() { 9750 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9751 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9752 DEFAULT_VERIFICATION_RESPONSE); 9753 } 9754 9755 /** 9756 * Check whether or not package verification has been enabled. 9757 * 9758 * @return true if verification should be performed 9759 */ 9760 private boolean isVerificationEnabled(int userId, int installFlags) { 9761 if (!DEFAULT_VERIFY_ENABLE) { 9762 return false; 9763 } 9764 9765 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9766 9767 // Check if installing from ADB 9768 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9769 // Do not run verification in a test harness environment 9770 if (ActivityManager.isRunningInTestHarness()) { 9771 return false; 9772 } 9773 if (ensureVerifyAppsEnabled) { 9774 return true; 9775 } 9776 // Check if the developer does not want package verification for ADB installs 9777 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9778 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9779 return false; 9780 } 9781 } 9782 9783 if (ensureVerifyAppsEnabled) { 9784 return true; 9785 } 9786 9787 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9788 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9789 } 9790 9791 @Override 9792 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9793 throws RemoteException { 9794 mContext.enforceCallingOrSelfPermission( 9795 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9796 "Only intentfilter verification agents can verify applications"); 9797 9798 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9799 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9800 Binder.getCallingUid(), verificationCode, failedDomains); 9801 msg.arg1 = id; 9802 msg.obj = response; 9803 mHandler.sendMessage(msg); 9804 } 9805 9806 @Override 9807 public int getIntentVerificationStatus(String packageName, int userId) { 9808 synchronized (mPackages) { 9809 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9810 } 9811 } 9812 9813 @Override 9814 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9815 mContext.enforceCallingOrSelfPermission( 9816 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9817 9818 boolean result = false; 9819 synchronized (mPackages) { 9820 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9821 } 9822 if (result) { 9823 scheduleWritePackageRestrictionsLocked(userId); 9824 } 9825 return result; 9826 } 9827 9828 @Override 9829 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9830 synchronized (mPackages) { 9831 return mSettings.getIntentFilterVerificationsLPr(packageName); 9832 } 9833 } 9834 9835 @Override 9836 public List<IntentFilter> getAllIntentFilters(String packageName) { 9837 if (TextUtils.isEmpty(packageName)) { 9838 return Collections.<IntentFilter>emptyList(); 9839 } 9840 synchronized (mPackages) { 9841 PackageParser.Package pkg = mPackages.get(packageName); 9842 if (pkg == null || pkg.activities == null) { 9843 return Collections.<IntentFilter>emptyList(); 9844 } 9845 final int count = pkg.activities.size(); 9846 ArrayList<IntentFilter> result = new ArrayList<>(); 9847 for (int n=0; n<count; n++) { 9848 PackageParser.Activity activity = pkg.activities.get(n); 9849 if (activity.intents != null || activity.intents.size() > 0) { 9850 result.addAll(activity.intents); 9851 } 9852 } 9853 return result; 9854 } 9855 } 9856 9857 @Override 9858 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9859 mContext.enforceCallingOrSelfPermission( 9860 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 9861 9862 synchronized (mPackages) { 9863 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 9864 if (packageName != null) { 9865 result |= updateIntentVerificationStatus(packageName, 9866 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9867 UserHandle.myUserId()); 9868 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 9869 packageName, userId); 9870 } 9871 return result; 9872 } 9873 } 9874 9875 @Override 9876 public String getDefaultBrowserPackageName(int userId) { 9877 synchronized (mPackages) { 9878 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9879 } 9880 } 9881 9882 /** 9883 * Get the "allow unknown sources" setting. 9884 * 9885 * @return the current "allow unknown sources" setting 9886 */ 9887 private int getUnknownSourcesSettings() { 9888 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9889 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9890 -1); 9891 } 9892 9893 @Override 9894 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9895 final int uid = Binder.getCallingUid(); 9896 // writer 9897 synchronized (mPackages) { 9898 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9899 if (targetPackageSetting == null) { 9900 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9901 } 9902 9903 PackageSetting installerPackageSetting; 9904 if (installerPackageName != null) { 9905 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9906 if (installerPackageSetting == null) { 9907 throw new IllegalArgumentException("Unknown installer package: " 9908 + installerPackageName); 9909 } 9910 } else { 9911 installerPackageSetting = null; 9912 } 9913 9914 Signature[] callerSignature; 9915 Object obj = mSettings.getUserIdLPr(uid); 9916 if (obj != null) { 9917 if (obj instanceof SharedUserSetting) { 9918 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9919 } else if (obj instanceof PackageSetting) { 9920 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9921 } else { 9922 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9923 } 9924 } else { 9925 throw new SecurityException("Unknown calling uid " + uid); 9926 } 9927 9928 // Verify: can't set installerPackageName to a package that is 9929 // not signed with the same cert as the caller. 9930 if (installerPackageSetting != null) { 9931 if (compareSignatures(callerSignature, 9932 installerPackageSetting.signatures.mSignatures) 9933 != PackageManager.SIGNATURE_MATCH) { 9934 throw new SecurityException( 9935 "Caller does not have same cert as new installer package " 9936 + installerPackageName); 9937 } 9938 } 9939 9940 // Verify: if target already has an installer package, it must 9941 // be signed with the same cert as the caller. 9942 if (targetPackageSetting.installerPackageName != null) { 9943 PackageSetting setting = mSettings.mPackages.get( 9944 targetPackageSetting.installerPackageName); 9945 // If the currently set package isn't valid, then it's always 9946 // okay to change it. 9947 if (setting != null) { 9948 if (compareSignatures(callerSignature, 9949 setting.signatures.mSignatures) 9950 != PackageManager.SIGNATURE_MATCH) { 9951 throw new SecurityException( 9952 "Caller does not have same cert as old installer package " 9953 + targetPackageSetting.installerPackageName); 9954 } 9955 } 9956 } 9957 9958 // Okay! 9959 targetPackageSetting.installerPackageName = installerPackageName; 9960 scheduleWriteSettingsLocked(); 9961 } 9962 } 9963 9964 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9965 // Queue up an async operation since the package installation may take a little while. 9966 mHandler.post(new Runnable() { 9967 public void run() { 9968 mHandler.removeCallbacks(this); 9969 // Result object to be returned 9970 PackageInstalledInfo res = new PackageInstalledInfo(); 9971 res.returnCode = currentStatus; 9972 res.uid = -1; 9973 res.pkg = null; 9974 res.removedInfo = new PackageRemovedInfo(); 9975 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9976 args.doPreInstall(res.returnCode); 9977 synchronized (mInstallLock) { 9978 installPackageLI(args, res); 9979 } 9980 args.doPostInstall(res.returnCode, res.uid); 9981 } 9982 9983 // A restore should be performed at this point if (a) the install 9984 // succeeded, (b) the operation is not an update, and (c) the new 9985 // package has not opted out of backup participation. 9986 final boolean update = res.removedInfo.removedPackage != null; 9987 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9988 boolean doRestore = !update 9989 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9990 9991 // Set up the post-install work request bookkeeping. This will be used 9992 // and cleaned up by the post-install event handling regardless of whether 9993 // there's a restore pass performed. Token values are >= 1. 9994 int token; 9995 if (mNextInstallToken < 0) mNextInstallToken = 1; 9996 token = mNextInstallToken++; 9997 9998 PostInstallData data = new PostInstallData(args, res); 9999 mRunningInstalls.put(token, data); 10000 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10001 10002 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10003 // Pass responsibility to the Backup Manager. It will perform a 10004 // restore if appropriate, then pass responsibility back to the 10005 // Package Manager to run the post-install observer callbacks 10006 // and broadcasts. 10007 IBackupManager bm = IBackupManager.Stub.asInterface( 10008 ServiceManager.getService(Context.BACKUP_SERVICE)); 10009 if (bm != null) { 10010 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10011 + " to BM for possible restore"); 10012 try { 10013 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 10014 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10015 } else { 10016 doRestore = false; 10017 } 10018 } catch (RemoteException e) { 10019 // can't happen; the backup manager is local 10020 } catch (Exception e) { 10021 Slog.e(TAG, "Exception trying to enqueue restore", e); 10022 doRestore = false; 10023 } 10024 } else { 10025 Slog.e(TAG, "Backup Manager not found!"); 10026 doRestore = false; 10027 } 10028 } 10029 10030 if (!doRestore) { 10031 // No restore possible, or the Backup Manager was mysteriously not 10032 // available -- just fire the post-install work request directly. 10033 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10034 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10035 mHandler.sendMessage(msg); 10036 } 10037 } 10038 }); 10039 } 10040 10041 private abstract class HandlerParams { 10042 private static final int MAX_RETRIES = 4; 10043 10044 /** 10045 * Number of times startCopy() has been attempted and had a non-fatal 10046 * error. 10047 */ 10048 private int mRetries = 0; 10049 10050 /** User handle for the user requesting the information or installation. */ 10051 private final UserHandle mUser; 10052 10053 HandlerParams(UserHandle user) { 10054 mUser = user; 10055 } 10056 10057 UserHandle getUser() { 10058 return mUser; 10059 } 10060 10061 final boolean startCopy() { 10062 boolean res; 10063 try { 10064 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10065 10066 if (++mRetries > MAX_RETRIES) { 10067 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10068 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10069 handleServiceError(); 10070 return false; 10071 } else { 10072 handleStartCopy(); 10073 res = true; 10074 } 10075 } catch (RemoteException e) { 10076 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10077 mHandler.sendEmptyMessage(MCS_RECONNECT); 10078 res = false; 10079 } 10080 handleReturnCode(); 10081 return res; 10082 } 10083 10084 final void serviceError() { 10085 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10086 handleServiceError(); 10087 handleReturnCode(); 10088 } 10089 10090 abstract void handleStartCopy() throws RemoteException; 10091 abstract void handleServiceError(); 10092 abstract void handleReturnCode(); 10093 } 10094 10095 class MeasureParams extends HandlerParams { 10096 private final PackageStats mStats; 10097 private boolean mSuccess; 10098 10099 private final IPackageStatsObserver mObserver; 10100 10101 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10102 super(new UserHandle(stats.userHandle)); 10103 mObserver = observer; 10104 mStats = stats; 10105 } 10106 10107 @Override 10108 public String toString() { 10109 return "MeasureParams{" 10110 + Integer.toHexString(System.identityHashCode(this)) 10111 + " " + mStats.packageName + "}"; 10112 } 10113 10114 @Override 10115 void handleStartCopy() throws RemoteException { 10116 synchronized (mInstallLock) { 10117 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10118 } 10119 10120 if (mSuccess) { 10121 final boolean mounted; 10122 if (Environment.isExternalStorageEmulated()) { 10123 mounted = true; 10124 } else { 10125 final String status = Environment.getExternalStorageState(); 10126 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10127 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10128 } 10129 10130 if (mounted) { 10131 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10132 10133 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10134 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10135 10136 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10137 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10138 10139 // Always subtract cache size, since it's a subdirectory 10140 mStats.externalDataSize -= mStats.externalCacheSize; 10141 10142 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10143 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10144 10145 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10146 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10147 } 10148 } 10149 } 10150 10151 @Override 10152 void handleReturnCode() { 10153 if (mObserver != null) { 10154 try { 10155 mObserver.onGetStatsCompleted(mStats, mSuccess); 10156 } catch (RemoteException e) { 10157 Slog.i(TAG, "Observer no longer exists."); 10158 } 10159 } 10160 } 10161 10162 @Override 10163 void handleServiceError() { 10164 Slog.e(TAG, "Could not measure application " + mStats.packageName 10165 + " external storage"); 10166 } 10167 } 10168 10169 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10170 throws RemoteException { 10171 long result = 0; 10172 for (File path : paths) { 10173 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10174 } 10175 return result; 10176 } 10177 10178 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10179 for (File path : paths) { 10180 try { 10181 mcs.clearDirectory(path.getAbsolutePath()); 10182 } catch (RemoteException e) { 10183 } 10184 } 10185 } 10186 10187 static class OriginInfo { 10188 /** 10189 * Location where install is coming from, before it has been 10190 * copied/renamed into place. This could be a single monolithic APK 10191 * file, or a cluster directory. This location may be untrusted. 10192 */ 10193 final File file; 10194 final String cid; 10195 10196 /** 10197 * Flag indicating that {@link #file} or {@link #cid} has already been 10198 * staged, meaning downstream users don't need to defensively copy the 10199 * contents. 10200 */ 10201 final boolean staged; 10202 10203 /** 10204 * Flag indicating that {@link #file} or {@link #cid} is an already 10205 * installed app that is being moved. 10206 */ 10207 final boolean existing; 10208 10209 final String resolvedPath; 10210 final File resolvedFile; 10211 10212 static OriginInfo fromNothing() { 10213 return new OriginInfo(null, null, false, false); 10214 } 10215 10216 static OriginInfo fromUntrustedFile(File file) { 10217 return new OriginInfo(file, null, false, false); 10218 } 10219 10220 static OriginInfo fromExistingFile(File file) { 10221 return new OriginInfo(file, null, false, true); 10222 } 10223 10224 static OriginInfo fromStagedFile(File file) { 10225 return new OriginInfo(file, null, true, false); 10226 } 10227 10228 static OriginInfo fromStagedContainer(String cid) { 10229 return new OriginInfo(null, cid, true, false); 10230 } 10231 10232 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10233 this.file = file; 10234 this.cid = cid; 10235 this.staged = staged; 10236 this.existing = existing; 10237 10238 if (cid != null) { 10239 resolvedPath = PackageHelper.getSdDir(cid); 10240 resolvedFile = new File(resolvedPath); 10241 } else if (file != null) { 10242 resolvedPath = file.getAbsolutePath(); 10243 resolvedFile = file; 10244 } else { 10245 resolvedPath = null; 10246 resolvedFile = null; 10247 } 10248 } 10249 } 10250 10251 class MoveInfo { 10252 final int moveId; 10253 final String fromUuid; 10254 final String toUuid; 10255 final String packageName; 10256 final String dataAppName; 10257 final int appId; 10258 final String seinfo; 10259 10260 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10261 String dataAppName, int appId, String seinfo) { 10262 this.moveId = moveId; 10263 this.fromUuid = fromUuid; 10264 this.toUuid = toUuid; 10265 this.packageName = packageName; 10266 this.dataAppName = dataAppName; 10267 this.appId = appId; 10268 this.seinfo = seinfo; 10269 } 10270 } 10271 10272 class InstallParams extends HandlerParams { 10273 final OriginInfo origin; 10274 final MoveInfo move; 10275 final IPackageInstallObserver2 observer; 10276 int installFlags; 10277 final String installerPackageName; 10278 final String volumeUuid; 10279 final VerificationParams verificationParams; 10280 private InstallArgs mArgs; 10281 private int mRet; 10282 final String packageAbiOverride; 10283 10284 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10285 int installFlags, String installerPackageName, String volumeUuid, 10286 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 10287 super(user); 10288 this.origin = origin; 10289 this.move = move; 10290 this.observer = observer; 10291 this.installFlags = installFlags; 10292 this.installerPackageName = installerPackageName; 10293 this.volumeUuid = volumeUuid; 10294 this.verificationParams = verificationParams; 10295 this.packageAbiOverride = packageAbiOverride; 10296 } 10297 10298 @Override 10299 public String toString() { 10300 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10301 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10302 } 10303 10304 public ManifestDigest getManifestDigest() { 10305 if (verificationParams == null) { 10306 return null; 10307 } 10308 return verificationParams.getManifestDigest(); 10309 } 10310 10311 private int installLocationPolicy(PackageInfoLite pkgLite) { 10312 String packageName = pkgLite.packageName; 10313 int installLocation = pkgLite.installLocation; 10314 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10315 // reader 10316 synchronized (mPackages) { 10317 PackageParser.Package pkg = mPackages.get(packageName); 10318 if (pkg != null) { 10319 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10320 // Check for downgrading. 10321 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 10322 try { 10323 checkDowngrade(pkg, pkgLite); 10324 } catch (PackageManagerException e) { 10325 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 10326 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 10327 } 10328 } 10329 // Check for updated system application. 10330 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10331 if (onSd) { 10332 Slog.w(TAG, "Cannot install update to system app on sdcard"); 10333 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 10334 } 10335 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10336 } else { 10337 if (onSd) { 10338 // Install flag overrides everything. 10339 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10340 } 10341 // If current upgrade specifies particular preference 10342 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10343 // Application explicitly specified internal. 10344 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10345 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10346 // App explictly prefers external. Let policy decide 10347 } else { 10348 // Prefer previous location 10349 if (isExternal(pkg)) { 10350 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10351 } 10352 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10353 } 10354 } 10355 } else { 10356 // Invalid install. Return error code 10357 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10358 } 10359 } 10360 } 10361 // All the special cases have been taken care of. 10362 // Return result based on recommended install location. 10363 if (onSd) { 10364 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10365 } 10366 return pkgLite.recommendedInstallLocation; 10367 } 10368 10369 /* 10370 * Invoke remote method to get package information and install 10371 * location values. Override install location based on default 10372 * policy if needed and then create install arguments based 10373 * on the install location. 10374 */ 10375 public void handleStartCopy() throws RemoteException { 10376 int ret = PackageManager.INSTALL_SUCCEEDED; 10377 10378 // If we're already staged, we've firmly committed to an install location 10379 if (origin.staged) { 10380 if (origin.file != null) { 10381 installFlags |= PackageManager.INSTALL_INTERNAL; 10382 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10383 } else if (origin.cid != null) { 10384 installFlags |= PackageManager.INSTALL_EXTERNAL; 10385 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10386 } else { 10387 throw new IllegalStateException("Invalid stage location"); 10388 } 10389 } 10390 10391 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10392 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10393 10394 PackageInfoLite pkgLite = null; 10395 10396 if (onInt && onSd) { 10397 // Check if both bits are set. 10398 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10399 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10400 } else { 10401 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10402 packageAbiOverride); 10403 10404 /* 10405 * If we have too little free space, try to free cache 10406 * before giving up. 10407 */ 10408 if (!origin.staged && pkgLite.recommendedInstallLocation 10409 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10410 // TODO: focus freeing disk space on the target device 10411 final StorageManager storage = StorageManager.from(mContext); 10412 final long lowThreshold = storage.getStorageLowBytes( 10413 Environment.getDataDirectory()); 10414 10415 final long sizeBytes = mContainerService.calculateInstalledSize( 10416 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10417 10418 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10419 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10420 installFlags, packageAbiOverride); 10421 } 10422 10423 /* 10424 * The cache free must have deleted the file we 10425 * downloaded to install. 10426 * 10427 * TODO: fix the "freeCache" call to not delete 10428 * the file we care about. 10429 */ 10430 if (pkgLite.recommendedInstallLocation 10431 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10432 pkgLite.recommendedInstallLocation 10433 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10434 } 10435 } 10436 } 10437 10438 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10439 int loc = pkgLite.recommendedInstallLocation; 10440 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10441 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10442 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10443 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10444 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10445 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10446 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10447 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10448 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10449 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10450 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10451 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10452 } else { 10453 // Override with defaults if needed. 10454 loc = installLocationPolicy(pkgLite); 10455 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10456 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10457 } else if (!onSd && !onInt) { 10458 // Override install location with flags 10459 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10460 // Set the flag to install on external media. 10461 installFlags |= PackageManager.INSTALL_EXTERNAL; 10462 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10463 } else { 10464 // Make sure the flag for installing on external 10465 // media is unset 10466 installFlags |= PackageManager.INSTALL_INTERNAL; 10467 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10468 } 10469 } 10470 } 10471 } 10472 10473 final InstallArgs args = createInstallArgs(this); 10474 mArgs = args; 10475 10476 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10477 /* 10478 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10479 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10480 */ 10481 int userIdentifier = getUser().getIdentifier(); 10482 if (userIdentifier == UserHandle.USER_ALL 10483 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10484 userIdentifier = UserHandle.USER_OWNER; 10485 } 10486 10487 /* 10488 * Determine if we have any installed package verifiers. If we 10489 * do, then we'll defer to them to verify the packages. 10490 */ 10491 final int requiredUid = mRequiredVerifierPackage == null ? -1 10492 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10493 if (!origin.existing && requiredUid != -1 10494 && isVerificationEnabled(userIdentifier, installFlags)) { 10495 final Intent verification = new Intent( 10496 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10497 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10498 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10499 PACKAGE_MIME_TYPE); 10500 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10501 10502 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10503 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10504 0 /* TODO: Which userId? */); 10505 10506 if (DEBUG_VERIFY) { 10507 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10508 + verification.toString() + " with " + pkgLite.verifiers.length 10509 + " optional verifiers"); 10510 } 10511 10512 final int verificationId = mPendingVerificationToken++; 10513 10514 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10515 10516 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10517 installerPackageName); 10518 10519 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10520 installFlags); 10521 10522 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10523 pkgLite.packageName); 10524 10525 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10526 pkgLite.versionCode); 10527 10528 if (verificationParams != null) { 10529 if (verificationParams.getVerificationURI() != null) { 10530 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10531 verificationParams.getVerificationURI()); 10532 } 10533 if (verificationParams.getOriginatingURI() != null) { 10534 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10535 verificationParams.getOriginatingURI()); 10536 } 10537 if (verificationParams.getReferrer() != null) { 10538 verification.putExtra(Intent.EXTRA_REFERRER, 10539 verificationParams.getReferrer()); 10540 } 10541 if (verificationParams.getOriginatingUid() >= 0) { 10542 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10543 verificationParams.getOriginatingUid()); 10544 } 10545 if (verificationParams.getInstallerUid() >= 0) { 10546 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10547 verificationParams.getInstallerUid()); 10548 } 10549 } 10550 10551 final PackageVerificationState verificationState = new PackageVerificationState( 10552 requiredUid, args); 10553 10554 mPendingVerification.append(verificationId, verificationState); 10555 10556 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10557 receivers, verificationState); 10558 10559 /* 10560 * If any sufficient verifiers were listed in the package 10561 * manifest, attempt to ask them. 10562 */ 10563 if (sufficientVerifiers != null) { 10564 final int N = sufficientVerifiers.size(); 10565 if (N == 0) { 10566 Slog.i(TAG, "Additional verifiers required, but none installed."); 10567 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10568 } else { 10569 for (int i = 0; i < N; i++) { 10570 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10571 10572 final Intent sufficientIntent = new Intent(verification); 10573 sufficientIntent.setComponent(verifierComponent); 10574 10575 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10576 } 10577 } 10578 } 10579 10580 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10581 mRequiredVerifierPackage, receivers); 10582 if (ret == PackageManager.INSTALL_SUCCEEDED 10583 && mRequiredVerifierPackage != null) { 10584 /* 10585 * Send the intent to the required verification agent, 10586 * but only start the verification timeout after the 10587 * target BroadcastReceivers have run. 10588 */ 10589 verification.setComponent(requiredVerifierComponent); 10590 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10591 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10592 new BroadcastReceiver() { 10593 @Override 10594 public void onReceive(Context context, Intent intent) { 10595 final Message msg = mHandler 10596 .obtainMessage(CHECK_PENDING_VERIFICATION); 10597 msg.arg1 = verificationId; 10598 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10599 } 10600 }, null, 0, null, null); 10601 10602 /* 10603 * We don't want the copy to proceed until verification 10604 * succeeds, so null out this field. 10605 */ 10606 mArgs = null; 10607 } 10608 } else { 10609 /* 10610 * No package verification is enabled, so immediately start 10611 * the remote call to initiate copy using temporary file. 10612 */ 10613 ret = args.copyApk(mContainerService, true); 10614 } 10615 } 10616 10617 mRet = ret; 10618 } 10619 10620 @Override 10621 void handleReturnCode() { 10622 // If mArgs is null, then MCS couldn't be reached. When it 10623 // reconnects, it will try again to install. At that point, this 10624 // will succeed. 10625 if (mArgs != null) { 10626 processPendingInstall(mArgs, mRet); 10627 } 10628 } 10629 10630 @Override 10631 void handleServiceError() { 10632 mArgs = createInstallArgs(this); 10633 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10634 } 10635 10636 public boolean isForwardLocked() { 10637 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10638 } 10639 } 10640 10641 /** 10642 * Used during creation of InstallArgs 10643 * 10644 * @param installFlags package installation flags 10645 * @return true if should be installed on external storage 10646 */ 10647 private static boolean installOnExternalAsec(int installFlags) { 10648 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10649 return false; 10650 } 10651 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10652 return true; 10653 } 10654 return false; 10655 } 10656 10657 /** 10658 * Used during creation of InstallArgs 10659 * 10660 * @param installFlags package installation flags 10661 * @return true if should be installed as forward locked 10662 */ 10663 private static boolean installForwardLocked(int installFlags) { 10664 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10665 } 10666 10667 private InstallArgs createInstallArgs(InstallParams params) { 10668 if (params.move != null) { 10669 return new MoveInstallArgs(params); 10670 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10671 return new AsecInstallArgs(params); 10672 } else { 10673 return new FileInstallArgs(params); 10674 } 10675 } 10676 10677 /** 10678 * Create args that describe an existing installed package. Typically used 10679 * when cleaning up old installs, or used as a move source. 10680 */ 10681 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10682 String resourcePath, String[] instructionSets) { 10683 final boolean isInAsec; 10684 if (installOnExternalAsec(installFlags)) { 10685 /* Apps on SD card are always in ASEC containers. */ 10686 isInAsec = true; 10687 } else if (installForwardLocked(installFlags) 10688 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10689 /* 10690 * Forward-locked apps are only in ASEC containers if they're the 10691 * new style 10692 */ 10693 isInAsec = true; 10694 } else { 10695 isInAsec = false; 10696 } 10697 10698 if (isInAsec) { 10699 return new AsecInstallArgs(codePath, instructionSets, 10700 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10701 } else { 10702 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10703 } 10704 } 10705 10706 static abstract class InstallArgs { 10707 /** @see InstallParams#origin */ 10708 final OriginInfo origin; 10709 /** @see InstallParams#move */ 10710 final MoveInfo move; 10711 10712 final IPackageInstallObserver2 observer; 10713 // Always refers to PackageManager flags only 10714 final int installFlags; 10715 final String installerPackageName; 10716 final String volumeUuid; 10717 final ManifestDigest manifestDigest; 10718 final UserHandle user; 10719 final String abiOverride; 10720 10721 // The list of instruction sets supported by this app. This is currently 10722 // only used during the rmdex() phase to clean up resources. We can get rid of this 10723 // if we move dex files under the common app path. 10724 /* nullable */ String[] instructionSets; 10725 10726 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10727 int installFlags, String installerPackageName, String volumeUuid, 10728 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10729 String abiOverride) { 10730 this.origin = origin; 10731 this.move = move; 10732 this.installFlags = installFlags; 10733 this.observer = observer; 10734 this.installerPackageName = installerPackageName; 10735 this.volumeUuid = volumeUuid; 10736 this.manifestDigest = manifestDigest; 10737 this.user = user; 10738 this.instructionSets = instructionSets; 10739 this.abiOverride = abiOverride; 10740 } 10741 10742 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10743 abstract int doPreInstall(int status); 10744 10745 /** 10746 * Rename package into final resting place. All paths on the given 10747 * scanned package should be updated to reflect the rename. 10748 */ 10749 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10750 abstract int doPostInstall(int status, int uid); 10751 10752 /** @see PackageSettingBase#codePathString */ 10753 abstract String getCodePath(); 10754 /** @see PackageSettingBase#resourcePathString */ 10755 abstract String getResourcePath(); 10756 10757 // Need installer lock especially for dex file removal. 10758 abstract void cleanUpResourcesLI(); 10759 abstract boolean doPostDeleteLI(boolean delete); 10760 10761 /** 10762 * Called before the source arguments are copied. This is used mostly 10763 * for MoveParams when it needs to read the source file to put it in the 10764 * destination. 10765 */ 10766 int doPreCopy() { 10767 return PackageManager.INSTALL_SUCCEEDED; 10768 } 10769 10770 /** 10771 * Called after the source arguments are copied. This is used mostly for 10772 * MoveParams when it needs to read the source file to put it in the 10773 * destination. 10774 * 10775 * @return 10776 */ 10777 int doPostCopy(int uid) { 10778 return PackageManager.INSTALL_SUCCEEDED; 10779 } 10780 10781 protected boolean isFwdLocked() { 10782 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10783 } 10784 10785 protected boolean isExternalAsec() { 10786 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10787 } 10788 10789 UserHandle getUser() { 10790 return user; 10791 } 10792 } 10793 10794 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10795 if (!allCodePaths.isEmpty()) { 10796 if (instructionSets == null) { 10797 throw new IllegalStateException("instructionSet == null"); 10798 } 10799 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10800 for (String codePath : allCodePaths) { 10801 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10802 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10803 if (retCode < 0) { 10804 Slog.w(TAG, "Couldn't remove dex file for package: " 10805 + " at location " + codePath + ", retcode=" + retCode); 10806 // we don't consider this to be a failure of the core package deletion 10807 } 10808 } 10809 } 10810 } 10811 } 10812 10813 /** 10814 * Logic to handle installation of non-ASEC applications, including copying 10815 * and renaming logic. 10816 */ 10817 class FileInstallArgs extends InstallArgs { 10818 private File codeFile; 10819 private File resourceFile; 10820 10821 // Example topology: 10822 // /data/app/com.example/base.apk 10823 // /data/app/com.example/split_foo.apk 10824 // /data/app/com.example/lib/arm/libfoo.so 10825 // /data/app/com.example/lib/arm64/libfoo.so 10826 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10827 10828 /** New install */ 10829 FileInstallArgs(InstallParams params) { 10830 super(params.origin, params.move, params.observer, params.installFlags, 10831 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10832 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10833 if (isFwdLocked()) { 10834 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10835 } 10836 } 10837 10838 /** Existing install */ 10839 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10840 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10841 null); 10842 this.codeFile = (codePath != null) ? new File(codePath) : null; 10843 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10844 } 10845 10846 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10847 if (origin.staged) { 10848 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10849 codeFile = origin.file; 10850 resourceFile = origin.file; 10851 return PackageManager.INSTALL_SUCCEEDED; 10852 } 10853 10854 try { 10855 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10856 codeFile = tempDir; 10857 resourceFile = tempDir; 10858 } catch (IOException e) { 10859 Slog.w(TAG, "Failed to create copy file: " + e); 10860 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10861 } 10862 10863 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10864 @Override 10865 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10866 if (!FileUtils.isValidExtFilename(name)) { 10867 throw new IllegalArgumentException("Invalid filename: " + name); 10868 } 10869 try { 10870 final File file = new File(codeFile, name); 10871 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10872 O_RDWR | O_CREAT, 0644); 10873 Os.chmod(file.getAbsolutePath(), 0644); 10874 return new ParcelFileDescriptor(fd); 10875 } catch (ErrnoException e) { 10876 throw new RemoteException("Failed to open: " + e.getMessage()); 10877 } 10878 } 10879 }; 10880 10881 int ret = PackageManager.INSTALL_SUCCEEDED; 10882 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10883 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10884 Slog.e(TAG, "Failed to copy package"); 10885 return ret; 10886 } 10887 10888 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10889 NativeLibraryHelper.Handle handle = null; 10890 try { 10891 handle = NativeLibraryHelper.Handle.create(codeFile); 10892 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10893 abiOverride); 10894 } catch (IOException e) { 10895 Slog.e(TAG, "Copying native libraries failed", e); 10896 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10897 } finally { 10898 IoUtils.closeQuietly(handle); 10899 } 10900 10901 return ret; 10902 } 10903 10904 int doPreInstall(int status) { 10905 if (status != PackageManager.INSTALL_SUCCEEDED) { 10906 cleanUp(); 10907 } 10908 return status; 10909 } 10910 10911 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10912 if (status != PackageManager.INSTALL_SUCCEEDED) { 10913 cleanUp(); 10914 return false; 10915 } 10916 10917 final File targetDir = codeFile.getParentFile(); 10918 final File beforeCodeFile = codeFile; 10919 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10920 10921 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10922 try { 10923 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10924 } catch (ErrnoException e) { 10925 Slog.w(TAG, "Failed to rename", e); 10926 return false; 10927 } 10928 10929 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10930 Slog.w(TAG, "Failed to restorecon"); 10931 return false; 10932 } 10933 10934 // Reflect the rename internally 10935 codeFile = afterCodeFile; 10936 resourceFile = afterCodeFile; 10937 10938 // Reflect the rename in scanned details 10939 pkg.codePath = afterCodeFile.getAbsolutePath(); 10940 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10941 pkg.baseCodePath); 10942 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10943 pkg.splitCodePaths); 10944 10945 // Reflect the rename in app info 10946 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10947 pkg.applicationInfo.setCodePath(pkg.codePath); 10948 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10949 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10950 pkg.applicationInfo.setResourcePath(pkg.codePath); 10951 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10952 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10953 10954 return true; 10955 } 10956 10957 int doPostInstall(int status, int uid) { 10958 if (status != PackageManager.INSTALL_SUCCEEDED) { 10959 cleanUp(); 10960 } 10961 return status; 10962 } 10963 10964 @Override 10965 String getCodePath() { 10966 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10967 } 10968 10969 @Override 10970 String getResourcePath() { 10971 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10972 } 10973 10974 private boolean cleanUp() { 10975 if (codeFile == null || !codeFile.exists()) { 10976 return false; 10977 } 10978 10979 if (codeFile.isDirectory()) { 10980 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10981 } else { 10982 codeFile.delete(); 10983 } 10984 10985 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10986 resourceFile.delete(); 10987 } 10988 10989 return true; 10990 } 10991 10992 void cleanUpResourcesLI() { 10993 // Try enumerating all code paths before deleting 10994 List<String> allCodePaths = Collections.EMPTY_LIST; 10995 if (codeFile != null && codeFile.exists()) { 10996 try { 10997 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10998 allCodePaths = pkg.getAllCodePaths(); 10999 } catch (PackageParserException e) { 11000 // Ignored; we tried our best 11001 } 11002 } 11003 11004 cleanUp(); 11005 removeDexFiles(allCodePaths, instructionSets); 11006 } 11007 11008 boolean doPostDeleteLI(boolean delete) { 11009 // XXX err, shouldn't we respect the delete flag? 11010 cleanUpResourcesLI(); 11011 return true; 11012 } 11013 } 11014 11015 private boolean isAsecExternal(String cid) { 11016 final String asecPath = PackageHelper.getSdFilesystem(cid); 11017 return !asecPath.startsWith(mAsecInternalPath); 11018 } 11019 11020 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11021 PackageManagerException { 11022 if (copyRet < 0) { 11023 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11024 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11025 throw new PackageManagerException(copyRet, message); 11026 } 11027 } 11028 } 11029 11030 /** 11031 * Extract the MountService "container ID" from the full code path of an 11032 * .apk. 11033 */ 11034 static String cidFromCodePath(String fullCodePath) { 11035 int eidx = fullCodePath.lastIndexOf("/"); 11036 String subStr1 = fullCodePath.substring(0, eidx); 11037 int sidx = subStr1.lastIndexOf("/"); 11038 return subStr1.substring(sidx+1, eidx); 11039 } 11040 11041 /** 11042 * Logic to handle installation of ASEC applications, including copying and 11043 * renaming logic. 11044 */ 11045 class AsecInstallArgs extends InstallArgs { 11046 static final String RES_FILE_NAME = "pkg.apk"; 11047 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11048 11049 String cid; 11050 String packagePath; 11051 String resourcePath; 11052 11053 /** New install */ 11054 AsecInstallArgs(InstallParams params) { 11055 super(params.origin, params.move, params.observer, params.installFlags, 11056 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11057 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11058 } 11059 11060 /** Existing install */ 11061 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11062 boolean isExternal, boolean isForwardLocked) { 11063 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11064 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11065 instructionSets, null); 11066 // Hackily pretend we're still looking at a full code path 11067 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11068 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11069 } 11070 11071 // Extract cid from fullCodePath 11072 int eidx = fullCodePath.lastIndexOf("/"); 11073 String subStr1 = fullCodePath.substring(0, eidx); 11074 int sidx = subStr1.lastIndexOf("/"); 11075 cid = subStr1.substring(sidx+1, eidx); 11076 setMountPath(subStr1); 11077 } 11078 11079 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11080 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11081 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 11082 instructionSets, null); 11083 this.cid = cid; 11084 setMountPath(PackageHelper.getSdDir(cid)); 11085 } 11086 11087 void createCopyFile() { 11088 cid = mInstallerService.allocateExternalStageCidLegacy(); 11089 } 11090 11091 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11092 if (origin.staged) { 11093 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11094 cid = origin.cid; 11095 setMountPath(PackageHelper.getSdDir(cid)); 11096 return PackageManager.INSTALL_SUCCEEDED; 11097 } 11098 11099 if (temp) { 11100 createCopyFile(); 11101 } else { 11102 /* 11103 * Pre-emptively destroy the container since it's destroyed if 11104 * copying fails due to it existing anyway. 11105 */ 11106 PackageHelper.destroySdDir(cid); 11107 } 11108 11109 final String newMountPath = imcs.copyPackageToContainer( 11110 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11111 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11112 11113 if (newMountPath != null) { 11114 setMountPath(newMountPath); 11115 return PackageManager.INSTALL_SUCCEEDED; 11116 } else { 11117 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11118 } 11119 } 11120 11121 @Override 11122 String getCodePath() { 11123 return packagePath; 11124 } 11125 11126 @Override 11127 String getResourcePath() { 11128 return resourcePath; 11129 } 11130 11131 int doPreInstall(int status) { 11132 if (status != PackageManager.INSTALL_SUCCEEDED) { 11133 // Destroy container 11134 PackageHelper.destroySdDir(cid); 11135 } else { 11136 boolean mounted = PackageHelper.isContainerMounted(cid); 11137 if (!mounted) { 11138 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11139 Process.SYSTEM_UID); 11140 if (newMountPath != null) { 11141 setMountPath(newMountPath); 11142 } else { 11143 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11144 } 11145 } 11146 } 11147 return status; 11148 } 11149 11150 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11151 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11152 String newMountPath = null; 11153 if (PackageHelper.isContainerMounted(cid)) { 11154 // Unmount the container 11155 if (!PackageHelper.unMountSdDir(cid)) { 11156 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11157 return false; 11158 } 11159 } 11160 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11161 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11162 " which might be stale. Will try to clean up."); 11163 // Clean up the stale container and proceed to recreate. 11164 if (!PackageHelper.destroySdDir(newCacheId)) { 11165 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11166 return false; 11167 } 11168 // Successfully cleaned up stale container. Try to rename again. 11169 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11170 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11171 + " inspite of cleaning it up."); 11172 return false; 11173 } 11174 } 11175 if (!PackageHelper.isContainerMounted(newCacheId)) { 11176 Slog.w(TAG, "Mounting container " + newCacheId); 11177 newMountPath = PackageHelper.mountSdDir(newCacheId, 11178 getEncryptKey(), Process.SYSTEM_UID); 11179 } else { 11180 newMountPath = PackageHelper.getSdDir(newCacheId); 11181 } 11182 if (newMountPath == null) { 11183 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11184 return false; 11185 } 11186 Log.i(TAG, "Succesfully renamed " + cid + 11187 " to " + newCacheId + 11188 " at new path: " + newMountPath); 11189 cid = newCacheId; 11190 11191 final File beforeCodeFile = new File(packagePath); 11192 setMountPath(newMountPath); 11193 final File afterCodeFile = new File(packagePath); 11194 11195 // Reflect the rename in scanned details 11196 pkg.codePath = afterCodeFile.getAbsolutePath(); 11197 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11198 pkg.baseCodePath); 11199 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11200 pkg.splitCodePaths); 11201 11202 // Reflect the rename in app info 11203 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11204 pkg.applicationInfo.setCodePath(pkg.codePath); 11205 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11206 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11207 pkg.applicationInfo.setResourcePath(pkg.codePath); 11208 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11209 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11210 11211 return true; 11212 } 11213 11214 private void setMountPath(String mountPath) { 11215 final File mountFile = new File(mountPath); 11216 11217 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11218 if (monolithicFile.exists()) { 11219 packagePath = monolithicFile.getAbsolutePath(); 11220 if (isFwdLocked()) { 11221 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11222 } else { 11223 resourcePath = packagePath; 11224 } 11225 } else { 11226 packagePath = mountFile.getAbsolutePath(); 11227 resourcePath = packagePath; 11228 } 11229 } 11230 11231 int doPostInstall(int status, int uid) { 11232 if (status != PackageManager.INSTALL_SUCCEEDED) { 11233 cleanUp(); 11234 } else { 11235 final int groupOwner; 11236 final String protectedFile; 11237 if (isFwdLocked()) { 11238 groupOwner = UserHandle.getSharedAppGid(uid); 11239 protectedFile = RES_FILE_NAME; 11240 } else { 11241 groupOwner = -1; 11242 protectedFile = null; 11243 } 11244 11245 if (uid < Process.FIRST_APPLICATION_UID 11246 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11247 Slog.e(TAG, "Failed to finalize " + cid); 11248 PackageHelper.destroySdDir(cid); 11249 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11250 } 11251 11252 boolean mounted = PackageHelper.isContainerMounted(cid); 11253 if (!mounted) { 11254 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11255 } 11256 } 11257 return status; 11258 } 11259 11260 private void cleanUp() { 11261 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11262 11263 // Destroy secure container 11264 PackageHelper.destroySdDir(cid); 11265 } 11266 11267 private List<String> getAllCodePaths() { 11268 final File codeFile = new File(getCodePath()); 11269 if (codeFile != null && codeFile.exists()) { 11270 try { 11271 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11272 return pkg.getAllCodePaths(); 11273 } catch (PackageParserException e) { 11274 // Ignored; we tried our best 11275 } 11276 } 11277 return Collections.EMPTY_LIST; 11278 } 11279 11280 void cleanUpResourcesLI() { 11281 // Enumerate all code paths before deleting 11282 cleanUpResourcesLI(getAllCodePaths()); 11283 } 11284 11285 private void cleanUpResourcesLI(List<String> allCodePaths) { 11286 cleanUp(); 11287 removeDexFiles(allCodePaths, instructionSets); 11288 } 11289 11290 String getPackageName() { 11291 return getAsecPackageName(cid); 11292 } 11293 11294 boolean doPostDeleteLI(boolean delete) { 11295 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 11296 final List<String> allCodePaths = getAllCodePaths(); 11297 boolean mounted = PackageHelper.isContainerMounted(cid); 11298 if (mounted) { 11299 // Unmount first 11300 if (PackageHelper.unMountSdDir(cid)) { 11301 mounted = false; 11302 } 11303 } 11304 if (!mounted && delete) { 11305 cleanUpResourcesLI(allCodePaths); 11306 } 11307 return !mounted; 11308 } 11309 11310 @Override 11311 int doPreCopy() { 11312 if (isFwdLocked()) { 11313 if (!PackageHelper.fixSdPermissions(cid, 11314 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 11315 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11316 } 11317 } 11318 11319 return PackageManager.INSTALL_SUCCEEDED; 11320 } 11321 11322 @Override 11323 int doPostCopy(int uid) { 11324 if (isFwdLocked()) { 11325 if (uid < Process.FIRST_APPLICATION_UID 11326 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 11327 RES_FILE_NAME)) { 11328 Slog.e(TAG, "Failed to finalize " + cid); 11329 PackageHelper.destroySdDir(cid); 11330 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11331 } 11332 } 11333 11334 return PackageManager.INSTALL_SUCCEEDED; 11335 } 11336 } 11337 11338 /** 11339 * Logic to handle movement of existing installed applications. 11340 */ 11341 class MoveInstallArgs extends InstallArgs { 11342 private File codeFile; 11343 private File resourceFile; 11344 11345 /** New install */ 11346 MoveInstallArgs(InstallParams params) { 11347 super(params.origin, params.move, params.observer, params.installFlags, 11348 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11349 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11350 } 11351 11352 int copyApk(IMediaContainerService imcs, boolean temp) { 11353 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11354 + move.fromUuid + " to " + move.toUuid); 11355 synchronized (mInstaller) { 11356 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11357 move.dataAppName, move.appId, move.seinfo) != 0) { 11358 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11359 } 11360 } 11361 11362 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11363 resourceFile = codeFile; 11364 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11365 11366 return PackageManager.INSTALL_SUCCEEDED; 11367 } 11368 11369 int doPreInstall(int status) { 11370 if (status != PackageManager.INSTALL_SUCCEEDED) { 11371 cleanUp(move.toUuid); 11372 } 11373 return status; 11374 } 11375 11376 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11377 if (status != PackageManager.INSTALL_SUCCEEDED) { 11378 cleanUp(move.toUuid); 11379 return false; 11380 } 11381 11382 // Reflect the move in app info 11383 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11384 pkg.applicationInfo.setCodePath(pkg.codePath); 11385 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11386 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11387 pkg.applicationInfo.setResourcePath(pkg.codePath); 11388 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11389 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11390 11391 return true; 11392 } 11393 11394 int doPostInstall(int status, int uid) { 11395 if (status == PackageManager.INSTALL_SUCCEEDED) { 11396 cleanUp(move.fromUuid); 11397 } else { 11398 cleanUp(move.toUuid); 11399 } 11400 return status; 11401 } 11402 11403 @Override 11404 String getCodePath() { 11405 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11406 } 11407 11408 @Override 11409 String getResourcePath() { 11410 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11411 } 11412 11413 private boolean cleanUp(String volumeUuid) { 11414 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 11415 move.dataAppName); 11416 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 11417 synchronized (mInstallLock) { 11418 // Clean up both app data and code 11419 removeDataDirsLI(volumeUuid, move.packageName); 11420 if (codeFile.isDirectory()) { 11421 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11422 } else { 11423 codeFile.delete(); 11424 } 11425 } 11426 return true; 11427 } 11428 11429 void cleanUpResourcesLI() { 11430 throw new UnsupportedOperationException(); 11431 } 11432 11433 boolean doPostDeleteLI(boolean delete) { 11434 throw new UnsupportedOperationException(); 11435 } 11436 } 11437 11438 static String getAsecPackageName(String packageCid) { 11439 int idx = packageCid.lastIndexOf("-"); 11440 if (idx == -1) { 11441 return packageCid; 11442 } 11443 return packageCid.substring(0, idx); 11444 } 11445 11446 // Utility method used to create code paths based on package name and available index. 11447 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11448 String idxStr = ""; 11449 int idx = 1; 11450 // Fall back to default value of idx=1 if prefix is not 11451 // part of oldCodePath 11452 if (oldCodePath != null) { 11453 String subStr = oldCodePath; 11454 // Drop the suffix right away 11455 if (suffix != null && subStr.endsWith(suffix)) { 11456 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11457 } 11458 // If oldCodePath already contains prefix find out the 11459 // ending index to either increment or decrement. 11460 int sidx = subStr.lastIndexOf(prefix); 11461 if (sidx != -1) { 11462 subStr = subStr.substring(sidx + prefix.length()); 11463 if (subStr != null) { 11464 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11465 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11466 } 11467 try { 11468 idx = Integer.parseInt(subStr); 11469 if (idx <= 1) { 11470 idx++; 11471 } else { 11472 idx--; 11473 } 11474 } catch(NumberFormatException e) { 11475 } 11476 } 11477 } 11478 } 11479 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11480 return prefix + idxStr; 11481 } 11482 11483 private File getNextCodePath(File targetDir, String packageName) { 11484 int suffix = 1; 11485 File result; 11486 do { 11487 result = new File(targetDir, packageName + "-" + suffix); 11488 suffix++; 11489 } while (result.exists()); 11490 return result; 11491 } 11492 11493 // Utility method that returns the relative package path with respect 11494 // to the installation directory. Like say for /data/data/com.test-1.apk 11495 // string com.test-1 is returned. 11496 static String deriveCodePathName(String codePath) { 11497 if (codePath == null) { 11498 return null; 11499 } 11500 final File codeFile = new File(codePath); 11501 final String name = codeFile.getName(); 11502 if (codeFile.isDirectory()) { 11503 return name; 11504 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11505 final int lastDot = name.lastIndexOf('.'); 11506 return name.substring(0, lastDot); 11507 } else { 11508 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11509 return null; 11510 } 11511 } 11512 11513 class PackageInstalledInfo { 11514 String name; 11515 int uid; 11516 // The set of users that originally had this package installed. 11517 int[] origUsers; 11518 // The set of users that now have this package installed. 11519 int[] newUsers; 11520 PackageParser.Package pkg; 11521 int returnCode; 11522 String returnMsg; 11523 PackageRemovedInfo removedInfo; 11524 11525 public void setError(int code, String msg) { 11526 returnCode = code; 11527 returnMsg = msg; 11528 Slog.w(TAG, msg); 11529 } 11530 11531 public void setError(String msg, PackageParserException e) { 11532 returnCode = e.error; 11533 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11534 Slog.w(TAG, msg, e); 11535 } 11536 11537 public void setError(String msg, PackageManagerException e) { 11538 returnCode = e.error; 11539 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11540 Slog.w(TAG, msg, e); 11541 } 11542 11543 // In some error cases we want to convey more info back to the observer 11544 String origPackage; 11545 String origPermission; 11546 } 11547 11548 /* 11549 * Install a non-existing package. 11550 */ 11551 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11552 UserHandle user, String installerPackageName, String volumeUuid, 11553 PackageInstalledInfo res) { 11554 // Remember this for later, in case we need to rollback this install 11555 String pkgName = pkg.packageName; 11556 11557 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11558 final boolean dataDirExists = Environment 11559 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists(); 11560 synchronized(mPackages) { 11561 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11562 // A package with the same name is already installed, though 11563 // it has been renamed to an older name. The package we 11564 // are trying to install should be installed as an update to 11565 // the existing one, but that has not been requested, so bail. 11566 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11567 + " without first uninstalling package running as " 11568 + mSettings.mRenamedPackages.get(pkgName)); 11569 return; 11570 } 11571 if (mPackages.containsKey(pkgName)) { 11572 // Don't allow installation over an existing package with the same name. 11573 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11574 + " without first uninstalling."); 11575 return; 11576 } 11577 } 11578 11579 try { 11580 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11581 System.currentTimeMillis(), user); 11582 11583 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11584 // delete the partially installed application. the data directory will have to be 11585 // restored if it was already existing 11586 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11587 // remove package from internal structures. Note that we want deletePackageX to 11588 // delete the package data and cache directories that it created in 11589 // scanPackageLocked, unless those directories existed before we even tried to 11590 // install. 11591 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11592 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11593 res.removedInfo, true); 11594 } 11595 11596 } catch (PackageManagerException e) { 11597 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11598 } 11599 } 11600 11601 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11602 // Can't rotate keys during boot or if sharedUser. 11603 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11604 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11605 return false; 11606 } 11607 // app is using upgradeKeySets; make sure all are valid 11608 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11609 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11610 for (int i = 0; i < upgradeKeySets.length; i++) { 11611 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11612 Slog.wtf(TAG, "Package " 11613 + (oldPs.name != null ? oldPs.name : "<null>") 11614 + " contains upgrade-key-set reference to unknown key-set: " 11615 + upgradeKeySets[i] 11616 + " reverting to signatures check."); 11617 return false; 11618 } 11619 } 11620 return true; 11621 } 11622 11623 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11624 // Upgrade keysets are being used. Determine if new package has a superset of the 11625 // required keys. 11626 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11627 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11628 for (int i = 0; i < upgradeKeySets.length; i++) { 11629 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11630 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11631 return true; 11632 } 11633 } 11634 return false; 11635 } 11636 11637 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11638 UserHandle user, String installerPackageName, String volumeUuid, 11639 PackageInstalledInfo res) { 11640 final PackageParser.Package oldPackage; 11641 final String pkgName = pkg.packageName; 11642 final int[] allUsers; 11643 final boolean[] perUserInstalled; 11644 final boolean weFroze; 11645 11646 // First find the old package info and check signatures 11647 synchronized(mPackages) { 11648 oldPackage = mPackages.get(pkgName); 11649 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11650 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11651 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11652 if(!checkUpgradeKeySetLP(ps, pkg)) { 11653 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11654 "New package not signed by keys specified by upgrade-keysets: " 11655 + pkgName); 11656 return; 11657 } 11658 } else { 11659 // default to original signature matching 11660 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11661 != PackageManager.SIGNATURE_MATCH) { 11662 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11663 "New package has a different signature: " + pkgName); 11664 return; 11665 } 11666 } 11667 11668 // In case of rollback, remember per-user/profile install state 11669 allUsers = sUserManager.getUserIds(); 11670 perUserInstalled = new boolean[allUsers.length]; 11671 for (int i = 0; i < allUsers.length; i++) { 11672 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11673 } 11674 11675 // Mark the app as frozen to prevent launching during the upgrade 11676 // process, and then kill all running instances 11677 if (!ps.frozen) { 11678 ps.frozen = true; 11679 weFroze = true; 11680 } else { 11681 weFroze = false; 11682 } 11683 } 11684 11685 // Now that we're guarded by frozen state, kill app during upgrade 11686 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11687 11688 try { 11689 boolean sysPkg = (isSystemApp(oldPackage)); 11690 if (sysPkg) { 11691 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11692 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11693 } else { 11694 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11695 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11696 } 11697 } finally { 11698 // Regardless of success or failure of upgrade steps above, always 11699 // unfreeze the package if we froze it 11700 if (weFroze) { 11701 unfreezePackage(pkgName); 11702 } 11703 } 11704 } 11705 11706 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11707 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11708 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11709 String volumeUuid, PackageInstalledInfo res) { 11710 String pkgName = deletedPackage.packageName; 11711 boolean deletedPkg = true; 11712 boolean updatedSettings = false; 11713 11714 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11715 + deletedPackage); 11716 long origUpdateTime; 11717 if (pkg.mExtras != null) { 11718 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11719 } else { 11720 origUpdateTime = 0; 11721 } 11722 11723 // First delete the existing package while retaining the data directory 11724 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11725 res.removedInfo, true)) { 11726 // If the existing package wasn't successfully deleted 11727 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11728 deletedPkg = false; 11729 } else { 11730 // Successfully deleted the old package; proceed with replace. 11731 11732 // If deleted package lived in a container, give users a chance to 11733 // relinquish resources before killing. 11734 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11735 if (DEBUG_INSTALL) { 11736 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11737 } 11738 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11739 final ArrayList<String> pkgList = new ArrayList<String>(1); 11740 pkgList.add(deletedPackage.applicationInfo.packageName); 11741 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11742 } 11743 11744 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11745 try { 11746 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11747 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11748 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11749 perUserInstalled, res, user); 11750 updatedSettings = true; 11751 } catch (PackageManagerException e) { 11752 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11753 } 11754 } 11755 11756 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11757 // remove package from internal structures. Note that we want deletePackageX to 11758 // delete the package data and cache directories that it created in 11759 // scanPackageLocked, unless those directories existed before we even tried to 11760 // install. 11761 if(updatedSettings) { 11762 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11763 deletePackageLI( 11764 pkgName, null, true, allUsers, perUserInstalled, 11765 PackageManager.DELETE_KEEP_DATA, 11766 res.removedInfo, true); 11767 } 11768 // Since we failed to install the new package we need to restore the old 11769 // package that we deleted. 11770 if (deletedPkg) { 11771 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11772 File restoreFile = new File(deletedPackage.codePath); 11773 // Parse old package 11774 boolean oldExternal = isExternal(deletedPackage); 11775 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11776 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11777 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11778 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11779 try { 11780 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11781 } catch (PackageManagerException e) { 11782 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11783 + e.getMessage()); 11784 return; 11785 } 11786 // Restore of old package succeeded. Update permissions. 11787 // writer 11788 synchronized (mPackages) { 11789 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11790 UPDATE_PERMISSIONS_ALL); 11791 // can downgrade to reader 11792 mSettings.writeLPr(); 11793 } 11794 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11795 } 11796 } 11797 } 11798 11799 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11800 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11801 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11802 String volumeUuid, PackageInstalledInfo res) { 11803 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11804 + ", old=" + deletedPackage); 11805 boolean disabledSystem = false; 11806 boolean updatedSettings = false; 11807 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11808 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11809 != 0) { 11810 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11811 } 11812 String packageName = deletedPackage.packageName; 11813 if (packageName == null) { 11814 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11815 "Attempt to delete null packageName."); 11816 return; 11817 } 11818 PackageParser.Package oldPkg; 11819 PackageSetting oldPkgSetting; 11820 // reader 11821 synchronized (mPackages) { 11822 oldPkg = mPackages.get(packageName); 11823 oldPkgSetting = mSettings.mPackages.get(packageName); 11824 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11825 (oldPkgSetting == null)) { 11826 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11827 "Couldn't find package:" + packageName + " information"); 11828 return; 11829 } 11830 } 11831 11832 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11833 res.removedInfo.removedPackage = packageName; 11834 // Remove existing system package 11835 removePackageLI(oldPkgSetting, true); 11836 // writer 11837 synchronized (mPackages) { 11838 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11839 if (!disabledSystem && deletedPackage != null) { 11840 // We didn't need to disable the .apk as a current system package, 11841 // which means we are replacing another update that is already 11842 // installed. We need to make sure to delete the older one's .apk. 11843 res.removedInfo.args = createInstallArgsForExisting(0, 11844 deletedPackage.applicationInfo.getCodePath(), 11845 deletedPackage.applicationInfo.getResourcePath(), 11846 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11847 } else { 11848 res.removedInfo.args = null; 11849 } 11850 } 11851 11852 // Successfully disabled the old package. Now proceed with re-installation 11853 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11854 11855 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11856 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11857 11858 PackageParser.Package newPackage = null; 11859 try { 11860 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11861 if (newPackage.mExtras != null) { 11862 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11863 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11864 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11865 11866 // is the update attempting to change shared user? that isn't going to work... 11867 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11868 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11869 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11870 + " to " + newPkgSetting.sharedUser); 11871 updatedSettings = true; 11872 } 11873 } 11874 11875 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11876 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11877 perUserInstalled, res, user); 11878 updatedSettings = true; 11879 } 11880 11881 } catch (PackageManagerException e) { 11882 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11883 } 11884 11885 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11886 // Re installation failed. Restore old information 11887 // Remove new pkg information 11888 if (newPackage != null) { 11889 removeInstalledPackageLI(newPackage, true); 11890 } 11891 // Add back the old system package 11892 try { 11893 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11894 } catch (PackageManagerException e) { 11895 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11896 } 11897 // Restore the old system information in Settings 11898 synchronized (mPackages) { 11899 if (disabledSystem) { 11900 mSettings.enableSystemPackageLPw(packageName); 11901 } 11902 if (updatedSettings) { 11903 mSettings.setInstallerPackageName(packageName, 11904 oldPkgSetting.installerPackageName); 11905 } 11906 mSettings.writeLPr(); 11907 } 11908 } 11909 } 11910 11911 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11912 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11913 UserHandle user) { 11914 String pkgName = newPackage.packageName; 11915 synchronized (mPackages) { 11916 //write settings. the installStatus will be incomplete at this stage. 11917 //note that the new package setting would have already been 11918 //added to mPackages. It hasn't been persisted yet. 11919 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11920 mSettings.writeLPr(); 11921 } 11922 11923 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11924 11925 synchronized (mPackages) { 11926 updatePermissionsLPw(newPackage.packageName, newPackage, 11927 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11928 ? UPDATE_PERMISSIONS_ALL : 0)); 11929 // For system-bundled packages, we assume that installing an upgraded version 11930 // of the package implies that the user actually wants to run that new code, 11931 // so we enable the package. 11932 PackageSetting ps = mSettings.mPackages.get(pkgName); 11933 if (ps != null) { 11934 if (isSystemApp(newPackage)) { 11935 // NB: implicit assumption that system package upgrades apply to all users 11936 if (DEBUG_INSTALL) { 11937 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11938 } 11939 if (res.origUsers != null) { 11940 for (int userHandle : res.origUsers) { 11941 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11942 userHandle, installerPackageName); 11943 } 11944 } 11945 // Also convey the prior install/uninstall state 11946 if (allUsers != null && perUserInstalled != null) { 11947 for (int i = 0; i < allUsers.length; i++) { 11948 if (DEBUG_INSTALL) { 11949 Slog.d(TAG, " user " + allUsers[i] 11950 + " => " + perUserInstalled[i]); 11951 } 11952 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11953 } 11954 // these install state changes will be persisted in the 11955 // upcoming call to mSettings.writeLPr(). 11956 } 11957 } 11958 // It's implied that when a user requests installation, they want the app to be 11959 // installed and enabled. 11960 int userId = user.getIdentifier(); 11961 if (userId != UserHandle.USER_ALL) { 11962 ps.setInstalled(true, userId); 11963 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11964 } 11965 } 11966 res.name = pkgName; 11967 res.uid = newPackage.applicationInfo.uid; 11968 res.pkg = newPackage; 11969 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11970 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11971 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11972 //to update install status 11973 mSettings.writeLPr(); 11974 } 11975 } 11976 11977 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11978 final int installFlags = args.installFlags; 11979 final String installerPackageName = args.installerPackageName; 11980 final String volumeUuid = args.volumeUuid; 11981 final File tmpPackageFile = new File(args.getCodePath()); 11982 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11983 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11984 || (args.volumeUuid != null)); 11985 boolean replace = false; 11986 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11987 if (args.move != null) { 11988 // moving a complete application; perfom an initial scan on the new install location 11989 scanFlags |= SCAN_INITIAL; 11990 } 11991 // Result object to be returned 11992 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11993 11994 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11995 // Retrieve PackageSettings and parse package 11996 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11997 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11998 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11999 PackageParser pp = new PackageParser(); 12000 pp.setSeparateProcesses(mSeparateProcesses); 12001 pp.setDisplayMetrics(mMetrics); 12002 12003 final PackageParser.Package pkg; 12004 try { 12005 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12006 } catch (PackageParserException e) { 12007 res.setError("Failed parse during installPackageLI", e); 12008 return; 12009 } 12010 12011 // Mark that we have an install time CPU ABI override. 12012 pkg.cpuAbiOverride = args.abiOverride; 12013 12014 String pkgName = res.name = pkg.packageName; 12015 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12016 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12017 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12018 return; 12019 } 12020 } 12021 12022 try { 12023 pp.collectCertificates(pkg, parseFlags); 12024 pp.collectManifestDigest(pkg); 12025 } catch (PackageParserException e) { 12026 res.setError("Failed collect during installPackageLI", e); 12027 return; 12028 } 12029 12030 /* If the installer passed in a manifest digest, compare it now. */ 12031 if (args.manifestDigest != null) { 12032 if (DEBUG_INSTALL) { 12033 final String parsedManifest = pkg.manifestDigest == null ? "null" 12034 : pkg.manifestDigest.toString(); 12035 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 12036 + parsedManifest); 12037 } 12038 12039 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 12040 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 12041 return; 12042 } 12043 } else if (DEBUG_INSTALL) { 12044 final String parsedManifest = pkg.manifestDigest == null 12045 ? "null" : pkg.manifestDigest.toString(); 12046 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 12047 } 12048 12049 // Get rid of all references to package scan path via parser. 12050 pp = null; 12051 String oldCodePath = null; 12052 boolean systemApp = false; 12053 synchronized (mPackages) { 12054 // Check if installing already existing package 12055 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12056 String oldName = mSettings.mRenamedPackages.get(pkgName); 12057 if (pkg.mOriginalPackages != null 12058 && pkg.mOriginalPackages.contains(oldName) 12059 && mPackages.containsKey(oldName)) { 12060 // This package is derived from an original package, 12061 // and this device has been updating from that original 12062 // name. We must continue using the original name, so 12063 // rename the new package here. 12064 pkg.setPackageName(oldName); 12065 pkgName = pkg.packageName; 12066 replace = true; 12067 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12068 + oldName + " pkgName=" + pkgName); 12069 } else if (mPackages.containsKey(pkgName)) { 12070 // This package, under its official name, already exists 12071 // on the device; we should replace it. 12072 replace = true; 12073 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12074 } 12075 12076 // Prevent apps opting out from runtime permissions 12077 if (replace) { 12078 PackageParser.Package oldPackage = mPackages.get(pkgName); 12079 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12080 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12081 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12082 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12083 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12084 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12085 + " doesn't support runtime permissions but the old" 12086 + " target SDK " + oldTargetSdk + " does."); 12087 return; 12088 } 12089 } 12090 } 12091 12092 PackageSetting ps = mSettings.mPackages.get(pkgName); 12093 if (ps != null) { 12094 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12095 12096 // Quick sanity check that we're signed correctly if updating; 12097 // we'll check this again later when scanning, but we want to 12098 // bail early here before tripping over redefined permissions. 12099 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12100 if (!checkUpgradeKeySetLP(ps, pkg)) { 12101 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12102 + pkg.packageName + " upgrade keys do not match the " 12103 + "previously installed version"); 12104 return; 12105 } 12106 } else { 12107 try { 12108 verifySignaturesLP(ps, pkg); 12109 } catch (PackageManagerException e) { 12110 res.setError(e.error, e.getMessage()); 12111 return; 12112 } 12113 } 12114 12115 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12116 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12117 systemApp = (ps.pkg.applicationInfo.flags & 12118 ApplicationInfo.FLAG_SYSTEM) != 0; 12119 } 12120 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12121 } 12122 12123 // Check whether the newly-scanned package wants to define an already-defined perm 12124 int N = pkg.permissions.size(); 12125 for (int i = N-1; i >= 0; i--) { 12126 PackageParser.Permission perm = pkg.permissions.get(i); 12127 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12128 if (bp != null) { 12129 // If the defining package is signed with our cert, it's okay. This 12130 // also includes the "updating the same package" case, of course. 12131 // "updating same package" could also involve key-rotation. 12132 final boolean sigsOk; 12133 if (bp.sourcePackage.equals(pkg.packageName) 12134 && (bp.packageSetting instanceof PackageSetting) 12135 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12136 scanFlags))) { 12137 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12138 } else { 12139 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12140 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12141 } 12142 if (!sigsOk) { 12143 // If the owning package is the system itself, we log but allow 12144 // install to proceed; we fail the install on all other permission 12145 // redefinitions. 12146 if (!bp.sourcePackage.equals("android")) { 12147 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12148 + pkg.packageName + " attempting to redeclare permission " 12149 + perm.info.name + " already owned by " + bp.sourcePackage); 12150 res.origPermission = perm.info.name; 12151 res.origPackage = bp.sourcePackage; 12152 return; 12153 } else { 12154 Slog.w(TAG, "Package " + pkg.packageName 12155 + " attempting to redeclare system permission " 12156 + perm.info.name + "; ignoring new declaration"); 12157 pkg.permissions.remove(i); 12158 } 12159 } 12160 } 12161 } 12162 12163 } 12164 12165 if (systemApp && onExternal) { 12166 // Disable updates to system apps on sdcard 12167 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12168 "Cannot install updates to system apps on sdcard"); 12169 return; 12170 } 12171 12172 if (args.move != null) { 12173 // We did an in-place move, so dex is ready to roll 12174 scanFlags |= SCAN_NO_DEX; 12175 scanFlags |= SCAN_MOVE; 12176 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12177 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12178 scanFlags |= SCAN_NO_DEX; 12179 12180 try { 12181 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 12182 true /* extract libs */); 12183 } catch (PackageManagerException pme) { 12184 Slog.e(TAG, "Error deriving application ABI", pme); 12185 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 12186 return; 12187 } 12188 12189 // Run dexopt before old package gets removed, to minimize time when app is unavailable 12190 int result = mPackageDexOptimizer 12191 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 12192 false /* defer */, false /* inclDependencies */); 12193 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 12194 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 12195 return; 12196 } 12197 } 12198 12199 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 12200 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 12201 return; 12202 } 12203 12204 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 12205 12206 if (replace) { 12207 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 12208 installerPackageName, volumeUuid, res); 12209 } else { 12210 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 12211 args.user, installerPackageName, volumeUuid, res); 12212 } 12213 synchronized (mPackages) { 12214 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12215 if (ps != null) { 12216 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12217 } 12218 } 12219 } 12220 12221 private void startIntentFilterVerifications(int userId, boolean replacing, 12222 PackageParser.Package pkg) { 12223 if (mIntentFilterVerifierComponent == null) { 12224 Slog.w(TAG, "No IntentFilter verification will not be done as " 12225 + "there is no IntentFilterVerifier available!"); 12226 return; 12227 } 12228 12229 final int verifierUid = getPackageUid( 12230 mIntentFilterVerifierComponent.getPackageName(), 12231 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 12232 12233 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 12234 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 12235 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 12236 mHandler.sendMessage(msg); 12237 } 12238 12239 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 12240 PackageParser.Package pkg) { 12241 int size = pkg.activities.size(); 12242 if (size == 0) { 12243 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12244 "No activity, so no need to verify any IntentFilter!"); 12245 return; 12246 } 12247 12248 final boolean hasDomainURLs = hasDomainURLs(pkg); 12249 if (!hasDomainURLs) { 12250 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12251 "No domain URLs, so no need to verify any IntentFilter!"); 12252 return; 12253 } 12254 12255 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 12256 + " if any IntentFilter from the " + size 12257 + " Activities needs verification ..."); 12258 12259 int count = 0; 12260 final String packageName = pkg.packageName; 12261 12262 synchronized (mPackages) { 12263 // If this is a new install and we see that we've already run verification for this 12264 // package, we have nothing to do: it means the state was restored from backup. 12265 if (!replacing) { 12266 IntentFilterVerificationInfo ivi = 12267 mSettings.getIntentFilterVerificationLPr(packageName); 12268 if (ivi != null) { 12269 if (DEBUG_DOMAIN_VERIFICATION) { 12270 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 12271 + ivi.getStatusString()); 12272 } 12273 return; 12274 } 12275 } 12276 12277 // If any filters need to be verified, then all need to be. 12278 boolean needToVerify = false; 12279 for (PackageParser.Activity a : pkg.activities) { 12280 for (ActivityIntentInfo filter : a.intents) { 12281 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 12282 if (DEBUG_DOMAIN_VERIFICATION) { 12283 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 12284 } 12285 needToVerify = true; 12286 break; 12287 } 12288 } 12289 } 12290 12291 if (needToVerify) { 12292 final int verificationId = mIntentFilterVerificationToken++; 12293 for (PackageParser.Activity a : pkg.activities) { 12294 for (ActivityIntentInfo filter : a.intents) { 12295 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 12296 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 12297 "Verification needed for IntentFilter:" + filter.toString()); 12298 mIntentFilterVerifier.addOneIntentFilterVerification( 12299 verifierUid, userId, verificationId, filter, packageName); 12300 count++; 12301 } 12302 } 12303 } 12304 } 12305 } 12306 12307 if (count > 0) { 12308 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 12309 + " IntentFilter verification" + (count > 1 ? "s" : "") 12310 + " for userId:" + userId); 12311 mIntentFilterVerifier.startVerifications(userId); 12312 } else { 12313 if (DEBUG_DOMAIN_VERIFICATION) { 12314 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 12315 } 12316 } 12317 } 12318 12319 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 12320 final ComponentName cn = filter.activity.getComponentName(); 12321 final String packageName = cn.getPackageName(); 12322 12323 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 12324 packageName); 12325 if (ivi == null) { 12326 return true; 12327 } 12328 int status = ivi.getStatus(); 12329 switch (status) { 12330 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 12331 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 12332 return true; 12333 12334 default: 12335 // Nothing to do 12336 return false; 12337 } 12338 } 12339 12340 private static boolean isMultiArch(PackageSetting ps) { 12341 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12342 } 12343 12344 private static boolean isMultiArch(ApplicationInfo info) { 12345 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 12346 } 12347 12348 private static boolean isExternal(PackageParser.Package pkg) { 12349 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12350 } 12351 12352 private static boolean isExternal(PackageSetting ps) { 12353 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12354 } 12355 12356 private static boolean isExternal(ApplicationInfo info) { 12357 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12358 } 12359 12360 private static boolean isSystemApp(PackageParser.Package pkg) { 12361 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12362 } 12363 12364 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12365 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12366 } 12367 12368 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12369 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12370 } 12371 12372 private static boolean isSystemApp(PackageSetting ps) { 12373 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12374 } 12375 12376 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12377 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12378 } 12379 12380 private int packageFlagsToInstallFlags(PackageSetting ps) { 12381 int installFlags = 0; 12382 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12383 // This existing package was an external ASEC install when we have 12384 // the external flag without a UUID 12385 installFlags |= PackageManager.INSTALL_EXTERNAL; 12386 } 12387 if (ps.isForwardLocked()) { 12388 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12389 } 12390 return installFlags; 12391 } 12392 12393 private void deleteTempPackageFiles() { 12394 final FilenameFilter filter = new FilenameFilter() { 12395 public boolean accept(File dir, String name) { 12396 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12397 } 12398 }; 12399 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12400 file.delete(); 12401 } 12402 } 12403 12404 @Override 12405 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12406 int flags) { 12407 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12408 flags); 12409 } 12410 12411 @Override 12412 public void deletePackage(final String packageName, 12413 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12414 mContext.enforceCallingOrSelfPermission( 12415 android.Manifest.permission.DELETE_PACKAGES, null); 12416 Preconditions.checkNotNull(packageName); 12417 Preconditions.checkNotNull(observer); 12418 final int uid = Binder.getCallingUid(); 12419 if (UserHandle.getUserId(uid) != userId) { 12420 mContext.enforceCallingPermission( 12421 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12422 "deletePackage for user " + userId); 12423 } 12424 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12425 try { 12426 observer.onPackageDeleted(packageName, 12427 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12428 } catch (RemoteException re) { 12429 } 12430 return; 12431 } 12432 12433 boolean uninstallBlocked = false; 12434 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12435 int[] users = sUserManager.getUserIds(); 12436 for (int i = 0; i < users.length; ++i) { 12437 if (getBlockUninstallForUser(packageName, users[i])) { 12438 uninstallBlocked = true; 12439 break; 12440 } 12441 } 12442 } else { 12443 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12444 } 12445 if (uninstallBlocked) { 12446 try { 12447 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12448 null); 12449 } catch (RemoteException re) { 12450 } 12451 return; 12452 } 12453 12454 if (DEBUG_REMOVE) { 12455 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12456 } 12457 // Queue up an async operation since the package deletion may take a little while. 12458 mHandler.post(new Runnable() { 12459 public void run() { 12460 mHandler.removeCallbacks(this); 12461 final int returnCode = deletePackageX(packageName, userId, flags); 12462 if (observer != null) { 12463 try { 12464 observer.onPackageDeleted(packageName, returnCode, null); 12465 } catch (RemoteException e) { 12466 Log.i(TAG, "Observer no longer exists."); 12467 } //end catch 12468 } //end if 12469 } //end run 12470 }); 12471 } 12472 12473 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12474 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12475 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12476 try { 12477 if (dpm != null) { 12478 if (dpm.isDeviceOwner(packageName)) { 12479 return true; 12480 } 12481 int[] users; 12482 if (userId == UserHandle.USER_ALL) { 12483 users = sUserManager.getUserIds(); 12484 } else { 12485 users = new int[]{userId}; 12486 } 12487 for (int i = 0; i < users.length; ++i) { 12488 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12489 return true; 12490 } 12491 } 12492 } 12493 } catch (RemoteException e) { 12494 } 12495 return false; 12496 } 12497 12498 /** 12499 * This method is an internal method that could be get invoked either 12500 * to delete an installed package or to clean up a failed installation. 12501 * After deleting an installed package, a broadcast is sent to notify any 12502 * listeners that the package has been installed. For cleaning up a failed 12503 * installation, the broadcast is not necessary since the package's 12504 * installation wouldn't have sent the initial broadcast either 12505 * The key steps in deleting a package are 12506 * deleting the package information in internal structures like mPackages, 12507 * deleting the packages base directories through installd 12508 * updating mSettings to reflect current status 12509 * persisting settings for later use 12510 * sending a broadcast if necessary 12511 */ 12512 private int deletePackageX(String packageName, int userId, int flags) { 12513 final PackageRemovedInfo info = new PackageRemovedInfo(); 12514 final boolean res; 12515 12516 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12517 ? UserHandle.ALL : new UserHandle(userId); 12518 12519 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12520 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12521 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12522 } 12523 12524 boolean removedForAllUsers = false; 12525 boolean systemUpdate = false; 12526 12527 // for the uninstall-updates case and restricted profiles, remember the per- 12528 // userhandle installed state 12529 int[] allUsers; 12530 boolean[] perUserInstalled; 12531 synchronized (mPackages) { 12532 PackageSetting ps = mSettings.mPackages.get(packageName); 12533 allUsers = sUserManager.getUserIds(); 12534 perUserInstalled = new boolean[allUsers.length]; 12535 for (int i = 0; i < allUsers.length; i++) { 12536 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12537 } 12538 } 12539 12540 synchronized (mInstallLock) { 12541 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12542 res = deletePackageLI(packageName, removeForUser, 12543 true, allUsers, perUserInstalled, 12544 flags | REMOVE_CHATTY, info, true); 12545 systemUpdate = info.isRemovedPackageSystemUpdate; 12546 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12547 removedForAllUsers = true; 12548 } 12549 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12550 + " removedForAllUsers=" + removedForAllUsers); 12551 } 12552 12553 if (res) { 12554 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12555 12556 // If the removed package was a system update, the old system package 12557 // was re-enabled; we need to broadcast this information 12558 if (systemUpdate) { 12559 Bundle extras = new Bundle(1); 12560 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12561 ? info.removedAppId : info.uid); 12562 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12563 12564 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12565 extras, null, null, null); 12566 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12567 extras, null, null, null); 12568 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12569 null, packageName, null, null); 12570 } 12571 } 12572 // Force a gc here. 12573 Runtime.getRuntime().gc(); 12574 // Delete the resources here after sending the broadcast to let 12575 // other processes clean up before deleting resources. 12576 if (info.args != null) { 12577 synchronized (mInstallLock) { 12578 info.args.doPostDeleteLI(true); 12579 } 12580 } 12581 12582 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12583 } 12584 12585 class PackageRemovedInfo { 12586 String removedPackage; 12587 int uid = -1; 12588 int removedAppId = -1; 12589 int[] removedUsers = null; 12590 boolean isRemovedPackageSystemUpdate = false; 12591 // Clean up resources deleted packages. 12592 InstallArgs args = null; 12593 12594 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12595 Bundle extras = new Bundle(1); 12596 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12597 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12598 if (replacing) { 12599 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12600 } 12601 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12602 if (removedPackage != null) { 12603 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12604 extras, null, null, removedUsers); 12605 if (fullRemove && !replacing) { 12606 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12607 extras, null, null, removedUsers); 12608 } 12609 } 12610 if (removedAppId >= 0) { 12611 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12612 removedUsers); 12613 } 12614 } 12615 } 12616 12617 /* 12618 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12619 * flag is not set, the data directory is removed as well. 12620 * make sure this flag is set for partially installed apps. If not its meaningless to 12621 * delete a partially installed application. 12622 */ 12623 private void removePackageDataLI(PackageSetting ps, 12624 int[] allUserHandles, boolean[] perUserInstalled, 12625 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12626 String packageName = ps.name; 12627 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12628 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12629 // Retrieve object to delete permissions for shared user later on 12630 final PackageSetting deletedPs; 12631 // reader 12632 synchronized (mPackages) { 12633 deletedPs = mSettings.mPackages.get(packageName); 12634 if (outInfo != null) { 12635 outInfo.removedPackage = packageName; 12636 outInfo.removedUsers = deletedPs != null 12637 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12638 : null; 12639 } 12640 } 12641 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12642 removeDataDirsLI(ps.volumeUuid, packageName); 12643 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12644 } 12645 // writer 12646 synchronized (mPackages) { 12647 if (deletedPs != null) { 12648 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12649 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12650 clearDefaultBrowserIfNeeded(packageName); 12651 if (outInfo != null) { 12652 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12653 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12654 } 12655 updatePermissionsLPw(deletedPs.name, null, 0); 12656 if (deletedPs.sharedUser != null) { 12657 // Remove permissions associated with package. Since runtime 12658 // permissions are per user we have to kill the removed package 12659 // or packages running under the shared user of the removed 12660 // package if revoking the permissions requested only by the removed 12661 // package is successful and this causes a change in gids. 12662 for (int userId : UserManagerService.getInstance().getUserIds()) { 12663 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12664 userId); 12665 if (userIdToKill == UserHandle.USER_ALL 12666 || userIdToKill >= UserHandle.USER_OWNER) { 12667 // If gids changed for this user, kill all affected packages. 12668 mHandler.post(new Runnable() { 12669 @Override 12670 public void run() { 12671 // This has to happen with no lock held. 12672 killSettingPackagesForUser(deletedPs, userIdToKill, 12673 KILL_APP_REASON_GIDS_CHANGED); 12674 } 12675 }); 12676 break; 12677 } 12678 } 12679 } 12680 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12681 } 12682 // make sure to preserve per-user disabled state if this removal was just 12683 // a downgrade of a system app to the factory package 12684 if (allUserHandles != null && perUserInstalled != null) { 12685 if (DEBUG_REMOVE) { 12686 Slog.d(TAG, "Propagating install state across downgrade"); 12687 } 12688 for (int i = 0; i < allUserHandles.length; i++) { 12689 if (DEBUG_REMOVE) { 12690 Slog.d(TAG, " user " + allUserHandles[i] 12691 + " => " + perUserInstalled[i]); 12692 } 12693 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12694 } 12695 } 12696 } 12697 // can downgrade to reader 12698 if (writeSettings) { 12699 // Save settings now 12700 mSettings.writeLPr(); 12701 } 12702 } 12703 if (outInfo != null) { 12704 // A user ID was deleted here. Go through all users and remove it 12705 // from KeyStore. 12706 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12707 } 12708 } 12709 12710 static boolean locationIsPrivileged(File path) { 12711 try { 12712 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12713 .getCanonicalPath(); 12714 return path.getCanonicalPath().startsWith(privilegedAppDir); 12715 } catch (IOException e) { 12716 Slog.e(TAG, "Unable to access code path " + path); 12717 } 12718 return false; 12719 } 12720 12721 /* 12722 * Tries to delete system package. 12723 */ 12724 private boolean deleteSystemPackageLI(PackageSetting newPs, 12725 int[] allUserHandles, boolean[] perUserInstalled, 12726 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12727 final boolean applyUserRestrictions 12728 = (allUserHandles != null) && (perUserInstalled != null); 12729 PackageSetting disabledPs = null; 12730 // Confirm if the system package has been updated 12731 // An updated system app can be deleted. This will also have to restore 12732 // the system pkg from system partition 12733 // reader 12734 synchronized (mPackages) { 12735 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12736 } 12737 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12738 + " disabledPs=" + disabledPs); 12739 if (disabledPs == null) { 12740 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12741 return false; 12742 } else if (DEBUG_REMOVE) { 12743 Slog.d(TAG, "Deleting system pkg from data partition"); 12744 } 12745 if (DEBUG_REMOVE) { 12746 if (applyUserRestrictions) { 12747 Slog.d(TAG, "Remembering install states:"); 12748 for (int i = 0; i < allUserHandles.length; i++) { 12749 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12750 } 12751 } 12752 } 12753 // Delete the updated package 12754 outInfo.isRemovedPackageSystemUpdate = true; 12755 if (disabledPs.versionCode < newPs.versionCode) { 12756 // Delete data for downgrades 12757 flags &= ~PackageManager.DELETE_KEEP_DATA; 12758 } else { 12759 // Preserve data by setting flag 12760 flags |= PackageManager.DELETE_KEEP_DATA; 12761 } 12762 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12763 allUserHandles, perUserInstalled, outInfo, writeSettings); 12764 if (!ret) { 12765 return false; 12766 } 12767 // writer 12768 synchronized (mPackages) { 12769 // Reinstate the old system package 12770 mSettings.enableSystemPackageLPw(newPs.name); 12771 // Remove any native libraries from the upgraded package. 12772 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12773 } 12774 // Install the system package 12775 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12776 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12777 if (locationIsPrivileged(disabledPs.codePath)) { 12778 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12779 } 12780 12781 final PackageParser.Package newPkg; 12782 try { 12783 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12784 } catch (PackageManagerException e) { 12785 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12786 return false; 12787 } 12788 12789 // writer 12790 synchronized (mPackages) { 12791 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12792 12793 // Propagate the permissions state as we do want to drop on the floor 12794 // runtime permissions. The update permissions method below will take 12795 // care of removing obsolete permissions and grant install permissions. 12796 ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState()); 12797 updatePermissionsLPw(newPkg.packageName, newPkg, 12798 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12799 12800 if (applyUserRestrictions) { 12801 if (DEBUG_REMOVE) { 12802 Slog.d(TAG, "Propagating install state across reinstall"); 12803 } 12804 for (int i = 0; i < allUserHandles.length; i++) { 12805 if (DEBUG_REMOVE) { 12806 Slog.d(TAG, " user " + allUserHandles[i] 12807 + " => " + perUserInstalled[i]); 12808 } 12809 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12810 } 12811 // Regardless of writeSettings we need to ensure that this restriction 12812 // state propagation is persisted 12813 mSettings.writeAllUsersPackageRestrictionsLPr(); 12814 } 12815 // can downgrade to reader here 12816 if (writeSettings) { 12817 mSettings.writeLPr(); 12818 } 12819 } 12820 return true; 12821 } 12822 12823 private boolean deleteInstalledPackageLI(PackageSetting ps, 12824 boolean deleteCodeAndResources, int flags, 12825 int[] allUserHandles, boolean[] perUserInstalled, 12826 PackageRemovedInfo outInfo, boolean writeSettings) { 12827 if (outInfo != null) { 12828 outInfo.uid = ps.appId; 12829 } 12830 12831 // Delete package data from internal structures and also remove data if flag is set 12832 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12833 12834 // Delete application code and resources 12835 if (deleteCodeAndResources && (outInfo != null)) { 12836 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12837 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12838 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12839 } 12840 return true; 12841 } 12842 12843 @Override 12844 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12845 int userId) { 12846 mContext.enforceCallingOrSelfPermission( 12847 android.Manifest.permission.DELETE_PACKAGES, null); 12848 synchronized (mPackages) { 12849 PackageSetting ps = mSettings.mPackages.get(packageName); 12850 if (ps == null) { 12851 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12852 return false; 12853 } 12854 if (!ps.getInstalled(userId)) { 12855 // Can't block uninstall for an app that is not installed or enabled. 12856 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12857 return false; 12858 } 12859 ps.setBlockUninstall(blockUninstall, userId); 12860 mSettings.writePackageRestrictionsLPr(userId); 12861 } 12862 return true; 12863 } 12864 12865 @Override 12866 public boolean getBlockUninstallForUser(String packageName, int userId) { 12867 synchronized (mPackages) { 12868 PackageSetting ps = mSettings.mPackages.get(packageName); 12869 if (ps == null) { 12870 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12871 return false; 12872 } 12873 return ps.getBlockUninstall(userId); 12874 } 12875 } 12876 12877 /* 12878 * This method handles package deletion in general 12879 */ 12880 private boolean deletePackageLI(String packageName, UserHandle user, 12881 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12882 int flags, PackageRemovedInfo outInfo, 12883 boolean writeSettings) { 12884 if (packageName == null) { 12885 Slog.w(TAG, "Attempt to delete null packageName."); 12886 return false; 12887 } 12888 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12889 PackageSetting ps; 12890 boolean dataOnly = false; 12891 int removeUser = -1; 12892 int appId = -1; 12893 synchronized (mPackages) { 12894 ps = mSettings.mPackages.get(packageName); 12895 if (ps == null) { 12896 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12897 return false; 12898 } 12899 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12900 && user.getIdentifier() != UserHandle.USER_ALL) { 12901 // The caller is asking that the package only be deleted for a single 12902 // user. To do this, we just mark its uninstalled state and delete 12903 // its data. If this is a system app, we only allow this to happen if 12904 // they have set the special DELETE_SYSTEM_APP which requests different 12905 // semantics than normal for uninstalling system apps. 12906 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12907 ps.setUserState(user.getIdentifier(), 12908 COMPONENT_ENABLED_STATE_DEFAULT, 12909 false, //installed 12910 true, //stopped 12911 true, //notLaunched 12912 false, //hidden 12913 null, null, null, 12914 false, // blockUninstall 12915 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12916 if (!isSystemApp(ps)) { 12917 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12918 // Other user still have this package installed, so all 12919 // we need to do is clear this user's data and save that 12920 // it is uninstalled. 12921 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12922 removeUser = user.getIdentifier(); 12923 appId = ps.appId; 12924 scheduleWritePackageRestrictionsLocked(removeUser); 12925 } else { 12926 // We need to set it back to 'installed' so the uninstall 12927 // broadcasts will be sent correctly. 12928 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12929 ps.setInstalled(true, user.getIdentifier()); 12930 } 12931 } else { 12932 // This is a system app, so we assume that the 12933 // other users still have this package installed, so all 12934 // we need to do is clear this user's data and save that 12935 // it is uninstalled. 12936 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12937 removeUser = user.getIdentifier(); 12938 appId = ps.appId; 12939 scheduleWritePackageRestrictionsLocked(removeUser); 12940 } 12941 } 12942 } 12943 12944 if (removeUser >= 0) { 12945 // From above, we determined that we are deleting this only 12946 // for a single user. Continue the work here. 12947 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12948 if (outInfo != null) { 12949 outInfo.removedPackage = packageName; 12950 outInfo.removedAppId = appId; 12951 outInfo.removedUsers = new int[] {removeUser}; 12952 } 12953 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12954 removeKeystoreDataIfNeeded(removeUser, appId); 12955 schedulePackageCleaning(packageName, removeUser, false); 12956 synchronized (mPackages) { 12957 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12958 scheduleWritePackageRestrictionsLocked(removeUser); 12959 } 12960 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser); 12961 } 12962 return true; 12963 } 12964 12965 if (dataOnly) { 12966 // Delete application data first 12967 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12968 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12969 return true; 12970 } 12971 12972 boolean ret = false; 12973 if (isSystemApp(ps)) { 12974 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12975 // When an updated system application is deleted we delete the existing resources as well and 12976 // fall back to existing code in system partition 12977 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12978 flags, outInfo, writeSettings); 12979 } else { 12980 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12981 // Kill application pre-emptively especially for apps on sd. 12982 killApplication(packageName, ps.appId, "uninstall pkg"); 12983 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12984 allUserHandles, perUserInstalled, 12985 outInfo, writeSettings); 12986 } 12987 12988 return ret; 12989 } 12990 12991 private final class ClearStorageConnection implements ServiceConnection { 12992 IMediaContainerService mContainerService; 12993 12994 @Override 12995 public void onServiceConnected(ComponentName name, IBinder service) { 12996 synchronized (this) { 12997 mContainerService = IMediaContainerService.Stub.asInterface(service); 12998 notifyAll(); 12999 } 13000 } 13001 13002 @Override 13003 public void onServiceDisconnected(ComponentName name) { 13004 } 13005 } 13006 13007 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13008 final boolean mounted; 13009 if (Environment.isExternalStorageEmulated()) { 13010 mounted = true; 13011 } else { 13012 final String status = Environment.getExternalStorageState(); 13013 13014 mounted = status.equals(Environment.MEDIA_MOUNTED) 13015 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13016 } 13017 13018 if (!mounted) { 13019 return; 13020 } 13021 13022 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13023 int[] users; 13024 if (userId == UserHandle.USER_ALL) { 13025 users = sUserManager.getUserIds(); 13026 } else { 13027 users = new int[] { userId }; 13028 } 13029 final ClearStorageConnection conn = new ClearStorageConnection(); 13030 if (mContext.bindServiceAsUser( 13031 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 13032 try { 13033 for (int curUser : users) { 13034 long timeout = SystemClock.uptimeMillis() + 5000; 13035 synchronized (conn) { 13036 long now = SystemClock.uptimeMillis(); 13037 while (conn.mContainerService == null && now < timeout) { 13038 try { 13039 conn.wait(timeout - now); 13040 } catch (InterruptedException e) { 13041 } 13042 } 13043 } 13044 if (conn.mContainerService == null) { 13045 return; 13046 } 13047 13048 final UserEnvironment userEnv = new UserEnvironment(curUser); 13049 clearDirectory(conn.mContainerService, 13050 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13051 if (allData) { 13052 clearDirectory(conn.mContainerService, 13053 userEnv.buildExternalStorageAppDataDirs(packageName)); 13054 clearDirectory(conn.mContainerService, 13055 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13056 } 13057 } 13058 } finally { 13059 mContext.unbindService(conn); 13060 } 13061 } 13062 } 13063 13064 @Override 13065 public void clearApplicationUserData(final String packageName, 13066 final IPackageDataObserver observer, final int userId) { 13067 mContext.enforceCallingOrSelfPermission( 13068 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13069 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13070 // Queue up an async operation since the package deletion may take a little while. 13071 mHandler.post(new Runnable() { 13072 public void run() { 13073 mHandler.removeCallbacks(this); 13074 final boolean succeeded; 13075 synchronized (mInstallLock) { 13076 succeeded = clearApplicationUserDataLI(packageName, userId); 13077 } 13078 clearExternalStorageDataSync(packageName, userId, true); 13079 if (succeeded) { 13080 // invoke DeviceStorageMonitor's update method to clear any notifications 13081 DeviceStorageMonitorInternal 13082 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13083 if (dsm != null) { 13084 dsm.checkMemory(); 13085 } 13086 } 13087 if(observer != null) { 13088 try { 13089 observer.onRemoveCompleted(packageName, succeeded); 13090 } catch (RemoteException e) { 13091 Log.i(TAG, "Observer no longer exists."); 13092 } 13093 } //end if observer 13094 } //end run 13095 }); 13096 } 13097 13098 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13099 if (packageName == null) { 13100 Slog.w(TAG, "Attempt to delete null packageName."); 13101 return false; 13102 } 13103 13104 // Try finding details about the requested package 13105 PackageParser.Package pkg; 13106 synchronized (mPackages) { 13107 pkg = mPackages.get(packageName); 13108 if (pkg == null) { 13109 final PackageSetting ps = mSettings.mPackages.get(packageName); 13110 if (ps != null) { 13111 pkg = ps.pkg; 13112 } 13113 } 13114 13115 if (pkg == null) { 13116 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13117 return false; 13118 } 13119 13120 PackageSetting ps = (PackageSetting) pkg.mExtras; 13121 resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId); 13122 } 13123 13124 // Always delete data directories for package, even if we found no other 13125 // record of app. This helps users recover from UID mismatches without 13126 // resorting to a full data wipe. 13127 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 13128 if (retCode < 0) { 13129 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 13130 return false; 13131 } 13132 13133 final int appId = pkg.applicationInfo.uid; 13134 removeKeystoreDataIfNeeded(userId, appId); 13135 13136 // Create a native library symlink only if we have native libraries 13137 // and if the native libraries are 32 bit libraries. We do not provide 13138 // this symlink for 64 bit libraries. 13139 if (pkg.applicationInfo.primaryCpuAbi != null && 13140 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 13141 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 13142 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 13143 nativeLibPath, userId) < 0) { 13144 Slog.w(TAG, "Failed linking native library dir"); 13145 return false; 13146 } 13147 } 13148 13149 return true; 13150 } 13151 13152 /** 13153 * Reverts user permission state changes (permissions and flags). 13154 * 13155 * @param ps The package for which to reset. 13156 * @param userId The device user for which to do a reset. 13157 */ 13158 private void resetUserChangesToRuntimePermissionsAndFlagsLocked( 13159 final PackageSetting ps, final int userId) { 13160 if (ps.pkg == null) { 13161 return; 13162 } 13163 13164 final int userSettableFlags = FLAG_PERMISSION_USER_SET 13165 | FLAG_PERMISSION_USER_FIXED 13166 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 13167 13168 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 13169 | FLAG_PERMISSION_POLICY_FIXED; 13170 13171 boolean writeInstallPermissions = false; 13172 boolean writeRuntimePermissions = false; 13173 13174 final int permissionCount = ps.pkg.requestedPermissions.size(); 13175 for (int i = 0; i < permissionCount; i++) { 13176 String permission = ps.pkg.requestedPermissions.get(i); 13177 13178 BasePermission bp = mSettings.mPermissions.get(permission); 13179 if (bp == null) { 13180 continue; 13181 } 13182 13183 // If shared user we just reset the state to which only this app contributed. 13184 if (ps.sharedUser != null) { 13185 boolean used = false; 13186 final int packageCount = ps.sharedUser.packages.size(); 13187 for (int j = 0; j < packageCount; j++) { 13188 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 13189 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 13190 && pkg.pkg.requestedPermissions.contains(permission)) { 13191 used = true; 13192 break; 13193 } 13194 } 13195 if (used) { 13196 continue; 13197 } 13198 } 13199 13200 PermissionsState permissionsState = ps.getPermissionsState(); 13201 13202 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 13203 13204 // Always clear the user settable flags. 13205 final boolean hasInstallState = permissionsState.getInstallPermissionState( 13206 bp.name) != null; 13207 if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) { 13208 if (hasInstallState) { 13209 writeInstallPermissions = true; 13210 } else { 13211 writeRuntimePermissions = true; 13212 } 13213 } 13214 13215 // Below is only runtime permission handling. 13216 if (!bp.isRuntime()) { 13217 continue; 13218 } 13219 13220 // Never clobber system or policy. 13221 if ((oldFlags & policyOrSystemFlags) != 0) { 13222 continue; 13223 } 13224 13225 // If this permission was granted by default, make sure it is. 13226 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 13227 if (permissionsState.grantRuntimePermission(bp, userId) 13228 != PERMISSION_OPERATION_FAILURE) { 13229 writeRuntimePermissions = true; 13230 } 13231 } else { 13232 // Otherwise, reset the permission. 13233 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 13234 switch (revokeResult) { 13235 case PERMISSION_OPERATION_SUCCESS: { 13236 writeRuntimePermissions = true; 13237 } break; 13238 13239 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 13240 writeRuntimePermissions = true; 13241 // If gids changed for this user, kill all affected packages. 13242 mHandler.post(new Runnable() { 13243 @Override 13244 public void run() { 13245 // This has to happen with no lock held. 13246 killSettingPackagesForUser(ps, userId, 13247 KILL_APP_REASON_GIDS_CHANGED); 13248 } 13249 }); 13250 } break; 13251 } 13252 } 13253 } 13254 13255 // Synchronously write as we are taking permissions away. 13256 if (writeRuntimePermissions) { 13257 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 13258 } 13259 13260 // Synchronously write as we are taking permissions away. 13261 if (writeInstallPermissions) { 13262 mSettings.writeLPr(); 13263 } 13264 } 13265 13266 /** 13267 * Remove entries from the keystore daemon. Will only remove it if the 13268 * {@code appId} is valid. 13269 */ 13270 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 13271 if (appId < 0) { 13272 return; 13273 } 13274 13275 final KeyStore keyStore = KeyStore.getInstance(); 13276 if (keyStore != null) { 13277 if (userId == UserHandle.USER_ALL) { 13278 for (final int individual : sUserManager.getUserIds()) { 13279 keyStore.clearUid(UserHandle.getUid(individual, appId)); 13280 } 13281 } else { 13282 keyStore.clearUid(UserHandle.getUid(userId, appId)); 13283 } 13284 } else { 13285 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 13286 } 13287 } 13288 13289 @Override 13290 public void deleteApplicationCacheFiles(final String packageName, 13291 final IPackageDataObserver observer) { 13292 mContext.enforceCallingOrSelfPermission( 13293 android.Manifest.permission.DELETE_CACHE_FILES, null); 13294 // Queue up an async operation since the package deletion may take a little while. 13295 final int userId = UserHandle.getCallingUserId(); 13296 mHandler.post(new Runnable() { 13297 public void run() { 13298 mHandler.removeCallbacks(this); 13299 final boolean succeded; 13300 synchronized (mInstallLock) { 13301 succeded = deleteApplicationCacheFilesLI(packageName, userId); 13302 } 13303 clearExternalStorageDataSync(packageName, userId, false); 13304 if (observer != null) { 13305 try { 13306 observer.onRemoveCompleted(packageName, succeded); 13307 } catch (RemoteException e) { 13308 Log.i(TAG, "Observer no longer exists."); 13309 } 13310 } //end if observer 13311 } //end run 13312 }); 13313 } 13314 13315 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 13316 if (packageName == null) { 13317 Slog.w(TAG, "Attempt to delete null packageName."); 13318 return false; 13319 } 13320 PackageParser.Package p; 13321 synchronized (mPackages) { 13322 p = mPackages.get(packageName); 13323 } 13324 if (p == null) { 13325 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13326 return false; 13327 } 13328 final ApplicationInfo applicationInfo = p.applicationInfo; 13329 if (applicationInfo == null) { 13330 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13331 return false; 13332 } 13333 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 13334 if (retCode < 0) { 13335 Slog.w(TAG, "Couldn't remove cache files for package: " 13336 + packageName + " u" + userId); 13337 return false; 13338 } 13339 return true; 13340 } 13341 13342 @Override 13343 public void getPackageSizeInfo(final String packageName, int userHandle, 13344 final IPackageStatsObserver observer) { 13345 mContext.enforceCallingOrSelfPermission( 13346 android.Manifest.permission.GET_PACKAGE_SIZE, null); 13347 if (packageName == null) { 13348 throw new IllegalArgumentException("Attempt to get size of null packageName"); 13349 } 13350 13351 PackageStats stats = new PackageStats(packageName, userHandle); 13352 13353 /* 13354 * Queue up an async operation since the package measurement may take a 13355 * little while. 13356 */ 13357 Message msg = mHandler.obtainMessage(INIT_COPY); 13358 msg.obj = new MeasureParams(stats, observer); 13359 mHandler.sendMessage(msg); 13360 } 13361 13362 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 13363 PackageStats pStats) { 13364 if (packageName == null) { 13365 Slog.w(TAG, "Attempt to get size of null packageName."); 13366 return false; 13367 } 13368 PackageParser.Package p; 13369 boolean dataOnly = false; 13370 String libDirRoot = null; 13371 String asecPath = null; 13372 PackageSetting ps = null; 13373 synchronized (mPackages) { 13374 p = mPackages.get(packageName); 13375 ps = mSettings.mPackages.get(packageName); 13376 if(p == null) { 13377 dataOnly = true; 13378 if((ps == null) || (ps.pkg == null)) { 13379 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 13380 return false; 13381 } 13382 p = ps.pkg; 13383 } 13384 if (ps != null) { 13385 libDirRoot = ps.legacyNativeLibraryPathString; 13386 } 13387 if (p != null && (isExternal(p) || p.isForwardLocked())) { 13388 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 13389 if (secureContainerId != null) { 13390 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 13391 } 13392 } 13393 } 13394 String publicSrcDir = null; 13395 if(!dataOnly) { 13396 final ApplicationInfo applicationInfo = p.applicationInfo; 13397 if (applicationInfo == null) { 13398 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 13399 return false; 13400 } 13401 if (p.isForwardLocked()) { 13402 publicSrcDir = applicationInfo.getBaseResourcePath(); 13403 } 13404 } 13405 // TODO: extend to measure size of split APKs 13406 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 13407 // not just the first level. 13408 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 13409 // just the primary. 13410 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 13411 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 13412 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13413 if (res < 0) { 13414 return false; 13415 } 13416 13417 // Fix-up for forward-locked applications in ASEC containers. 13418 if (!isExternal(p)) { 13419 pStats.codeSize += pStats.externalCodeSize; 13420 pStats.externalCodeSize = 0L; 13421 } 13422 13423 return true; 13424 } 13425 13426 13427 @Override 13428 public void addPackageToPreferred(String packageName) { 13429 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13430 } 13431 13432 @Override 13433 public void removePackageFromPreferred(String packageName) { 13434 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13435 } 13436 13437 @Override 13438 public List<PackageInfo> getPreferredPackages(int flags) { 13439 return new ArrayList<PackageInfo>(); 13440 } 13441 13442 private int getUidTargetSdkVersionLockedLPr(int uid) { 13443 Object obj = mSettings.getUserIdLPr(uid); 13444 if (obj instanceof SharedUserSetting) { 13445 final SharedUserSetting sus = (SharedUserSetting) obj; 13446 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13447 final Iterator<PackageSetting> it = sus.packages.iterator(); 13448 while (it.hasNext()) { 13449 final PackageSetting ps = it.next(); 13450 if (ps.pkg != null) { 13451 int v = ps.pkg.applicationInfo.targetSdkVersion; 13452 if (v < vers) vers = v; 13453 } 13454 } 13455 return vers; 13456 } else if (obj instanceof PackageSetting) { 13457 final PackageSetting ps = (PackageSetting) obj; 13458 if (ps.pkg != null) { 13459 return ps.pkg.applicationInfo.targetSdkVersion; 13460 } 13461 } 13462 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13463 } 13464 13465 @Override 13466 public void addPreferredActivity(IntentFilter filter, int match, 13467 ComponentName[] set, ComponentName activity, int userId) { 13468 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13469 "Adding preferred"); 13470 } 13471 13472 private void addPreferredActivityInternal(IntentFilter filter, int match, 13473 ComponentName[] set, ComponentName activity, boolean always, int userId, 13474 String opname) { 13475 // writer 13476 int callingUid = Binder.getCallingUid(); 13477 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13478 if (filter.countActions() == 0) { 13479 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13480 return; 13481 } 13482 synchronized (mPackages) { 13483 if (mContext.checkCallingOrSelfPermission( 13484 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13485 != PackageManager.PERMISSION_GRANTED) { 13486 if (getUidTargetSdkVersionLockedLPr(callingUid) 13487 < Build.VERSION_CODES.FROYO) { 13488 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13489 + callingUid); 13490 return; 13491 } 13492 mContext.enforceCallingOrSelfPermission( 13493 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13494 } 13495 13496 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13497 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13498 + userId + ":"); 13499 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13500 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13501 scheduleWritePackageRestrictionsLocked(userId); 13502 } 13503 } 13504 13505 @Override 13506 public void replacePreferredActivity(IntentFilter filter, int match, 13507 ComponentName[] set, ComponentName activity, int userId) { 13508 if (filter.countActions() != 1) { 13509 throw new IllegalArgumentException( 13510 "replacePreferredActivity expects filter to have only 1 action."); 13511 } 13512 if (filter.countDataAuthorities() != 0 13513 || filter.countDataPaths() != 0 13514 || filter.countDataSchemes() > 1 13515 || filter.countDataTypes() != 0) { 13516 throw new IllegalArgumentException( 13517 "replacePreferredActivity expects filter to have no data authorities, " + 13518 "paths, or types; and at most one scheme."); 13519 } 13520 13521 final int callingUid = Binder.getCallingUid(); 13522 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13523 synchronized (mPackages) { 13524 if (mContext.checkCallingOrSelfPermission( 13525 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13526 != PackageManager.PERMISSION_GRANTED) { 13527 if (getUidTargetSdkVersionLockedLPr(callingUid) 13528 < Build.VERSION_CODES.FROYO) { 13529 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13530 + Binder.getCallingUid()); 13531 return; 13532 } 13533 mContext.enforceCallingOrSelfPermission( 13534 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13535 } 13536 13537 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13538 if (pir != null) { 13539 // Get all of the existing entries that exactly match this filter. 13540 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13541 if (existing != null && existing.size() == 1) { 13542 PreferredActivity cur = existing.get(0); 13543 if (DEBUG_PREFERRED) { 13544 Slog.i(TAG, "Checking replace of preferred:"); 13545 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13546 if (!cur.mPref.mAlways) { 13547 Slog.i(TAG, " -- CUR; not mAlways!"); 13548 } else { 13549 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13550 Slog.i(TAG, " -- CUR: mSet=" 13551 + Arrays.toString(cur.mPref.mSetComponents)); 13552 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13553 Slog.i(TAG, " -- NEW: mMatch=" 13554 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13555 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13556 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13557 } 13558 } 13559 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13560 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13561 && cur.mPref.sameSet(set)) { 13562 // Setting the preferred activity to what it happens to be already 13563 if (DEBUG_PREFERRED) { 13564 Slog.i(TAG, "Replacing with same preferred activity " 13565 + cur.mPref.mShortComponent + " for user " 13566 + userId + ":"); 13567 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13568 } 13569 return; 13570 } 13571 } 13572 13573 if (existing != null) { 13574 if (DEBUG_PREFERRED) { 13575 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13576 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13577 } 13578 for (int i = 0; i < existing.size(); i++) { 13579 PreferredActivity pa = existing.get(i); 13580 if (DEBUG_PREFERRED) { 13581 Slog.i(TAG, "Removing existing preferred activity " 13582 + pa.mPref.mComponent + ":"); 13583 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13584 } 13585 pir.removeFilter(pa); 13586 } 13587 } 13588 } 13589 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13590 "Replacing preferred"); 13591 } 13592 } 13593 13594 @Override 13595 public void clearPackagePreferredActivities(String packageName) { 13596 final int uid = Binder.getCallingUid(); 13597 // writer 13598 synchronized (mPackages) { 13599 PackageParser.Package pkg = mPackages.get(packageName); 13600 if (pkg == null || pkg.applicationInfo.uid != uid) { 13601 if (mContext.checkCallingOrSelfPermission( 13602 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13603 != PackageManager.PERMISSION_GRANTED) { 13604 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13605 < Build.VERSION_CODES.FROYO) { 13606 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13607 + Binder.getCallingUid()); 13608 return; 13609 } 13610 mContext.enforceCallingOrSelfPermission( 13611 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13612 } 13613 } 13614 13615 int user = UserHandle.getCallingUserId(); 13616 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13617 scheduleWritePackageRestrictionsLocked(user); 13618 } 13619 } 13620 } 13621 13622 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13623 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13624 ArrayList<PreferredActivity> removed = null; 13625 boolean changed = false; 13626 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13627 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13628 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13629 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13630 continue; 13631 } 13632 Iterator<PreferredActivity> it = pir.filterIterator(); 13633 while (it.hasNext()) { 13634 PreferredActivity pa = it.next(); 13635 // Mark entry for removal only if it matches the package name 13636 // and the entry is of type "always". 13637 if (packageName == null || 13638 (pa.mPref.mComponent.getPackageName().equals(packageName) 13639 && pa.mPref.mAlways)) { 13640 if (removed == null) { 13641 removed = new ArrayList<PreferredActivity>(); 13642 } 13643 removed.add(pa); 13644 } 13645 } 13646 if (removed != null) { 13647 for (int j=0; j<removed.size(); j++) { 13648 PreferredActivity pa = removed.get(j); 13649 pir.removeFilter(pa); 13650 } 13651 changed = true; 13652 } 13653 } 13654 return changed; 13655 } 13656 13657 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13658 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13659 if (userId == UserHandle.USER_ALL) { 13660 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13661 sUserManager.getUserIds())) { 13662 for (int oneUserId : sUserManager.getUserIds()) { 13663 scheduleWritePackageRestrictionsLocked(oneUserId); 13664 } 13665 } 13666 } else { 13667 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13668 scheduleWritePackageRestrictionsLocked(userId); 13669 } 13670 } 13671 } 13672 13673 13674 void clearDefaultBrowserIfNeeded(String packageName) { 13675 for (int oneUserId : sUserManager.getUserIds()) { 13676 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13677 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13678 if (packageName.equals(defaultBrowserPackageName)) { 13679 setDefaultBrowserPackageName(null, oneUserId); 13680 } 13681 } 13682 } 13683 13684 @Override 13685 public void resetPreferredActivities(int userId) { 13686 mContext.enforceCallingOrSelfPermission( 13687 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13688 // writer 13689 synchronized (mPackages) { 13690 clearPackagePreferredActivitiesLPw(null, userId); 13691 mSettings.applyDefaultPreferredAppsLPw(this, userId); 13692 applyFactoryDefaultBrowserLPw(userId); 13693 primeDomainVerificationsLPw(userId); 13694 13695 scheduleWritePackageRestrictionsLocked(userId); 13696 } 13697 } 13698 13699 @Override 13700 public int getPreferredActivities(List<IntentFilter> outFilters, 13701 List<ComponentName> outActivities, String packageName) { 13702 13703 int num = 0; 13704 final int userId = UserHandle.getCallingUserId(); 13705 // reader 13706 synchronized (mPackages) { 13707 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13708 if (pir != null) { 13709 final Iterator<PreferredActivity> it = pir.filterIterator(); 13710 while (it.hasNext()) { 13711 final PreferredActivity pa = it.next(); 13712 if (packageName == null 13713 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13714 && pa.mPref.mAlways)) { 13715 if (outFilters != null) { 13716 outFilters.add(new IntentFilter(pa)); 13717 } 13718 if (outActivities != null) { 13719 outActivities.add(pa.mPref.mComponent); 13720 } 13721 } 13722 } 13723 } 13724 } 13725 13726 return num; 13727 } 13728 13729 @Override 13730 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13731 int userId) { 13732 int callingUid = Binder.getCallingUid(); 13733 if (callingUid != Process.SYSTEM_UID) { 13734 throw new SecurityException( 13735 "addPersistentPreferredActivity can only be run by the system"); 13736 } 13737 if (filter.countActions() == 0) { 13738 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13739 return; 13740 } 13741 synchronized (mPackages) { 13742 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13743 " :"); 13744 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13745 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13746 new PersistentPreferredActivity(filter, activity)); 13747 scheduleWritePackageRestrictionsLocked(userId); 13748 } 13749 } 13750 13751 @Override 13752 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13753 int callingUid = Binder.getCallingUid(); 13754 if (callingUid != Process.SYSTEM_UID) { 13755 throw new SecurityException( 13756 "clearPackagePersistentPreferredActivities can only be run by the system"); 13757 } 13758 ArrayList<PersistentPreferredActivity> removed = null; 13759 boolean changed = false; 13760 synchronized (mPackages) { 13761 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13762 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13763 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13764 .valueAt(i); 13765 if (userId != thisUserId) { 13766 continue; 13767 } 13768 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13769 while (it.hasNext()) { 13770 PersistentPreferredActivity ppa = it.next(); 13771 // Mark entry for removal only if it matches the package name. 13772 if (ppa.mComponent.getPackageName().equals(packageName)) { 13773 if (removed == null) { 13774 removed = new ArrayList<PersistentPreferredActivity>(); 13775 } 13776 removed.add(ppa); 13777 } 13778 } 13779 if (removed != null) { 13780 for (int j=0; j<removed.size(); j++) { 13781 PersistentPreferredActivity ppa = removed.get(j); 13782 ppir.removeFilter(ppa); 13783 } 13784 changed = true; 13785 } 13786 } 13787 13788 if (changed) { 13789 scheduleWritePackageRestrictionsLocked(userId); 13790 } 13791 } 13792 } 13793 13794 /** 13795 * Common machinery for picking apart a restored XML blob and passing 13796 * it to a caller-supplied functor to be applied to the running system. 13797 */ 13798 private void restoreFromXml(XmlPullParser parser, int userId, 13799 String expectedStartTag, BlobXmlRestorer functor) 13800 throws IOException, XmlPullParserException { 13801 int type; 13802 while ((type = parser.next()) != XmlPullParser.START_TAG 13803 && type != XmlPullParser.END_DOCUMENT) { 13804 } 13805 if (type != XmlPullParser.START_TAG) { 13806 // oops didn't find a start tag?! 13807 if (DEBUG_BACKUP) { 13808 Slog.e(TAG, "Didn't find start tag during restore"); 13809 } 13810 return; 13811 } 13812 13813 // this is supposed to be TAG_PREFERRED_BACKUP 13814 if (!expectedStartTag.equals(parser.getName())) { 13815 if (DEBUG_BACKUP) { 13816 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13817 } 13818 return; 13819 } 13820 13821 // skip interfering stuff, then we're aligned with the backing implementation 13822 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13823 functor.apply(parser, userId); 13824 } 13825 13826 private interface BlobXmlRestorer { 13827 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 13828 } 13829 13830 /** 13831 * Non-Binder method, support for the backup/restore mechanism: write the 13832 * full set of preferred activities in its canonical XML format. Returns the 13833 * XML output as a byte array, or null if there is none. 13834 */ 13835 @Override 13836 public byte[] getPreferredActivityBackup(int userId) { 13837 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13838 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13839 } 13840 13841 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13842 try { 13843 final XmlSerializer serializer = new FastXmlSerializer(); 13844 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13845 serializer.startDocument(null, true); 13846 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13847 13848 synchronized (mPackages) { 13849 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13850 } 13851 13852 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13853 serializer.endDocument(); 13854 serializer.flush(); 13855 } catch (Exception e) { 13856 if (DEBUG_BACKUP) { 13857 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13858 } 13859 return null; 13860 } 13861 13862 return dataStream.toByteArray(); 13863 } 13864 13865 @Override 13866 public void restorePreferredActivities(byte[] backup, int userId) { 13867 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13868 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13869 } 13870 13871 try { 13872 final XmlPullParser parser = Xml.newPullParser(); 13873 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13874 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 13875 new BlobXmlRestorer() { 13876 @Override 13877 public void apply(XmlPullParser parser, int userId) 13878 throws XmlPullParserException, IOException { 13879 synchronized (mPackages) { 13880 mSettings.readPreferredActivitiesLPw(parser, userId); 13881 } 13882 } 13883 } ); 13884 } catch (Exception e) { 13885 if (DEBUG_BACKUP) { 13886 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13887 } 13888 } 13889 } 13890 13891 /** 13892 * Non-Binder method, support for the backup/restore mechanism: write the 13893 * default browser (etc) settings in its canonical XML format. Returns the default 13894 * browser XML representation as a byte array, or null if there is none. 13895 */ 13896 @Override 13897 public byte[] getDefaultAppsBackup(int userId) { 13898 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13899 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 13900 } 13901 13902 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13903 try { 13904 final XmlSerializer serializer = new FastXmlSerializer(); 13905 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13906 serializer.startDocument(null, true); 13907 serializer.startTag(null, TAG_DEFAULT_APPS); 13908 13909 synchronized (mPackages) { 13910 mSettings.writeDefaultAppsLPr(serializer, userId); 13911 } 13912 13913 serializer.endTag(null, TAG_DEFAULT_APPS); 13914 serializer.endDocument(); 13915 serializer.flush(); 13916 } catch (Exception e) { 13917 if (DEBUG_BACKUP) { 13918 Slog.e(TAG, "Unable to write default apps for backup", e); 13919 } 13920 return null; 13921 } 13922 13923 return dataStream.toByteArray(); 13924 } 13925 13926 @Override 13927 public void restoreDefaultApps(byte[] backup, int userId) { 13928 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13929 throw new SecurityException("Only the system may call restoreDefaultApps()"); 13930 } 13931 13932 try { 13933 final XmlPullParser parser = Xml.newPullParser(); 13934 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13935 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 13936 new BlobXmlRestorer() { 13937 @Override 13938 public void apply(XmlPullParser parser, int userId) 13939 throws XmlPullParserException, IOException { 13940 synchronized (mPackages) { 13941 mSettings.readDefaultAppsLPw(parser, userId); 13942 } 13943 } 13944 } ); 13945 } catch (Exception e) { 13946 if (DEBUG_BACKUP) { 13947 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 13948 } 13949 } 13950 } 13951 13952 @Override 13953 public byte[] getIntentFilterVerificationBackup(int userId) { 13954 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13955 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 13956 } 13957 13958 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13959 try { 13960 final XmlSerializer serializer = new FastXmlSerializer(); 13961 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13962 serializer.startDocument(null, true); 13963 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 13964 13965 synchronized (mPackages) { 13966 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 13967 } 13968 13969 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 13970 serializer.endDocument(); 13971 serializer.flush(); 13972 } catch (Exception e) { 13973 if (DEBUG_BACKUP) { 13974 Slog.e(TAG, "Unable to write default apps for backup", e); 13975 } 13976 return null; 13977 } 13978 13979 return dataStream.toByteArray(); 13980 } 13981 13982 @Override 13983 public void restoreIntentFilterVerification(byte[] backup, int userId) { 13984 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13985 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13986 } 13987 13988 try { 13989 final XmlPullParser parser = Xml.newPullParser(); 13990 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13991 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 13992 new BlobXmlRestorer() { 13993 @Override 13994 public void apply(XmlPullParser parser, int userId) 13995 throws XmlPullParserException, IOException { 13996 synchronized (mPackages) { 13997 mSettings.readAllDomainVerificationsLPr(parser, userId); 13998 mSettings.writeLPr(); 13999 } 14000 } 14001 } ); 14002 } catch (Exception e) { 14003 if (DEBUG_BACKUP) { 14004 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14005 } 14006 } 14007 } 14008 14009 @Override 14010 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14011 int sourceUserId, int targetUserId, int flags) { 14012 mContext.enforceCallingOrSelfPermission( 14013 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14014 int callingUid = Binder.getCallingUid(); 14015 enforceOwnerRights(ownerPackage, callingUid); 14016 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14017 if (intentFilter.countActions() == 0) { 14018 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14019 return; 14020 } 14021 synchronized (mPackages) { 14022 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14023 ownerPackage, targetUserId, flags); 14024 CrossProfileIntentResolver resolver = 14025 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14026 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14027 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14028 if (existing != null) { 14029 int size = existing.size(); 14030 for (int i = 0; i < size; i++) { 14031 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14032 return; 14033 } 14034 } 14035 } 14036 resolver.addFilter(newFilter); 14037 scheduleWritePackageRestrictionsLocked(sourceUserId); 14038 } 14039 } 14040 14041 @Override 14042 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14043 mContext.enforceCallingOrSelfPermission( 14044 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14045 int callingUid = Binder.getCallingUid(); 14046 enforceOwnerRights(ownerPackage, callingUid); 14047 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14048 synchronized (mPackages) { 14049 CrossProfileIntentResolver resolver = 14050 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14051 ArraySet<CrossProfileIntentFilter> set = 14052 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14053 for (CrossProfileIntentFilter filter : set) { 14054 if (filter.getOwnerPackage().equals(ownerPackage)) { 14055 resolver.removeFilter(filter); 14056 } 14057 } 14058 scheduleWritePackageRestrictionsLocked(sourceUserId); 14059 } 14060 } 14061 14062 // Enforcing that callingUid is owning pkg on userId 14063 private void enforceOwnerRights(String pkg, int callingUid) { 14064 // The system owns everything. 14065 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 14066 return; 14067 } 14068 int callingUserId = UserHandle.getUserId(callingUid); 14069 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 14070 if (pi == null) { 14071 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 14072 + callingUserId); 14073 } 14074 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 14075 throw new SecurityException("Calling uid " + callingUid 14076 + " does not own package " + pkg); 14077 } 14078 } 14079 14080 @Override 14081 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 14082 Intent intent = new Intent(Intent.ACTION_MAIN); 14083 intent.addCategory(Intent.CATEGORY_HOME); 14084 14085 final int callingUserId = UserHandle.getCallingUserId(); 14086 List<ResolveInfo> list = queryIntentActivities(intent, null, 14087 PackageManager.GET_META_DATA, callingUserId); 14088 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 14089 true, false, false, callingUserId); 14090 14091 allHomeCandidates.clear(); 14092 if (list != null) { 14093 for (ResolveInfo ri : list) { 14094 allHomeCandidates.add(ri); 14095 } 14096 } 14097 return (preferred == null || preferred.activityInfo == null) 14098 ? null 14099 : new ComponentName(preferred.activityInfo.packageName, 14100 preferred.activityInfo.name); 14101 } 14102 14103 @Override 14104 public void setApplicationEnabledSetting(String appPackageName, 14105 int newState, int flags, int userId, String callingPackage) { 14106 if (!sUserManager.exists(userId)) return; 14107 if (callingPackage == null) { 14108 callingPackage = Integer.toString(Binder.getCallingUid()); 14109 } 14110 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 14111 } 14112 14113 @Override 14114 public void setComponentEnabledSetting(ComponentName componentName, 14115 int newState, int flags, int userId) { 14116 if (!sUserManager.exists(userId)) return; 14117 setEnabledSetting(componentName.getPackageName(), 14118 componentName.getClassName(), newState, flags, userId, null); 14119 } 14120 14121 private void setEnabledSetting(final String packageName, String className, int newState, 14122 final int flags, int userId, String callingPackage) { 14123 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 14124 || newState == COMPONENT_ENABLED_STATE_ENABLED 14125 || newState == COMPONENT_ENABLED_STATE_DISABLED 14126 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 14127 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 14128 throw new IllegalArgumentException("Invalid new component state: " 14129 + newState); 14130 } 14131 PackageSetting pkgSetting; 14132 final int uid = Binder.getCallingUid(); 14133 final int permission = mContext.checkCallingOrSelfPermission( 14134 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14135 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 14136 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14137 boolean sendNow = false; 14138 boolean isApp = (className == null); 14139 String componentName = isApp ? packageName : className; 14140 int packageUid = -1; 14141 ArrayList<String> components; 14142 14143 // writer 14144 synchronized (mPackages) { 14145 pkgSetting = mSettings.mPackages.get(packageName); 14146 if (pkgSetting == null) { 14147 if (className == null) { 14148 throw new IllegalArgumentException( 14149 "Unknown package: " + packageName); 14150 } 14151 throw new IllegalArgumentException( 14152 "Unknown component: " + packageName 14153 + "/" + className); 14154 } 14155 // Allow root and verify that userId is not being specified by a different user 14156 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 14157 throw new SecurityException( 14158 "Permission Denial: attempt to change component state from pid=" 14159 + Binder.getCallingPid() 14160 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 14161 } 14162 if (className == null) { 14163 // We're dealing with an application/package level state change 14164 if (pkgSetting.getEnabled(userId) == newState) { 14165 // Nothing to do 14166 return; 14167 } 14168 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 14169 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 14170 // Don't care about who enables an app. 14171 callingPackage = null; 14172 } 14173 pkgSetting.setEnabled(newState, userId, callingPackage); 14174 // pkgSetting.pkg.mSetEnabled = newState; 14175 } else { 14176 // We're dealing with a component level state change 14177 // First, verify that this is a valid class name. 14178 PackageParser.Package pkg = pkgSetting.pkg; 14179 if (pkg == null || !pkg.hasComponentClassName(className)) { 14180 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 14181 throw new IllegalArgumentException("Component class " + className 14182 + " does not exist in " + packageName); 14183 } else { 14184 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 14185 + className + " does not exist in " + packageName); 14186 } 14187 } 14188 switch (newState) { 14189 case COMPONENT_ENABLED_STATE_ENABLED: 14190 if (!pkgSetting.enableComponentLPw(className, userId)) { 14191 return; 14192 } 14193 break; 14194 case COMPONENT_ENABLED_STATE_DISABLED: 14195 if (!pkgSetting.disableComponentLPw(className, userId)) { 14196 return; 14197 } 14198 break; 14199 case COMPONENT_ENABLED_STATE_DEFAULT: 14200 if (!pkgSetting.restoreComponentLPw(className, userId)) { 14201 return; 14202 } 14203 break; 14204 default: 14205 Slog.e(TAG, "Invalid new component state: " + newState); 14206 return; 14207 } 14208 } 14209 scheduleWritePackageRestrictionsLocked(userId); 14210 components = mPendingBroadcasts.get(userId, packageName); 14211 final boolean newPackage = components == null; 14212 if (newPackage) { 14213 components = new ArrayList<String>(); 14214 } 14215 if (!components.contains(componentName)) { 14216 components.add(componentName); 14217 } 14218 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 14219 sendNow = true; 14220 // Purge entry from pending broadcast list if another one exists already 14221 // since we are sending one right away. 14222 mPendingBroadcasts.remove(userId, packageName); 14223 } else { 14224 if (newPackage) { 14225 mPendingBroadcasts.put(userId, packageName, components); 14226 } 14227 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 14228 // Schedule a message 14229 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 14230 } 14231 } 14232 } 14233 14234 long callingId = Binder.clearCallingIdentity(); 14235 try { 14236 if (sendNow) { 14237 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 14238 sendPackageChangedBroadcast(packageName, 14239 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 14240 } 14241 } finally { 14242 Binder.restoreCallingIdentity(callingId); 14243 } 14244 } 14245 14246 private void sendPackageChangedBroadcast(String packageName, 14247 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 14248 if (DEBUG_INSTALL) 14249 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 14250 + componentNames); 14251 Bundle extras = new Bundle(4); 14252 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 14253 String nameList[] = new String[componentNames.size()]; 14254 componentNames.toArray(nameList); 14255 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 14256 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 14257 extras.putInt(Intent.EXTRA_UID, packageUid); 14258 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 14259 new int[] {UserHandle.getUserId(packageUid)}); 14260 } 14261 14262 @Override 14263 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 14264 if (!sUserManager.exists(userId)) return; 14265 final int uid = Binder.getCallingUid(); 14266 final int permission = mContext.checkCallingOrSelfPermission( 14267 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 14268 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 14269 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 14270 // writer 14271 synchronized (mPackages) { 14272 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 14273 allowedByPermission, uid, userId)) { 14274 scheduleWritePackageRestrictionsLocked(userId); 14275 } 14276 } 14277 } 14278 14279 @Override 14280 public String getInstallerPackageName(String packageName) { 14281 // reader 14282 synchronized (mPackages) { 14283 return mSettings.getInstallerPackageNameLPr(packageName); 14284 } 14285 } 14286 14287 @Override 14288 public int getApplicationEnabledSetting(String packageName, int userId) { 14289 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14290 int uid = Binder.getCallingUid(); 14291 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 14292 // reader 14293 synchronized (mPackages) { 14294 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 14295 } 14296 } 14297 14298 @Override 14299 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 14300 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 14301 int uid = Binder.getCallingUid(); 14302 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 14303 // reader 14304 synchronized (mPackages) { 14305 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 14306 } 14307 } 14308 14309 @Override 14310 public void enterSafeMode() { 14311 enforceSystemOrRoot("Only the system can request entering safe mode"); 14312 14313 if (!mSystemReady) { 14314 mSafeMode = true; 14315 } 14316 } 14317 14318 @Override 14319 public void systemReady() { 14320 mSystemReady = true; 14321 14322 // Read the compatibilty setting when the system is ready. 14323 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 14324 mContext.getContentResolver(), 14325 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 14326 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 14327 if (DEBUG_SETTINGS) { 14328 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 14329 } 14330 14331 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 14332 14333 synchronized (mPackages) { 14334 // Verify that all of the preferred activity components actually 14335 // exist. It is possible for applications to be updated and at 14336 // that point remove a previously declared activity component that 14337 // had been set as a preferred activity. We try to clean this up 14338 // the next time we encounter that preferred activity, but it is 14339 // possible for the user flow to never be able to return to that 14340 // situation so here we do a sanity check to make sure we haven't 14341 // left any junk around. 14342 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 14343 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14344 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14345 removed.clear(); 14346 for (PreferredActivity pa : pir.filterSet()) { 14347 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 14348 removed.add(pa); 14349 } 14350 } 14351 if (removed.size() > 0) { 14352 for (int r=0; r<removed.size(); r++) { 14353 PreferredActivity pa = removed.get(r); 14354 Slog.w(TAG, "Removing dangling preferred activity: " 14355 + pa.mPref.mComponent); 14356 pir.removeFilter(pa); 14357 } 14358 mSettings.writePackageRestrictionsLPr( 14359 mSettings.mPreferredActivities.keyAt(i)); 14360 } 14361 } 14362 14363 for (int userId : UserManagerService.getInstance().getUserIds()) { 14364 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 14365 grantPermissionsUserIds = ArrayUtils.appendInt( 14366 grantPermissionsUserIds, userId); 14367 } 14368 } 14369 } 14370 sUserManager.systemReady(); 14371 14372 // If we upgraded grant all default permissions before kicking off. 14373 for (int userId : grantPermissionsUserIds) { 14374 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 14375 } 14376 14377 // Kick off any messages waiting for system ready 14378 if (mPostSystemReadyMessages != null) { 14379 for (Message msg : mPostSystemReadyMessages) { 14380 msg.sendToTarget(); 14381 } 14382 mPostSystemReadyMessages = null; 14383 } 14384 14385 // Watch for external volumes that come and go over time 14386 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14387 storage.registerListener(mStorageListener); 14388 14389 mInstallerService.systemReady(); 14390 mPackageDexOptimizer.systemReady(); 14391 } 14392 14393 @Override 14394 public boolean isSafeMode() { 14395 return mSafeMode; 14396 } 14397 14398 @Override 14399 public boolean hasSystemUidErrors() { 14400 return mHasSystemUidErrors; 14401 } 14402 14403 static String arrayToString(int[] array) { 14404 StringBuffer buf = new StringBuffer(128); 14405 buf.append('['); 14406 if (array != null) { 14407 for (int i=0; i<array.length; i++) { 14408 if (i > 0) buf.append(", "); 14409 buf.append(array[i]); 14410 } 14411 } 14412 buf.append(']'); 14413 return buf.toString(); 14414 } 14415 14416 static class DumpState { 14417 public static final int DUMP_LIBS = 1 << 0; 14418 public static final int DUMP_FEATURES = 1 << 1; 14419 public static final int DUMP_RESOLVERS = 1 << 2; 14420 public static final int DUMP_PERMISSIONS = 1 << 3; 14421 public static final int DUMP_PACKAGES = 1 << 4; 14422 public static final int DUMP_SHARED_USERS = 1 << 5; 14423 public static final int DUMP_MESSAGES = 1 << 6; 14424 public static final int DUMP_PROVIDERS = 1 << 7; 14425 public static final int DUMP_VERIFIERS = 1 << 8; 14426 public static final int DUMP_PREFERRED = 1 << 9; 14427 public static final int DUMP_PREFERRED_XML = 1 << 10; 14428 public static final int DUMP_KEYSETS = 1 << 11; 14429 public static final int DUMP_VERSION = 1 << 12; 14430 public static final int DUMP_INSTALLS = 1 << 13; 14431 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 14432 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 14433 14434 public static final int OPTION_SHOW_FILTERS = 1 << 0; 14435 14436 private int mTypes; 14437 14438 private int mOptions; 14439 14440 private boolean mTitlePrinted; 14441 14442 private SharedUserSetting mSharedUser; 14443 14444 public boolean isDumping(int type) { 14445 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 14446 return true; 14447 } 14448 14449 return (mTypes & type) != 0; 14450 } 14451 14452 public void setDump(int type) { 14453 mTypes |= type; 14454 } 14455 14456 public boolean isOptionEnabled(int option) { 14457 return (mOptions & option) != 0; 14458 } 14459 14460 public void setOptionEnabled(int option) { 14461 mOptions |= option; 14462 } 14463 14464 public boolean onTitlePrinted() { 14465 final boolean printed = mTitlePrinted; 14466 mTitlePrinted = true; 14467 return printed; 14468 } 14469 14470 public boolean getTitlePrinted() { 14471 return mTitlePrinted; 14472 } 14473 14474 public void setTitlePrinted(boolean enabled) { 14475 mTitlePrinted = enabled; 14476 } 14477 14478 public SharedUserSetting getSharedUser() { 14479 return mSharedUser; 14480 } 14481 14482 public void setSharedUser(SharedUserSetting user) { 14483 mSharedUser = user; 14484 } 14485 } 14486 14487 @Override 14488 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 14489 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 14490 != PackageManager.PERMISSION_GRANTED) { 14491 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 14492 + Binder.getCallingPid() 14493 + ", uid=" + Binder.getCallingUid() 14494 + " without permission " 14495 + android.Manifest.permission.DUMP); 14496 return; 14497 } 14498 14499 DumpState dumpState = new DumpState(); 14500 boolean fullPreferred = false; 14501 boolean checkin = false; 14502 14503 String packageName = null; 14504 ArraySet<String> permissionNames = null; 14505 14506 int opti = 0; 14507 while (opti < args.length) { 14508 String opt = args[opti]; 14509 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14510 break; 14511 } 14512 opti++; 14513 14514 if ("-a".equals(opt)) { 14515 // Right now we only know how to print all. 14516 } else if ("-h".equals(opt)) { 14517 pw.println("Package manager dump options:"); 14518 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 14519 pw.println(" --checkin: dump for a checkin"); 14520 pw.println(" -f: print details of intent filters"); 14521 pw.println(" -h: print this help"); 14522 pw.println(" cmd may be one of:"); 14523 pw.println(" l[ibraries]: list known shared libraries"); 14524 pw.println(" f[ibraries]: list device features"); 14525 pw.println(" k[eysets]: print known keysets"); 14526 pw.println(" r[esolvers]: dump intent resolvers"); 14527 pw.println(" perm[issions]: dump permissions"); 14528 pw.println(" permission [name ...]: dump declaration and use of given permission"); 14529 pw.println(" pref[erred]: print preferred package settings"); 14530 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 14531 pw.println(" prov[iders]: dump content providers"); 14532 pw.println(" p[ackages]: dump installed packages"); 14533 pw.println(" s[hared-users]: dump shared user IDs"); 14534 pw.println(" m[essages]: print collected runtime messages"); 14535 pw.println(" v[erifiers]: print package verifier info"); 14536 pw.println(" version: print database version info"); 14537 pw.println(" write: write current settings now"); 14538 pw.println(" <package.name>: info about given package"); 14539 pw.println(" installs: details about install sessions"); 14540 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 14541 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 14542 return; 14543 } else if ("--checkin".equals(opt)) { 14544 checkin = true; 14545 } else if ("-f".equals(opt)) { 14546 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14547 } else { 14548 pw.println("Unknown argument: " + opt + "; use -h for help"); 14549 } 14550 } 14551 14552 // Is the caller requesting to dump a particular piece of data? 14553 if (opti < args.length) { 14554 String cmd = args[opti]; 14555 opti++; 14556 // Is this a package name? 14557 if ("android".equals(cmd) || cmd.contains(".")) { 14558 packageName = cmd; 14559 // When dumping a single package, we always dump all of its 14560 // filter information since the amount of data will be reasonable. 14561 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14562 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14563 dumpState.setDump(DumpState.DUMP_LIBS); 14564 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14565 dumpState.setDump(DumpState.DUMP_FEATURES); 14566 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14567 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14568 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14569 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14570 } else if ("permission".equals(cmd)) { 14571 if (opti >= args.length) { 14572 pw.println("Error: permission requires permission name"); 14573 return; 14574 } 14575 permissionNames = new ArraySet<>(); 14576 while (opti < args.length) { 14577 permissionNames.add(args[opti]); 14578 opti++; 14579 } 14580 dumpState.setDump(DumpState.DUMP_PERMISSIONS 14581 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 14582 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14583 dumpState.setDump(DumpState.DUMP_PREFERRED); 14584 } else if ("preferred-xml".equals(cmd)) { 14585 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14586 if (opti < args.length && "--full".equals(args[opti])) { 14587 fullPreferred = true; 14588 opti++; 14589 } 14590 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14591 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14592 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14593 dumpState.setDump(DumpState.DUMP_PACKAGES); 14594 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14595 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14596 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14597 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14598 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14599 dumpState.setDump(DumpState.DUMP_MESSAGES); 14600 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14601 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14602 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14603 || "intent-filter-verifiers".equals(cmd)) { 14604 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14605 } else if ("version".equals(cmd)) { 14606 dumpState.setDump(DumpState.DUMP_VERSION); 14607 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14608 dumpState.setDump(DumpState.DUMP_KEYSETS); 14609 } else if ("installs".equals(cmd)) { 14610 dumpState.setDump(DumpState.DUMP_INSTALLS); 14611 } else if ("write".equals(cmd)) { 14612 synchronized (mPackages) { 14613 mSettings.writeLPr(); 14614 pw.println("Settings written."); 14615 return; 14616 } 14617 } 14618 } 14619 14620 if (checkin) { 14621 pw.println("vers,1"); 14622 } 14623 14624 // reader 14625 synchronized (mPackages) { 14626 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14627 if (!checkin) { 14628 if (dumpState.onTitlePrinted()) 14629 pw.println(); 14630 pw.println("Database versions:"); 14631 pw.print(" SDK Version:"); 14632 pw.print(" internal="); 14633 pw.print(mSettings.mInternalSdkPlatform); 14634 pw.print(" external="); 14635 pw.println(mSettings.mExternalSdkPlatform); 14636 pw.print(" DB Version:"); 14637 pw.print(" internal="); 14638 pw.print(mSettings.mInternalDatabaseVersion); 14639 pw.print(" external="); 14640 pw.println(mSettings.mExternalDatabaseVersion); 14641 } 14642 } 14643 14644 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14645 if (!checkin) { 14646 if (dumpState.onTitlePrinted()) 14647 pw.println(); 14648 pw.println("Verifiers:"); 14649 pw.print(" Required: "); 14650 pw.print(mRequiredVerifierPackage); 14651 pw.print(" (uid="); 14652 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14653 pw.println(")"); 14654 } else if (mRequiredVerifierPackage != null) { 14655 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14656 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14657 } 14658 } 14659 14660 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14661 packageName == null) { 14662 if (mIntentFilterVerifierComponent != null) { 14663 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14664 if (!checkin) { 14665 if (dumpState.onTitlePrinted()) 14666 pw.println(); 14667 pw.println("Intent Filter Verifier:"); 14668 pw.print(" Using: "); 14669 pw.print(verifierPackageName); 14670 pw.print(" (uid="); 14671 pw.print(getPackageUid(verifierPackageName, 0)); 14672 pw.println(")"); 14673 } else if (verifierPackageName != null) { 14674 pw.print("ifv,"); pw.print(verifierPackageName); 14675 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14676 } 14677 } else { 14678 pw.println(); 14679 pw.println("No Intent Filter Verifier available!"); 14680 } 14681 } 14682 14683 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14684 boolean printedHeader = false; 14685 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14686 while (it.hasNext()) { 14687 String name = it.next(); 14688 SharedLibraryEntry ent = mSharedLibraries.get(name); 14689 if (!checkin) { 14690 if (!printedHeader) { 14691 if (dumpState.onTitlePrinted()) 14692 pw.println(); 14693 pw.println("Libraries:"); 14694 printedHeader = true; 14695 } 14696 pw.print(" "); 14697 } else { 14698 pw.print("lib,"); 14699 } 14700 pw.print(name); 14701 if (!checkin) { 14702 pw.print(" -> "); 14703 } 14704 if (ent.path != null) { 14705 if (!checkin) { 14706 pw.print("(jar) "); 14707 pw.print(ent.path); 14708 } else { 14709 pw.print(",jar,"); 14710 pw.print(ent.path); 14711 } 14712 } else { 14713 if (!checkin) { 14714 pw.print("(apk) "); 14715 pw.print(ent.apk); 14716 } else { 14717 pw.print(",apk,"); 14718 pw.print(ent.apk); 14719 } 14720 } 14721 pw.println(); 14722 } 14723 } 14724 14725 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14726 if (dumpState.onTitlePrinted()) 14727 pw.println(); 14728 if (!checkin) { 14729 pw.println("Features:"); 14730 } 14731 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14732 while (it.hasNext()) { 14733 String name = it.next(); 14734 if (!checkin) { 14735 pw.print(" "); 14736 } else { 14737 pw.print("feat,"); 14738 } 14739 pw.println(name); 14740 } 14741 } 14742 14743 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14744 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14745 : "Activity Resolver Table:", " ", packageName, 14746 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14747 dumpState.setTitlePrinted(true); 14748 } 14749 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14750 : "Receiver Resolver Table:", " ", packageName, 14751 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14752 dumpState.setTitlePrinted(true); 14753 } 14754 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14755 : "Service Resolver Table:", " ", packageName, 14756 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14757 dumpState.setTitlePrinted(true); 14758 } 14759 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14760 : "Provider Resolver Table:", " ", packageName, 14761 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14762 dumpState.setTitlePrinted(true); 14763 } 14764 } 14765 14766 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14767 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14768 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14769 int user = mSettings.mPreferredActivities.keyAt(i); 14770 if (pir.dump(pw, 14771 dumpState.getTitlePrinted() 14772 ? "\nPreferred Activities User " + user + ":" 14773 : "Preferred Activities User " + user + ":", " ", 14774 packageName, true, false)) { 14775 dumpState.setTitlePrinted(true); 14776 } 14777 } 14778 } 14779 14780 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14781 pw.flush(); 14782 FileOutputStream fout = new FileOutputStream(fd); 14783 BufferedOutputStream str = new BufferedOutputStream(fout); 14784 XmlSerializer serializer = new FastXmlSerializer(); 14785 try { 14786 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14787 serializer.startDocument(null, true); 14788 serializer.setFeature( 14789 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14790 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14791 serializer.endDocument(); 14792 serializer.flush(); 14793 } catch (IllegalArgumentException e) { 14794 pw.println("Failed writing: " + e); 14795 } catch (IllegalStateException e) { 14796 pw.println("Failed writing: " + e); 14797 } catch (IOException e) { 14798 pw.println("Failed writing: " + e); 14799 } 14800 } 14801 14802 if (!checkin 14803 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14804 && packageName == null) { 14805 pw.println(); 14806 int count = mSettings.mPackages.size(); 14807 if (count == 0) { 14808 pw.println("No applications!"); 14809 pw.println(); 14810 } else { 14811 final String prefix = " "; 14812 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14813 if (allPackageSettings.size() == 0) { 14814 pw.println("No domain preferred apps!"); 14815 pw.println(); 14816 } else { 14817 pw.println("App verification status:"); 14818 pw.println(); 14819 count = 0; 14820 for (PackageSetting ps : allPackageSettings) { 14821 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14822 if (ivi == null || ivi.getPackageName() == null) continue; 14823 pw.println(prefix + "Package: " + ivi.getPackageName()); 14824 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14825 pw.println(prefix + "Status: " + ivi.getStatusString()); 14826 pw.println(); 14827 count++; 14828 } 14829 if (count == 0) { 14830 pw.println(prefix + "No app verification established."); 14831 pw.println(); 14832 } 14833 for (int userId : sUserManager.getUserIds()) { 14834 pw.println("App linkages for user " + userId + ":"); 14835 pw.println(); 14836 count = 0; 14837 for (PackageSetting ps : allPackageSettings) { 14838 final int status = ps.getDomainVerificationStatusForUser(userId); 14839 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14840 continue; 14841 } 14842 pw.println(prefix + "Package: " + ps.name); 14843 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 14844 String statusStr = IntentFilterVerificationInfo. 14845 getStatusStringFromValue(status); 14846 pw.println(prefix + "Status: " + statusStr); 14847 pw.println(); 14848 count++; 14849 } 14850 if (count == 0) { 14851 pw.println(prefix + "No configured app linkages."); 14852 pw.println(); 14853 } 14854 } 14855 } 14856 } 14857 } 14858 14859 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14860 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 14861 if (packageName == null && permissionNames == null) { 14862 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14863 if (iperm == 0) { 14864 if (dumpState.onTitlePrinted()) 14865 pw.println(); 14866 pw.println("AppOp Permissions:"); 14867 } 14868 pw.print(" AppOp Permission "); 14869 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14870 pw.println(":"); 14871 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14872 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14873 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14874 } 14875 } 14876 } 14877 } 14878 14879 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14880 boolean printedSomething = false; 14881 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14882 if (packageName != null && !packageName.equals(p.info.packageName)) { 14883 continue; 14884 } 14885 if (!printedSomething) { 14886 if (dumpState.onTitlePrinted()) 14887 pw.println(); 14888 pw.println("Registered ContentProviders:"); 14889 printedSomething = true; 14890 } 14891 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14892 pw.print(" "); pw.println(p.toString()); 14893 } 14894 printedSomething = false; 14895 for (Map.Entry<String, PackageParser.Provider> entry : 14896 mProvidersByAuthority.entrySet()) { 14897 PackageParser.Provider p = entry.getValue(); 14898 if (packageName != null && !packageName.equals(p.info.packageName)) { 14899 continue; 14900 } 14901 if (!printedSomething) { 14902 if (dumpState.onTitlePrinted()) 14903 pw.println(); 14904 pw.println("ContentProvider Authorities:"); 14905 printedSomething = true; 14906 } 14907 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14908 pw.print(" "); pw.println(p.toString()); 14909 if (p.info != null && p.info.applicationInfo != null) { 14910 final String appInfo = p.info.applicationInfo.toString(); 14911 pw.print(" applicationInfo="); pw.println(appInfo); 14912 } 14913 } 14914 } 14915 14916 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14917 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14918 } 14919 14920 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14921 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 14922 } 14923 14924 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14925 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 14926 } 14927 14928 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14929 // XXX should handle packageName != null by dumping only install data that 14930 // the given package is involved with. 14931 if (dumpState.onTitlePrinted()) pw.println(); 14932 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14933 } 14934 14935 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14936 if (dumpState.onTitlePrinted()) pw.println(); 14937 mSettings.dumpReadMessagesLPr(pw, dumpState); 14938 14939 pw.println(); 14940 pw.println("Package warning messages:"); 14941 BufferedReader in = null; 14942 String line = null; 14943 try { 14944 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14945 while ((line = in.readLine()) != null) { 14946 if (line.contains("ignored: updated version")) continue; 14947 pw.println(line); 14948 } 14949 } catch (IOException ignored) { 14950 } finally { 14951 IoUtils.closeQuietly(in); 14952 } 14953 } 14954 14955 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14956 BufferedReader in = null; 14957 String line = null; 14958 try { 14959 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14960 while ((line = in.readLine()) != null) { 14961 if (line.contains("ignored: updated version")) continue; 14962 pw.print("msg,"); 14963 pw.println(line); 14964 } 14965 } catch (IOException ignored) { 14966 } finally { 14967 IoUtils.closeQuietly(in); 14968 } 14969 } 14970 } 14971 } 14972 14973 private String dumpDomainString(String packageName) { 14974 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 14975 List<IntentFilter> filters = getAllIntentFilters(packageName); 14976 14977 ArraySet<String> result = new ArraySet<>(); 14978 if (iviList.size() > 0) { 14979 for (IntentFilterVerificationInfo ivi : iviList) { 14980 for (String host : ivi.getDomains()) { 14981 result.add(host); 14982 } 14983 } 14984 } 14985 if (filters != null && filters.size() > 0) { 14986 for (IntentFilter filter : filters) { 14987 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 14988 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) { 14989 result.addAll(filter.getHostsList()); 14990 } 14991 } 14992 } 14993 14994 StringBuilder sb = new StringBuilder(result.size() * 16); 14995 for (String domain : result) { 14996 if (sb.length() > 0) sb.append(" "); 14997 sb.append(domain); 14998 } 14999 return sb.toString(); 15000 } 15001 15002 // ------- apps on sdcard specific code ------- 15003 static final boolean DEBUG_SD_INSTALL = false; 15004 15005 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 15006 15007 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 15008 15009 private boolean mMediaMounted = false; 15010 15011 static String getEncryptKey() { 15012 try { 15013 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 15014 SD_ENCRYPTION_KEYSTORE_NAME); 15015 if (sdEncKey == null) { 15016 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 15017 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 15018 if (sdEncKey == null) { 15019 Slog.e(TAG, "Failed to create encryption keys"); 15020 return null; 15021 } 15022 } 15023 return sdEncKey; 15024 } catch (NoSuchAlgorithmException nsae) { 15025 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 15026 return null; 15027 } catch (IOException ioe) { 15028 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 15029 return null; 15030 } 15031 } 15032 15033 /* 15034 * Update media status on PackageManager. 15035 */ 15036 @Override 15037 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 15038 int callingUid = Binder.getCallingUid(); 15039 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15040 throw new SecurityException("Media status can only be updated by the system"); 15041 } 15042 // reader; this apparently protects mMediaMounted, but should probably 15043 // be a different lock in that case. 15044 synchronized (mPackages) { 15045 Log.i(TAG, "Updating external media status from " 15046 + (mMediaMounted ? "mounted" : "unmounted") + " to " 15047 + (mediaStatus ? "mounted" : "unmounted")); 15048 if (DEBUG_SD_INSTALL) 15049 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 15050 + ", mMediaMounted=" + mMediaMounted); 15051 if (mediaStatus == mMediaMounted) { 15052 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 15053 : 0, -1); 15054 mHandler.sendMessage(msg); 15055 return; 15056 } 15057 mMediaMounted = mediaStatus; 15058 } 15059 // Queue up an async operation since the package installation may take a 15060 // little while. 15061 mHandler.post(new Runnable() { 15062 public void run() { 15063 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 15064 } 15065 }); 15066 } 15067 15068 /** 15069 * Called by MountService when the initial ASECs to scan are available. 15070 * Should block until all the ASEC containers are finished being scanned. 15071 */ 15072 public void scanAvailableAsecs() { 15073 updateExternalMediaStatusInner(true, false, false); 15074 if (mShouldRestoreconData) { 15075 SELinuxMMAC.setRestoreconDone(); 15076 mShouldRestoreconData = false; 15077 } 15078 } 15079 15080 /* 15081 * Collect information of applications on external media, map them against 15082 * existing containers and update information based on current mount status. 15083 * Please note that we always have to report status if reportStatus has been 15084 * set to true especially when unloading packages. 15085 */ 15086 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 15087 boolean externalStorage) { 15088 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 15089 int[] uidArr = EmptyArray.INT; 15090 15091 final String[] list = PackageHelper.getSecureContainerList(); 15092 if (ArrayUtils.isEmpty(list)) { 15093 Log.i(TAG, "No secure containers found"); 15094 } else { 15095 // Process list of secure containers and categorize them 15096 // as active or stale based on their package internal state. 15097 15098 // reader 15099 synchronized (mPackages) { 15100 for (String cid : list) { 15101 // Leave stages untouched for now; installer service owns them 15102 if (PackageInstallerService.isStageName(cid)) continue; 15103 15104 if (DEBUG_SD_INSTALL) 15105 Log.i(TAG, "Processing container " + cid); 15106 String pkgName = getAsecPackageName(cid); 15107 if (pkgName == null) { 15108 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 15109 continue; 15110 } 15111 if (DEBUG_SD_INSTALL) 15112 Log.i(TAG, "Looking for pkg : " + pkgName); 15113 15114 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15115 if (ps == null) { 15116 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 15117 continue; 15118 } 15119 15120 /* 15121 * Skip packages that are not external if we're unmounting 15122 * external storage. 15123 */ 15124 if (externalStorage && !isMounted && !isExternal(ps)) { 15125 continue; 15126 } 15127 15128 final AsecInstallArgs args = new AsecInstallArgs(cid, 15129 getAppDexInstructionSets(ps), ps.isForwardLocked()); 15130 // The package status is changed only if the code path 15131 // matches between settings and the container id. 15132 if (ps.codePathString != null 15133 && ps.codePathString.startsWith(args.getCodePath())) { 15134 if (DEBUG_SD_INSTALL) { 15135 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 15136 + " at code path: " + ps.codePathString); 15137 } 15138 15139 // We do have a valid package installed on sdcard 15140 processCids.put(args, ps.codePathString); 15141 final int uid = ps.appId; 15142 if (uid != -1) { 15143 uidArr = ArrayUtils.appendInt(uidArr, uid); 15144 } 15145 } else { 15146 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 15147 + ps.codePathString); 15148 } 15149 } 15150 } 15151 15152 Arrays.sort(uidArr); 15153 } 15154 15155 // Process packages with valid entries. 15156 if (isMounted) { 15157 if (DEBUG_SD_INSTALL) 15158 Log.i(TAG, "Loading packages"); 15159 loadMediaPackages(processCids, uidArr); 15160 startCleaningPackages(); 15161 mInstallerService.onSecureContainersAvailable(); 15162 } else { 15163 if (DEBUG_SD_INSTALL) 15164 Log.i(TAG, "Unloading packages"); 15165 unloadMediaPackages(processCids, uidArr, reportStatus); 15166 } 15167 } 15168 15169 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15170 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 15171 final int size = infos.size(); 15172 final String[] packageNames = new String[size]; 15173 final int[] packageUids = new int[size]; 15174 for (int i = 0; i < size; i++) { 15175 final ApplicationInfo info = infos.get(i); 15176 packageNames[i] = info.packageName; 15177 packageUids[i] = info.uid; 15178 } 15179 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 15180 finishedReceiver); 15181 } 15182 15183 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15184 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15185 sendResourcesChangedBroadcast(mediaStatus, replacing, 15186 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 15187 } 15188 15189 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 15190 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 15191 int size = pkgList.length; 15192 if (size > 0) { 15193 // Send broadcasts here 15194 Bundle extras = new Bundle(); 15195 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 15196 if (uidArr != null) { 15197 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 15198 } 15199 if (replacing) { 15200 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 15201 } 15202 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 15203 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 15204 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 15205 } 15206 } 15207 15208 /* 15209 * Look at potentially valid container ids from processCids If package 15210 * information doesn't match the one on record or package scanning fails, 15211 * the cid is added to list of removeCids. We currently don't delete stale 15212 * containers. 15213 */ 15214 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 15215 ArrayList<String> pkgList = new ArrayList<String>(); 15216 Set<AsecInstallArgs> keys = processCids.keySet(); 15217 15218 for (AsecInstallArgs args : keys) { 15219 String codePath = processCids.get(args); 15220 if (DEBUG_SD_INSTALL) 15221 Log.i(TAG, "Loading container : " + args.cid); 15222 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15223 try { 15224 // Make sure there are no container errors first. 15225 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 15226 Slog.e(TAG, "Failed to mount cid : " + args.cid 15227 + " when installing from sdcard"); 15228 continue; 15229 } 15230 // Check code path here. 15231 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 15232 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 15233 + " does not match one in settings " + codePath); 15234 continue; 15235 } 15236 // Parse package 15237 int parseFlags = mDefParseFlags; 15238 if (args.isExternalAsec()) { 15239 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 15240 } 15241 if (args.isFwdLocked()) { 15242 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 15243 } 15244 15245 synchronized (mInstallLock) { 15246 PackageParser.Package pkg = null; 15247 try { 15248 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 15249 } catch (PackageManagerException e) { 15250 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 15251 } 15252 // Scan the package 15253 if (pkg != null) { 15254 /* 15255 * TODO why is the lock being held? doPostInstall is 15256 * called in other places without the lock. This needs 15257 * to be straightened out. 15258 */ 15259 // writer 15260 synchronized (mPackages) { 15261 retCode = PackageManager.INSTALL_SUCCEEDED; 15262 pkgList.add(pkg.packageName); 15263 // Post process args 15264 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 15265 pkg.applicationInfo.uid); 15266 } 15267 } else { 15268 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 15269 } 15270 } 15271 15272 } finally { 15273 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 15274 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 15275 } 15276 } 15277 } 15278 // writer 15279 synchronized (mPackages) { 15280 // If the platform SDK has changed since the last time we booted, 15281 // we need to re-grant app permission to catch any new ones that 15282 // appear. This is really a hack, and means that apps can in some 15283 // cases get permissions that the user didn't initially explicitly 15284 // allow... it would be nice to have some better way to handle 15285 // this situation. 15286 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 15287 if (regrantPermissions) 15288 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 15289 + mSdkVersion + "; regranting permissions for external storage"); 15290 mSettings.mExternalSdkPlatform = mSdkVersion; 15291 15292 // Make sure group IDs have been assigned, and any permission 15293 // changes in other apps are accounted for 15294 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 15295 | (regrantPermissions 15296 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 15297 : 0)); 15298 15299 mSettings.updateExternalDatabaseVersion(); 15300 15301 // can downgrade to reader 15302 // Persist settings 15303 mSettings.writeLPr(); 15304 } 15305 // Send a broadcast to let everyone know we are done processing 15306 if (pkgList.size() > 0) { 15307 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 15308 } 15309 } 15310 15311 /* 15312 * Utility method to unload a list of specified containers 15313 */ 15314 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 15315 // Just unmount all valid containers. 15316 for (AsecInstallArgs arg : cidArgs) { 15317 synchronized (mInstallLock) { 15318 arg.doPostDeleteLI(false); 15319 } 15320 } 15321 } 15322 15323 /* 15324 * Unload packages mounted on external media. This involves deleting package 15325 * data from internal structures, sending broadcasts about diabled packages, 15326 * gc'ing to free up references, unmounting all secure containers 15327 * corresponding to packages on external media, and posting a 15328 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 15329 * that we always have to post this message if status has been requested no 15330 * matter what. 15331 */ 15332 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 15333 final boolean reportStatus) { 15334 if (DEBUG_SD_INSTALL) 15335 Log.i(TAG, "unloading media packages"); 15336 ArrayList<String> pkgList = new ArrayList<String>(); 15337 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 15338 final Set<AsecInstallArgs> keys = processCids.keySet(); 15339 for (AsecInstallArgs args : keys) { 15340 String pkgName = args.getPackageName(); 15341 if (DEBUG_SD_INSTALL) 15342 Log.i(TAG, "Trying to unload pkg : " + pkgName); 15343 // Delete package internally 15344 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15345 synchronized (mInstallLock) { 15346 boolean res = deletePackageLI(pkgName, null, false, null, null, 15347 PackageManager.DELETE_KEEP_DATA, outInfo, false); 15348 if (res) { 15349 pkgList.add(pkgName); 15350 } else { 15351 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 15352 failedList.add(args); 15353 } 15354 } 15355 } 15356 15357 // reader 15358 synchronized (mPackages) { 15359 // We didn't update the settings after removing each package; 15360 // write them now for all packages. 15361 mSettings.writeLPr(); 15362 } 15363 15364 // We have to absolutely send UPDATED_MEDIA_STATUS only 15365 // after confirming that all the receivers processed the ordered 15366 // broadcast when packages get disabled, force a gc to clean things up. 15367 // and unload all the containers. 15368 if (pkgList.size() > 0) { 15369 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 15370 new IIntentReceiver.Stub() { 15371 public void performReceive(Intent intent, int resultCode, String data, 15372 Bundle extras, boolean ordered, boolean sticky, 15373 int sendingUser) throws RemoteException { 15374 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 15375 reportStatus ? 1 : 0, 1, keys); 15376 mHandler.sendMessage(msg); 15377 } 15378 }); 15379 } else { 15380 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 15381 keys); 15382 mHandler.sendMessage(msg); 15383 } 15384 } 15385 15386 private void loadPrivatePackages(VolumeInfo vol) { 15387 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 15388 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 15389 synchronized (mInstallLock) { 15390 synchronized (mPackages) { 15391 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15392 for (PackageSetting ps : packages) { 15393 final PackageParser.Package pkg; 15394 try { 15395 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 15396 loaded.add(pkg.applicationInfo); 15397 } catch (PackageManagerException e) { 15398 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 15399 } 15400 } 15401 15402 // TODO: regrant any permissions that changed based since original install 15403 15404 mSettings.writeLPr(); 15405 } 15406 } 15407 15408 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 15409 sendResourcesChangedBroadcast(true, false, loaded, null); 15410 } 15411 15412 private void unloadPrivatePackages(VolumeInfo vol) { 15413 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 15414 synchronized (mInstallLock) { 15415 synchronized (mPackages) { 15416 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 15417 for (PackageSetting ps : packages) { 15418 if (ps.pkg == null) continue; 15419 15420 final ApplicationInfo info = ps.pkg.applicationInfo; 15421 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 15422 if (deletePackageLI(ps.name, null, false, null, null, 15423 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 15424 unloaded.add(info); 15425 } else { 15426 Slog.w(TAG, "Failed to unload " + ps.codePath); 15427 } 15428 } 15429 15430 mSettings.writeLPr(); 15431 } 15432 } 15433 15434 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 15435 sendResourcesChangedBroadcast(false, false, unloaded, null); 15436 } 15437 15438 /** 15439 * Examine all users present on given mounted volume, and destroy data 15440 * belonging to users that are no longer valid, or whose user ID has been 15441 * recycled. 15442 */ 15443 private void reconcileUsers(String volumeUuid) { 15444 final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles(); 15445 if (ArrayUtils.isEmpty(files)) { 15446 Slog.d(TAG, "No users found on " + volumeUuid); 15447 return; 15448 } 15449 15450 for (File file : files) { 15451 if (!file.isDirectory()) continue; 15452 15453 final int userId; 15454 final UserInfo info; 15455 try { 15456 userId = Integer.parseInt(file.getName()); 15457 info = sUserManager.getUserInfo(userId); 15458 } catch (NumberFormatException e) { 15459 Slog.w(TAG, "Invalid user directory " + file); 15460 continue; 15461 } 15462 15463 boolean destroyUser = false; 15464 if (info == null) { 15465 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15466 + " because no matching user was found"); 15467 destroyUser = true; 15468 } else { 15469 try { 15470 UserManagerService.enforceSerialNumber(file, info.serialNumber); 15471 } catch (IOException e) { 15472 logCriticalInfo(Log.WARN, "Destroying user directory " + file 15473 + " because we failed to enforce serial number: " + e); 15474 destroyUser = true; 15475 } 15476 } 15477 15478 if (destroyUser) { 15479 synchronized (mInstallLock) { 15480 mInstaller.removeUserDataDirs(volumeUuid, userId); 15481 } 15482 } 15483 } 15484 15485 final UserManager um = mContext.getSystemService(UserManager.class); 15486 for (UserInfo user : um.getUsers()) { 15487 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 15488 if (userDir.exists()) continue; 15489 15490 try { 15491 UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id); 15492 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 15493 } catch (IOException e) { 15494 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 15495 } 15496 } 15497 } 15498 15499 /** 15500 * Examine all apps present on given mounted volume, and destroy apps that 15501 * aren't expected, either due to uninstallation or reinstallation on 15502 * another volume. 15503 */ 15504 private void reconcileApps(String volumeUuid) { 15505 final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles(); 15506 if (ArrayUtils.isEmpty(files)) { 15507 Slog.d(TAG, "No apps found on " + volumeUuid); 15508 return; 15509 } 15510 15511 for (File file : files) { 15512 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 15513 && !PackageInstallerService.isStageName(file.getName()); 15514 if (!isPackage) { 15515 // Ignore entries which are not packages 15516 continue; 15517 } 15518 15519 boolean destroyApp = false; 15520 String packageName = null; 15521 try { 15522 final PackageLite pkg = PackageParser.parsePackageLite(file, 15523 PackageParser.PARSE_MUST_BE_APK); 15524 packageName = pkg.packageName; 15525 15526 synchronized (mPackages) { 15527 final PackageSetting ps = mSettings.mPackages.get(packageName); 15528 if (ps == null) { 15529 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 15530 + volumeUuid + " because we found no install record"); 15531 destroyApp = true; 15532 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 15533 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 15534 + volumeUuid + " because we expected it on " + ps.volumeUuid); 15535 destroyApp = true; 15536 } 15537 } 15538 15539 } catch (PackageParserException e) { 15540 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 15541 destroyApp = true; 15542 } 15543 15544 if (destroyApp) { 15545 synchronized (mInstallLock) { 15546 if (packageName != null) { 15547 removeDataDirsLI(volumeUuid, packageName); 15548 } 15549 if (file.isDirectory()) { 15550 mInstaller.rmPackageDir(file.getAbsolutePath()); 15551 } else { 15552 file.delete(); 15553 } 15554 } 15555 } 15556 } 15557 } 15558 15559 private void unfreezePackage(String packageName) { 15560 synchronized (mPackages) { 15561 final PackageSetting ps = mSettings.mPackages.get(packageName); 15562 if (ps != null) { 15563 ps.frozen = false; 15564 } 15565 } 15566 } 15567 15568 @Override 15569 public int movePackage(final String packageName, final String volumeUuid) { 15570 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15571 15572 final int moveId = mNextMoveId.getAndIncrement(); 15573 try { 15574 movePackageInternal(packageName, volumeUuid, moveId); 15575 } catch (PackageManagerException e) { 15576 Slog.w(TAG, "Failed to move " + packageName, e); 15577 mMoveCallbacks.notifyStatusChanged(moveId, 15578 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15579 } 15580 return moveId; 15581 } 15582 15583 private void movePackageInternal(final String packageName, final String volumeUuid, 15584 final int moveId) throws PackageManagerException { 15585 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 15586 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15587 final PackageManager pm = mContext.getPackageManager(); 15588 15589 final boolean currentAsec; 15590 final String currentVolumeUuid; 15591 final File codeFile; 15592 final String installerPackageName; 15593 final String packageAbiOverride; 15594 final int appId; 15595 final String seinfo; 15596 final String label; 15597 15598 // reader 15599 synchronized (mPackages) { 15600 final PackageParser.Package pkg = mPackages.get(packageName); 15601 final PackageSetting ps = mSettings.mPackages.get(packageName); 15602 if (pkg == null || ps == null) { 15603 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 15604 } 15605 15606 if (pkg.applicationInfo.isSystemApp()) { 15607 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 15608 "Cannot move system application"); 15609 } 15610 15611 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 15612 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15613 "Package already moved to " + volumeUuid); 15614 } 15615 15616 final File probe = new File(pkg.codePath); 15617 final File probeOat = new File(probe, "oat"); 15618 if (!probe.isDirectory() || !probeOat.isDirectory()) { 15619 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15620 "Move only supported for modern cluster style installs"); 15621 } 15622 15623 if (ps.frozen) { 15624 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 15625 "Failed to move already frozen package"); 15626 } 15627 ps.frozen = true; 15628 15629 currentAsec = pkg.applicationInfo.isForwardLocked() 15630 || pkg.applicationInfo.isExternalAsec(); 15631 currentVolumeUuid = ps.volumeUuid; 15632 codeFile = new File(pkg.codePath); 15633 installerPackageName = ps.installerPackageName; 15634 packageAbiOverride = ps.cpuAbiOverrideString; 15635 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15636 seinfo = pkg.applicationInfo.seinfo; 15637 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 15638 } 15639 15640 // Now that we're guarded by frozen state, kill app during move 15641 killApplication(packageName, appId, "move pkg"); 15642 15643 final Bundle extras = new Bundle(); 15644 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 15645 extras.putString(Intent.EXTRA_TITLE, label); 15646 mMoveCallbacks.notifyCreated(moveId, extras); 15647 15648 int installFlags; 15649 final boolean moveCompleteApp; 15650 final File measurePath; 15651 15652 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 15653 installFlags = INSTALL_INTERNAL; 15654 moveCompleteApp = !currentAsec; 15655 measurePath = Environment.getDataAppDirectory(volumeUuid); 15656 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 15657 installFlags = INSTALL_EXTERNAL; 15658 moveCompleteApp = false; 15659 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 15660 } else { 15661 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 15662 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 15663 || !volume.isMountedWritable()) { 15664 unfreezePackage(packageName); 15665 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15666 "Move location not mounted private volume"); 15667 } 15668 15669 Preconditions.checkState(!currentAsec); 15670 15671 installFlags = INSTALL_INTERNAL; 15672 moveCompleteApp = true; 15673 measurePath = Environment.getDataAppDirectory(volumeUuid); 15674 } 15675 15676 final PackageStats stats = new PackageStats(null, -1); 15677 synchronized (mInstaller) { 15678 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 15679 unfreezePackage(packageName); 15680 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15681 "Failed to measure package size"); 15682 } 15683 } 15684 15685 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 15686 + stats.dataSize); 15687 15688 final long startFreeBytes = measurePath.getFreeSpace(); 15689 final long sizeBytes; 15690 if (moveCompleteApp) { 15691 sizeBytes = stats.codeSize + stats.dataSize; 15692 } else { 15693 sizeBytes = stats.codeSize; 15694 } 15695 15696 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 15697 unfreezePackage(packageName); 15698 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 15699 "Not enough free space to move"); 15700 } 15701 15702 mMoveCallbacks.notifyStatusChanged(moveId, 10); 15703 15704 final CountDownLatch installedLatch = new CountDownLatch(1); 15705 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 15706 @Override 15707 public void onUserActionRequired(Intent intent) throws RemoteException { 15708 throw new IllegalStateException(); 15709 } 15710 15711 @Override 15712 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 15713 Bundle extras) throws RemoteException { 15714 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 15715 + PackageManager.installStatusToString(returnCode, msg)); 15716 15717 installedLatch.countDown(); 15718 15719 // Regardless of success or failure of the move operation, 15720 // always unfreeze the package 15721 unfreezePackage(packageName); 15722 15723 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15724 switch (status) { 15725 case PackageInstaller.STATUS_SUCCESS: 15726 mMoveCallbacks.notifyStatusChanged(moveId, 15727 PackageManager.MOVE_SUCCEEDED); 15728 break; 15729 case PackageInstaller.STATUS_FAILURE_STORAGE: 15730 mMoveCallbacks.notifyStatusChanged(moveId, 15731 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15732 break; 15733 default: 15734 mMoveCallbacks.notifyStatusChanged(moveId, 15735 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15736 break; 15737 } 15738 } 15739 }; 15740 15741 final MoveInfo move; 15742 if (moveCompleteApp) { 15743 // Kick off a thread to report progress estimates 15744 new Thread() { 15745 @Override 15746 public void run() { 15747 while (true) { 15748 try { 15749 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15750 break; 15751 } 15752 } catch (InterruptedException ignored) { 15753 } 15754 15755 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15756 final int progress = 10 + (int) MathUtils.constrain( 15757 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15758 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15759 } 15760 } 15761 }.start(); 15762 15763 final String dataAppName = codeFile.getName(); 15764 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15765 dataAppName, appId, seinfo); 15766 } else { 15767 move = null; 15768 } 15769 15770 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15771 15772 final Message msg = mHandler.obtainMessage(INIT_COPY); 15773 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15774 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15775 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15776 mHandler.sendMessage(msg); 15777 } 15778 15779 @Override 15780 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15781 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15782 15783 final int realMoveId = mNextMoveId.getAndIncrement(); 15784 final Bundle extras = new Bundle(); 15785 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15786 mMoveCallbacks.notifyCreated(realMoveId, extras); 15787 15788 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15789 @Override 15790 public void onCreated(int moveId, Bundle extras) { 15791 // Ignored 15792 } 15793 15794 @Override 15795 public void onStatusChanged(int moveId, int status, long estMillis) { 15796 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15797 } 15798 }; 15799 15800 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15801 storage.setPrimaryStorageUuid(volumeUuid, callback); 15802 return realMoveId; 15803 } 15804 15805 @Override 15806 public int getMoveStatus(int moveId) { 15807 mContext.enforceCallingOrSelfPermission( 15808 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15809 return mMoveCallbacks.mLastStatus.get(moveId); 15810 } 15811 15812 @Override 15813 public void registerMoveCallback(IPackageMoveObserver callback) { 15814 mContext.enforceCallingOrSelfPermission( 15815 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15816 mMoveCallbacks.register(callback); 15817 } 15818 15819 @Override 15820 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15821 mContext.enforceCallingOrSelfPermission( 15822 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15823 mMoveCallbacks.unregister(callback); 15824 } 15825 15826 @Override 15827 public boolean setInstallLocation(int loc) { 15828 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15829 null); 15830 if (getInstallLocation() == loc) { 15831 return true; 15832 } 15833 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15834 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15835 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15836 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15837 return true; 15838 } 15839 return false; 15840 } 15841 15842 @Override 15843 public int getInstallLocation() { 15844 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15845 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15846 PackageHelper.APP_INSTALL_AUTO); 15847 } 15848 15849 /** Called by UserManagerService */ 15850 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15851 mDirtyUsers.remove(userHandle); 15852 mSettings.removeUserLPw(userHandle); 15853 mPendingBroadcasts.remove(userHandle); 15854 if (mInstaller != null) { 15855 // Technically, we shouldn't be doing this with the package lock 15856 // held. However, this is very rare, and there is already so much 15857 // other disk I/O going on, that we'll let it slide for now. 15858 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15859 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 15860 final String volumeUuid = vol.getFsUuid(); 15861 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15862 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15863 } 15864 } 15865 mUserNeedsBadging.delete(userHandle); 15866 removeUnusedPackagesLILPw(userManager, userHandle); 15867 } 15868 15869 /** 15870 * We're removing userHandle and would like to remove any downloaded packages 15871 * that are no longer in use by any other user. 15872 * @param userHandle the user being removed 15873 */ 15874 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15875 final boolean DEBUG_CLEAN_APKS = false; 15876 int [] users = userManager.getUserIdsLPr(); 15877 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15878 while (psit.hasNext()) { 15879 PackageSetting ps = psit.next(); 15880 if (ps.pkg == null) { 15881 continue; 15882 } 15883 final String packageName = ps.pkg.packageName; 15884 // Skip over if system app 15885 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15886 continue; 15887 } 15888 if (DEBUG_CLEAN_APKS) { 15889 Slog.i(TAG, "Checking package " + packageName); 15890 } 15891 boolean keep = false; 15892 for (int i = 0; i < users.length; i++) { 15893 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15894 keep = true; 15895 if (DEBUG_CLEAN_APKS) { 15896 Slog.i(TAG, " Keeping package " + packageName + " for user " 15897 + users[i]); 15898 } 15899 break; 15900 } 15901 } 15902 if (!keep) { 15903 if (DEBUG_CLEAN_APKS) { 15904 Slog.i(TAG, " Removing package " + packageName); 15905 } 15906 mHandler.post(new Runnable() { 15907 public void run() { 15908 deletePackageX(packageName, userHandle, 0); 15909 } //end run 15910 }); 15911 } 15912 } 15913 } 15914 15915 /** Called by UserManagerService */ 15916 void createNewUserLILPw(int userHandle) { 15917 if (mInstaller != null) { 15918 mInstaller.createUserConfig(userHandle); 15919 mSettings.createNewUserLILPw(this, mInstaller, userHandle); 15920 applyFactoryDefaultBrowserLPw(userHandle); 15921 primeDomainVerificationsLPw(userHandle); 15922 } 15923 } 15924 15925 void newUserCreatedLILPw(final int userHandle) { 15926 // We cannot grant the default permissions with a lock held as 15927 // we query providers from other components for default handlers 15928 // such as enabled IMEs, etc. 15929 mHandler.post(new Runnable() { 15930 @Override 15931 public void run() { 15932 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15933 } 15934 }); 15935 } 15936 15937 @Override 15938 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15939 mContext.enforceCallingOrSelfPermission( 15940 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15941 "Only package verification agents can read the verifier device identity"); 15942 15943 synchronized (mPackages) { 15944 return mSettings.getVerifierDeviceIdentityLPw(); 15945 } 15946 } 15947 15948 @Override 15949 public void setPermissionEnforced(String permission, boolean enforced) { 15950 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15951 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15952 synchronized (mPackages) { 15953 if (mSettings.mReadExternalStorageEnforced == null 15954 || mSettings.mReadExternalStorageEnforced != enforced) { 15955 mSettings.mReadExternalStorageEnforced = enforced; 15956 mSettings.writeLPr(); 15957 } 15958 } 15959 // kill any non-foreground processes so we restart them and 15960 // grant/revoke the GID. 15961 final IActivityManager am = ActivityManagerNative.getDefault(); 15962 if (am != null) { 15963 final long token = Binder.clearCallingIdentity(); 15964 try { 15965 am.killProcessesBelowForeground("setPermissionEnforcement"); 15966 } catch (RemoteException e) { 15967 } finally { 15968 Binder.restoreCallingIdentity(token); 15969 } 15970 } 15971 } else { 15972 throw new IllegalArgumentException("No selective enforcement for " + permission); 15973 } 15974 } 15975 15976 @Override 15977 @Deprecated 15978 public boolean isPermissionEnforced(String permission) { 15979 return true; 15980 } 15981 15982 @Override 15983 public boolean isStorageLow() { 15984 final long token = Binder.clearCallingIdentity(); 15985 try { 15986 final DeviceStorageMonitorInternal 15987 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15988 if (dsm != null) { 15989 return dsm.isMemoryLow(); 15990 } else { 15991 return false; 15992 } 15993 } finally { 15994 Binder.restoreCallingIdentity(token); 15995 } 15996 } 15997 15998 @Override 15999 public IPackageInstaller getPackageInstaller() { 16000 return mInstallerService; 16001 } 16002 16003 private boolean userNeedsBadging(int userId) { 16004 int index = mUserNeedsBadging.indexOfKey(userId); 16005 if (index < 0) { 16006 final UserInfo userInfo; 16007 final long token = Binder.clearCallingIdentity(); 16008 try { 16009 userInfo = sUserManager.getUserInfo(userId); 16010 } finally { 16011 Binder.restoreCallingIdentity(token); 16012 } 16013 final boolean b; 16014 if (userInfo != null && userInfo.isManagedProfile()) { 16015 b = true; 16016 } else { 16017 b = false; 16018 } 16019 mUserNeedsBadging.put(userId, b); 16020 return b; 16021 } 16022 return mUserNeedsBadging.valueAt(index); 16023 } 16024 16025 @Override 16026 public KeySet getKeySetByAlias(String packageName, String alias) { 16027 if (packageName == null || alias == null) { 16028 return null; 16029 } 16030 synchronized(mPackages) { 16031 final PackageParser.Package pkg = mPackages.get(packageName); 16032 if (pkg == null) { 16033 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16034 throw new IllegalArgumentException("Unknown package: " + packageName); 16035 } 16036 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16037 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 16038 } 16039 } 16040 16041 @Override 16042 public KeySet getSigningKeySet(String packageName) { 16043 if (packageName == null) { 16044 return null; 16045 } 16046 synchronized(mPackages) { 16047 final PackageParser.Package pkg = mPackages.get(packageName); 16048 if (pkg == null) { 16049 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16050 throw new IllegalArgumentException("Unknown package: " + packageName); 16051 } 16052 if (pkg.applicationInfo.uid != Binder.getCallingUid() 16053 && Process.SYSTEM_UID != Binder.getCallingUid()) { 16054 throw new SecurityException("May not access signing KeySet of other apps."); 16055 } 16056 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16057 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 16058 } 16059 } 16060 16061 @Override 16062 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 16063 if (packageName == null || ks == null) { 16064 return false; 16065 } 16066 synchronized(mPackages) { 16067 final PackageParser.Package pkg = mPackages.get(packageName); 16068 if (pkg == null) { 16069 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16070 throw new IllegalArgumentException("Unknown package: " + packageName); 16071 } 16072 IBinder ksh = ks.getToken(); 16073 if (ksh instanceof KeySetHandle) { 16074 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16075 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 16076 } 16077 return false; 16078 } 16079 } 16080 16081 @Override 16082 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 16083 if (packageName == null || ks == null) { 16084 return false; 16085 } 16086 synchronized(mPackages) { 16087 final PackageParser.Package pkg = mPackages.get(packageName); 16088 if (pkg == null) { 16089 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 16090 throw new IllegalArgumentException("Unknown package: " + packageName); 16091 } 16092 IBinder ksh = ks.getToken(); 16093 if (ksh instanceof KeySetHandle) { 16094 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16095 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 16096 } 16097 return false; 16098 } 16099 } 16100 16101 public void getUsageStatsIfNoPackageUsageInfo() { 16102 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 16103 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 16104 if (usm == null) { 16105 throw new IllegalStateException("UsageStatsManager must be initialized"); 16106 } 16107 long now = System.currentTimeMillis(); 16108 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 16109 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 16110 String packageName = entry.getKey(); 16111 PackageParser.Package pkg = mPackages.get(packageName); 16112 if (pkg == null) { 16113 continue; 16114 } 16115 UsageStats usage = entry.getValue(); 16116 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 16117 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 16118 } 16119 } 16120 } 16121 16122 /** 16123 * Check and throw if the given before/after packages would be considered a 16124 * downgrade. 16125 */ 16126 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 16127 throws PackageManagerException { 16128 if (after.versionCode < before.mVersionCode) { 16129 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16130 "Update version code " + after.versionCode + " is older than current " 16131 + before.mVersionCode); 16132 } else if (after.versionCode == before.mVersionCode) { 16133 if (after.baseRevisionCode < before.baseRevisionCode) { 16134 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16135 "Update base revision code " + after.baseRevisionCode 16136 + " is older than current " + before.baseRevisionCode); 16137 } 16138 16139 if (!ArrayUtils.isEmpty(after.splitNames)) { 16140 for (int i = 0; i < after.splitNames.length; i++) { 16141 final String splitName = after.splitNames[i]; 16142 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 16143 if (j != -1) { 16144 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 16145 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 16146 "Update split " + splitName + " revision code " 16147 + after.splitRevisionCodes[i] + " is older than current " 16148 + before.splitRevisionCodes[j]); 16149 } 16150 } 16151 } 16152 } 16153 } 16154 } 16155 16156 private static class MoveCallbacks extends Handler { 16157 private static final int MSG_CREATED = 1; 16158 private static final int MSG_STATUS_CHANGED = 2; 16159 16160 private final RemoteCallbackList<IPackageMoveObserver> 16161 mCallbacks = new RemoteCallbackList<>(); 16162 16163 private final SparseIntArray mLastStatus = new SparseIntArray(); 16164 16165 public MoveCallbacks(Looper looper) { 16166 super(looper); 16167 } 16168 16169 public void register(IPackageMoveObserver callback) { 16170 mCallbacks.register(callback); 16171 } 16172 16173 public void unregister(IPackageMoveObserver callback) { 16174 mCallbacks.unregister(callback); 16175 } 16176 16177 @Override 16178 public void handleMessage(Message msg) { 16179 final SomeArgs args = (SomeArgs) msg.obj; 16180 final int n = mCallbacks.beginBroadcast(); 16181 for (int i = 0; i < n; i++) { 16182 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 16183 try { 16184 invokeCallback(callback, msg.what, args); 16185 } catch (RemoteException ignored) { 16186 } 16187 } 16188 mCallbacks.finishBroadcast(); 16189 args.recycle(); 16190 } 16191 16192 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 16193 throws RemoteException { 16194 switch (what) { 16195 case MSG_CREATED: { 16196 callback.onCreated(args.argi1, (Bundle) args.arg2); 16197 break; 16198 } 16199 case MSG_STATUS_CHANGED: { 16200 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 16201 break; 16202 } 16203 } 16204 } 16205 16206 private void notifyCreated(int moveId, Bundle extras) { 16207 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 16208 16209 final SomeArgs args = SomeArgs.obtain(); 16210 args.argi1 = moveId; 16211 args.arg2 = extras; 16212 obtainMessage(MSG_CREATED, args).sendToTarget(); 16213 } 16214 16215 private void notifyStatusChanged(int moveId, int status) { 16216 notifyStatusChanged(moveId, status, -1); 16217 } 16218 16219 private void notifyStatusChanged(int moveId, int status, long estMillis) { 16220 Slog.v(TAG, "Move " + moveId + " status " + status); 16221 16222 final SomeArgs args = SomeArgs.obtain(); 16223 args.argi1 = moveId; 16224 args.argi2 = status; 16225 args.arg3 = estMillis; 16226 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 16227 16228 synchronized (mLastStatus) { 16229 mLastStatus.put(moveId, status); 16230 } 16231 } 16232 } 16233 16234 private final class OnPermissionChangeListeners extends Handler { 16235 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 16236 16237 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 16238 new RemoteCallbackList<>(); 16239 16240 public OnPermissionChangeListeners(Looper looper) { 16241 super(looper); 16242 } 16243 16244 @Override 16245 public void handleMessage(Message msg) { 16246 switch (msg.what) { 16247 case MSG_ON_PERMISSIONS_CHANGED: { 16248 final int uid = msg.arg1; 16249 handleOnPermissionsChanged(uid); 16250 } break; 16251 } 16252 } 16253 16254 public void addListenerLocked(IOnPermissionsChangeListener listener) { 16255 mPermissionListeners.register(listener); 16256 16257 } 16258 16259 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 16260 mPermissionListeners.unregister(listener); 16261 } 16262 16263 public void onPermissionsChanged(int uid) { 16264 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 16265 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 16266 } 16267 } 16268 16269 private void handleOnPermissionsChanged(int uid) { 16270 final int count = mPermissionListeners.beginBroadcast(); 16271 try { 16272 for (int i = 0; i < count; i++) { 16273 IOnPermissionsChangeListener callback = mPermissionListeners 16274 .getBroadcastItem(i); 16275 try { 16276 callback.onPermissionsChanged(uid); 16277 } catch (RemoteException e) { 16278 Log.e(TAG, "Permission listener is dead", e); 16279 } 16280 } 16281 } finally { 16282 mPermissionListeners.finishBroadcast(); 16283 } 16284 } 16285 } 16286 16287 private class PackageManagerInternalImpl extends PackageManagerInternal { 16288 @Override 16289 public void setLocationPackagesProvider(PackagesProvider provider) { 16290 synchronized (mPackages) { 16291 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 16292 } 16293 } 16294 16295 @Override 16296 public void setImePackagesProvider(PackagesProvider provider) { 16297 synchronized (mPackages) { 16298 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 16299 } 16300 } 16301 16302 @Override 16303 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 16304 synchronized (mPackages) { 16305 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 16306 } 16307 } 16308 16309 @Override 16310 public void setSmsAppPackagesProvider(PackagesProvider provider) { 16311 synchronized (mPackages) { 16312 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 16313 } 16314 } 16315 16316 @Override 16317 public void setDialerAppPackagesProvider(PackagesProvider provider) { 16318 synchronized (mPackages) { 16319 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 16320 } 16321 } 16322 16323 @Override 16324 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 16325 synchronized (mPackages) { 16326 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider); 16327 } 16328 } 16329 16330 @Override 16331 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 16332 synchronized (mPackages) { 16333 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 16334 packageName, userId); 16335 } 16336 } 16337 16338 @Override 16339 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 16340 synchronized (mPackages) { 16341 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 16342 packageName, userId); 16343 } 16344 } 16345 } 16346 16347 @Override 16348 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 16349 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 16350 synchronized (mPackages) { 16351 final long identity = Binder.clearCallingIdentity(); 16352 try { 16353 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 16354 packageNames, userId); 16355 } finally { 16356 Binder.restoreCallingIdentity(identity); 16357 } 16358 } 16359 } 16360 16361 private static void enforceSystemOrPhoneCaller(String tag) { 16362 int callingUid = Binder.getCallingUid(); 16363 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 16364 throw new SecurityException( 16365 "Cannot call " + tag + " from UID " + callingUid); 16366 } 16367 } 16368} 16369